monotone

monotone Mtn Source Tree

Root/sqlite/vdbeaux.c

1/*
2** 2003 September 6
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
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.
10**
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.
16*/
17#include "sqliteInt.h"
18#include "os.h"
19#include <ctype.h>
20#include "vdbeInt.h"
21
22
23/*
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.
27*/
28#ifdef SQLITE_DEBUG
29int sqlite3_vdbe_addop_trace = 0;
30#endif
31
32
33/*
34** Create a new virtual database engine.
35*/
36Vdbe *sqlite3VdbeCreate(sqlite3 *db){
37 Vdbe *p;
38 p = sqliteMalloc( sizeof(Vdbe) );
39 if( p==0 ) return 0;
40 p->db = db;
41 if( db->pVdbe ){
42 db->pVdbe->pPrev = p;
43 }
44 p->pNext = db->pVdbe;
45 p->pPrev = 0;
46 db->pVdbe = p;
47 p->magic = VDBE_MAGIC_INIT;
48 return p;
49}
50
51/*
52** Remember the SQL string for a prepared statement.
53*/
54void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
55 if( p==0 ) return;
56 assert( p->zSql==0 );
57 p->zSql = sqlite3StrNDup(z, n);
58}
59
60/*
61** Return the SQL associated with a prepared statement
62*/
63const char *sqlite3VdbeGetSql(Vdbe *p){
64 return p->zSql;
65}
66
67/*
68** Swap all content between two VDBE structures.
69*/
70void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
71 Vdbe tmp, *pTmp;
72 char *zTmp;
73 int nTmp;
74 tmp = *pA;
75 *pA = *pB;
76 *pB = tmp;
77 pTmp = pA->pNext;
78 pA->pNext = pB->pNext;
79 pB->pNext = pTmp;
80 pTmp = pA->pPrev;
81 pA->pPrev = pB->pPrev;
82 pB->pPrev = pTmp;
83 zTmp = pA->zSql;
84 pA->zSql = pB->zSql;
85 pB->zSql = zTmp;
86 nTmp = pA->nSql;
87 pA->nSql = pB->nSql;
88 pB->nSql = nTmp;
89}
90
91#ifdef SQLITE_DEBUG
92/*
93** Turn tracing on or off
94*/
95void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
96 p->trace = trace;
97}
98#endif
99
100/*
101** Resize the Vdbe.aOp array so that it contains at least N
102** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
103** the Vdbe.aOp array will be sized to contain exactly N
104** elements. Vdbe.nOpAlloc is set to reflect the new size of
105** the array.
106**
107** If an out-of-memory error occurs while resizing the array,
108** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
109** any opcodes already allocated can be correctly deallocated
110** along with the rest of the Vdbe).
111*/
112static void resizeOpArray(Vdbe *p, int N){
113 int runMode = p->magic==VDBE_MAGIC_RUN;
114 if( runMode || p->nOpAlloc<N ){
115 VdbeOp *pNew;
116 int nNew = N + 100*(!runMode);
117 int oldSize = p->nOpAlloc;
118 pNew = sqliteRealloc(p->aOp, nNew*sizeof(Op));
119 if( pNew ){
120 p->nOpAlloc = nNew;
121 p->aOp = pNew;
122 if( nNew>oldSize ){
123 memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
124 }
125 }
126 }
127}
128
129/*
130** Add a new instruction to the list of instructions current in the
131** VDBE. Return the address of the new instruction.
132**
133** Parameters:
134**
135** p Pointer to the VDBE
136**
137** op The opcode for this instruction
138**
139** p1, p2 First two of the three possible operands.
140**
141** Use the sqlite3VdbeResolveLabel() function to fix an address and
142** the sqlite3VdbeChangeP3() function to change the value of the P3
143** operand.
144*/
145int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
146 int i;
147 VdbeOp *pOp;
148
149 i = p->nOp;
150 assert( p->magic==VDBE_MAGIC_INIT );
151 if( p->nOpAlloc<=i ){
152 resizeOpArray(p, i+1);
153 if( sqlite3MallocFailed() ){
154 return 0;
155 }
156 }
157 p->nOp++;
158 pOp = &p->aOp[i];
159 pOp->opcode = op;
160 pOp->p1 = p1;
161 pOp->p2 = p2;
162 pOp->p3 = 0;
163 pOp->p3type = P3_NOTUSED;
164 p->expired = 0;
165#ifdef SQLITE_DEBUG
166 if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
167#endif
168 return i;
169}
170
171/*
172** Add an opcode that includes the p3 value.
173*/
174int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
175 int addr = sqlite3VdbeAddOp(p, op, p1, p2);
176 sqlite3VdbeChangeP3(p, addr, zP3, p3type);
177 return addr;
178}
179
180/*
181** Create a new symbolic label for an instruction that has yet to be
182** coded. The symbolic label is really just a negative number. The
183** label can be used as the P2 value of an operation. Later, when
184** the label is resolved to a specific address, the VDBE will scan
185** through its operation list and change all values of P2 which match
186** the label into the resolved address.
187**
188** The VDBE knows that a P2 value is a label because labels are
189** always negative and P2 values are suppose to be non-negative.
190** Hence, a negative P2 value is a label that has yet to be resolved.
191**
192** Zero is returned if a malloc() fails.
193*/
194int sqlite3VdbeMakeLabel(Vdbe *p){
195 int i;
196 i = p->nLabel++;
197 assert( p->magic==VDBE_MAGIC_INIT );
198 if( i>=p->nLabelAlloc ){
199 p->nLabelAlloc = p->nLabelAlloc*2 + 10;
200 p->aLabel = sqliteReallocOrFree(p->aLabel,
201 p->nLabelAlloc*sizeof(p->aLabel[0]));
202 }
203 if( p->aLabel ){
204 p->aLabel[i] = -1;
205 }
206 return -1-i;
207}
208
209/*
210** Resolve label "x" to be the address of the next instruction to
211** be inserted. The parameter "x" must have been obtained from
212** a prior call to sqlite3VdbeMakeLabel().
213*/
214void sqlite3VdbeResolveLabel(Vdbe *p, int x){
215 int j = -1-x;
216 assert( p->magic==VDBE_MAGIC_INIT );
217 assert( j>=0 && j<p->nLabel );
218 if( p->aLabel ){
219 p->aLabel[j] = p->nOp;
220 }
221}
222
223/*
224** Return non-zero if opcode 'op' is guarenteed not to push more values
225** onto the VDBE stack than it pops off.
226*/
227static int opcodeNoPush(u8 op){
228 /* The 10 NOPUSH_MASK_n constants are defined in the automatically
229 ** generated header file opcodes.h. Each is a 16-bit bitmask, one
230 ** bit corresponding to each opcode implemented by the virtual
231 ** machine in vdbe.c. The bit is true if the word "no-push" appears
232 ** in a comment on the same line as the "case OP_XXX:" in
233 ** sqlite3VdbeExec() in vdbe.c.
234 **
235 ** If the bit is true, then the corresponding opcode is guarenteed not
236 ** to grow the stack when it is executed. Otherwise, it may grow the
237 ** stack by at most one entry.
238 **
239 ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
240 ** one bit for opcodes 16 to 31, and so on.
241 **
242 ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
243 ** because the file is generated by an awk program. Awk manipulates
244 ** all numbers as floating-point and we don't want to risk a rounding
245 ** error if someone builds with an awk that uses (for example) 32-bit
246 ** IEEE floats.
247 */
248 static const u32 masks[5] = {
249 NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
250 NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
251 NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
252 NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
253 NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
254 };
255 assert( op<32*5 );
256 return (masks[op>>5] & (1<<(op&0x1F)));
257}
258
259#ifndef NDEBUG
260int sqlite3VdbeOpcodeNoPush(u8 op){
261 return opcodeNoPush(op);
262}
263#endif
264
265/*
266** Loop through the program looking for P2 values that are negative.
267** Each such value is a label. Resolve the label by setting the P2
268** value to its correct non-zero value.
269**
270** This routine is called once after all opcodes have been inserted.
271**
272** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
273** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
274** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
275**
276** The integer *pMaxStack is set to the maximum number of vdbe stack
277** entries that static analysis reveals this program might need.
278**
279** This routine also does the following optimization: It scans for
280** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
281** IdxInsert instructions where P2!=0. If no such instruction is
282** found, then every Statement instruction is changed to a Noop. In
283** this way, we avoid creating the statement journal file unnecessarily.
284*/
285static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
286 int i;
287 int nMaxArgs = 0;
288 int nMaxStack = p->nOp;
289 Op *pOp;
290 int *aLabel = p->aLabel;
291 int doesStatementRollback = 0;
292 int hasStatementBegin = 0;
293 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
294 u8 opcode = pOp->opcode;
295
296 if( opcode==OP_Function || opcode==OP_AggStep
297#ifndef SQLITE_OMIT_VIRTUALTABLE
298 || opcode==OP_VUpdate
299#endif
300 ){
301 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
302 }else if( opcode==OP_Halt ){
303 if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
304 doesStatementRollback = 1;
305 }
306 }else if( opcode==OP_Statement ){
307 hasStatementBegin = 1;
308 }else if( opcode==OP_VFilter ){
309 int n;
310 assert( p->nOp - i >= 3 );
311 assert( pOp[-2].opcode==OP_Integer );
312 n = pOp[-2].p1;
313 if( n>nMaxArgs ) nMaxArgs = n;
314 }
315 if( opcodeNoPush(opcode) ){
316 nMaxStack--;
317 }
318
319 if( pOp->p2>=0 ) continue;
320 assert( -1-pOp->p2<p->nLabel );
321 pOp->p2 = aLabel[-1-pOp->p2];
322 }
323 sqliteFree(p->aLabel);
324 p->aLabel = 0;
325
326 *pMaxFuncArgs = nMaxArgs;
327 *pMaxStack = nMaxStack;
328
329 /* If we never rollback a statement transaction, then statement
330 ** transactions are not needed. So change every OP_Statement
331 ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
332 ** which can be expensive on some platforms.
333 */
334 if( hasStatementBegin && !doesStatementRollback ){
335 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
336 if( pOp->opcode==OP_Statement ){
337 pOp->opcode = OP_Noop;
338 }
339 }
340 }
341}
342
343/*
344** Return the address of the next instruction to be inserted.
345*/
346int sqlite3VdbeCurrentAddr(Vdbe *p){
347 assert( p->magic==VDBE_MAGIC_INIT );
348 return p->nOp;
349}
350
351/*
352** Add a whole list of operations to the operation stack. Return the
353** address of the first operation added.
354*/
355int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
356 int addr;
357 assert( p->magic==VDBE_MAGIC_INIT );
358 resizeOpArray(p, p->nOp + nOp);
359 if( sqlite3MallocFailed() ){
360 return 0;
361 }
362 addr = p->nOp;
363 if( nOp>0 ){
364 int i;
365 VdbeOpList const *pIn = aOp;
366 for(i=0; i<nOp; i++, pIn++){
367 int p2 = pIn->p2;
368 VdbeOp *pOut = &p->aOp[i+addr];
369 pOut->opcode = pIn->opcode;
370 pOut->p1 = pIn->p1;
371 pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
372 pOut->p3 = pIn->p3;
373 pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
374#ifdef SQLITE_DEBUG
375 if( sqlite3_vdbe_addop_trace ){
376 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
377 }
378#endif
379 }
380 p->nOp += nOp;
381 }
382 return addr;
383}
384
385/*
386** Change the value of the P1 operand for a specific instruction.
387** This routine is useful when a large program is loaded from a
388** static array using sqlite3VdbeAddOpList but we want to make a
389** few minor changes to the program.
390*/
391void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
392 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
393 if( p && addr>=0 && p->nOp>addr && p->aOp ){
394 p->aOp[addr].p1 = val;
395 }
396}
397
398/*
399** Change the value of the P2 operand for a specific instruction.
400** This routine is useful for setting a jump destination.
401*/
402void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
403 assert( val>=0 );
404 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
405 if( p && addr>=0 && p->nOp>addr && p->aOp ){
406 p->aOp[addr].p2 = val;
407 }
408}
409
410/*
411** Change the P2 operand of instruction addr so that it points to
412** the address of the next instruction to be coded.
413*/
414void sqlite3VdbeJumpHere(Vdbe *p, int addr){
415 sqlite3VdbeChangeP2(p, addr, p->nOp);
416}
417
418
419/*
420** If the input FuncDef structure is ephemeral, then free it. If
421** the FuncDef is not ephermal, then do nothing.
422*/
423static void freeEphemeralFunction(FuncDef *pDef){
424 if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
425 sqliteFree(pDef);
426 }
427}
428
429/*
430** Delete a P3 value if necessary.
431*/
432static void freeP3(int p3type, void *p3){
433 if( p3 ){
434 switch( p3type ){
435 case P3_DYNAMIC:
436 case P3_KEYINFO:
437 case P3_KEYINFO_HANDOFF: {
438 sqliteFree(p3);
439 break;
440 }
441 case P3_MPRINTF: {
442 sqlite3_free(p3);
443 break;
444 }
445 case P3_VDBEFUNC: {
446 VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
447 freeEphemeralFunction(pVdbeFunc->pFunc);
448 sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
449 sqliteFree(pVdbeFunc);
450 break;
451 }
452 case P3_FUNCDEF: {
453 freeEphemeralFunction((FuncDef*)p3);
454 break;
455 }
456 case P3_MEM: {
457 sqlite3ValueFree((sqlite3_value*)p3);
458 break;
459 }
460 }
461 }
462}
463
464
465/*
466** Change N opcodes starting at addr to No-ops.
467*/
468void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
469 if( p && p->aOp ){
470 VdbeOp *pOp = &p->aOp[addr];
471 while( N-- ){
472 freeP3(pOp->p3type, pOp->p3);
473 memset(pOp, 0, sizeof(pOp[0]));
474 pOp->opcode = OP_Noop;
475 pOp++;
476 }
477 }
478}
479
480/*
481** Change the value of the P3 operand for a specific instruction.
482** This routine is useful when a large program is loaded from a
483** static array using sqlite3VdbeAddOpList but we want to make a
484** few minor changes to the program.
485**
486** If n>=0 then the P3 operand is dynamic, meaning that a copy of
487** the string is made into memory obtained from sqliteMalloc().
488** A value of n==0 means copy bytes of zP3 up to and including the
489** first null byte. If n>0 then copy n+1 bytes of zP3.
490**
491** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
492** A copy is made of the KeyInfo structure into memory obtained from
493** sqliteMalloc, to be freed when the Vdbe is finalized.
494** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
495** stored in memory that the caller has obtained from sqliteMalloc. The
496** caller should not free the allocation, it will be freed when the Vdbe is
497** finalized.
498**
499** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
500** to a string or structure that is guaranteed to exist for the lifetime of
501** the Vdbe. In these cases we can just copy the pointer.
502**
503** If addr<0 then change P3 on the most recently inserted instruction.
504*/
505void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
506 Op *pOp;
507 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
508 if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
509 if (n != P3_KEYINFO) {
510 freeP3(n, (void*)*(char**)&zP3);
511 }
512 return;
513 }
514 if( addr<0 || addr>=p->nOp ){
515 addr = p->nOp - 1;
516 if( addr<0 ) return;
517 }
518 pOp = &p->aOp[addr];
519 freeP3(pOp->p3type, pOp->p3);
520 pOp->p3 = 0;
521 if( zP3==0 ){
522 pOp->p3 = 0;
523 pOp->p3type = P3_NOTUSED;
524 }else if( n==P3_KEYINFO ){
525 KeyInfo *pKeyInfo;
526 int nField, nByte;
527
528 nField = ((KeyInfo*)zP3)->nField;
529 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
530 pKeyInfo = sqliteMallocRaw( nByte );
531 pOp->p3 = (char*)pKeyInfo;
532 if( pKeyInfo ){
533 unsigned char *aSortOrder;
534 memcpy(pKeyInfo, zP3, nByte);
535 aSortOrder = pKeyInfo->aSortOrder;
536 if( aSortOrder ){
537 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
538 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
539 }
540 pOp->p3type = P3_KEYINFO;
541 }else{
542 pOp->p3type = P3_NOTUSED;
543 }
544 }else if( n==P3_KEYINFO_HANDOFF ){
545 pOp->p3 = (char*)zP3;
546 pOp->p3type = P3_KEYINFO;
547 }else if( n<0 ){
548 pOp->p3 = (char*)zP3;
549 pOp->p3type = n;
550 }else{
551 if( n==0 ) n = strlen(zP3);
552 pOp->p3 = sqliteStrNDup(zP3, n);
553 pOp->p3type = P3_DYNAMIC;
554 }
555}
556
557#ifndef NDEBUG
558/*
559** Replace the P3 field of the most recently coded instruction with
560** comment text.
561*/
562void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
563 va_list ap;
564 assert( p->nOp>0 || p->aOp==0 );
565 assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || sqlite3MallocFailed() );
566 va_start(ap, zFormat);
567 sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
568 va_end(ap);
569}
570#endif
571
572/*
573** Return the opcode for a given address.
574*/
575VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
576 assert( p->magic==VDBE_MAGIC_INIT );
577 assert( (addr>=0 && addr<p->nOp) || sqlite3MallocFailed() );
578 return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
579}
580
581#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
582 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
583/*
584** Compute a string that describes the P3 parameter for an opcode.
585** Use zTemp for any required temporary buffer space.
586*/
587static char *displayP3(Op *pOp, char *zTemp, int nTemp){
588 char *zP3;
589 assert( nTemp>=20 );
590 switch( pOp->p3type ){
591 case P3_KEYINFO: {
592 int i, j;
593 KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
594 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
595 i = strlen(zTemp);
596 for(j=0; j<pKeyInfo->nField; j++){
597 CollSeq *pColl = pKeyInfo->aColl[j];
598 if( pColl ){
599 int n = strlen(pColl->zName);
600 if( i+n>nTemp-6 ){
601 memcpy(&zTemp[i],",...",4);
602 break;
603 }
604 zTemp[i++] = ',';
605 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
606 zTemp[i++] = '-';
607 }
608 memcpy(&zTemp[i], pColl->zName,n+1);
609 i += n;
610 }else if( i+4<nTemp-6 ){
611 memcpy(&zTemp[i],",nil",4);
612 i += 4;
613 }
614 }
615 zTemp[i++] = ')';
616 zTemp[i] = 0;
617 assert( i<nTemp );
618 zP3 = zTemp;
619 break;
620 }
621 case P3_COLLSEQ: {
622 CollSeq *pColl = (CollSeq*)pOp->p3;
623 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
624 zP3 = zTemp;
625 break;
626 }
627 case P3_FUNCDEF: {
628 FuncDef *pDef = (FuncDef*)pOp->p3;
629 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
630 zP3 = zTemp;
631 break;
632 }
633#ifndef SQLITE_OMIT_VIRTUALTABLE
634 case P3_VTAB: {
635 sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
636 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
637 zP3 = zTemp;
638 break;
639 }
640#endif
641 default: {
642 zP3 = pOp->p3;
643 if( zP3==0 || pOp->opcode==OP_Noop ){
644 zP3 = "";
645 }
646 }
647 }
648 assert( zP3!=0 );
649 return zP3;
650}
651#endif
652
653
654#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
655/*
656** Print a single opcode. This routine is used for debugging only.
657*/
658void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
659 char *zP3;
660 char zPtr[50];
661 static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
662 if( pOut==0 ) pOut = stdout;
663 zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
664 fprintf(pOut, zFormat1,
665 pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
666 fflush(pOut);
667}
668#endif
669
670/*
671** Release an array of N Mem elements
672*/
673static void releaseMemArray(Mem *p, int N){
674 if( p ){
675 while( N-->0 ){
676 sqlite3VdbeMemRelease(p++);
677 }
678 }
679}
680
681#ifndef SQLITE_OMIT_EXPLAIN
682/*
683** Give a listing of the program in the virtual machine.
684**
685** The interface is the same as sqlite3VdbeExec(). But instead of
686** running the code, it invokes the callback once for each instruction.
687** This feature is used to implement "EXPLAIN".
688*/
689int sqlite3VdbeList(
690 Vdbe *p /* The VDBE */
691){
692 sqlite3 *db = p->db;
693 int i;
694 int rc = SQLITE_OK;
695
696 assert( p->explain );
697 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
698 assert( db->magic==SQLITE_MAGIC_BUSY );
699 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
700
701 /* Even though this opcode does not put dynamic strings onto the
702 ** the stack, they may become dynamic if the user calls
703 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
704 */
705 if( p->pTos==&p->aStack[4] ){
706 releaseMemArray(p->aStack, 5);
707 }
708 p->resOnStack = 0;
709
710 do{
711 i = p->pc++;
712 }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
713 if( i>=p->nOp ){
714 p->rc = SQLITE_OK;
715 rc = SQLITE_DONE;
716 }else if( db->u1.isInterrupted ){
717 p->rc = SQLITE_INTERRUPT;
718 rc = SQLITE_ERROR;
719 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
720 }else{
721 Op *pOp = &p->aOp[i];
722 Mem *pMem = p->aStack;
723 pMem->flags = MEM_Int;
724 pMem->type = SQLITE_INTEGER;
725 pMem->u.i = i; /* Program counter */
726 pMem++;
727
728 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
729 pMem->z = (char*)sqlite3OpcodeNames[pOp->opcode]; /* Opcode */
730 assert( pMem->z!=0 );
731 pMem->n = strlen(pMem->z);
732 pMem->type = SQLITE_TEXT;
733 pMem->enc = SQLITE_UTF8;
734 pMem++;
735
736 pMem->flags = MEM_Int;
737 pMem->u.i = pOp->p1; /* P1 */
738 pMem->type = SQLITE_INTEGER;
739 pMem++;
740
741 pMem->flags = MEM_Int;
742 pMem->u.i = pOp->p2; /* P2 */
743 pMem->type = SQLITE_INTEGER;
744 pMem++;
745
746 pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P3 */
747 pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
748 assert( pMem->z!=0 );
749 pMem->n = strlen(pMem->z);
750 pMem->type = SQLITE_TEXT;
751 pMem->enc = SQLITE_UTF8;
752
753 p->nResColumn = 5 - 2*(p->explain-1);
754 p->pTos = pMem;
755 p->rc = SQLITE_OK;
756 p->resOnStack = 1;
757 rc = SQLITE_ROW;
758 }
759 return rc;
760}
761#endif /* SQLITE_OMIT_EXPLAIN */
762
763#ifdef SQLITE_DEBUG
764/*
765** Print the SQL that was used to generate a VDBE program.
766*/
767void sqlite3VdbePrintSql(Vdbe *p){
768 int nOp = p->nOp;
769 VdbeOp *pOp;
770 if( nOp<1 ) return;
771 pOp = &p->aOp[nOp-1];
772 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
773 const char *z = pOp->p3;
774 while( isspace(*(u8*)z) ) z++;
775 printf("SQL: [%s]\n", z);
776 }
777}
778#endif
779
780#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
781/*
782** Print an IOTRACE message showing SQL content.
783*/
784void sqlite3VdbeIOTraceSql(Vdbe *p){
785 int nOp = p->nOp;
786 VdbeOp *pOp;
787 if( sqlite3_io_trace==0 ) return;
788 if( nOp<1 ) return;
789 pOp = &p->aOp[nOp-1];
790 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
791 char *z = sqlite3StrDup(pOp->p3);
792 int i, j;
793 for(i=0; isspace((unsigned char)z[i]); i++){}
794 for(j=0; z[i]; i++){
795 if( isspace((unsigned char)z[i]) ){
796 if( z[i-1]!=' ' ){
797 z[j++] = ' ';
798 }
799 }else{
800 z[j++] = z[i];
801 }
802 }
803 z[j] = 0;
804 sqlite3_io_trace("SQL %s\n", z);
805 sqliteFree(z);
806 }
807}
808#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
809
810
811/*
812** Prepare a virtual machine for execution. This involves things such
813** as allocating stack space and initializing the program counter.
814** After the VDBE has be prepped, it can be executed by one or more
815** calls to sqlite3VdbeExec().
816**
817** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
818** VDBE_MAGIC_RUN.
819*/
820void sqlite3VdbeMakeReady(
821 Vdbe *p, /* The VDBE */
822 int nVar, /* Number of '?' see in the SQL statement */
823 int nMem, /* Number of memory cells to allocate */
824 int nCursor, /* Number of cursors to allocate */
825 int isExplain /* True if the EXPLAIN keywords is present */
826){
827 int n;
828
829 assert( p!=0 );
830 assert( p->magic==VDBE_MAGIC_INIT );
831
832 /* There should be at least one opcode.
833 */
834 assert( p->nOp>0 );
835
836 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
837 * is because the call to resizeOpArray() below may shrink the
838 * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
839 * state.
840 */
841 p->magic = VDBE_MAGIC_RUN;
842
843 /* No instruction ever pushes more than a single element onto the
844 ** stack. And the stack never grows on successive executions of the
845 ** same loop. So the total number of instructions is an upper bound
846 ** on the maximum stack depth required. (Added later:) The
847 ** resolveP2Values() call computes a tighter upper bound on the
848 ** stack size.
849 **
850 ** Allocation all the stack space we will ever need.
851 */
852 if( p->aStack==0 ){
853 int nArg; /* Maximum number of args passed to a user function. */
854 int nStack; /* Maximum number of stack entries required */
855 resolveP2Values(p, &nArg, &nStack);
856 resizeOpArray(p, p->nOp);
857 assert( nVar>=0 );
858 assert( nStack<p->nOp );
859 if( isExplain ){
860 nStack = 10;
861 }
862 p->aStack = sqliteMalloc(
863 nStack*sizeof(p->aStack[0]) /* aStack */
864 + nArg*sizeof(Mem*) /* apArg */
865 + nVar*sizeof(Mem) /* aVar */
866 + nVar*sizeof(char*) /* azVar */
867 + nMem*sizeof(Mem) /* aMem */
868 + nCursor*sizeof(Cursor*) /* apCsr */
869 );
870 if( !sqlite3MallocFailed() ){
871 p->aMem = &p->aStack[nStack];
872 p->nMem = nMem;
873 p->aVar = &p->aMem[nMem];
874 p->nVar = nVar;
875 p->okVar = 0;
876 p->apArg = (Mem**)&p->aVar[nVar];
877 p->azVar = (char**)&p->apArg[nArg];
878 p->apCsr = (Cursor**)&p->azVar[nVar];
879 p->nCursor = nCursor;
880 for(n=0; n<nVar; n++){
881 p->aVar[n].flags = MEM_Null;
882 }
883 }
884 }
885 for(n=0; n<p->nMem; n++){
886 p->aMem[n].flags = MEM_Null;
887 }
888
889 p->pTos = &p->aStack[-1];
890 p->pc = -1;
891 p->rc = SQLITE_OK;
892 p->uniqueCnt = 0;
893 p->returnDepth = 0;
894 p->errorAction = OE_Abort;
895 p->popStack = 0;
896 p->explain |= isExplain;
897 p->magic = VDBE_MAGIC_RUN;
898 p->nChange = 0;
899 p->cacheCtr = 1;
900 p->minWriteFileFormat = 255;
901#ifdef VDBE_PROFILE
902 {
903 int i;
904 for(i=0; i<p->nOp; i++){
905 p->aOp[i].cnt = 0;
906 p->aOp[i].cycles = 0;
907 }
908 }
909#endif
910}
911
912/*
913** Close a cursor and release all the resources that cursor happens
914** to hold.
915*/
916void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
917 if( pCx==0 ){
918 return;
919 }
920 if( pCx->pCursor ){
921 sqlite3BtreeCloseCursor(pCx->pCursor);
922 }
923 if( pCx->pBt ){
924 sqlite3BtreeClose(pCx->pBt);
925 }
926#ifndef SQLITE_OMIT_VIRTUALTABLE
927 if( pCx->pVtabCursor ){
928 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
929 const sqlite3_module *pModule = pCx->pModule;
930 p->inVtabMethod = 1;
931 sqlite3SafetyOff(p->db);
932 pModule->xClose(pVtabCursor);
933 sqlite3SafetyOn(p->db);
934 p->inVtabMethod = 0;
935 }
936#endif
937 sqliteFree(pCx->pData);
938 sqliteFree(pCx->aType);
939 sqliteFree(pCx);
940}
941
942/*
943** Close all cursors
944*/
945static void closeAllCursors(Vdbe *p){
946 int i;
947 if( p->apCsr==0 ) return;
948 for(i=0; i<p->nCursor; i++){
949 if( !p->inVtabMethod || (p->apCsr[i] && !p->apCsr[i]->pVtabCursor) ){
950 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
951 p->apCsr[i] = 0;
952 }
953 }
954}
955
956/*
957** Clean up the VM after execution.
958**
959** This routine will automatically close any cursors, lists, and/or
960** sorters that were left open. It also deletes the values of
961** variables in the aVar[] array.
962*/
963static void Cleanup(Vdbe *p){
964 int i;
965 if( p->aStack ){
966 releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
967 p->pTos = &p->aStack[-1];
968 }
969 closeAllCursors(p);
970 releaseMemArray(p->aMem, p->nMem);
971 sqlite3VdbeFifoClear(&p->sFifo);
972 if( p->contextStack ){
973 for(i=0; i<p->contextStackTop; i++){
974 sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
975 }
976 sqliteFree(p->contextStack);
977 }
978 p->contextStack = 0;
979 p->contextStackDepth = 0;
980 p->contextStackTop = 0;
981 sqliteFree(p->zErrMsg);
982 p->zErrMsg = 0;
983}
984
985/*
986** Set the number of result columns that will be returned by this SQL
987** statement. This is now set at compile time, rather than during
988** execution of the vdbe program so that sqlite3_column_count() can
989** be called on an SQL statement before sqlite3_step().
990*/
991void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
992 Mem *pColName;
993 int n;
994 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
995 sqliteFree(p->aColName);
996 n = nResColumn*COLNAME_N;
997 p->nResColumn = nResColumn;
998 p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
999 if( p->aColName==0 ) return;
1000 while( n-- > 0 ){
1001 (pColName++)->flags = MEM_Null;
1002 }
1003}
1004
1005/*
1006** Set the name of the idx'th column to be returned by the SQL statement.
1007** zName must be a pointer to a nul terminated string.
1008**
1009** This call must be made after a call to sqlite3VdbeSetNumCols().
1010**
1011** If N==P3_STATIC it means that zName is a pointer to a constant static
1012** string and we can just copy the pointer. If it is P3_DYNAMIC, then
1013** the string is freed using sqliteFree() when the vdbe is finished with
1014** it. Otherwise, N bytes of zName are copied.
1015*/
1016int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
1017 int rc;
1018 Mem *pColName;
1019 assert( idx<p->nResColumn );
1020 assert( var<COLNAME_N );
1021 if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
1022 assert( p->aColName!=0 );
1023 pColName = &(p->aColName[idx+var*p->nResColumn]);
1024 if( N==P3_DYNAMIC || N==P3_STATIC ){
1025 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
1026 }else{
1027 rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
1028 }
1029 if( rc==SQLITE_OK && N==P3_DYNAMIC ){
1030 pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
1031 pColName->xDel = 0;
1032 }
1033 return rc;
1034}
1035
1036/*
1037** A read or write transaction may or may not be active on database handle
1038** db. If a transaction is active, commit it. If there is a
1039** write-transaction spanning more than one database file, this routine
1040** takes care of the master journal trickery.
1041*/
1042static int vdbeCommit(sqlite3 *db){
1043 int i;
1044 int nTrans = 0; /* Number of databases with an active write-transaction */
1045 int rc = SQLITE_OK;
1046 int needXcommit = 0;
1047
1048 /* Before doing anything else, call the xSync() callback for any
1049 ** virtual module tables written in this transaction. This has to
1050 ** be done before determining whether a master journal file is
1051 ** required, as an xSync() callback may add an attached database
1052 ** to the transaction.
1053 */
1054 rc = sqlite3VtabSync(db, rc);
1055 if( rc!=SQLITE_OK ){
1056 return rc;
1057 }
1058
1059 /* This loop determines (a) if the commit hook should be invoked and
1060 ** (b) how many database files have open write transactions, not
1061 ** including the temp database. (b) is important because if more than
1062 ** one database file has an open write transaction, a master journal
1063 ** file is required for an atomic commit.
1064 */
1065 for(i=0; i<db->nDb; i++){
1066 Btree *pBt = db->aDb[i].pBt;
1067 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1068 needXcommit = 1;
1069 if( i!=1 ) nTrans++;
1070 }
1071 }
1072
1073 /* If there are any write-transactions at all, invoke the commit hook */
1074 if( needXcommit && db->xCommitCallback ){
1075 sqlite3SafetyOff(db);
1076 rc = db->xCommitCallback(db->pCommitArg);
1077 sqlite3SafetyOn(db);
1078 if( rc ){
1079 return SQLITE_CONSTRAINT;
1080 }
1081 }
1082
1083 /* The simple case - no more than one database file (not counting the
1084 ** TEMP database) has a transaction active. There is no need for the
1085 ** master-journal.
1086 **
1087 ** If the return value of sqlite3BtreeGetFilename() is a zero length
1088 ** string, it means the main database is :memory:. In that case we do
1089 ** not support atomic multi-file commits, so use the simple case then
1090 ** too.
1091 */
1092 if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
1093 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1094 Btree *pBt = db->aDb[i].pBt;
1095 if( pBt ){
1096 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
1097 }
1098 }
1099
1100 /* Do the commit only if all databases successfully complete phase 1.
1101 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1102 ** IO error while deleting or truncating a journal file. It is unlikely,
1103 ** but could happen. In this case abandon processing and return the error.
1104 */
1105 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1106 Btree *pBt = db->aDb[i].pBt;
1107 if( pBt ){
1108 rc = sqlite3BtreeCommitPhaseTwo(pBt);
1109 }
1110 }
1111 if( rc==SQLITE_OK ){
1112 sqlite3VtabCommit(db);
1113 }
1114 }
1115
1116 /* The complex case - There is a multi-file write-transaction active.
1117 ** This requires a master journal file to ensure the transaction is
1118 ** committed atomicly.
1119 */
1120#ifndef SQLITE_OMIT_DISKIO
1121 else{
1122 int needSync = 0;
1123 char *zMaster = 0; /* File-name for the master journal */
1124 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
1125 OsFile *master = 0;
1126
1127 /* Select a master journal file name */
1128 do {
1129 u32 random;
1130 sqliteFree(zMaster);
1131 sqlite3Randomness(sizeof(random), &random);
1132 zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
1133 if( !zMaster ){
1134 return SQLITE_NOMEM;
1135 }
1136 }while( sqlite3OsFileExists(zMaster) );
1137
1138 /* Open the master journal. */
1139 rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
1140 if( rc!=SQLITE_OK ){
1141 sqliteFree(zMaster);
1142 return rc;
1143 }
1144
1145 /* Write the name of each database file in the transaction into the new
1146 ** master journal file. If an error occurs at this point close
1147 ** and delete the master journal file. All the individual journal files
1148 ** still have 'null' as the master journal pointer, so they will roll
1149 ** back independently if a failure occurs.
1150 */
1151 for(i=0; i<db->nDb; i++){
1152 Btree *pBt = db->aDb[i].pBt;
1153 if( i==1 ) continue; /* Ignore the TEMP database */
1154 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1155 char const *zFile = sqlite3BtreeGetJournalname(pBt);
1156 if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
1157 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1158 needSync = 1;
1159 }
1160 rc = sqlite3OsWrite(master, zFile, strlen(zFile)+1);
1161 if( rc!=SQLITE_OK ){
1162 sqlite3OsClose(&master);
1163 sqlite3OsDelete(zMaster);
1164 sqliteFree(zMaster);
1165 return rc;
1166 }
1167 }
1168 }
1169
1170
1171 /* Sync the master journal file. Before doing this, open the directory
1172 ** the master journal file is store in so that it gets synced too.
1173 */
1174 zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
1175 rc = sqlite3OsOpenDirectory(master, zMainFile);
1176 if( rc!=SQLITE_OK ||
1177 (needSync && (rc=sqlite3OsSync(master,0))!=SQLITE_OK) ){
1178 sqlite3OsClose(&master);
1179 sqlite3OsDelete(zMaster);
1180 sqliteFree(zMaster);
1181 return rc;
1182 }
1183
1184 /* Sync all the db files involved in the transaction. The same call
1185 ** sets the master journal pointer in each individual journal. If
1186 ** an error occurs here, do not delete the master journal file.
1187 **
1188 ** If the error occurs during the first call to
1189 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
1190 ** master journal file will be orphaned. But we cannot delete it,
1191 ** in case the master journal file name was written into the journal
1192 ** file before the failure occured.
1193 */
1194 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1195 Btree *pBt = db->aDb[i].pBt;
1196 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
1197 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
1198 }
1199 }
1200 sqlite3OsClose(&master);
1201 if( rc!=SQLITE_OK ){
1202 sqliteFree(zMaster);
1203 return rc;
1204 }
1205
1206 /* Delete the master journal file. This commits the transaction. After
1207 ** doing this the directory is synced again before any individual
1208 ** transaction files are deleted.
1209 */
1210 rc = sqlite3OsDelete(zMaster);
1211 sqliteFree(zMaster);
1212 zMaster = 0;
1213 if( rc ){
1214 return rc;
1215 }
1216 rc = sqlite3OsSyncDirectory(zMainFile);
1217 if( rc!=SQLITE_OK ){
1218 /* This is not good. The master journal file has been deleted, but
1219 ** the directory sync failed. There is no completely safe course of
1220 ** action from here. The individual journals contain the name of the
1221 ** master journal file, but there is no way of knowing if that
1222 ** master journal exists now or if it will exist after the operating
1223 ** system crash that may follow the fsync() failure.
1224 */
1225 return rc;
1226 }
1227
1228 /* All files and directories have already been synced, so the following
1229 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
1230 ** deleting or truncating journals. If something goes wrong while
1231 ** this is happening we don't really care. The integrity of the
1232 ** transaction is already guaranteed, but some stray 'cold' journals
1233 ** may be lying around. Returning an error code won't help matters.
1234 */
1235 disable_simulated_io_errors();
1236 for(i=0; i<db->nDb; i++){
1237 Btree *pBt = db->aDb[i].pBt;
1238 if( pBt ){
1239 sqlite3BtreeCommitPhaseTwo(pBt);
1240 }
1241 }
1242 enable_simulated_io_errors();
1243
1244 sqlite3VtabCommit(db);
1245 }
1246#endif
1247
1248 return rc;
1249}
1250
1251/*
1252** This routine checks that the sqlite3.activeVdbeCnt count variable
1253** matches the number of vdbe's in the list sqlite3.pVdbe that are
1254** currently active. An assertion fails if the two counts do not match.
1255** This is an internal self-check only - it is not an essential processing
1256** step.
1257**
1258** This is a no-op if NDEBUG is defined.
1259*/
1260#ifndef NDEBUG
1261static void checkActiveVdbeCnt(sqlite3 *db){
1262 Vdbe *p;
1263 int cnt = 0;
1264 p = db->pVdbe;
1265 while( p ){
1266 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1267 cnt++;
1268 }
1269 p = p->pNext;
1270 }
1271 assert( cnt==db->activeVdbeCnt );
1272}
1273#else
1274#define checkActiveVdbeCnt(x)
1275#endif
1276
1277/*
1278** Find every active VM other than pVdbe and change its status to
1279** aborted. This happens when one VM causes a rollback due to an
1280** ON CONFLICT ROLLBACK clause (for example). The other VMs must be
1281** aborted so that they do not have data rolled out from underneath
1282** them leading to a segfault.
1283*/
1284void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
1285 Vdbe *pOther;
1286 for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
1287 if( pOther==pExcept ) continue;
1288 if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
1289 checkActiveVdbeCnt(db);
1290 closeAllCursors(pOther);
1291 checkActiveVdbeCnt(db);
1292 pOther->aborted = 1;
1293 }
1294}
1295
1296/*
1297** This routine is called the when a VDBE tries to halt. If the VDBE
1298** has made changes and is in autocommit mode, then commit those
1299** changes. If a rollback is needed, then do the rollback.
1300**
1301** This routine is the only way to move the state of a VM from
1302** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
1303**
1304** Return an error code. If the commit could not complete because of
1305** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
1306** means the close did not happen and needs to be repeated.
1307*/
1308int sqlite3VdbeHalt(Vdbe *p){
1309 sqlite3 *db = p->db;
1310 int i;
1311 int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
1312 int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
1313
1314 /* This function contains the logic that determines if a statement or
1315 ** transaction will be committed or rolled back as a result of the
1316 ** execution of this virtual machine.
1317 **
1318 ** Special errors:
1319 **
1320 ** If an SQLITE_NOMEM error has occured in a statement that writes to
1321 ** the database, then either a statement or transaction must be rolled
1322 ** back to ensure the tree-structures are in a consistent state. A
1323 ** statement transaction is rolled back if one is open, otherwise the
1324 ** entire transaction must be rolled back.
1325 **
1326 ** If an SQLITE_IOERR error has occured in a statement that writes to
1327 ** the database, then the entire transaction must be rolled back. The
1328 ** I/O error may have caused garbage to be written to the journal
1329 ** file. Were the transaction to continue and eventually be rolled
1330 ** back that garbage might end up in the database file.
1331 **
1332 ** In both of the above cases, the Vdbe.errorAction variable is
1333 ** ignored. If the sqlite3.autoCommit flag is false and a transaction
1334 ** is rolled back, it will be set to true.
1335 **
1336 ** Other errors:
1337 **
1338 ** No error:
1339 **
1340 */
1341
1342 if( sqlite3MallocFailed() ){
1343 p->rc = SQLITE_NOMEM;
1344 }
1345 if( p->magic!=VDBE_MAGIC_RUN ){
1346 /* Already halted. Nothing to do. */
1347 assert( p->magic==VDBE_MAGIC_HALT );
1348#ifndef SQLITE_OMIT_VIRTUALTABLE
1349 closeAllCursors(p);
1350#endif
1351 return SQLITE_OK;
1352 }
1353 closeAllCursors(p);
1354 checkActiveVdbeCnt(db);
1355
1356 /* No commit or rollback needed if the program never started */
1357 if( p->pc>=0 ){
1358 int mrc; /* Primary error code from p->rc */
1359 /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
1360 mrc = p->rc & 0xff;
1361 isSpecialError = (
1362 (mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR || mrc==SQLITE_INTERRUPT)?1:0);
1363 if( isSpecialError ){
1364 /* This loop does static analysis of the query to see which of the
1365 ** following three categories it falls into:
1366 **
1367 ** Read-only
1368 ** Query with statement journal
1369 ** Query without statement journal
1370 **
1371 ** We could do something more elegant than this static analysis (i.e.
1372 ** store the type of query as part of the compliation phase), but
1373 ** handling malloc() or IO failure is a fairly obscure edge case so
1374 ** this is probably easier. Todo: Might be an opportunity to reduce
1375 ** code size a very small amount though...
1376 */
1377 int isReadOnly = 1;
1378 int isStatement = 0;
1379 assert(p->aOp || p->nOp==0);
1380 for(i=0; i<p->nOp; i++){
1381 switch( p->aOp[i].opcode ){
1382 case OP_Transaction:
1383 /* This is a bit strange. If we hit a malloc() or IO error and
1384 ** the statement did not open a statement transaction, we will
1385 ** rollback any active transaction and abort all other active
1386 ** statements. Or, if this is an SQLITE_INTERRUPT error, we
1387 ** will only rollback if the interrupted statement was a write.
1388 **
1389 ** It could be argued that read-only statements should never
1390 ** rollback anything. But careful analysis is required before
1391 ** making this change
1392 */
1393 if( p->aOp[i].p2 || mrc!=SQLITE_INTERRUPT ){
1394 isReadOnly = 0;
1395 }
1396 break;
1397 case OP_Statement:
1398 isStatement = 1;
1399 break;
1400 }
1401 }
1402
1403 /* If the query was read-only, we need do no rollback at all. Otherwise,
1404 ** proceed with the special handling.
1405 */
1406 if( !isReadOnly ){
1407 if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
1408 xFunc = sqlite3BtreeRollbackStmt;
1409 p->rc = SQLITE_BUSY;
1410 } else if( p->rc==SQLITE_NOMEM && isStatement ){
1411 xFunc = sqlite3BtreeRollbackStmt;
1412 }else{
1413 /* We are forced to roll back the active transaction. Before doing
1414 ** so, abort any other statements this handle currently has active.
1415 */
1416 sqlite3AbortOtherActiveVdbes(db, p);
1417 sqlite3RollbackAll(db);
1418 db->autoCommit = 1;
1419 }
1420 }
1421 }
1422
1423 /* If the auto-commit flag is set and this is the only active vdbe, then
1424 ** we do either a commit or rollback of the current transaction.
1425 **
1426 ** Note: This block also runs if one of the special errors handled
1427 ** above has occured.
1428 */
1429 if( db->autoCommit && db->activeVdbeCnt==1 ){
1430 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
1431/* The auto-commit flag is true, and the vdbe program was
1432 ** successful or hit an 'OR FAIL' constraint. This means a commit
1433 ** is required.
1434 */
1435 int rc = vdbeCommit(db);
1436 if( rc==SQLITE_BUSY ){
1437 return SQLITE_BUSY;
1438 }else if( rc!=SQLITE_OK ){
1439 p->rc = rc;
1440 sqlite3RollbackAll(db);
1441 }else{
1442 sqlite3CommitInternalChanges(db);
1443 }
1444 }else{
1445 sqlite3RollbackAll(db);
1446 }
1447 }else if( !xFunc ){
1448 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1449 xFunc = sqlite3BtreeCommitStmt;
1450 }else if( p->errorAction==OE_Abort ){
1451 xFunc = sqlite3BtreeRollbackStmt;
1452 }else{
1453 sqlite3AbortOtherActiveVdbes(db, p);
1454 sqlite3RollbackAll(db);
1455 db->autoCommit = 1;
1456 }
1457 }
1458
1459 /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
1460 ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
1461 ** and the return code is still SQLITE_OK, set the return code to the new
1462 ** error value.
1463 */
1464 assert(!xFunc ||
1465 xFunc==sqlite3BtreeCommitStmt ||
1466 xFunc==sqlite3BtreeRollbackStmt
1467 );
1468 for(i=0; xFunc && i<db->nDb; i++){
1469 int rc;
1470 Btree *pBt = db->aDb[i].pBt;
1471 if( pBt ){
1472 rc = xFunc(pBt);
1473 if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
1474 p->rc = rc;
1475 sqlite3SetString(&p->zErrMsg, 0);
1476 }
1477 }
1478 }
1479
1480 /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
1481 ** set the change counter.
1482 */
1483 if( p->changeCntOn && p->pc>=0 ){
1484 if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1485 sqlite3VdbeSetChanges(db, p->nChange);
1486 }else{
1487 sqlite3VdbeSetChanges(db, 0);
1488 }
1489 p->nChange = 0;
1490 }
1491
1492 /* Rollback or commit any schema changes that occurred. */
1493 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
1494 sqlite3ResetInternalSchema(db, 0);
1495 db->flags = (db->flags | SQLITE_InternChanges);
1496 }
1497 }
1498
1499 /* We have successfully halted and closed the VM. Record this fact. */
1500 if( p->pc>=0 ){
1501 db->activeVdbeCnt--;
1502 }
1503 p->magic = VDBE_MAGIC_HALT;
1504 checkActiveVdbeCnt(db);
1505
1506 return SQLITE_OK;
1507}
1508
1509/*
1510** Each VDBE holds the result of the most recent sqlite3_step() call
1511** in p->rc. This routine sets that result back to SQLITE_OK.
1512*/
1513void sqlite3VdbeResetStepResult(Vdbe *p){
1514 p->rc = SQLITE_OK;
1515}
1516
1517/*
1518** Clean up a VDBE after execution but do not delete the VDBE just yet.
1519** Write any error messages into *pzErrMsg. Return the result code.
1520**
1521** After this routine is run, the VDBE should be ready to be executed
1522** again.
1523**
1524** To look at it another way, this routine resets the state of the
1525** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1526** VDBE_MAGIC_INIT.
1527*/
1528int sqlite3VdbeReset(Vdbe *p){
1529 sqlite3 *db;
1530 db = p->db;
1531
1532 /* If the VM did not run to completion or if it encountered an
1533 ** error, then it might not have been halted properly. So halt
1534 ** it now.
1535 */
1536 sqlite3SafetyOn(db);
1537 sqlite3VdbeHalt(p);
1538 sqlite3SafetyOff(db);
1539
1540 /* If the VDBE has be run even partially, then transfer the error code
1541 ** and error message from the VDBE into the main database structure. But
1542 ** if the VDBE has just been set to run but has not actually executed any
1543 ** instructions yet, leave the main database error information unchanged.
1544 */
1545 if( p->pc>=0 ){
1546 if( p->zErrMsg ){
1547 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
1548 db->errCode = p->rc;
1549 p->zErrMsg = 0;
1550 }else if( p->rc ){
1551 sqlite3Error(db, p->rc, 0);
1552 }else{
1553 sqlite3Error(db, SQLITE_OK, 0);
1554 }
1555 }else if( p->rc && p->expired ){
1556 /* The expired flag was set on the VDBE before the first call
1557 ** to sqlite3_step(). For consistency (since sqlite3_step() was
1558 ** called), set the database error in this case as well.
1559 */
1560 sqlite3Error(db, p->rc, 0);
1561 }
1562
1563 /* Reclaim all memory used by the VDBE
1564 */
1565 Cleanup(p);
1566
1567 /* Save profiling information from this VDBE run.
1568 */
1569 assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
1570#ifdef VDBE_PROFILE
1571 {
1572 FILE *out = fopen("vdbe_profile.out", "a");
1573 if( out ){
1574 int i;
1575 fprintf(out, "---- ");
1576 for(i=0; i<p->nOp; i++){
1577 fprintf(out, "%02x", p->aOp[i].opcode);
1578 }
1579 fprintf(out, "\n");
1580 for(i=0; i<p->nOp; i++){
1581 fprintf(out, "%6d %10lld %8lld ",
1582 p->aOp[i].cnt,
1583 p->aOp[i].cycles,
1584 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1585 );
1586 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1587 }
1588 fclose(out);
1589 }
1590 }
1591#endif
1592 p->magic = VDBE_MAGIC_INIT;
1593 p->aborted = 0;
1594 if( p->rc==SQLITE_SCHEMA ){
1595 sqlite3ResetInternalSchema(db, 0);
1596 }
1597 return p->rc & db->errMask;
1598}
1599
1600/*
1601** Clean up and delete a VDBE after execution. Return an integer which is
1602** the result code. Write any error message text into *pzErrMsg.
1603*/
1604int sqlite3VdbeFinalize(Vdbe *p){
1605 int rc = SQLITE_OK;
1606 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1607 rc = sqlite3VdbeReset(p);
1608 assert( (rc & p->db->errMask)==rc );
1609 }else if( p->magic!=VDBE_MAGIC_INIT ){
1610 return SQLITE_MISUSE;
1611 }
1612 sqlite3VdbeDelete(p);
1613 return rc;
1614}
1615
1616/*
1617** Call the destructor for each auxdata entry in pVdbeFunc for which
1618** the corresponding bit in mask is clear. Auxdata entries beyond 31
1619** are always destroyed. To destroy all auxdata entries, call this
1620** routine with mask==0.
1621*/
1622void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1623 int i;
1624 for(i=0; i<pVdbeFunc->nAux; i++){
1625 struct AuxData *pAux = &pVdbeFunc->apAux[i];
1626 if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1627 if( pAux->xDelete ){
1628 pAux->xDelete(pAux->pAux);
1629 }
1630 pAux->pAux = 0;
1631 }
1632 }
1633}
1634
1635/*
1636** Delete an entire VDBE.
1637*/
1638void sqlite3VdbeDelete(Vdbe *p){
1639 int i;
1640 if( p==0 ) return;
1641 Cleanup(p);
1642 if( p->pPrev ){
1643 p->pPrev->pNext = p->pNext;
1644 }else{
1645 assert( p->db->pVdbe==p );
1646 p->db->pVdbe = p->pNext;
1647 }
1648 if( p->pNext ){
1649 p->pNext->pPrev = p->pPrev;
1650 }
1651 if( p->aOp ){
1652 for(i=0; i<p->nOp; i++){
1653 Op *pOp = &p->aOp[i];
1654 freeP3(pOp->p3type, pOp->p3);
1655 }
1656 sqliteFree(p->aOp);
1657 }
1658 releaseMemArray(p->aVar, p->nVar);
1659 sqliteFree(p->aLabel);
1660 sqliteFree(p->aStack);
1661 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1662 sqliteFree(p->aColName);
1663 sqliteFree(p->zSql);
1664 p->magic = VDBE_MAGIC_DEAD;
1665 sqliteFree(p);
1666}
1667
1668/*
1669** If a MoveTo operation is pending on the given cursor, then do that
1670** MoveTo now. Return an error code. If no MoveTo is pending, this
1671** routine does nothing and returns SQLITE_OK.
1672*/
1673int sqlite3VdbeCursorMoveto(Cursor *p){
1674 if( p->deferredMoveto ){
1675 int res, rc;
1676#ifdef SQLITE_TEST
1677 extern int sqlite3_search_count;
1678#endif
1679 assert( p->isTable );
1680 rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
1681 if( rc ) return rc;
1682 *p->pIncrKey = 0;
1683 p->lastRowid = keyToInt(p->movetoTarget);
1684 p->rowidIsValid = res==0;
1685 if( res<0 ){
1686 rc = sqlite3BtreeNext(p->pCursor, &res);
1687 if( rc ) return rc;
1688 }
1689#ifdef SQLITE_TEST
1690 sqlite3_search_count++;
1691#endif
1692 p->deferredMoveto = 0;
1693 p->cacheStatus = CACHE_STALE;
1694 }
1695 return SQLITE_OK;
1696}
1697
1698/*
1699** The following functions:
1700**
1701** sqlite3VdbeSerialType()
1702** sqlite3VdbeSerialTypeLen()
1703** sqlite3VdbeSerialRead()
1704** sqlite3VdbeSerialLen()
1705** sqlite3VdbeSerialWrite()
1706**
1707** encapsulate the code that serializes values for storage in SQLite
1708** data and index records. Each serialized value consists of a
1709** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
1710** integer, stored as a varint.
1711**
1712** In an SQLite index record, the serial type is stored directly before
1713** the blob of data that it corresponds to. In a table record, all serial
1714** types are stored at the start of the record, and the blobs of data at
1715** the end. Hence these functions allow the caller to handle the
1716** serial-type and data blob seperately.
1717**
1718** The following table describes the various storage classes for data:
1719**
1720** serial type bytes of data type
1721** -------------- --------------- ---------------
1722** 0 0 NULL
1723** 1 1 signed integer
1724** 2 2 signed integer
1725** 3 3 signed integer
1726** 4 4 signed integer
1727** 5 6 signed integer
1728** 6 8 signed integer
1729** 7 8 IEEE float
1730** 8 0 Integer constant 0
1731** 9 0 Integer constant 1
1732** 10,11 reserved for expansion
1733** N>=12 and even (N-12)/2 BLOB
1734** N>=13 and odd (N-13)/2 text
1735**
1736** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
1737** of SQLite will not understand those serial types.
1738*/
1739
1740/*
1741** Return the serial-type for the value stored in pMem.
1742*/
1743u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
1744 int flags = pMem->flags;
1745 int n;
1746
1747 if( flags&MEM_Null ){
1748 return 0;
1749 }
1750 if( flags&MEM_Int ){
1751 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
1752# define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
1753 i64 i = pMem->u.i;
1754 u64 u;
1755 if( file_format>=4 && (i&1)==i ){
1756 return 8+i;
1757 }
1758 u = i<0 ? -i : i;
1759 if( u<=127 ) return 1;
1760 if( u<=32767 ) return 2;
1761 if( u<=8388607 ) return 3;
1762 if( u<=2147483647 ) return 4;
1763 if( u<=MAX_6BYTE ) return 5;
1764 return 6;
1765 }
1766 if( flags&MEM_Real ){
1767 return 7;
1768 }
1769 assert( flags&(MEM_Str|MEM_Blob) );
1770 n = pMem->n;
1771 if( flags & MEM_Zero ){
1772 n += pMem->u.i;
1773 }
1774 assert( n>=0 );
1775 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
1776}
1777
1778/*
1779** Return the length of the data corresponding to the supplied serial-type.
1780*/
1781int sqlite3VdbeSerialTypeLen(u32 serial_type){
1782 if( serial_type>=12 ){
1783 return (serial_type-12)/2;
1784 }else{
1785 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
1786 return aSize[serial_type];
1787 }
1788}
1789
1790/*
1791** If we are on an architecture with mixed-endian floating
1792** points (ex: ARM7) then swap the lower 4 bytes with the
1793** upper 4 bytes. Return the result.
1794**
1795** For most architectures, this is a no-op.
1796**
1797** (later): It is reported to me that the mixed-endian problem
1798** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
1799** that early versions of GCC stored the two words of a 64-bit
1800** float in the wrong order. And that error has been propagated
1801** ever since. The blame is not necessarily with GCC, though.
1802** GCC might have just copying the problem from a prior compiler.
1803** I am also told that newer versions of GCC that follow a different
1804** ABI get the byte order right.
1805**
1806** Developers using SQLite on an ARM7 should compile and run their
1807** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
1808** enabled, some asserts below will ensure that the byte order of
1809** floating point values is correct.
1810*/
1811#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
1812static double floatSwap(double in){
1813 union {
1814 double r;
1815 u32 i[2];
1816 } u;
1817 u32 t;
1818
1819 u.r = in;
1820 t = u.i[0];
1821 u.i[0] = u.i[1];
1822 u.i[1] = t;
1823 return u.r;
1824}
1825# define swapMixedEndianFloat(X) X = floatSwap(X)
1826#else
1827# define swapMixedEndianFloat(X)
1828#endif
1829
1830/*
1831** Write the serialized data blob for the value stored in pMem into
1832** buf. It is assumed that the caller has allocated sufficient space.
1833** Return the number of bytes written.
1834**
1835** nBuf is the amount of space left in buf[]. nBuf must always be
1836** large enough to hold the entire field. Except, if the field is
1837** a blob with a zero-filled tail, then buf[] might be just the right
1838** size to hold everything except for the zero-filled tail. If buf[]
1839** is only big enough to hold the non-zero prefix, then only write that
1840** prefix into buf[]. But if buf[] is large enough to hold both the
1841** prefix and the tail then write the prefix and set the tail to all
1842** zeros.
1843**
1844** Return the number of bytes actually written into buf[]. The number
1845** of bytes in the zero-filled tail is included in the return value only
1846** if those bytes were zeroed in buf[].
1847*/
1848int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
1849 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
1850 int len;
1851
1852 /* Integer and Real */
1853 if( serial_type<=7 && serial_type>0 ){
1854 u64 v;
1855 int i;
1856 if( serial_type==7 ){
1857 assert( sizeof(v)==sizeof(pMem->r) );
1858 swapMixedEndianFloat(pMem->r);
1859 memcpy(&v, &pMem->r, sizeof(v));
1860 }else{
1861 v = pMem->u.i;
1862 }
1863 len = i = sqlite3VdbeSerialTypeLen(serial_type);
1864 assert( len<=nBuf );
1865 while( i-- ){
1866 buf[i] = (v&0xFF);
1867 v >>= 8;
1868 }
1869 return len;
1870 }
1871
1872 /* String or blob */
1873 if( serial_type>=12 ){
1874 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
1875 == sqlite3VdbeSerialTypeLen(serial_type) );
1876 assert( pMem->n<=nBuf );
1877 len = pMem->n;
1878 memcpy(buf, pMem->z, len);
1879 if( pMem->flags & MEM_Zero ){
1880 len += pMem->u.i;
1881 if( len>nBuf ){
1882 len = nBuf;
1883 }
1884 memset(&buf[pMem->n], 0, len-pMem->n);
1885 }
1886 return len;
1887 }
1888
1889 /* NULL or constants 0 or 1 */
1890 return 0;
1891}
1892
1893/*
1894** Deserialize the data blob pointed to by buf as serial type serial_type
1895** and store the result in pMem. Return the number of bytes read.
1896*/
1897int sqlite3VdbeSerialGet(
1898 const unsigned char *buf, /* Buffer to deserialize from */
1899 u32 serial_type, /* Serial type to deserialize */
1900 Mem *pMem /* Memory cell to write value into */
1901){
1902 switch( serial_type ){
1903 case 10: /* Reserved for future use */
1904 case 11: /* Reserved for future use */
1905 case 0: { /* NULL */
1906 pMem->flags = MEM_Null;
1907 break;
1908 }
1909 case 1: { /* 1-byte signed integer */
1910 pMem->u.i = (signed char)buf[0];
1911 pMem->flags = MEM_Int;
1912 return 1;
1913 }
1914 case 2: { /* 2-byte signed integer */
1915 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
1916 pMem->flags = MEM_Int;
1917 return 2;
1918 }
1919 case 3: { /* 3-byte signed integer */
1920 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
1921 pMem->flags = MEM_Int;
1922 return 3;
1923 }
1924 case 4: { /* 4-byte signed integer */
1925 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1926 pMem->flags = MEM_Int;
1927 return 4;
1928 }
1929 case 5: { /* 6-byte signed integer */
1930 u64 x = (((signed char)buf[0])<<8) | buf[1];
1931 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
1932 x = (x<<32) | y;
1933 pMem->u.i = *(i64*)&x;
1934 pMem->flags = MEM_Int;
1935 return 6;
1936 }
1937 case 6: /* 8-byte signed integer */
1938 case 7: { /* IEEE floating point */
1939 u64 x;
1940 u32 y;
1941#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
1942 /* Verify that integers and floating point values use the same
1943 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
1944 ** defined that 64-bit floating point values really are mixed
1945 ** endian.
1946 */
1947 static const u64 t1 = ((u64)0x3ff00000)<<32;
1948 static const double r1 = 1.0;
1949 double r2 = r1;
1950 swapMixedEndianFloat(r2);
1951 assert( sizeof(r2)==sizeof(t1) && memcmp(&r2, &t1, sizeof(r1))==0 );
1952#endif
1953
1954 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
1955 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
1956 x = (x<<32) | y;
1957 if( serial_type==6 ){
1958 pMem->u.i = *(i64*)&x;
1959 pMem->flags = MEM_Int;
1960 }else{
1961 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
1962 memcpy(&pMem->r, &x, sizeof(x));
1963 swapMixedEndianFloat(pMem->r);
1964 pMem->flags = MEM_Real;
1965 }
1966 return 8;
1967 }
1968 case 8: /* Integer 0 */
1969 case 9: { /* Integer 1 */
1970 pMem->u.i = serial_type-8;
1971 pMem->flags = MEM_Int;
1972 return 0;
1973 }
1974 default: {
1975 int len = (serial_type-12)/2;
1976 pMem->z = (char *)buf;
1977 pMem->n = len;
1978 pMem->xDel = 0;
1979 if( serial_type&0x01 ){
1980 pMem->flags = MEM_Str | MEM_Ephem;
1981 }else{
1982 pMem->flags = MEM_Blob | MEM_Ephem;
1983 }
1984 return len;
1985 }
1986 }
1987 return 0;
1988}
1989
1990/*
1991** The header of a record consists of a sequence variable-length integers.
1992** These integers are almost always small and are encoded as a single byte.
1993** The following macro takes advantage this fact to provide a fast decode
1994** of the integers in a record header. It is faster for the common case
1995** where the integer is a single byte. It is a little slower when the
1996** integer is two or more bytes. But overall it is faster.
1997**
1998** The following expressions are equivalent:
1999**
2000** x = sqlite3GetVarint32( A, &B );
2001**
2002** x = GetVarint( A, B );
2003**
2004*/
2005#define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
2006
2007/*
2008** This function compares the two table rows or index records specified by
2009** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
2010** or positive integer if {nKey1, pKey1} is less than, equal to or
2011** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings
2012** composed by the OP_MakeRecord opcode of the VDBE.
2013*/
2014int sqlite3VdbeRecordCompare(
2015 void *userData,
2016 int nKey1, const void *pKey1,
2017 int nKey2, const void *pKey2
2018){
2019 KeyInfo *pKeyInfo = (KeyInfo*)userData;
2020 u32 d1, d2; /* Offset into aKey[] of next data element */
2021 u32 idx1, idx2; /* Offset into aKey[] of next header element */
2022 u32 szHdr1, szHdr2; /* Number of bytes in header */
2023 int i = 0;
2024 int nField;
2025 int rc = 0;
2026 const unsigned char *aKey1 = (const unsigned char *)pKey1;
2027 const unsigned char *aKey2 = (const unsigned char *)pKey2;
2028
2029 Mem mem1;
2030 Mem mem2;
2031 mem1.enc = pKeyInfo->enc;
2032 mem2.enc = pKeyInfo->enc;
2033
2034 idx1 = GetVarint(aKey1, szHdr1);
2035 d1 = szHdr1;
2036 idx2 = GetVarint(aKey2, szHdr2);
2037 d2 = szHdr2;
2038 nField = pKeyInfo->nField;
2039 while( idx1<szHdr1 && idx2<szHdr2 ){
2040 u32 serial_type1;
2041 u32 serial_type2;
2042
2043 /* Read the serial types for the next element in each key. */
2044 idx1 += GetVarint( aKey1+idx1, serial_type1 );
2045 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
2046 idx2 += GetVarint( aKey2+idx2, serial_type2 );
2047 if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
2048
2049 /* Extract the values to be compared.
2050 */
2051 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
2052 d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
2053
2054 /* Do the comparison
2055 */
2056 rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
2057 if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
2058 if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
2059 if( rc!=0 ){
2060 break;
2061 }
2062 i++;
2063 }
2064
2065 /* One of the keys ran out of fields, but all the fields up to that point
2066 ** were equal. If the incrKey flag is true, then the second key is
2067 ** treated as larger.
2068 */
2069 if( rc==0 ){
2070 if( pKeyInfo->incrKey ){
2071 rc = -1;
2072 }else if( d1<nKey1 ){
2073 rc = 1;
2074 }else if( d2<nKey2 ){
2075 rc = -1;
2076 }
2077 }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
2078 && pKeyInfo->aSortOrder[i] ){
2079 rc = -rc;
2080 }
2081
2082 return rc;
2083}
2084
2085/*
2086** The argument is an index entry composed using the OP_MakeRecord opcode.
2087** The last entry in this record should be an integer (specifically
2088** an integer rowid). This routine returns the number of bytes in
2089** that integer.
2090*/
2091int sqlite3VdbeIdxRowidLen(const u8 *aKey){
2092 u32 szHdr; /* Size of the header */
2093 u32 typeRowid; /* Serial type of the rowid */
2094
2095 sqlite3GetVarint32(aKey, &szHdr);
2096 sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
2097 return sqlite3VdbeSerialTypeLen(typeRowid);
2098}
2099
2100
2101/*
2102** pCur points at an index entry created using the OP_MakeRecord opcode.
2103** Read the rowid (the last field in the record) and store it in *rowid.
2104** Return SQLITE_OK if everything works, or an error code otherwise.
2105*/
2106int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
2107 i64 nCellKey = 0;
2108 int rc;
2109 u32 szHdr; /* Size of the header */
2110 u32 typeRowid; /* Serial type of the rowid */
2111 u32 lenRowid; /* Size of the rowid */
2112 Mem m, v;
2113
2114 sqlite3BtreeKeySize(pCur, &nCellKey);
2115 if( nCellKey<=0 ){
2116 return SQLITE_CORRUPT_BKPT;
2117 }
2118 rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
2119 if( rc ){
2120 return rc;
2121 }
2122 sqlite3GetVarint32((u8*)m.z, &szHdr);
2123 sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
2124 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
2125 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
2126 *rowid = v.u.i;
2127 sqlite3VdbeMemRelease(&m);
2128 return SQLITE_OK;
2129}
2130
2131/*
2132** Compare the key of the index entry that cursor pC is point to against
2133** the key string in pKey (of length nKey). Write into *pRes a number
2134** that is negative, zero, or positive if pC is less than, equal to,
2135** or greater than pKey. Return SQLITE_OK on success.
2136**
2137** pKey is either created without a rowid or is truncated so that it
2138** omits the rowid at the end. The rowid at the end of the index entry
2139** is ignored as well.
2140*/
2141int sqlite3VdbeIdxKeyCompare(
2142 Cursor *pC, /* The cursor to compare against */
2143 int nKey, const u8 *pKey, /* The key to compare */
2144 int *res /* Write the comparison result here */
2145){
2146 i64 nCellKey = 0;
2147 int rc;
2148 BtCursor *pCur = pC->pCursor;
2149 int lenRowid;
2150 Mem m;
2151
2152 sqlite3BtreeKeySize(pCur, &nCellKey);
2153 if( nCellKey<=0 ){
2154 *res = 0;
2155 return SQLITE_OK;
2156 }
2157 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
2158 if( rc ){
2159 return rc;
2160 }
2161 lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
2162 *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
2163 sqlite3VdbeMemRelease(&m);
2164 return SQLITE_OK;
2165}
2166
2167/*
2168** This routine sets the value to be returned by subsequent calls to
2169** sqlite3_changes() on the database handle 'db'.
2170*/
2171void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
2172 db->nChange = nChange;
2173 db->nTotalChange += nChange;
2174}
2175
2176/*
2177** Set a flag in the vdbe to update the change counter when it is finalised
2178** or reset.
2179*/
2180void sqlite3VdbeCountChanges(Vdbe *v){
2181 v->changeCntOn = 1;
2182}
2183
2184/*
2185** Mark every prepared statement associated with a database connection
2186** as expired.
2187**
2188** An expired statement means that recompilation of the statement is
2189** recommend. Statements expire when things happen that make their
2190** programs obsolete. Removing user-defined functions or collating
2191** sequences, or changing an authorization function are the types of
2192** things that make prepared statements obsolete.
2193*/
2194void sqlite3ExpirePreparedStatements(sqlite3 *db){
2195 Vdbe *p;
2196 for(p = db->pVdbe; p; p=p->pNext){
2197 p->expired = 1;
2198 }
2199}
2200
2201/*
2202** Return the database associated with the Vdbe.
2203*/
2204sqlite3 *sqlite3VdbeDb(Vdbe *v){
2205 return v->db;
2206}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status