Remove incorrect NEVER() macro added by the previous check-in.
[sqlite.git] / src / vdbeaux.c
blob4b07647519a052e86cec402ab821a1f7b3230308
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.
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.)
15 #include "sqliteInt.h"
16 #include "vdbeInt.h"
19 ** Create a new virtual database engine.
21 Vdbe *sqlite3VdbeCreate(Parse *pParse){
22 sqlite3 *db = pParse->db;
23 Vdbe *p;
24 p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
25 if( p==0 ) return 0;
26 memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
27 p->db = db;
28 if( db->pVdbe ){
29 db->pVdbe->pPrev = p;
31 p->pNext = db->pVdbe;
32 p->pPrev = 0;
33 db->pVdbe = p;
34 p->magic = VDBE_MAGIC_INIT;
35 p->pParse = pParse;
36 pParse->pVdbe = p;
37 assert( pParse->aLabel==0 );
38 assert( pParse->nLabel==0 );
39 assert( pParse->nOpAlloc==0 );
40 assert( pParse->szOpAlloc==0 );
41 sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
42 return p;
46 ** Change the error string stored in Vdbe.zErrMsg
48 void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
49 va_list ap;
50 sqlite3DbFree(p->db, p->zErrMsg);
51 va_start(ap, zFormat);
52 p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
53 va_end(ap);
57 ** Remember the SQL string for a prepared statement.
59 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
60 if( p==0 ) return;
61 p->prepFlags = prepFlags;
62 if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
63 p->expmask = 0;
65 assert( p->zSql==0 );
66 p->zSql = sqlite3DbStrNDup(p->db, z, n);
70 ** Swap all content between two VDBE structures.
72 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
73 Vdbe tmp, *pTmp;
74 char *zTmp;
75 assert( pA->db==pB->db );
76 tmp = *pA;
77 *pA = *pB;
78 *pB = tmp;
79 pTmp = pA->pNext;
80 pA->pNext = pB->pNext;
81 pB->pNext = pTmp;
82 pTmp = pA->pPrev;
83 pA->pPrev = pB->pPrev;
84 pB->pPrev = pTmp;
85 zTmp = pA->zSql;
86 pA->zSql = pB->zSql;
87 pB->zSql = zTmp;
88 pB->expmask = pA->expmask;
89 pB->prepFlags = pA->prepFlags;
90 memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
91 pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
95 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
96 ** than its current size. nOp is guaranteed to be less than or equal
97 ** to 1024/sizeof(Op).
99 ** If an out-of-memory error occurs while resizing the array, return
100 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
101 ** unchanged (this is so that any opcodes already allocated can be
102 ** correctly deallocated along with the rest of the Vdbe).
104 static int growOpArray(Vdbe *v, int nOp){
105 VdbeOp *pNew;
106 Parse *p = v->pParse;
108 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
109 ** more frequent reallocs and hence provide more opportunities for
110 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
111 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
112 ** by the minimum* amount required until the size reaches 512. Normal
113 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
114 ** size of the op array or add 1KB of space, whichever is smaller. */
115 #ifdef SQLITE_TEST_REALLOC_STRESS
116 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
117 #else
118 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
119 UNUSED_PARAMETER(nOp);
120 #endif
122 /* Ensure that the size of a VDBE does not grow too large */
123 if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
124 sqlite3OomFault(p->db);
125 return SQLITE_NOMEM;
128 assert( nOp<=(1024/sizeof(Op)) );
129 assert( nNew>=(p->nOpAlloc+nOp) );
130 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
131 if( pNew ){
132 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
133 p->nOpAlloc = p->szOpAlloc/sizeof(Op);
134 v->aOp = pNew;
136 return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
139 #ifdef SQLITE_DEBUG
140 /* This routine is just a convenient place to set a breakpoint that will
141 ** fire after each opcode is inserted and displayed using
142 ** "PRAGMA vdbe_addoptrace=on".
144 static void test_addop_breakpoint(void){
145 static int n = 0;
146 n++;
148 #endif
151 ** Add a new instruction to the list of instructions current in the
152 ** VDBE. Return the address of the new instruction.
154 ** Parameters:
156 ** p Pointer to the VDBE
158 ** op The opcode for this instruction
160 ** p1, p2, p3 Operands
162 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
163 ** the sqlite3VdbeChangeP4() function to change the value of the P4
164 ** operand.
166 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
167 assert( p->pParse->nOpAlloc<=p->nOp );
168 if( growOpArray(p, 1) ) return 1;
169 assert( p->pParse->nOpAlloc>p->nOp );
170 return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
172 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
173 int i;
174 VdbeOp *pOp;
176 i = p->nOp;
177 assert( p->magic==VDBE_MAGIC_INIT );
178 assert( op>=0 && op<0xff );
179 if( p->pParse->nOpAlloc<=i ){
180 return growOp3(p, op, p1, p2, p3);
182 p->nOp++;
183 pOp = &p->aOp[i];
184 pOp->opcode = (u8)op;
185 pOp->p5 = 0;
186 pOp->p1 = p1;
187 pOp->p2 = p2;
188 pOp->p3 = p3;
189 pOp->p4.p = 0;
190 pOp->p4type = P4_NOTUSED;
191 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
192 pOp->zComment = 0;
193 #endif
194 #ifdef SQLITE_DEBUG
195 if( p->db->flags & SQLITE_VdbeAddopTrace ){
196 int jj, kk;
197 Parse *pParse = p->pParse;
198 for(jj=kk=0; jj<pParse->nColCache; jj++){
199 struct yColCache *x = pParse->aColCache + jj;
200 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
201 kk++;
203 if( kk ) printf("\n");
204 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
205 test_addop_breakpoint();
207 #endif
208 #ifdef VDBE_PROFILE
209 pOp->cycles = 0;
210 pOp->cnt = 0;
211 #endif
212 #ifdef SQLITE_VDBE_COVERAGE
213 pOp->iSrcLine = 0;
214 #endif
215 return i;
217 int sqlite3VdbeAddOp0(Vdbe *p, int op){
218 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
220 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
221 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
223 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
224 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
227 /* Generate code for an unconditional jump to instruction iDest
229 int sqlite3VdbeGoto(Vdbe *p, int iDest){
230 return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
233 /* Generate code to cause the string zStr to be loaded into
234 ** register iDest
236 int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
237 return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
241 ** Generate code that initializes multiple registers to string or integer
242 ** constants. The registers begin with iDest and increase consecutively.
243 ** One register is initialized for each characgter in zTypes[]. For each
244 ** "s" character in zTypes[], the register is a string if the argument is
245 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
246 ** in zTypes[], the register is initialized to an integer.
248 ** If the input string does not end with "X" then an OP_ResultRow instruction
249 ** is generated for the values inserted.
251 void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
252 va_list ap;
253 int i;
254 char c;
255 va_start(ap, zTypes);
256 for(i=0; (c = zTypes[i])!=0; i++){
257 if( c=='s' ){
258 const char *z = va_arg(ap, const char*);
259 sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
260 }else if( c=='i' ){
261 sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
262 }else{
263 goto skip_op_resultrow;
266 sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
267 skip_op_resultrow:
268 va_end(ap);
272 ** Add an opcode that includes the p4 value as a pointer.
274 int sqlite3VdbeAddOp4(
275 Vdbe *p, /* Add the opcode to this VM */
276 int op, /* The new opcode */
277 int p1, /* The P1 operand */
278 int p2, /* The P2 operand */
279 int p3, /* The P3 operand */
280 const char *zP4, /* The P4 operand */
281 int p4type /* P4 operand type */
283 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
284 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
285 return addr;
289 ** Add an opcode that includes the p4 value with a P4_INT64 or
290 ** P4_REAL type.
292 int sqlite3VdbeAddOp4Dup8(
293 Vdbe *p, /* Add the opcode to this VM */
294 int op, /* The new opcode */
295 int p1, /* The P1 operand */
296 int p2, /* The P2 operand */
297 int p3, /* The P3 operand */
298 const u8 *zP4, /* The P4 operand */
299 int p4type /* P4 operand type */
301 char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
302 if( p4copy ) memcpy(p4copy, zP4, 8);
303 return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
306 #ifndef SQLITE_OMIT_EXPLAIN
308 ** Return the address of the current EXPLAIN QUERY PLAN baseline.
309 ** 0 means "none".
311 int sqlite3VdbeExplainParent(Parse *pParse){
312 VdbeOp *pOp;
313 if( pParse->addrExplain==0 ) return 0;
314 pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
315 return pOp->p2;
319 ** Add a new OP_Explain opcode.
321 ** If the bPush flag is true, then make this opcode the parent for
322 ** subsequent Explains until sqlite3VdbeExplainPop() is called.
324 void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
325 if( pParse->explain==2 ){
326 char *zMsg;
327 Vdbe *v = pParse->pVdbe;
328 va_list ap;
329 int iThis;
330 va_start(ap, zFmt);
331 zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
332 va_end(ap);
333 v = pParse->pVdbe;
334 iThis = v->nOp;
335 sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
336 zMsg, P4_DYNAMIC);
337 if( bPush) pParse->addrExplain = iThis;
342 ** Pop the EXPLAIN QUERY PLAN stack one level.
344 void sqlite3VdbeExplainPop(Parse *pParse){
345 pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
347 #endif /* SQLITE_OMIT_EXPLAIN */
350 ** Add an OP_ParseSchema opcode. This routine is broken out from
351 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
352 ** as having been used.
354 ** The zWhere string must have been obtained from sqlite3_malloc().
355 ** This routine will take ownership of the allocated memory.
357 void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
358 int j;
359 sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
360 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
364 ** Add an opcode that includes the p4 value as an integer.
366 int sqlite3VdbeAddOp4Int(
367 Vdbe *p, /* Add the opcode to this VM */
368 int op, /* The new opcode */
369 int p1, /* The P1 operand */
370 int p2, /* The P2 operand */
371 int p3, /* The P3 operand */
372 int p4 /* The P4 operand as an integer */
374 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
375 if( p->db->mallocFailed==0 ){
376 VdbeOp *pOp = &p->aOp[addr];
377 pOp->p4type = P4_INT32;
378 pOp->p4.i = p4;
380 return addr;
383 /* Insert the end of a co-routine
385 void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
386 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
388 /* Clear the temporary register cache, thereby ensuring that each
389 ** co-routine has its own independent set of registers, because co-routines
390 ** might expect their registers to be preserved across an OP_Yield, and
391 ** that could cause problems if two or more co-routines are using the same
392 ** temporary register.
394 v->pParse->nTempReg = 0;
395 v->pParse->nRangeReg = 0;
399 ** Create a new symbolic label for an instruction that has yet to be
400 ** coded. The symbolic label is really just a negative number. The
401 ** label can be used as the P2 value of an operation. Later, when
402 ** the label is resolved to a specific address, the VDBE will scan
403 ** through its operation list and change all values of P2 which match
404 ** the label into the resolved address.
406 ** The VDBE knows that a P2 value is a label because labels are
407 ** always negative and P2 values are suppose to be non-negative.
408 ** Hence, a negative P2 value is a label that has yet to be resolved.
410 ** Zero is returned if a malloc() fails.
412 int sqlite3VdbeMakeLabel(Vdbe *v){
413 Parse *p = v->pParse;
414 int i = p->nLabel++;
415 assert( v->magic==VDBE_MAGIC_INIT );
416 if( (i & (i-1))==0 ){
417 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
418 (i*2+1)*sizeof(p->aLabel[0]));
420 if( p->aLabel ){
421 p->aLabel[i] = -1;
423 return ADDR(i);
427 ** Resolve label "x" to be the address of the next instruction to
428 ** be inserted. The parameter "x" must have been obtained from
429 ** a prior call to sqlite3VdbeMakeLabel().
431 void sqlite3VdbeResolveLabel(Vdbe *v, int x){
432 Parse *p = v->pParse;
433 int j = ADDR(x);
434 assert( v->magic==VDBE_MAGIC_INIT );
435 assert( j<p->nLabel );
436 assert( j>=0 );
437 if( p->aLabel ){
438 #ifdef SQLITE_DEBUG
439 if( p->db->flags & SQLITE_VdbeAddopTrace ){
440 printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
442 #endif
443 assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
444 p->aLabel[j] = v->nOp;
448 #ifdef SQLITE_COVERAGE_TEST
450 ** Return TRUE if and only if the label x has already been resolved.
451 ** Return FALSE (zero) if label x is still unresolved.
453 ** This routine is only used inside of testcase() macros, and so it
454 ** only exists when measuring test coverage.
456 int sqlite3VdbeLabelHasBeenResolved(Vdbe *v, int x){
457 return v->pParse->aLabel && v->pParse->aLabel[ADDR(x)]>=0;
459 #endif /* SQLITE_COVERAGE_TEST */
462 ** Mark the VDBE as one that can only be run one time.
464 void sqlite3VdbeRunOnlyOnce(Vdbe *p){
465 p->runOnlyOnce = 1;
469 ** Mark the VDBE as one that can only be run multiple times.
471 void sqlite3VdbeReusable(Vdbe *p){
472 p->runOnlyOnce = 0;
475 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
478 ** The following type and function are used to iterate through all opcodes
479 ** in a Vdbe main program and each of the sub-programs (triggers) it may
480 ** invoke directly or indirectly. It should be used as follows:
482 ** Op *pOp;
483 ** VdbeOpIter sIter;
485 ** memset(&sIter, 0, sizeof(sIter));
486 ** sIter.v = v; // v is of type Vdbe*
487 ** while( (pOp = opIterNext(&sIter)) ){
488 ** // Do something with pOp
489 ** }
490 ** sqlite3DbFree(v->db, sIter.apSub);
493 typedef struct VdbeOpIter VdbeOpIter;
494 struct VdbeOpIter {
495 Vdbe *v; /* Vdbe to iterate through the opcodes of */
496 SubProgram **apSub; /* Array of subprograms */
497 int nSub; /* Number of entries in apSub */
498 int iAddr; /* Address of next instruction to return */
499 int iSub; /* 0 = main program, 1 = first sub-program etc. */
501 static Op *opIterNext(VdbeOpIter *p){
502 Vdbe *v = p->v;
503 Op *pRet = 0;
504 Op *aOp;
505 int nOp;
507 if( p->iSub<=p->nSub ){
509 if( p->iSub==0 ){
510 aOp = v->aOp;
511 nOp = v->nOp;
512 }else{
513 aOp = p->apSub[p->iSub-1]->aOp;
514 nOp = p->apSub[p->iSub-1]->nOp;
516 assert( p->iAddr<nOp );
518 pRet = &aOp[p->iAddr];
519 p->iAddr++;
520 if( p->iAddr==nOp ){
521 p->iSub++;
522 p->iAddr = 0;
525 if( pRet->p4type==P4_SUBPROGRAM ){
526 int nByte = (p->nSub+1)*sizeof(SubProgram*);
527 int j;
528 for(j=0; j<p->nSub; j++){
529 if( p->apSub[j]==pRet->p4.pProgram ) break;
531 if( j==p->nSub ){
532 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
533 if( !p->apSub ){
534 pRet = 0;
535 }else{
536 p->apSub[p->nSub++] = pRet->p4.pProgram;
542 return pRet;
546 ** Check if the program stored in the VM associated with pParse may
547 ** throw an ABORT exception (causing the statement, but not entire transaction
548 ** to be rolled back). This condition is true if the main program or any
549 ** sub-programs contains any of the following:
551 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
552 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
553 ** * OP_Destroy
554 ** * OP_VUpdate
555 ** * OP_VRename
556 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
557 ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
558 ** (for CREATE TABLE AS SELECT ...)
560 ** Then check that the value of Parse.mayAbort is true if an
561 ** ABORT may be thrown, or false otherwise. Return true if it does
562 ** match, or false otherwise. This function is intended to be used as
563 ** part of an assert statement in the compiler. Similar to:
565 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
567 int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
568 int hasAbort = 0;
569 int hasFkCounter = 0;
570 int hasCreateTable = 0;
571 int hasInitCoroutine = 0;
572 Op *pOp;
573 VdbeOpIter sIter;
574 memset(&sIter, 0, sizeof(sIter));
575 sIter.v = v;
577 while( (pOp = opIterNext(&sIter))!=0 ){
578 int opcode = pOp->opcode;
579 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
580 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
581 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
583 hasAbort = 1;
584 break;
586 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
587 if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
588 #ifndef SQLITE_OMIT_FOREIGN_KEY
589 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
590 hasFkCounter = 1;
592 #endif
594 sqlite3DbFree(v->db, sIter.apSub);
596 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
597 ** If malloc failed, then the while() loop above may not have iterated
598 ** through all opcodes and hasAbort may be set incorrectly. Return
599 ** true for this case to prevent the assert() in the callers frame
600 ** from failing. */
601 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
602 || (hasCreateTable && hasInitCoroutine) );
604 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
607 ** This routine is called after all opcodes have been inserted. It loops
608 ** through all the opcodes and fixes up some details.
610 ** (1) For each jump instruction with a negative P2 value (a label)
611 ** resolve the P2 value to an actual address.
613 ** (2) Compute the maximum number of arguments used by any SQL function
614 ** and store that value in *pMaxFuncArgs.
616 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
617 ** indicate what the prepared statement actually does.
619 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
621 ** (5) Reclaim the memory allocated for storing labels.
623 ** This routine will only function correctly if the mkopcodeh.tcl generator
624 ** script numbers the opcodes correctly. Changes to this routine must be
625 ** coordinated with changes to mkopcodeh.tcl.
627 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
628 int nMaxArgs = *pMaxFuncArgs;
629 Op *pOp;
630 Parse *pParse = p->pParse;
631 int *aLabel = pParse->aLabel;
632 p->readOnly = 1;
633 p->bIsReader = 0;
634 pOp = &p->aOp[p->nOp-1];
635 while(1){
637 /* Only JUMP opcodes and the short list of special opcodes in the switch
638 ** below need to be considered. The mkopcodeh.tcl generator script groups
639 ** all these opcodes together near the front of the opcode list. Skip
640 ** any opcode that does not need processing by virtual of the fact that
641 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
643 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
644 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
645 ** cases from this switch! */
646 switch( pOp->opcode ){
647 case OP_Transaction: {
648 if( pOp->p2!=0 ) p->readOnly = 0;
649 /* fall thru */
651 case OP_AutoCommit:
652 case OP_Savepoint: {
653 p->bIsReader = 1;
654 break;
656 #ifndef SQLITE_OMIT_WAL
657 case OP_Checkpoint:
658 #endif
659 case OP_Vacuum:
660 case OP_JournalMode: {
661 p->readOnly = 0;
662 p->bIsReader = 1;
663 break;
665 case OP_Next:
666 case OP_NextIfOpen:
667 case OP_SorterNext: {
668 pOp->p4.xAdvance = sqlite3BtreeNext;
669 pOp->p4type = P4_ADVANCE;
670 /* The code generator never codes any of these opcodes as a jump
671 ** to a label. They are always coded as a jump backwards to a
672 ** known address */
673 assert( pOp->p2>=0 );
674 break;
676 case OP_Prev:
677 case OP_PrevIfOpen: {
678 pOp->p4.xAdvance = sqlite3BtreePrevious;
679 pOp->p4type = P4_ADVANCE;
680 /* The code generator never codes any of these opcodes as a jump
681 ** to a label. They are always coded as a jump backwards to a
682 ** known address */
683 assert( pOp->p2>=0 );
684 break;
686 #ifndef SQLITE_OMIT_VIRTUALTABLE
687 case OP_VUpdate: {
688 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
689 break;
691 case OP_VFilter: {
692 int n;
693 assert( (pOp - p->aOp) >= 3 );
694 assert( pOp[-1].opcode==OP_Integer );
695 n = pOp[-1].p1;
696 if( n>nMaxArgs ) nMaxArgs = n;
697 /* Fall through into the default case */
699 #endif
700 default: {
701 if( pOp->p2<0 ){
702 /* The mkopcodeh.tcl script has so arranged things that the only
703 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
704 ** have non-negative values for P2. */
705 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
706 assert( ADDR(pOp->p2)<pParse->nLabel );
707 pOp->p2 = aLabel[ADDR(pOp->p2)];
709 break;
712 /* The mkopcodeh.tcl script has so arranged things that the only
713 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
714 ** have non-negative values for P2. */
715 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
717 if( pOp==p->aOp ) break;
718 pOp--;
720 sqlite3DbFree(p->db, pParse->aLabel);
721 pParse->aLabel = 0;
722 pParse->nLabel = 0;
723 *pMaxFuncArgs = nMaxArgs;
724 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
728 ** Return the address of the next instruction to be inserted.
730 int sqlite3VdbeCurrentAddr(Vdbe *p){
731 assert( p->magic==VDBE_MAGIC_INIT );
732 return p->nOp;
736 ** Verify that at least N opcode slots are available in p without
737 ** having to malloc for more space (except when compiled using
738 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
739 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
740 ** fail due to a OOM fault and hence that the return value from
741 ** sqlite3VdbeAddOpList() will always be non-NULL.
743 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
744 void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
745 assert( p->nOp + N <= p->pParse->nOpAlloc );
747 #endif
750 ** Verify that the VM passed as the only argument does not contain
751 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
752 ** by code in pragma.c to ensure that the implementation of certain
753 ** pragmas comports with the flags specified in the mkpragmatab.tcl
754 ** script.
756 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
757 void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
758 int i;
759 for(i=0; i<p->nOp; i++){
760 assert( p->aOp[i].opcode!=OP_ResultRow );
763 #endif
766 ** This function returns a pointer to the array of opcodes associated with
767 ** the Vdbe passed as the first argument. It is the callers responsibility
768 ** to arrange for the returned array to be eventually freed using the
769 ** vdbeFreeOpArray() function.
771 ** Before returning, *pnOp is set to the number of entries in the returned
772 ** array. Also, *pnMaxArg is set to the larger of its current value and
773 ** the number of entries in the Vdbe.apArg[] array required to execute the
774 ** returned program.
776 VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
777 VdbeOp *aOp = p->aOp;
778 assert( aOp && !p->db->mallocFailed );
780 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
781 assert( DbMaskAllZero(p->btreeMask) );
783 resolveP2Values(p, pnMaxArg);
784 *pnOp = p->nOp;
785 p->aOp = 0;
786 return aOp;
790 ** Add a whole list of operations to the operation stack. Return a
791 ** pointer to the first operation inserted.
793 ** Non-zero P2 arguments to jump instructions are automatically adjusted
794 ** so that the jump target is relative to the first operation inserted.
796 VdbeOp *sqlite3VdbeAddOpList(
797 Vdbe *p, /* Add opcodes to the prepared statement */
798 int nOp, /* Number of opcodes to add */
799 VdbeOpList const *aOp, /* The opcodes to be added */
800 int iLineno /* Source-file line number of first opcode */
802 int i;
803 VdbeOp *pOut, *pFirst;
804 assert( nOp>0 );
805 assert( p->magic==VDBE_MAGIC_INIT );
806 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
807 return 0;
809 pFirst = pOut = &p->aOp[p->nOp];
810 for(i=0; i<nOp; i++, aOp++, pOut++){
811 pOut->opcode = aOp->opcode;
812 pOut->p1 = aOp->p1;
813 pOut->p2 = aOp->p2;
814 assert( aOp->p2>=0 );
815 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
816 pOut->p2 += p->nOp;
818 pOut->p3 = aOp->p3;
819 pOut->p4type = P4_NOTUSED;
820 pOut->p4.p = 0;
821 pOut->p5 = 0;
822 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
823 pOut->zComment = 0;
824 #endif
825 #ifdef SQLITE_VDBE_COVERAGE
826 pOut->iSrcLine = iLineno+i;
827 #else
828 (void)iLineno;
829 #endif
830 #ifdef SQLITE_DEBUG
831 if( p->db->flags & SQLITE_VdbeAddopTrace ){
832 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
834 #endif
836 p->nOp += nOp;
837 return pFirst;
840 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
842 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
844 void sqlite3VdbeScanStatus(
845 Vdbe *p, /* VM to add scanstatus() to */
846 int addrExplain, /* Address of OP_Explain (or 0) */
847 int addrLoop, /* Address of loop counter */
848 int addrVisit, /* Address of rows visited counter */
849 LogEst nEst, /* Estimated number of output rows */
850 const char *zName /* Name of table or index being scanned */
852 int nByte = (p->nScan+1) * sizeof(ScanStatus);
853 ScanStatus *aNew;
854 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
855 if( aNew ){
856 ScanStatus *pNew = &aNew[p->nScan++];
857 pNew->addrExplain = addrExplain;
858 pNew->addrLoop = addrLoop;
859 pNew->addrVisit = addrVisit;
860 pNew->nEst = nEst;
861 pNew->zName = sqlite3DbStrDup(p->db, zName);
862 p->aScan = aNew;
865 #endif
869 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
870 ** for a specific instruction.
872 void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
873 sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
875 void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
876 sqlite3VdbeGetOp(p,addr)->p1 = val;
878 void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
879 sqlite3VdbeGetOp(p,addr)->p2 = val;
881 void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
882 sqlite3VdbeGetOp(p,addr)->p3 = val;
884 void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
885 assert( p->nOp>0 || p->db->mallocFailed );
886 if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
890 ** Change the P2 operand of instruction addr so that it points to
891 ** the address of the next instruction to be coded.
893 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
894 sqlite3VdbeChangeP2(p, addr, p->nOp);
899 ** If the input FuncDef structure is ephemeral, then free it. If
900 ** the FuncDef is not ephermal, then do nothing.
902 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
903 if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
904 sqlite3DbFreeNN(db, pDef);
908 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
911 ** Delete a P4 value if necessary.
913 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
914 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
915 sqlite3DbFreeNN(db, p);
917 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
918 freeEphemeralFunction(db, p->pFunc);
919 sqlite3DbFreeNN(db, p);
921 static void freeP4(sqlite3 *db, int p4type, void *p4){
922 assert( db );
923 switch( p4type ){
924 case P4_FUNCCTX: {
925 freeP4FuncCtx(db, (sqlite3_context*)p4);
926 break;
928 case P4_REAL:
929 case P4_INT64:
930 case P4_DYNAMIC:
931 case P4_DYNBLOB:
932 case P4_INTARRAY: {
933 sqlite3DbFree(db, p4);
934 break;
936 case P4_KEYINFO: {
937 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
938 break;
940 #ifdef SQLITE_ENABLE_CURSOR_HINTS
941 case P4_EXPR: {
942 sqlite3ExprDelete(db, (Expr*)p4);
943 break;
945 #endif
946 case P4_FUNCDEF: {
947 freeEphemeralFunction(db, (FuncDef*)p4);
948 break;
950 case P4_MEM: {
951 if( db->pnBytesFreed==0 ){
952 sqlite3ValueFree((sqlite3_value*)p4);
953 }else{
954 freeP4Mem(db, (Mem*)p4);
956 break;
958 case P4_VTAB : {
959 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
960 break;
966 ** Free the space allocated for aOp and any p4 values allocated for the
967 ** opcodes contained within. If aOp is not NULL it is assumed to contain
968 ** nOp entries.
970 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
971 if( aOp ){
972 Op *pOp;
973 for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
974 if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
975 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
976 sqlite3DbFree(db, pOp->zComment);
977 #endif
979 sqlite3DbFreeNN(db, aOp);
984 ** Link the SubProgram object passed as the second argument into the linked
985 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
986 ** objects when the VM is no longer required.
988 void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
989 p->pNext = pVdbe->pProgram;
990 pVdbe->pProgram = p;
994 ** Change the opcode at addr into OP_Noop
996 int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
997 VdbeOp *pOp;
998 if( p->db->mallocFailed ) return 0;
999 assert( addr>=0 && addr<p->nOp );
1000 pOp = &p->aOp[addr];
1001 freeP4(p->db, pOp->p4type, pOp->p4.p);
1002 pOp->p4type = P4_NOTUSED;
1003 pOp->p4.z = 0;
1004 pOp->opcode = OP_Noop;
1005 return 1;
1009 ** If the last opcode is "op" and it is not a jump destination,
1010 ** then remove it. Return true if and only if an opcode was removed.
1012 int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
1013 if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
1014 return sqlite3VdbeChangeToNoop(p, p->nOp-1);
1015 }else{
1016 return 0;
1021 ** Change the value of the P4 operand for a specific instruction.
1022 ** This routine is useful when a large program is loaded from a
1023 ** static array using sqlite3VdbeAddOpList but we want to make a
1024 ** few minor changes to the program.
1026 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
1027 ** the string is made into memory obtained from sqlite3_malloc().
1028 ** A value of n==0 means copy bytes of zP4 up to and including the
1029 ** first null byte. If n>0 then copy n+1 bytes of zP4.
1031 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
1032 ** to a string or structure that is guaranteed to exist for the lifetime of
1033 ** the Vdbe. In these cases we can just copy the pointer.
1035 ** If addr<0 then change P4 on the most recently inserted instruction.
1037 static void SQLITE_NOINLINE vdbeChangeP4Full(
1038 Vdbe *p,
1039 Op *pOp,
1040 const char *zP4,
1041 int n
1043 if( pOp->p4type ){
1044 freeP4(p->db, pOp->p4type, pOp->p4.p);
1045 pOp->p4type = 0;
1046 pOp->p4.p = 0;
1048 if( n<0 ){
1049 sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
1050 }else{
1051 if( n==0 ) n = sqlite3Strlen30(zP4);
1052 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
1053 pOp->p4type = P4_DYNAMIC;
1056 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
1057 Op *pOp;
1058 sqlite3 *db;
1059 assert( p!=0 );
1060 db = p->db;
1061 assert( p->magic==VDBE_MAGIC_INIT );
1062 assert( p->aOp!=0 || db->mallocFailed );
1063 if( db->mallocFailed ){
1064 if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
1065 return;
1067 assert( p->nOp>0 );
1068 assert( addr<p->nOp );
1069 if( addr<0 ){
1070 addr = p->nOp - 1;
1072 pOp = &p->aOp[addr];
1073 if( n>=0 || pOp->p4type ){
1074 vdbeChangeP4Full(p, pOp, zP4, n);
1075 return;
1077 if( n==P4_INT32 ){
1078 /* Note: this cast is safe, because the origin data point was an int
1079 ** that was cast to a (const char *). */
1080 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
1081 pOp->p4type = P4_INT32;
1082 }else if( zP4!=0 ){
1083 assert( n<0 );
1084 pOp->p4.p = (void*)zP4;
1085 pOp->p4type = (signed char)n;
1086 if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
1091 ** Change the P4 operand of the most recently coded instruction
1092 ** to the value defined by the arguments. This is a high-speed
1093 ** version of sqlite3VdbeChangeP4().
1095 ** The P4 operand must not have been previously defined. And the new
1096 ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
1097 ** those cases.
1099 void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
1100 VdbeOp *pOp;
1101 assert( n!=P4_INT32 && n!=P4_VTAB );
1102 assert( n<=0 );
1103 if( p->db->mallocFailed ){
1104 freeP4(p->db, n, pP4);
1105 }else{
1106 assert( pP4!=0 );
1107 assert( p->nOp>0 );
1108 pOp = &p->aOp[p->nOp-1];
1109 assert( pOp->p4type==P4_NOTUSED );
1110 pOp->p4type = n;
1111 pOp->p4.p = pP4;
1116 ** Set the P4 on the most recently added opcode to the KeyInfo for the
1117 ** index given.
1119 void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
1120 Vdbe *v = pParse->pVdbe;
1121 KeyInfo *pKeyInfo;
1122 assert( v!=0 );
1123 assert( pIdx!=0 );
1124 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
1125 if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1128 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1130 ** Change the comment on the most recently coded instruction. Or
1131 ** insert a No-op and add the comment to that new instruction. This
1132 ** makes the code easier to read during debugging. None of this happens
1133 ** in a production build.
1135 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
1136 assert( p->nOp>0 || p->aOp==0 );
1137 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
1138 if( p->nOp ){
1139 assert( p->aOp );
1140 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
1141 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
1144 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
1145 va_list ap;
1146 if( p ){
1147 va_start(ap, zFormat);
1148 vdbeVComment(p, zFormat, ap);
1149 va_end(ap);
1152 void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
1153 va_list ap;
1154 if( p ){
1155 sqlite3VdbeAddOp0(p, OP_Noop);
1156 va_start(ap, zFormat);
1157 vdbeVComment(p, zFormat, ap);
1158 va_end(ap);
1161 #endif /* NDEBUG */
1163 #ifdef SQLITE_VDBE_COVERAGE
1165 ** Set the value if the iSrcLine field for the previously coded instruction.
1167 void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
1168 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
1170 #endif /* SQLITE_VDBE_COVERAGE */
1173 ** Return the opcode for a given address. If the address is -1, then
1174 ** return the most recently inserted opcode.
1176 ** If a memory allocation error has occurred prior to the calling of this
1177 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
1178 ** is readable but not writable, though it is cast to a writable value.
1179 ** The return of a dummy opcode allows the call to continue functioning
1180 ** after an OOM fault without having to check to see if the return from
1181 ** this routine is a valid pointer. But because the dummy.opcode is 0,
1182 ** dummy will never be written to. This is verified by code inspection and
1183 ** by running with Valgrind.
1185 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
1186 /* C89 specifies that the constant "dummy" will be initialized to all
1187 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
1188 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
1189 assert( p->magic==VDBE_MAGIC_INIT );
1190 if( addr<0 ){
1191 addr = p->nOp - 1;
1193 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
1194 if( p->db->mallocFailed ){
1195 return (VdbeOp*)&dummy;
1196 }else{
1197 return &p->aOp[addr];
1201 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
1203 ** Return an integer value for one of the parameters to the opcode pOp
1204 ** determined by character c.
1206 static int translateP(char c, const Op *pOp){
1207 if( c=='1' ) return pOp->p1;
1208 if( c=='2' ) return pOp->p2;
1209 if( c=='3' ) return pOp->p3;
1210 if( c=='4' ) return pOp->p4.i;
1211 return pOp->p5;
1215 ** Compute a string for the "comment" field of a VDBE opcode listing.
1217 ** The Synopsis: field in comments in the vdbe.c source file gets converted
1218 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
1219 ** absence of other comments, this synopsis becomes the comment on the opcode.
1220 ** Some translation occurs:
1222 ** "PX" -> "r[X]"
1223 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
1224 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
1225 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
1227 static int displayComment(
1228 const Op *pOp, /* The opcode to be commented */
1229 const char *zP4, /* Previously obtained value for P4 */
1230 char *zTemp, /* Write result here */
1231 int nTemp /* Space available in zTemp[] */
1233 const char *zOpName;
1234 const char *zSynopsis;
1235 int nOpName;
1236 int ii, jj;
1237 char zAlt[50];
1238 zOpName = sqlite3OpcodeName(pOp->opcode);
1239 nOpName = sqlite3Strlen30(zOpName);
1240 if( zOpName[nOpName+1] ){
1241 int seenCom = 0;
1242 char c;
1243 zSynopsis = zOpName += nOpName + 1;
1244 if( strncmp(zSynopsis,"IF ",3)==0 ){
1245 if( pOp->p5 & SQLITE_STOREP2 ){
1246 sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
1247 }else{
1248 sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
1250 zSynopsis = zAlt;
1252 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
1253 if( c=='P' ){
1254 c = zSynopsis[++ii];
1255 if( c=='4' ){
1256 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
1257 }else if( c=='X' ){
1258 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
1259 seenCom = 1;
1260 }else{
1261 int v1 = translateP(c, pOp);
1262 int v2;
1263 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
1264 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1265 ii += 3;
1266 jj += sqlite3Strlen30(zTemp+jj);
1267 v2 = translateP(zSynopsis[ii], pOp);
1268 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
1269 ii += 2;
1270 v2++;
1272 if( v2>1 ){
1273 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
1275 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1276 ii += 4;
1279 jj += sqlite3Strlen30(zTemp+jj);
1280 }else{
1281 zTemp[jj++] = c;
1284 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
1285 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
1286 jj += sqlite3Strlen30(zTemp+jj);
1288 if( jj<nTemp ) zTemp[jj] = 0;
1289 }else if( pOp->zComment ){
1290 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1291 jj = sqlite3Strlen30(zTemp);
1292 }else{
1293 zTemp[0] = 0;
1294 jj = 0;
1296 return jj;
1298 #endif /* SQLITE_DEBUG */
1300 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
1302 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
1303 ** that can be displayed in the P4 column of EXPLAIN output.
1305 static void displayP4Expr(StrAccum *p, Expr *pExpr){
1306 const char *zOp = 0;
1307 switch( pExpr->op ){
1308 case TK_STRING:
1309 sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
1310 break;
1311 case TK_INTEGER:
1312 sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
1313 break;
1314 case TK_NULL:
1315 sqlite3_str_appendf(p, "NULL");
1316 break;
1317 case TK_REGISTER: {
1318 sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
1319 break;
1321 case TK_COLUMN: {
1322 if( pExpr->iColumn<0 ){
1323 sqlite3_str_appendf(p, "rowid");
1324 }else{
1325 sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
1327 break;
1329 case TK_LT: zOp = "LT"; break;
1330 case TK_LE: zOp = "LE"; break;
1331 case TK_GT: zOp = "GT"; break;
1332 case TK_GE: zOp = "GE"; break;
1333 case TK_NE: zOp = "NE"; break;
1334 case TK_EQ: zOp = "EQ"; break;
1335 case TK_IS: zOp = "IS"; break;
1336 case TK_ISNOT: zOp = "ISNOT"; break;
1337 case TK_AND: zOp = "AND"; break;
1338 case TK_OR: zOp = "OR"; break;
1339 case TK_PLUS: zOp = "ADD"; break;
1340 case TK_STAR: zOp = "MUL"; break;
1341 case TK_MINUS: zOp = "SUB"; break;
1342 case TK_REM: zOp = "REM"; break;
1343 case TK_BITAND: zOp = "BITAND"; break;
1344 case TK_BITOR: zOp = "BITOR"; break;
1345 case TK_SLASH: zOp = "DIV"; break;
1346 case TK_LSHIFT: zOp = "LSHIFT"; break;
1347 case TK_RSHIFT: zOp = "RSHIFT"; break;
1348 case TK_CONCAT: zOp = "CONCAT"; break;
1349 case TK_UMINUS: zOp = "MINUS"; break;
1350 case TK_UPLUS: zOp = "PLUS"; break;
1351 case TK_BITNOT: zOp = "BITNOT"; break;
1352 case TK_NOT: zOp = "NOT"; break;
1353 case TK_ISNULL: zOp = "ISNULL"; break;
1354 case TK_NOTNULL: zOp = "NOTNULL"; break;
1356 default:
1357 sqlite3_str_appendf(p, "%s", "expr");
1358 break;
1361 if( zOp ){
1362 sqlite3_str_appendf(p, "%s(", zOp);
1363 displayP4Expr(p, pExpr->pLeft);
1364 if( pExpr->pRight ){
1365 sqlite3_str_append(p, ",", 1);
1366 displayP4Expr(p, pExpr->pRight);
1368 sqlite3_str_append(p, ")", 1);
1371 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
1374 #if VDBE_DISPLAY_P4
1376 ** Compute a string that describes the P4 parameter for an opcode.
1377 ** Use zTemp for any required temporary buffer space.
1379 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1380 char *zP4 = zTemp;
1381 StrAccum x;
1382 assert( nTemp>=20 );
1383 sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
1384 switch( pOp->p4type ){
1385 case P4_KEYINFO: {
1386 int j;
1387 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
1388 assert( pKeyInfo->aSortOrder!=0 );
1389 sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
1390 for(j=0; j<pKeyInfo->nKeyField; j++){
1391 CollSeq *pColl = pKeyInfo->aColl[j];
1392 const char *zColl = pColl ? pColl->zName : "";
1393 if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
1394 sqlite3_str_appendf(&x, ",%s%s",
1395 pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
1397 sqlite3_str_append(&x, ")", 1);
1398 break;
1400 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1401 case P4_EXPR: {
1402 displayP4Expr(&x, pOp->p4.pExpr);
1403 break;
1405 #endif
1406 case P4_COLLSEQ: {
1407 CollSeq *pColl = pOp->p4.pColl;
1408 sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
1409 break;
1411 case P4_FUNCDEF: {
1412 FuncDef *pDef = pOp->p4.pFunc;
1413 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1414 break;
1416 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1417 case P4_FUNCCTX: {
1418 FuncDef *pDef = pOp->p4.pCtx->pFunc;
1419 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1420 break;
1422 #endif
1423 case P4_INT64: {
1424 sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
1425 break;
1427 case P4_INT32: {
1428 sqlite3_str_appendf(&x, "%d", pOp->p4.i);
1429 break;
1431 case P4_REAL: {
1432 sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
1433 break;
1435 case P4_MEM: {
1436 Mem *pMem = pOp->p4.pMem;
1437 if( pMem->flags & MEM_Str ){
1438 zP4 = pMem->z;
1439 }else if( pMem->flags & MEM_Int ){
1440 sqlite3_str_appendf(&x, "%lld", pMem->u.i);
1441 }else if( pMem->flags & MEM_Real ){
1442 sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
1443 }else if( pMem->flags & MEM_Null ){
1444 zP4 = "NULL";
1445 }else{
1446 assert( pMem->flags & MEM_Blob );
1447 zP4 = "(blob)";
1449 break;
1451 #ifndef SQLITE_OMIT_VIRTUALTABLE
1452 case P4_VTAB: {
1453 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
1454 sqlite3_str_appendf(&x, "vtab:%p", pVtab);
1455 break;
1457 #endif
1458 case P4_INTARRAY: {
1459 int i;
1460 int *ai = pOp->p4.ai;
1461 int n = ai[0]; /* The first element of an INTARRAY is always the
1462 ** count of the number of elements to follow */
1463 for(i=1; i<=n; i++){
1464 sqlite3_str_appendf(&x, ",%d", ai[i]);
1466 zTemp[0] = '[';
1467 sqlite3_str_append(&x, "]", 1);
1468 break;
1470 case P4_SUBPROGRAM: {
1471 sqlite3_str_appendf(&x, "program");
1472 break;
1474 case P4_DYNBLOB:
1475 case P4_ADVANCE: {
1476 zTemp[0] = 0;
1477 break;
1479 case P4_TABLE: {
1480 sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
1481 break;
1483 default: {
1484 zP4 = pOp->p4.z;
1485 if( zP4==0 ){
1486 zP4 = zTemp;
1487 zTemp[0] = 0;
1491 sqlite3StrAccumFinish(&x);
1492 assert( zP4!=0 );
1493 return zP4;
1495 #endif /* VDBE_DISPLAY_P4 */
1498 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
1500 ** The prepared statements need to know in advance the complete set of
1501 ** attached databases that will be use. A mask of these databases
1502 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
1503 ** p->btreeMask of databases that will require a lock.
1505 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
1506 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
1507 assert( i<(int)sizeof(p->btreeMask)*8 );
1508 DbMaskSet(p->btreeMask, i);
1509 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
1510 DbMaskSet(p->lockMask, i);
1514 #if !defined(SQLITE_OMIT_SHARED_CACHE)
1516 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1517 ** this routine obtains the mutex associated with each BtShared structure
1518 ** that may be accessed by the VM passed as an argument. In doing so it also
1519 ** sets the BtShared.db member of each of the BtShared structures, ensuring
1520 ** that the correct busy-handler callback is invoked if required.
1522 ** If SQLite is not threadsafe but does support shared-cache mode, then
1523 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1524 ** of all of BtShared structures accessible via the database handle
1525 ** associated with the VM.
1527 ** If SQLite is not threadsafe and does not support shared-cache mode, this
1528 ** function is a no-op.
1530 ** The p->btreeMask field is a bitmask of all btrees that the prepared
1531 ** statement p will ever use. Let N be the number of bits in p->btreeMask
1532 ** corresponding to btrees that use shared cache. Then the runtime of
1533 ** this routine is N*N. But as N is rarely more than 1, this should not
1534 ** be a problem.
1536 void sqlite3VdbeEnter(Vdbe *p){
1537 int i;
1538 sqlite3 *db;
1539 Db *aDb;
1540 int nDb;
1541 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
1542 db = p->db;
1543 aDb = db->aDb;
1544 nDb = db->nDb;
1545 for(i=0; i<nDb; i++){
1546 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1547 sqlite3BtreeEnter(aDb[i].pBt);
1551 #endif
1553 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1555 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1557 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
1558 int i;
1559 sqlite3 *db;
1560 Db *aDb;
1561 int nDb;
1562 db = p->db;
1563 aDb = db->aDb;
1564 nDb = db->nDb;
1565 for(i=0; i<nDb; i++){
1566 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1567 sqlite3BtreeLeave(aDb[i].pBt);
1571 void sqlite3VdbeLeave(Vdbe *p){
1572 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
1573 vdbeLeave(p);
1575 #endif
1577 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1579 ** Print a single opcode. This routine is used for debugging only.
1581 void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
1582 char *zP4;
1583 char zPtr[50];
1584 char zCom[100];
1585 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
1586 if( pOut==0 ) pOut = stdout;
1587 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
1588 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1589 displayComment(pOp, zP4, zCom, sizeof(zCom));
1590 #else
1591 zCom[0] = 0;
1592 #endif
1593 /* NB: The sqlite3OpcodeName() function is implemented by code created
1594 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1595 ** information from the vdbe.c source text */
1596 fprintf(pOut, zFormat1, pc,
1597 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
1598 zCom
1600 fflush(pOut);
1602 #endif
1605 ** Initialize an array of N Mem element.
1607 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
1608 while( (N--)>0 ){
1609 p->db = db;
1610 p->flags = flags;
1611 p->szMalloc = 0;
1612 #ifdef SQLITE_DEBUG
1613 p->pScopyFrom = 0;
1614 #endif
1615 p++;
1620 ** Release an array of N Mem elements
1622 static void releaseMemArray(Mem *p, int N){
1623 if( p && N ){
1624 Mem *pEnd = &p[N];
1625 sqlite3 *db = p->db;
1626 if( db->pnBytesFreed ){
1628 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
1629 }while( (++p)<pEnd );
1630 return;
1633 assert( (&p[1])==pEnd || p[0].db==p[1].db );
1634 assert( sqlite3VdbeCheckMemInvariants(p) );
1636 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1637 ** that takes advantage of the fact that the memory cell value is
1638 ** being set to NULL after releasing any dynamic resources.
1640 ** The justification for duplicating code is that according to
1641 ** callgrind, this causes a certain test case to hit the CPU 4.7
1642 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1643 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1644 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1645 ** with no indexes using a single prepared INSERT statement, bind()
1646 ** and reset(). Inserts are grouped into a transaction.
1648 testcase( p->flags & MEM_Agg );
1649 testcase( p->flags & MEM_Dyn );
1650 testcase( p->flags & MEM_Frame );
1651 testcase( p->flags & MEM_RowSet );
1652 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
1653 sqlite3VdbeMemRelease(p);
1654 }else if( p->szMalloc ){
1655 sqlite3DbFreeNN(db, p->zMalloc);
1656 p->szMalloc = 0;
1659 p->flags = MEM_Undefined;
1660 }while( (++p)<pEnd );
1665 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1666 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1668 void sqlite3VdbeFrameDelete(VdbeFrame *p){
1669 int i;
1670 Mem *aMem = VdbeFrameMem(p);
1671 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1672 for(i=0; i<p->nChildCsr; i++){
1673 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1675 releaseMemArray(aMem, p->nChildMem);
1676 sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
1677 sqlite3DbFree(p->v->db, p);
1680 #ifndef SQLITE_OMIT_EXPLAIN
1682 ** Give a listing of the program in the virtual machine.
1684 ** The interface is the same as sqlite3VdbeExec(). But instead of
1685 ** running the code, it invokes the callback once for each instruction.
1686 ** This feature is used to implement "EXPLAIN".
1688 ** When p->explain==1, each instruction is listed. When
1689 ** p->explain==2, only OP_Explain instructions are listed and these
1690 ** are shown in a different format. p->explain==2 is used to implement
1691 ** EXPLAIN QUERY PLAN.
1692 ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
1693 ** are also shown, so that the boundaries between the main program and
1694 ** each trigger are clear.
1696 ** When p->explain==1, first the main program is listed, then each of
1697 ** the trigger subprograms are listed one by one.
1699 int sqlite3VdbeList(
1700 Vdbe *p /* The VDBE */
1702 int nRow; /* Stop when row count reaches this */
1703 int nSub = 0; /* Number of sub-vdbes seen so far */
1704 SubProgram **apSub = 0; /* Array of sub-vdbes */
1705 Mem *pSub = 0; /* Memory cell hold array of subprogs */
1706 sqlite3 *db = p->db; /* The database connection */
1707 int i; /* Loop counter */
1708 int rc = SQLITE_OK; /* Return code */
1709 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
1710 int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
1711 Op *pOp = 0;
1713 assert( p->explain );
1714 assert( p->magic==VDBE_MAGIC_RUN );
1715 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
1717 /* Even though this opcode does not use dynamic strings for
1718 ** the result, result columns may become dynamic if the user calls
1719 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1721 releaseMemArray(pMem, 8);
1722 p->pResultSet = 0;
1724 if( p->rc==SQLITE_NOMEM ){
1725 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1726 ** sqlite3_column_text16() failed. */
1727 sqlite3OomFault(db);
1728 return SQLITE_ERROR;
1731 /* When the number of output rows reaches nRow, that means the
1732 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1733 ** nRow is the sum of the number of rows in the main program, plus
1734 ** the sum of the number of rows in all trigger subprograms encountered
1735 ** so far. The nRow value will increase as new trigger subprograms are
1736 ** encountered, but p->pc will eventually catch up to nRow.
1738 nRow = p->nOp;
1739 if( bListSubprogs ){
1740 /* The first 8 memory cells are used for the result set. So we will
1741 ** commandeer the 9th cell to use as storage for an array of pointers
1742 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1743 ** cells. */
1744 assert( p->nMem>9 );
1745 pSub = &p->aMem[9];
1746 if( pSub->flags&MEM_Blob ){
1747 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1748 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1749 nSub = pSub->n/sizeof(Vdbe*);
1750 apSub = (SubProgram **)pSub->z;
1752 for(i=0; i<nSub; i++){
1753 nRow += apSub[i]->nOp;
1757 while(1){ /* Loop exits via break */
1758 i = p->pc++;
1759 if( i>=nRow ){
1760 p->rc = SQLITE_OK;
1761 rc = SQLITE_DONE;
1762 break;
1764 if( i<p->nOp ){
1765 /* The output line number is small enough that we are still in the
1766 ** main program. */
1767 pOp = &p->aOp[i];
1768 }else{
1769 /* We are currently listing subprograms. Figure out which one and
1770 ** pick up the appropriate opcode. */
1771 int j;
1772 i -= p->nOp;
1773 for(j=0; i>=apSub[j]->nOp; j++){
1774 i -= apSub[j]->nOp;
1776 pOp = &apSub[j]->aOp[i];
1779 /* When an OP_Program opcode is encounter (the only opcode that has
1780 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1781 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1782 ** has not already been seen.
1784 if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
1785 int nByte = (nSub+1)*sizeof(SubProgram*);
1786 int j;
1787 for(j=0; j<nSub; j++){
1788 if( apSub[j]==pOp->p4.pProgram ) break;
1790 if( j==nSub ){
1791 p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
1792 if( p->rc!=SQLITE_OK ){
1793 rc = SQLITE_ERROR;
1794 break;
1796 apSub = (SubProgram **)pSub->z;
1797 apSub[nSub++] = pOp->p4.pProgram;
1798 pSub->flags |= MEM_Blob;
1799 pSub->n = nSub*sizeof(SubProgram*);
1800 nRow += pOp->p4.pProgram->nOp;
1803 if( p->explain<2 ) break;
1804 if( pOp->opcode==OP_Explain ) break;
1805 if( pOp->opcode==OP_Init && p->pc>1 ) break;
1808 if( rc==SQLITE_OK ){
1809 if( db->u1.isInterrupted ){
1810 p->rc = SQLITE_INTERRUPT;
1811 rc = SQLITE_ERROR;
1812 sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
1813 }else{
1814 char *zP4;
1815 if( p->explain==1 ){
1816 pMem->flags = MEM_Int;
1817 pMem->u.i = i; /* Program counter */
1818 pMem++;
1820 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
1821 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
1822 assert( pMem->z!=0 );
1823 pMem->n = sqlite3Strlen30(pMem->z);
1824 pMem->enc = SQLITE_UTF8;
1825 pMem++;
1828 pMem->flags = MEM_Int;
1829 pMem->u.i = pOp->p1; /* P1 */
1830 pMem++;
1832 pMem->flags = MEM_Int;
1833 pMem->u.i = pOp->p2; /* P2 */
1834 pMem++;
1836 pMem->flags = MEM_Int;
1837 pMem->u.i = pOp->p3; /* P3 */
1838 pMem++;
1840 if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
1841 assert( p->db->mallocFailed );
1842 return SQLITE_ERROR;
1844 pMem->flags = MEM_Str|MEM_Term;
1845 zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
1846 if( zP4!=pMem->z ){
1847 pMem->n = 0;
1848 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
1849 }else{
1850 assert( pMem->z!=0 );
1851 pMem->n = sqlite3Strlen30(pMem->z);
1852 pMem->enc = SQLITE_UTF8;
1854 pMem++;
1856 if( p->explain==1 ){
1857 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
1858 assert( p->db->mallocFailed );
1859 return SQLITE_ERROR;
1861 pMem->flags = MEM_Str|MEM_Term;
1862 pMem->n = 2;
1863 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
1864 pMem->enc = SQLITE_UTF8;
1865 pMem++;
1867 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1868 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
1869 assert( p->db->mallocFailed );
1870 return SQLITE_ERROR;
1872 pMem->flags = MEM_Str|MEM_Term;
1873 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
1874 pMem->enc = SQLITE_UTF8;
1875 #else
1876 pMem->flags = MEM_Null; /* Comment */
1877 #endif
1880 p->nResColumn = 8 - 4*(p->explain-1);
1881 p->pResultSet = &p->aMem[1];
1882 p->rc = SQLITE_OK;
1883 rc = SQLITE_ROW;
1886 return rc;
1888 #endif /* SQLITE_OMIT_EXPLAIN */
1890 #ifdef SQLITE_DEBUG
1892 ** Print the SQL that was used to generate a VDBE program.
1894 void sqlite3VdbePrintSql(Vdbe *p){
1895 const char *z = 0;
1896 if( p->zSql ){
1897 z = p->zSql;
1898 }else if( p->nOp>=1 ){
1899 const VdbeOp *pOp = &p->aOp[0];
1900 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1901 z = pOp->p4.z;
1902 while( sqlite3Isspace(*z) ) z++;
1905 if( z ) printf("SQL: [%s]\n", z);
1907 #endif
1909 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1911 ** Print an IOTRACE message showing SQL content.
1913 void sqlite3VdbeIOTraceSql(Vdbe *p){
1914 int nOp = p->nOp;
1915 VdbeOp *pOp;
1916 if( sqlite3IoTrace==0 ) return;
1917 if( nOp<1 ) return;
1918 pOp = &p->aOp[0];
1919 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
1920 int i, j;
1921 char z[1000];
1922 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
1923 for(i=0; sqlite3Isspace(z[i]); i++){}
1924 for(j=0; z[i]; i++){
1925 if( sqlite3Isspace(z[i]) ){
1926 if( z[i-1]!=' ' ){
1927 z[j++] = ' ';
1929 }else{
1930 z[j++] = z[i];
1933 z[j] = 0;
1934 sqlite3IoTrace("SQL %s\n", z);
1937 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1939 /* An instance of this object describes bulk memory available for use
1940 ** by subcomponents of a prepared statement. Space is allocated out
1941 ** of a ReusableSpace object by the allocSpace() routine below.
1943 struct ReusableSpace {
1944 u8 *pSpace; /* Available memory */
1945 int nFree; /* Bytes of available memory */
1946 int nNeeded; /* Total bytes that could not be allocated */
1949 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
1950 ** from the ReusableSpace object. Return a pointer to the allocated
1951 ** memory on success. If insufficient memory is available in the
1952 ** ReusableSpace object, increase the ReusableSpace.nNeeded
1953 ** value by the amount needed and return NULL.
1955 ** If pBuf is not initially NULL, that means that the memory has already
1956 ** been allocated by a prior call to this routine, so just return a copy
1957 ** of pBuf and leave ReusableSpace unchanged.
1959 ** This allocator is employed to repurpose unused slots at the end of the
1960 ** opcode array of prepared state for other memory needs of the prepared
1961 ** statement.
1963 static void *allocSpace(
1964 struct ReusableSpace *p, /* Bulk memory available for allocation */
1965 void *pBuf, /* Pointer to a prior allocation */
1966 int nByte /* Bytes of memory needed */
1968 assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
1969 if( pBuf==0 ){
1970 nByte = ROUND8(nByte);
1971 if( nByte <= p->nFree ){
1972 p->nFree -= nByte;
1973 pBuf = &p->pSpace[p->nFree];
1974 }else{
1975 p->nNeeded += nByte;
1978 assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
1979 return pBuf;
1983 ** Rewind the VDBE back to the beginning in preparation for
1984 ** running it.
1986 void sqlite3VdbeRewind(Vdbe *p){
1987 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1988 int i;
1989 #endif
1990 assert( p!=0 );
1991 assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
1993 /* There should be at least one opcode.
1995 assert( p->nOp>0 );
1997 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
1998 p->magic = VDBE_MAGIC_RUN;
2000 #ifdef SQLITE_DEBUG
2001 for(i=0; i<p->nMem; i++){
2002 assert( p->aMem[i].db==p->db );
2004 #endif
2005 p->pc = -1;
2006 p->rc = SQLITE_OK;
2007 p->errorAction = OE_Abort;
2008 p->nChange = 0;
2009 p->cacheCtr = 1;
2010 p->minWriteFileFormat = 255;
2011 p->iStatement = 0;
2012 p->nFkConstraint = 0;
2013 #ifdef VDBE_PROFILE
2014 for(i=0; i<p->nOp; i++){
2015 p->aOp[i].cnt = 0;
2016 p->aOp[i].cycles = 0;
2018 #endif
2022 ** Prepare a virtual machine for execution for the first time after
2023 ** creating the virtual machine. This involves things such
2024 ** as allocating registers and initializing the program counter.
2025 ** After the VDBE has be prepped, it can be executed by one or more
2026 ** calls to sqlite3VdbeExec().
2028 ** This function may be called exactly once on each virtual machine.
2029 ** After this routine is called the VM has been "packaged" and is ready
2030 ** to run. After this routine is called, further calls to
2031 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
2032 ** the Vdbe from the Parse object that helped generate it so that the
2033 ** the Vdbe becomes an independent entity and the Parse object can be
2034 ** destroyed.
2036 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
2037 ** to its initial state after it has been run.
2039 void sqlite3VdbeMakeReady(
2040 Vdbe *p, /* The VDBE */
2041 Parse *pParse /* Parsing context */
2043 sqlite3 *db; /* The database connection */
2044 int nVar; /* Number of parameters */
2045 int nMem; /* Number of VM memory registers */
2046 int nCursor; /* Number of cursors required */
2047 int nArg; /* Number of arguments in subprograms */
2048 int n; /* Loop counter */
2049 struct ReusableSpace x; /* Reusable bulk memory */
2051 assert( p!=0 );
2052 assert( p->nOp>0 );
2053 assert( pParse!=0 );
2054 assert( p->magic==VDBE_MAGIC_INIT );
2055 assert( pParse==p->pParse );
2056 db = p->db;
2057 assert( db->mallocFailed==0 );
2058 nVar = pParse->nVar;
2059 nMem = pParse->nMem;
2060 nCursor = pParse->nTab;
2061 nArg = pParse->nMaxArg;
2063 /* Each cursor uses a memory cell. The first cursor (cursor 0) can
2064 ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
2065 ** space at the end of aMem[] for cursors 1 and greater.
2066 ** See also: allocateCursor().
2068 nMem += nCursor;
2069 if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
2071 /* Figure out how much reusable memory is available at the end of the
2072 ** opcode array. This extra memory will be reallocated for other elements
2073 ** of the prepared statement.
2075 n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
2076 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
2077 assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
2078 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
2079 assert( x.nFree>=0 );
2080 assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
2082 resolveP2Values(p, &nArg);
2083 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
2084 if( pParse->explain && nMem<10 ){
2085 nMem = 10;
2087 p->expired = 0;
2089 /* Memory for registers, parameters, cursor, etc, is allocated in one or two
2090 ** passes. On the first pass, we try to reuse unused memory at the
2091 ** end of the opcode array. If we are unable to satisfy all memory
2092 ** requirements by reusing the opcode array tail, then the second
2093 ** pass will fill in the remainder using a fresh memory allocation.
2095 ** This two-pass approach that reuses as much memory as possible from
2096 ** the leftover memory at the end of the opcode array. This can significantly
2097 ** reduce the amount of memory held by a prepared statement.
2099 do {
2100 x.nNeeded = 0;
2101 p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
2102 p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
2103 p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
2104 p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
2105 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2106 p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
2107 #endif
2108 if( x.nNeeded==0 ) break;
2109 x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
2110 x.nFree = x.nNeeded;
2111 }while( !db->mallocFailed );
2113 p->pVList = pParse->pVList;
2114 pParse->pVList = 0;
2115 p->explain = pParse->explain;
2116 if( db->mallocFailed ){
2117 p->nVar = 0;
2118 p->nCursor = 0;
2119 p->nMem = 0;
2120 }else{
2121 p->nCursor = nCursor;
2122 p->nVar = (ynVar)nVar;
2123 initMemArray(p->aVar, nVar, db, MEM_Null);
2124 p->nMem = nMem;
2125 initMemArray(p->aMem, nMem, db, MEM_Undefined);
2126 memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
2127 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2128 memset(p->anExec, 0, p->nOp*sizeof(i64));
2129 #endif
2131 sqlite3VdbeRewind(p);
2135 ** Close a VDBE cursor and release all the resources that cursor
2136 ** happens to hold.
2138 void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
2139 if( pCx==0 ){
2140 return;
2142 assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
2143 switch( pCx->eCurType ){
2144 case CURTYPE_SORTER: {
2145 sqlite3VdbeSorterClose(p->db, pCx);
2146 break;
2148 case CURTYPE_BTREE: {
2149 if( pCx->isEphemeral ){
2150 if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
2151 /* The pCx->pCursor will be close automatically, if it exists, by
2152 ** the call above. */
2153 }else{
2154 assert( pCx->uc.pCursor!=0 );
2155 sqlite3BtreeCloseCursor(pCx->uc.pCursor);
2157 break;
2159 #ifndef SQLITE_OMIT_VIRTUALTABLE
2160 case CURTYPE_VTAB: {
2161 sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
2162 const sqlite3_module *pModule = pVCur->pVtab->pModule;
2163 assert( pVCur->pVtab->nRef>0 );
2164 pVCur->pVtab->nRef--;
2165 pModule->xClose(pVCur);
2166 break;
2168 #endif
2173 ** Close all cursors in the current frame.
2175 static void closeCursorsInFrame(Vdbe *p){
2176 if( p->apCsr ){
2177 int i;
2178 for(i=0; i<p->nCursor; i++){
2179 VdbeCursor *pC = p->apCsr[i];
2180 if( pC ){
2181 sqlite3VdbeFreeCursor(p, pC);
2182 p->apCsr[i] = 0;
2189 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
2190 ** is used, for example, when a trigger sub-program is halted to restore
2191 ** control to the main program.
2193 int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
2194 Vdbe *v = pFrame->v;
2195 closeCursorsInFrame(v);
2196 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2197 v->anExec = pFrame->anExec;
2198 #endif
2199 v->aOp = pFrame->aOp;
2200 v->nOp = pFrame->nOp;
2201 v->aMem = pFrame->aMem;
2202 v->nMem = pFrame->nMem;
2203 v->apCsr = pFrame->apCsr;
2204 v->nCursor = pFrame->nCursor;
2205 v->db->lastRowid = pFrame->lastRowid;
2206 v->nChange = pFrame->nChange;
2207 v->db->nChange = pFrame->nDbChange;
2208 sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
2209 v->pAuxData = pFrame->pAuxData;
2210 pFrame->pAuxData = 0;
2211 return pFrame->pc;
2215 ** Close all cursors.
2217 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
2218 ** cell array. This is necessary as the memory cell array may contain
2219 ** pointers to VdbeFrame objects, which may in turn contain pointers to
2220 ** open cursors.
2222 static void closeAllCursors(Vdbe *p){
2223 if( p->pFrame ){
2224 VdbeFrame *pFrame;
2225 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2226 sqlite3VdbeFrameRestore(pFrame);
2227 p->pFrame = 0;
2228 p->nFrame = 0;
2230 assert( p->nFrame==0 );
2231 closeCursorsInFrame(p);
2232 if( p->aMem ){
2233 releaseMemArray(p->aMem, p->nMem);
2235 while( p->pDelFrame ){
2236 VdbeFrame *pDel = p->pDelFrame;
2237 p->pDelFrame = pDel->pParent;
2238 sqlite3VdbeFrameDelete(pDel);
2241 /* Delete any auxdata allocations made by the VM */
2242 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
2243 assert( p->pAuxData==0 );
2247 ** Set the number of result columns that will be returned by this SQL
2248 ** statement. This is now set at compile time, rather than during
2249 ** execution of the vdbe program so that sqlite3_column_count() can
2250 ** be called on an SQL statement before sqlite3_step().
2252 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
2253 int n;
2254 sqlite3 *db = p->db;
2256 if( p->nResColumn ){
2257 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2258 sqlite3DbFree(db, p->aColName);
2260 n = nResColumn*COLNAME_N;
2261 p->nResColumn = (u16)nResColumn;
2262 p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
2263 if( p->aColName==0 ) return;
2264 initMemArray(p->aColName, n, db, MEM_Null);
2268 ** Set the name of the idx'th column to be returned by the SQL statement.
2269 ** zName must be a pointer to a nul terminated string.
2271 ** This call must be made after a call to sqlite3VdbeSetNumCols().
2273 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
2274 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
2275 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
2277 int sqlite3VdbeSetColName(
2278 Vdbe *p, /* Vdbe being configured */
2279 int idx, /* Index of column zName applies to */
2280 int var, /* One of the COLNAME_* constants */
2281 const char *zName, /* Pointer to buffer containing name */
2282 void (*xDel)(void*) /* Memory management strategy for zName */
2284 int rc;
2285 Mem *pColName;
2286 assert( idx<p->nResColumn );
2287 assert( var<COLNAME_N );
2288 if( p->db->mallocFailed ){
2289 assert( !zName || xDel!=SQLITE_DYNAMIC );
2290 return SQLITE_NOMEM_BKPT;
2292 assert( p->aColName!=0 );
2293 pColName = &(p->aColName[idx+var*p->nResColumn]);
2294 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
2295 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
2296 return rc;
2300 ** A read or write transaction may or may not be active on database handle
2301 ** db. If a transaction is active, commit it. If there is a
2302 ** write-transaction spanning more than one database file, this routine
2303 ** takes care of the master journal trickery.
2305 static int vdbeCommit(sqlite3 *db, Vdbe *p){
2306 int i;
2307 int nTrans = 0; /* Number of databases with an active write-transaction
2308 ** that are candidates for a two-phase commit using a
2309 ** master-journal */
2310 int rc = SQLITE_OK;
2311 int needXcommit = 0;
2313 #ifdef SQLITE_OMIT_VIRTUALTABLE
2314 /* With this option, sqlite3VtabSync() is defined to be simply
2315 ** SQLITE_OK so p is not used.
2317 UNUSED_PARAMETER(p);
2318 #endif
2320 /* Before doing anything else, call the xSync() callback for any
2321 ** virtual module tables written in this transaction. This has to
2322 ** be done before determining whether a master journal file is
2323 ** required, as an xSync() callback may add an attached database
2324 ** to the transaction.
2326 rc = sqlite3VtabSync(db, p);
2328 /* This loop determines (a) if the commit hook should be invoked and
2329 ** (b) how many database files have open write transactions, not
2330 ** including the temp database. (b) is important because if more than
2331 ** one database file has an open write transaction, a master journal
2332 ** file is required for an atomic commit.
2334 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2335 Btree *pBt = db->aDb[i].pBt;
2336 if( sqlite3BtreeIsInTrans(pBt) ){
2337 /* Whether or not a database might need a master journal depends upon
2338 ** its journal mode (among other things). This matrix determines which
2339 ** journal modes use a master journal and which do not */
2340 static const u8 aMJNeeded[] = {
2341 /* DELETE */ 1,
2342 /* PERSIST */ 1,
2343 /* OFF */ 0,
2344 /* TRUNCATE */ 1,
2345 /* MEMORY */ 0,
2346 /* WAL */ 0
2348 Pager *pPager; /* Pager associated with pBt */
2349 needXcommit = 1;
2350 sqlite3BtreeEnter(pBt);
2351 pPager = sqlite3BtreePager(pBt);
2352 if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
2353 && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
2354 && sqlite3PagerIsMemdb(pPager)==0
2356 assert( i!=1 );
2357 nTrans++;
2359 rc = sqlite3PagerExclusiveLock(pPager);
2360 sqlite3BtreeLeave(pBt);
2363 if( rc!=SQLITE_OK ){
2364 return rc;
2367 /* If there are any write-transactions at all, invoke the commit hook */
2368 if( needXcommit && db->xCommitCallback ){
2369 rc = db->xCommitCallback(db->pCommitArg);
2370 if( rc ){
2371 return SQLITE_CONSTRAINT_COMMITHOOK;
2375 /* The simple case - no more than one database file (not counting the
2376 ** TEMP database) has a transaction active. There is no need for the
2377 ** master-journal.
2379 ** If the return value of sqlite3BtreeGetFilename() is a zero length
2380 ** string, it means the main database is :memory: or a temp file. In
2381 ** that case we do not support atomic multi-file commits, so use the
2382 ** simple case then too.
2384 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
2385 || nTrans<=1
2387 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2388 Btree *pBt = db->aDb[i].pBt;
2389 if( pBt ){
2390 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
2394 /* Do the commit only if all databases successfully complete phase 1.
2395 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2396 ** IO error while deleting or truncating a journal file. It is unlikely,
2397 ** but could happen. In this case abandon processing and return the error.
2399 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2400 Btree *pBt = db->aDb[i].pBt;
2401 if( pBt ){
2402 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
2405 if( rc==SQLITE_OK ){
2406 sqlite3VtabCommit(db);
2410 /* The complex case - There is a multi-file write-transaction active.
2411 ** This requires a master journal file to ensure the transaction is
2412 ** committed atomically.
2414 #ifndef SQLITE_OMIT_DISKIO
2415 else{
2416 sqlite3_vfs *pVfs = db->pVfs;
2417 char *zMaster = 0; /* File-name for the master journal */
2418 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
2419 sqlite3_file *pMaster = 0;
2420 i64 offset = 0;
2421 int res;
2422 int retryCount = 0;
2423 int nMainFile;
2425 /* Select a master journal file name */
2426 nMainFile = sqlite3Strlen30(zMainFile);
2427 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
2428 if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
2429 do {
2430 u32 iRandom;
2431 if( retryCount ){
2432 if( retryCount>100 ){
2433 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2434 sqlite3OsDelete(pVfs, zMaster, 0);
2435 break;
2436 }else if( retryCount==1 ){
2437 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2440 retryCount++;
2441 sqlite3_randomness(sizeof(iRandom), &iRandom);
2442 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
2443 (iRandom>>8)&0xffffff, iRandom&0xff);
2444 /* The antipenultimate character of the master journal name must
2445 ** be "9" to avoid name collisions when using 8+3 filenames. */
2446 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
2447 sqlite3FileSuffix3(zMainFile, zMaster);
2448 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2449 }while( rc==SQLITE_OK && res );
2450 if( rc==SQLITE_OK ){
2451 /* Open the master journal. */
2452 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2453 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2454 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2457 if( rc!=SQLITE_OK ){
2458 sqlite3DbFree(db, zMaster);
2459 return rc;
2462 /* Write the name of each database file in the transaction into the new
2463 ** master journal file. If an error occurs at this point close
2464 ** and delete the master journal file. All the individual journal files
2465 ** still have 'null' as the master journal pointer, so they will roll
2466 ** back independently if a failure occurs.
2468 for(i=0; i<db->nDb; i++){
2469 Btree *pBt = db->aDb[i].pBt;
2470 if( sqlite3BtreeIsInTrans(pBt) ){
2471 char const *zFile = sqlite3BtreeGetJournalname(pBt);
2472 if( zFile==0 ){
2473 continue; /* Ignore TEMP and :memory: databases */
2475 assert( zFile[0]!=0 );
2476 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2477 offset += sqlite3Strlen30(zFile)+1;
2478 if( rc!=SQLITE_OK ){
2479 sqlite3OsCloseFree(pMaster);
2480 sqlite3OsDelete(pVfs, zMaster, 0);
2481 sqlite3DbFree(db, zMaster);
2482 return rc;
2487 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2488 ** flag is set this is not required.
2490 if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2491 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2493 sqlite3OsCloseFree(pMaster);
2494 sqlite3OsDelete(pVfs, zMaster, 0);
2495 sqlite3DbFree(db, zMaster);
2496 return rc;
2499 /* Sync all the db files involved in the transaction. The same call
2500 ** sets the master journal pointer in each individual journal. If
2501 ** an error occurs here, do not delete the master journal file.
2503 ** If the error occurs during the first call to
2504 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2505 ** master journal file will be orphaned. But we cannot delete it,
2506 ** in case the master journal file name was written into the journal
2507 ** file before the failure occurred.
2509 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2510 Btree *pBt = db->aDb[i].pBt;
2511 if( pBt ){
2512 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
2515 sqlite3OsCloseFree(pMaster);
2516 assert( rc!=SQLITE_BUSY );
2517 if( rc!=SQLITE_OK ){
2518 sqlite3DbFree(db, zMaster);
2519 return rc;
2522 /* Delete the master journal file. This commits the transaction. After
2523 ** doing this the directory is synced again before any individual
2524 ** transaction files are deleted.
2526 rc = sqlite3OsDelete(pVfs, zMaster, 1);
2527 sqlite3DbFree(db, zMaster);
2528 zMaster = 0;
2529 if( rc ){
2530 return rc;
2533 /* All files and directories have already been synced, so the following
2534 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2535 ** deleting or truncating journals. If something goes wrong while
2536 ** this is happening we don't really care. The integrity of the
2537 ** transaction is already guaranteed, but some stray 'cold' journals
2538 ** may be lying around. Returning an error code won't help matters.
2540 disable_simulated_io_errors();
2541 sqlite3BeginBenignMalloc();
2542 for(i=0; i<db->nDb; i++){
2543 Btree *pBt = db->aDb[i].pBt;
2544 if( pBt ){
2545 sqlite3BtreeCommitPhaseTwo(pBt, 1);
2548 sqlite3EndBenignMalloc();
2549 enable_simulated_io_errors();
2551 sqlite3VtabCommit(db);
2553 #endif
2555 return rc;
2559 ** This routine checks that the sqlite3.nVdbeActive count variable
2560 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
2561 ** currently active. An assertion fails if the two counts do not match.
2562 ** This is an internal self-check only - it is not an essential processing
2563 ** step.
2565 ** This is a no-op if NDEBUG is defined.
2567 #ifndef NDEBUG
2568 static void checkActiveVdbeCnt(sqlite3 *db){
2569 Vdbe *p;
2570 int cnt = 0;
2571 int nWrite = 0;
2572 int nRead = 0;
2573 p = db->pVdbe;
2574 while( p ){
2575 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
2576 cnt++;
2577 if( p->readOnly==0 ) nWrite++;
2578 if( p->bIsReader ) nRead++;
2580 p = p->pNext;
2582 assert( cnt==db->nVdbeActive );
2583 assert( nWrite==db->nVdbeWrite );
2584 assert( nRead==db->nVdbeRead );
2586 #else
2587 #define checkActiveVdbeCnt(x)
2588 #endif
2591 ** If the Vdbe passed as the first argument opened a statement-transaction,
2592 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2593 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2594 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2595 ** statement transaction is committed.
2597 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2598 ** Otherwise SQLITE_OK.
2600 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
2601 sqlite3 *const db = p->db;
2602 int rc = SQLITE_OK;
2603 int i;
2604 const int iSavepoint = p->iStatement-1;
2606 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2607 assert( db->nStatement>0 );
2608 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2610 for(i=0; i<db->nDb; i++){
2611 int rc2 = SQLITE_OK;
2612 Btree *pBt = db->aDb[i].pBt;
2613 if( pBt ){
2614 if( eOp==SAVEPOINT_ROLLBACK ){
2615 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2617 if( rc2==SQLITE_OK ){
2618 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2620 if( rc==SQLITE_OK ){
2621 rc = rc2;
2625 db->nStatement--;
2626 p->iStatement = 0;
2628 if( rc==SQLITE_OK ){
2629 if( eOp==SAVEPOINT_ROLLBACK ){
2630 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2632 if( rc==SQLITE_OK ){
2633 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2637 /* If the statement transaction is being rolled back, also restore the
2638 ** database handles deferred constraint counter to the value it had when
2639 ** the statement transaction was opened. */
2640 if( eOp==SAVEPOINT_ROLLBACK ){
2641 db->nDeferredCons = p->nStmtDefCons;
2642 db->nDeferredImmCons = p->nStmtDefImmCons;
2644 return rc;
2646 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
2647 if( p->db->nStatement && p->iStatement ){
2648 return vdbeCloseStatement(p, eOp);
2650 return SQLITE_OK;
2655 ** This function is called when a transaction opened by the database
2656 ** handle associated with the VM passed as an argument is about to be
2657 ** committed. If there are outstanding deferred foreign key constraint
2658 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2660 ** If there are outstanding FK violations and this function returns
2661 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2662 ** and write an error message to it. Then return SQLITE_ERROR.
2664 #ifndef SQLITE_OMIT_FOREIGN_KEY
2665 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
2666 sqlite3 *db = p->db;
2667 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2668 || (!deferred && p->nFkConstraint>0)
2670 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2671 p->errorAction = OE_Abort;
2672 sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
2673 return SQLITE_ERROR;
2675 return SQLITE_OK;
2677 #endif
2680 ** This routine is called the when a VDBE tries to halt. If the VDBE
2681 ** has made changes and is in autocommit mode, then commit those
2682 ** changes. If a rollback is needed, then do the rollback.
2684 ** This routine is the only way to move the state of a VM from
2685 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2686 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2688 ** Return an error code. If the commit could not complete because of
2689 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2690 ** means the close did not happen and needs to be repeated.
2692 int sqlite3VdbeHalt(Vdbe *p){
2693 int rc; /* Used to store transient return codes */
2694 sqlite3 *db = p->db;
2696 /* This function contains the logic that determines if a statement or
2697 ** transaction will be committed or rolled back as a result of the
2698 ** execution of this virtual machine.
2700 ** If any of the following errors occur:
2702 ** SQLITE_NOMEM
2703 ** SQLITE_IOERR
2704 ** SQLITE_FULL
2705 ** SQLITE_INTERRUPT
2707 ** Then the internal cache might have been left in an inconsistent
2708 ** state. We need to rollback the statement transaction, if there is
2709 ** one, or the complete transaction if there is no statement transaction.
2712 if( p->magic!=VDBE_MAGIC_RUN ){
2713 return SQLITE_OK;
2715 if( db->mallocFailed ){
2716 p->rc = SQLITE_NOMEM_BKPT;
2718 closeAllCursors(p);
2719 checkActiveVdbeCnt(db);
2721 /* No commit or rollback needed if the program never started or if the
2722 ** SQL statement does not read or write a database file. */
2723 if( p->pc>=0 && p->bIsReader ){
2724 int mrc; /* Primary error code from p->rc */
2725 int eStatementOp = 0;
2726 int isSpecialError; /* Set to true if a 'special' error */
2728 /* Lock all btrees used by the statement */
2729 sqlite3VdbeEnter(p);
2731 /* Check for one of the special errors */
2732 mrc = p->rc & 0xff;
2733 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
2734 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
2735 if( isSpecialError ){
2736 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2737 ** no rollback is necessary. Otherwise, at least a savepoint
2738 ** transaction must be rolled back to restore the database to a
2739 ** consistent state.
2741 ** Even if the statement is read-only, it is important to perform
2742 ** a statement or transaction rollback operation. If the error
2743 ** occurred while writing to the journal, sub-journal or database
2744 ** file as part of an effort to free up cache space (see function
2745 ** pagerStress() in pager.c), the rollback is required to restore
2746 ** the pager to a consistent state.
2748 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
2749 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
2750 eStatementOp = SAVEPOINT_ROLLBACK;
2751 }else{
2752 /* We are forced to roll back the active transaction. Before doing
2753 ** so, abort any other statements this handle currently has active.
2755 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2756 sqlite3CloseSavepoints(db);
2757 db->autoCommit = 1;
2758 p->nChange = 0;
2763 /* Check for immediate foreign key violations. */
2764 if( p->rc==SQLITE_OK ){
2765 sqlite3VdbeCheckFk(p, 0);
2768 /* If the auto-commit flag is set and this is the only active writer
2769 ** VM, then we do either a commit or rollback of the current transaction.
2771 ** Note: This block also runs if one of the special errors handled
2772 ** above has occurred.
2774 if( !sqlite3VtabInSync(db)
2775 && db->autoCommit
2776 && db->nVdbeWrite==(p->readOnly==0)
2778 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
2779 rc = sqlite3VdbeCheckFk(p, 1);
2780 if( rc!=SQLITE_OK ){
2781 if( NEVER(p->readOnly) ){
2782 sqlite3VdbeLeave(p);
2783 return SQLITE_ERROR;
2785 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
2786 }else{
2787 /* The auto-commit flag is true, the vdbe program was successful
2788 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2789 ** key constraints to hold up the transaction. This means a commit
2790 ** is required. */
2791 rc = vdbeCommit(db, p);
2793 if( rc==SQLITE_BUSY && p->readOnly ){
2794 sqlite3VdbeLeave(p);
2795 return SQLITE_BUSY;
2796 }else if( rc!=SQLITE_OK ){
2797 p->rc = rc;
2798 sqlite3RollbackAll(db, SQLITE_OK);
2799 p->nChange = 0;
2800 }else{
2801 db->nDeferredCons = 0;
2802 db->nDeferredImmCons = 0;
2803 db->flags &= ~SQLITE_DeferFKs;
2804 sqlite3CommitInternalChanges(db);
2806 }else{
2807 sqlite3RollbackAll(db, SQLITE_OK);
2808 p->nChange = 0;
2810 db->nStatement = 0;
2811 }else if( eStatementOp==0 ){
2812 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
2813 eStatementOp = SAVEPOINT_RELEASE;
2814 }else if( p->errorAction==OE_Abort ){
2815 eStatementOp = SAVEPOINT_ROLLBACK;
2816 }else{
2817 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2818 sqlite3CloseSavepoints(db);
2819 db->autoCommit = 1;
2820 p->nChange = 0;
2824 /* If eStatementOp is non-zero, then a statement transaction needs to
2825 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2826 ** do so. If this operation returns an error, and the current statement
2827 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2828 ** current statement error code.
2830 if( eStatementOp ){
2831 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
2832 if( rc ){
2833 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
2834 p->rc = rc;
2835 sqlite3DbFree(db, p->zErrMsg);
2836 p->zErrMsg = 0;
2838 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2839 sqlite3CloseSavepoints(db);
2840 db->autoCommit = 1;
2841 p->nChange = 0;
2845 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2846 ** has been rolled back, update the database connection change-counter.
2848 if( p->changeCntOn ){
2849 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
2850 sqlite3VdbeSetChanges(db, p->nChange);
2851 }else{
2852 sqlite3VdbeSetChanges(db, 0);
2854 p->nChange = 0;
2857 /* Release the locks */
2858 sqlite3VdbeLeave(p);
2861 /* We have successfully halted and closed the VM. Record this fact. */
2862 if( p->pc>=0 ){
2863 db->nVdbeActive--;
2864 if( !p->readOnly ) db->nVdbeWrite--;
2865 if( p->bIsReader ) db->nVdbeRead--;
2866 assert( db->nVdbeActive>=db->nVdbeRead );
2867 assert( db->nVdbeRead>=db->nVdbeWrite );
2868 assert( db->nVdbeWrite>=0 );
2870 p->magic = VDBE_MAGIC_HALT;
2871 checkActiveVdbeCnt(db);
2872 if( db->mallocFailed ){
2873 p->rc = SQLITE_NOMEM_BKPT;
2876 /* If the auto-commit flag is set to true, then any locks that were held
2877 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2878 ** to invoke any required unlock-notify callbacks.
2880 if( db->autoCommit ){
2881 sqlite3ConnectionUnlocked(db);
2884 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
2885 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
2890 ** Each VDBE holds the result of the most recent sqlite3_step() call
2891 ** in p->rc. This routine sets that result back to SQLITE_OK.
2893 void sqlite3VdbeResetStepResult(Vdbe *p){
2894 p->rc = SQLITE_OK;
2898 ** Copy the error code and error message belonging to the VDBE passed
2899 ** as the first argument to its database handle (so that they will be
2900 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2902 ** This function does not clear the VDBE error code or message, just
2903 ** copies them to the database handle.
2905 int sqlite3VdbeTransferError(Vdbe *p){
2906 sqlite3 *db = p->db;
2907 int rc = p->rc;
2908 if( p->zErrMsg ){
2909 db->bBenignMalloc++;
2910 sqlite3BeginBenignMalloc();
2911 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
2912 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2913 sqlite3EndBenignMalloc();
2914 db->bBenignMalloc--;
2915 }else if( db->pErr ){
2916 sqlite3ValueSetNull(db->pErr);
2918 db->errCode = rc;
2919 return rc;
2922 #ifdef SQLITE_ENABLE_SQLLOG
2924 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2925 ** invoke it.
2927 static void vdbeInvokeSqllog(Vdbe *v){
2928 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2929 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2930 assert( v->db->init.busy==0 );
2931 if( zExpanded ){
2932 sqlite3GlobalConfig.xSqllog(
2933 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2935 sqlite3DbFree(v->db, zExpanded);
2939 #else
2940 # define vdbeInvokeSqllog(x)
2941 #endif
2944 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2945 ** Write any error messages into *pzErrMsg. Return the result code.
2947 ** After this routine is run, the VDBE should be ready to be executed
2948 ** again.
2950 ** To look at it another way, this routine resets the state of the
2951 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2952 ** VDBE_MAGIC_INIT.
2954 int sqlite3VdbeReset(Vdbe *p){
2955 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
2956 int i;
2957 #endif
2959 sqlite3 *db;
2960 db = p->db;
2962 /* If the VM did not run to completion or if it encountered an
2963 ** error, then it might not have been halted properly. So halt
2964 ** it now.
2966 sqlite3VdbeHalt(p);
2968 /* If the VDBE has be run even partially, then transfer the error code
2969 ** and error message from the VDBE into the main database structure. But
2970 ** if the VDBE has just been set to run but has not actually executed any
2971 ** instructions yet, leave the main database error information unchanged.
2973 if( p->pc>=0 ){
2974 vdbeInvokeSqllog(p);
2975 sqlite3VdbeTransferError(p);
2976 if( p->runOnlyOnce ) p->expired = 1;
2977 }else if( p->rc && p->expired ){
2978 /* The expired flag was set on the VDBE before the first call
2979 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2980 ** called), set the database error in this case as well.
2982 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
2985 /* Reset register contents and reclaim error message memory.
2987 #ifdef SQLITE_DEBUG
2988 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
2989 ** Vdbe.aMem[] arrays have already been cleaned up. */
2990 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
2991 if( p->aMem ){
2992 for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
2994 #endif
2995 sqlite3DbFree(db, p->zErrMsg);
2996 p->zErrMsg = 0;
2997 p->pResultSet = 0;
2999 /* Save profiling information from this VDBE run.
3001 #ifdef VDBE_PROFILE
3003 FILE *out = fopen("vdbe_profile.out", "a");
3004 if( out ){
3005 fprintf(out, "---- ");
3006 for(i=0; i<p->nOp; i++){
3007 fprintf(out, "%02x", p->aOp[i].opcode);
3009 fprintf(out, "\n");
3010 if( p->zSql ){
3011 char c, pc = 0;
3012 fprintf(out, "-- ");
3013 for(i=0; (c = p->zSql[i])!=0; i++){
3014 if( pc=='\n' ) fprintf(out, "-- ");
3015 putc(c, out);
3016 pc = c;
3018 if( pc!='\n' ) fprintf(out, "\n");
3020 for(i=0; i<p->nOp; i++){
3021 char zHdr[100];
3022 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
3023 p->aOp[i].cnt,
3024 p->aOp[i].cycles,
3025 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
3027 fprintf(out, "%s", zHdr);
3028 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
3030 fclose(out);
3033 #endif
3034 p->magic = VDBE_MAGIC_RESET;
3035 return p->rc & db->errMask;
3039 ** Clean up and delete a VDBE after execution. Return an integer which is
3040 ** the result code. Write any error message text into *pzErrMsg.
3042 int sqlite3VdbeFinalize(Vdbe *p){
3043 int rc = SQLITE_OK;
3044 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
3045 rc = sqlite3VdbeReset(p);
3046 assert( (rc & p->db->errMask)==rc );
3048 sqlite3VdbeDelete(p);
3049 return rc;
3053 ** If parameter iOp is less than zero, then invoke the destructor for
3054 ** all auxiliary data pointers currently cached by the VM passed as
3055 ** the first argument.
3057 ** Or, if iOp is greater than or equal to zero, then the destructor is
3058 ** only invoked for those auxiliary data pointers created by the user
3059 ** function invoked by the OP_Function opcode at instruction iOp of
3060 ** VM pVdbe, and only then if:
3062 ** * the associated function parameter is the 32nd or later (counting
3063 ** from left to right), or
3065 ** * the corresponding bit in argument mask is clear (where the first
3066 ** function parameter corresponds to bit 0 etc.).
3068 void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
3069 while( *pp ){
3070 AuxData *pAux = *pp;
3071 if( (iOp<0)
3072 || (pAux->iAuxOp==iOp
3073 && pAux->iAuxArg>=0
3074 && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
3076 testcase( pAux->iAuxArg==31 );
3077 if( pAux->xDeleteAux ){
3078 pAux->xDeleteAux(pAux->pAux);
3080 *pp = pAux->pNextAux;
3081 sqlite3DbFree(db, pAux);
3082 }else{
3083 pp= &pAux->pNextAux;
3089 ** Free all memory associated with the Vdbe passed as the second argument,
3090 ** except for object itself, which is preserved.
3092 ** The difference between this function and sqlite3VdbeDelete() is that
3093 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
3094 ** the database connection and frees the object itself.
3096 void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
3097 SubProgram *pSub, *pNext;
3098 assert( p->db==0 || p->db==db );
3099 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
3100 for(pSub=p->pProgram; pSub; pSub=pNext){
3101 pNext = pSub->pNext;
3102 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
3103 sqlite3DbFree(db, pSub);
3105 if( p->magic!=VDBE_MAGIC_INIT ){
3106 releaseMemArray(p->aVar, p->nVar);
3107 sqlite3DbFree(db, p->pVList);
3108 sqlite3DbFree(db, p->pFree);
3110 vdbeFreeOpArray(db, p->aOp, p->nOp);
3111 sqlite3DbFree(db, p->aColName);
3112 sqlite3DbFree(db, p->zSql);
3113 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3115 int i;
3116 for(i=0; i<p->nScan; i++){
3117 sqlite3DbFree(db, p->aScan[i].zName);
3119 sqlite3DbFree(db, p->aScan);
3121 #endif
3125 ** Delete an entire VDBE.
3127 void sqlite3VdbeDelete(Vdbe *p){
3128 sqlite3 *db;
3130 assert( p!=0 );
3131 db = p->db;
3132 assert( sqlite3_mutex_held(db->mutex) );
3133 sqlite3VdbeClearObject(db, p);
3134 if( p->pPrev ){
3135 p->pPrev->pNext = p->pNext;
3136 }else{
3137 assert( db->pVdbe==p );
3138 db->pVdbe = p->pNext;
3140 if( p->pNext ){
3141 p->pNext->pPrev = p->pPrev;
3143 p->magic = VDBE_MAGIC_DEAD;
3144 p->db = 0;
3145 sqlite3DbFreeNN(db, p);
3149 ** The cursor "p" has a pending seek operation that has not yet been
3150 ** carried out. Seek the cursor now. If an error occurs, return
3151 ** the appropriate error code.
3153 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
3154 int res, rc;
3155 #ifdef SQLITE_TEST
3156 extern int sqlite3_search_count;
3157 #endif
3158 assert( p->deferredMoveto );
3159 assert( p->isTable );
3160 assert( p->eCurType==CURTYPE_BTREE );
3161 rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
3162 if( rc ) return rc;
3163 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
3164 #ifdef SQLITE_TEST
3165 sqlite3_search_count++;
3166 #endif
3167 p->deferredMoveto = 0;
3168 p->cacheStatus = CACHE_STALE;
3169 return SQLITE_OK;
3173 ** Something has moved cursor "p" out of place. Maybe the row it was
3174 ** pointed to was deleted out from under it. Or maybe the btree was
3175 ** rebalanced. Whatever the cause, try to restore "p" to the place it
3176 ** is supposed to be pointing. If the row was deleted out from under the
3177 ** cursor, set the cursor to point to a NULL row.
3179 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
3180 int isDifferentRow, rc;
3181 assert( p->eCurType==CURTYPE_BTREE );
3182 assert( p->uc.pCursor!=0 );
3183 assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
3184 rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
3185 p->cacheStatus = CACHE_STALE;
3186 if( isDifferentRow ) p->nullRow = 1;
3187 return rc;
3191 ** Check to ensure that the cursor is valid. Restore the cursor
3192 ** if need be. Return any I/O error from the restore operation.
3194 int sqlite3VdbeCursorRestore(VdbeCursor *p){
3195 assert( p->eCurType==CURTYPE_BTREE );
3196 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3197 return handleMovedCursor(p);
3199 return SQLITE_OK;
3203 ** Make sure the cursor p is ready to read or write the row to which it
3204 ** was last positioned. Return an error code if an OOM fault or I/O error
3205 ** prevents us from positioning the cursor to its correct position.
3207 ** If a MoveTo operation is pending on the given cursor, then do that
3208 ** MoveTo now. If no move is pending, check to see if the row has been
3209 ** deleted out from under the cursor and if it has, mark the row as
3210 ** a NULL row.
3212 ** If the cursor is already pointing to the correct row and that row has
3213 ** not been deleted out from under the cursor, then this routine is a no-op.
3215 int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
3216 VdbeCursor *p = *pp;
3217 assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
3218 if( p->deferredMoveto ){
3219 int iMap;
3220 if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
3221 *pp = p->pAltCursor;
3222 *piCol = iMap - 1;
3223 return SQLITE_OK;
3225 return handleDeferredMoveto(p);
3227 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3228 return handleMovedCursor(p);
3230 return SQLITE_OK;
3234 ** The following functions:
3236 ** sqlite3VdbeSerialType()
3237 ** sqlite3VdbeSerialTypeLen()
3238 ** sqlite3VdbeSerialLen()
3239 ** sqlite3VdbeSerialPut()
3240 ** sqlite3VdbeSerialGet()
3242 ** encapsulate the code that serializes values for storage in SQLite
3243 ** data and index records. Each serialized value consists of a
3244 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3245 ** integer, stored as a varint.
3247 ** In an SQLite index record, the serial type is stored directly before
3248 ** the blob of data that it corresponds to. In a table record, all serial
3249 ** types are stored at the start of the record, and the blobs of data at
3250 ** the end. Hence these functions allow the caller to handle the
3251 ** serial-type and data blob separately.
3253 ** The following table describes the various storage classes for data:
3255 ** serial type bytes of data type
3256 ** -------------- --------------- ---------------
3257 ** 0 0 NULL
3258 ** 1 1 signed integer
3259 ** 2 2 signed integer
3260 ** 3 3 signed integer
3261 ** 4 4 signed integer
3262 ** 5 6 signed integer
3263 ** 6 8 signed integer
3264 ** 7 8 IEEE float
3265 ** 8 0 Integer constant 0
3266 ** 9 0 Integer constant 1
3267 ** 10,11 reserved for expansion
3268 ** N>=12 and even (N-12)/2 BLOB
3269 ** N>=13 and odd (N-13)/2 text
3271 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
3272 ** of SQLite will not understand those serial types.
3276 ** Return the serial-type for the value stored in pMem.
3278 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
3279 int flags = pMem->flags;
3280 u32 n;
3282 assert( pLen!=0 );
3283 if( flags&MEM_Null ){
3284 *pLen = 0;
3285 return 0;
3287 if( flags&MEM_Int ){
3288 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3289 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
3290 i64 i = pMem->u.i;
3291 u64 u;
3292 if( i<0 ){
3293 u = ~i;
3294 }else{
3295 u = i;
3297 if( u<=127 ){
3298 if( (i&1)==i && file_format>=4 ){
3299 *pLen = 0;
3300 return 8+(u32)u;
3301 }else{
3302 *pLen = 1;
3303 return 1;
3306 if( u<=32767 ){ *pLen = 2; return 2; }
3307 if( u<=8388607 ){ *pLen = 3; return 3; }
3308 if( u<=2147483647 ){ *pLen = 4; return 4; }
3309 if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
3310 *pLen = 8;
3311 return 6;
3313 if( flags&MEM_Real ){
3314 *pLen = 8;
3315 return 7;
3317 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
3318 assert( pMem->n>=0 );
3319 n = (u32)pMem->n;
3320 if( flags & MEM_Zero ){
3321 n += pMem->u.nZero;
3323 *pLen = n;
3324 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
3328 ** The sizes for serial types less than 128
3330 static const u8 sqlite3SmallTypeSizes[] = {
3331 /* 0 1 2 3 4 5 6 7 8 9 */
3332 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
3333 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
3334 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
3335 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
3336 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3337 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3338 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3339 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3340 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3341 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3342 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3343 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3344 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
3348 ** Return the length of the data corresponding to the supplied serial-type.
3350 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
3351 if( serial_type>=128 ){
3352 return (serial_type-12)/2;
3353 }else{
3354 assert( serial_type<12
3355 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
3356 return sqlite3SmallTypeSizes[serial_type];
3359 u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
3360 assert( serial_type<128 );
3361 return sqlite3SmallTypeSizes[serial_type];
3365 ** If we are on an architecture with mixed-endian floating
3366 ** points (ex: ARM7) then swap the lower 4 bytes with the
3367 ** upper 4 bytes. Return the result.
3369 ** For most architectures, this is a no-op.
3371 ** (later): It is reported to me that the mixed-endian problem
3372 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
3373 ** that early versions of GCC stored the two words of a 64-bit
3374 ** float in the wrong order. And that error has been propagated
3375 ** ever since. The blame is not necessarily with GCC, though.
3376 ** GCC might have just copying the problem from a prior compiler.
3377 ** I am also told that newer versions of GCC that follow a different
3378 ** ABI get the byte order right.
3380 ** Developers using SQLite on an ARM7 should compile and run their
3381 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
3382 ** enabled, some asserts below will ensure that the byte order of
3383 ** floating point values is correct.
3385 ** (2007-08-30) Frank van Vugt has studied this problem closely
3386 ** and has send his findings to the SQLite developers. Frank
3387 ** writes that some Linux kernels offer floating point hardware
3388 ** emulation that uses only 32-bit mantissas instead of a full
3389 ** 48-bits as required by the IEEE standard. (This is the
3390 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
3391 ** byte swapping becomes very complicated. To avoid problems,
3392 ** the necessary byte swapping is carried out using a 64-bit integer
3393 ** rather than a 64-bit float. Frank assures us that the code here
3394 ** works for him. We, the developers, have no way to independently
3395 ** verify this, but Frank seems to know what he is talking about
3396 ** so we trust him.
3398 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
3399 static u64 floatSwap(u64 in){
3400 union {
3401 u64 r;
3402 u32 i[2];
3403 } u;
3404 u32 t;
3406 u.r = in;
3407 t = u.i[0];
3408 u.i[0] = u.i[1];
3409 u.i[1] = t;
3410 return u.r;
3412 # define swapMixedEndianFloat(X) X = floatSwap(X)
3413 #else
3414 # define swapMixedEndianFloat(X)
3415 #endif
3418 ** Write the serialized data blob for the value stored in pMem into
3419 ** buf. It is assumed that the caller has allocated sufficient space.
3420 ** Return the number of bytes written.
3422 ** nBuf is the amount of space left in buf[]. The caller is responsible
3423 ** for allocating enough space to buf[] to hold the entire field, exclusive
3424 ** of the pMem->u.nZero bytes for a MEM_Zero value.
3426 ** Return the number of bytes actually written into buf[]. The number
3427 ** of bytes in the zero-filled tail is included in the return value only
3428 ** if those bytes were zeroed in buf[].
3430 u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
3431 u32 len;
3433 /* Integer and Real */
3434 if( serial_type<=7 && serial_type>0 ){
3435 u64 v;
3436 u32 i;
3437 if( serial_type==7 ){
3438 assert( sizeof(v)==sizeof(pMem->u.r) );
3439 memcpy(&v, &pMem->u.r, sizeof(v));
3440 swapMixedEndianFloat(v);
3441 }else{
3442 v = pMem->u.i;
3444 len = i = sqlite3SmallTypeSizes[serial_type];
3445 assert( i>0 );
3447 buf[--i] = (u8)(v&0xFF);
3448 v >>= 8;
3449 }while( i );
3450 return len;
3453 /* String or blob */
3454 if( serial_type>=12 ){
3455 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
3456 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
3457 len = pMem->n;
3458 if( len>0 ) memcpy(buf, pMem->z, len);
3459 return len;
3462 /* NULL or constants 0 or 1 */
3463 return 0;
3466 /* Input "x" is a sequence of unsigned characters that represent a
3467 ** big-endian integer. Return the equivalent native integer
3469 #define ONE_BYTE_INT(x) ((i8)(x)[0])
3470 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
3471 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3472 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3473 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3476 ** Deserialize the data blob pointed to by buf as serial type serial_type
3477 ** and store the result in pMem. Return the number of bytes read.
3479 ** This function is implemented as two separate routines for performance.
3480 ** The few cases that require local variables are broken out into a separate
3481 ** routine so that in most cases the overhead of moving the stack pointer
3482 ** is avoided.
3484 static u32 SQLITE_NOINLINE serialGet(
3485 const unsigned char *buf, /* Buffer to deserialize from */
3486 u32 serial_type, /* Serial type to deserialize */
3487 Mem *pMem /* Memory cell to write value into */
3489 u64 x = FOUR_BYTE_UINT(buf);
3490 u32 y = FOUR_BYTE_UINT(buf+4);
3491 x = (x<<32) + y;
3492 if( serial_type==6 ){
3493 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3494 ** twos-complement integer. */
3495 pMem->u.i = *(i64*)&x;
3496 pMem->flags = MEM_Int;
3497 testcase( pMem->u.i<0 );
3498 }else{
3499 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3500 ** floating point number. */
3501 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3502 /* Verify that integers and floating point values use the same
3503 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3504 ** defined that 64-bit floating point values really are mixed
3505 ** endian.
3507 static const u64 t1 = ((u64)0x3ff00000)<<32;
3508 static const double r1 = 1.0;
3509 u64 t2 = t1;
3510 swapMixedEndianFloat(t2);
3511 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3512 #endif
3513 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
3514 swapMixedEndianFloat(x);
3515 memcpy(&pMem->u.r, &x, sizeof(x));
3516 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
3518 return 8;
3520 u32 sqlite3VdbeSerialGet(
3521 const unsigned char *buf, /* Buffer to deserialize from */
3522 u32 serial_type, /* Serial type to deserialize */
3523 Mem *pMem /* Memory cell to write value into */
3525 switch( serial_type ){
3526 case 10: { /* Internal use only: NULL with virtual table
3527 ** UPDATE no-change flag set */
3528 pMem->flags = MEM_Null|MEM_Zero;
3529 pMem->n = 0;
3530 pMem->u.nZero = 0;
3531 break;
3533 case 11: /* Reserved for future use */
3534 case 0: { /* Null */
3535 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3536 pMem->flags = MEM_Null;
3537 break;
3539 case 1: {
3540 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3541 ** integer. */
3542 pMem->u.i = ONE_BYTE_INT(buf);
3543 pMem->flags = MEM_Int;
3544 testcase( pMem->u.i<0 );
3545 return 1;
3547 case 2: { /* 2-byte signed integer */
3548 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3549 ** twos-complement integer. */
3550 pMem->u.i = TWO_BYTE_INT(buf);
3551 pMem->flags = MEM_Int;
3552 testcase( pMem->u.i<0 );
3553 return 2;
3555 case 3: { /* 3-byte signed integer */
3556 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3557 ** twos-complement integer. */
3558 pMem->u.i = THREE_BYTE_INT(buf);
3559 pMem->flags = MEM_Int;
3560 testcase( pMem->u.i<0 );
3561 return 3;
3563 case 4: { /* 4-byte signed integer */
3564 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3565 ** twos-complement integer. */
3566 pMem->u.i = FOUR_BYTE_INT(buf);
3567 #ifdef __HP_cc
3568 /* Work around a sign-extension bug in the HP compiler for HP/UX */
3569 if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
3570 #endif
3571 pMem->flags = MEM_Int;
3572 testcase( pMem->u.i<0 );
3573 return 4;
3575 case 5: { /* 6-byte signed integer */
3576 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3577 ** twos-complement integer. */
3578 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
3579 pMem->flags = MEM_Int;
3580 testcase( pMem->u.i<0 );
3581 return 6;
3583 case 6: /* 8-byte signed integer */
3584 case 7: { /* IEEE floating point */
3585 /* These use local variables, so do them in a separate routine
3586 ** to avoid having to move the frame pointer in the common case */
3587 return serialGet(buf,serial_type,pMem);
3589 case 8: /* Integer 0 */
3590 case 9: { /* Integer 1 */
3591 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3592 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
3593 pMem->u.i = serial_type-8;
3594 pMem->flags = MEM_Int;
3595 return 0;
3597 default: {
3598 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3599 ** length.
3600 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3601 ** (N-13)/2 bytes in length. */
3602 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
3603 pMem->z = (char *)buf;
3604 pMem->n = (serial_type-12)/2;
3605 pMem->flags = aFlag[serial_type&1];
3606 return pMem->n;
3609 return 0;
3612 ** This routine is used to allocate sufficient space for an UnpackedRecord
3613 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3614 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
3616 ** The space is either allocated using sqlite3DbMallocRaw() or from within
3617 ** the unaligned buffer passed via the second and third arguments (presumably
3618 ** stack space). If the former, then *ppFree is set to a pointer that should
3619 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3620 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3621 ** before returning.
3623 ** If an OOM error occurs, NULL is returned.
3625 UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3626 KeyInfo *pKeyInfo /* Description of the record */
3628 UnpackedRecord *p; /* Unpacked record to return */
3629 int nByte; /* Number of bytes required for *p */
3630 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
3631 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3632 if( !p ) return 0;
3633 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
3634 assert( pKeyInfo->aSortOrder!=0 );
3635 p->pKeyInfo = pKeyInfo;
3636 p->nField = pKeyInfo->nKeyField + 1;
3637 return p;
3641 ** Given the nKey-byte encoding of a record in pKey[], populate the
3642 ** UnpackedRecord structure indicated by the fourth argument with the
3643 ** contents of the decoded record.
3645 void sqlite3VdbeRecordUnpack(
3646 KeyInfo *pKeyInfo, /* Information about the record format */
3647 int nKey, /* Size of the binary record */
3648 const void *pKey, /* The binary record */
3649 UnpackedRecord *p /* Populate this structure before returning. */
3651 const unsigned char *aKey = (const unsigned char *)pKey;
3652 int d;
3653 u32 idx; /* Offset in aKey[] to read from */
3654 u16 u; /* Unsigned loop counter */
3655 u32 szHdr;
3656 Mem *pMem = p->aMem;
3658 p->default_rc = 0;
3659 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
3660 idx = getVarint32(aKey, szHdr);
3661 d = szHdr;
3662 u = 0;
3663 while( idx<szHdr && d<=nKey ){
3664 u32 serial_type;
3666 idx += getVarint32(&aKey[idx], serial_type);
3667 pMem->enc = pKeyInfo->enc;
3668 pMem->db = pKeyInfo->db;
3669 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
3670 pMem->szMalloc = 0;
3671 pMem->z = 0;
3672 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
3673 pMem++;
3674 if( (++u)>=p->nField ) break;
3676 assert( u<=pKeyInfo->nKeyField + 1 );
3677 p->nField = u;
3680 #ifdef SQLITE_DEBUG
3682 ** This function compares two index or table record keys in the same way
3683 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3684 ** this function deserializes and compares values using the
3685 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3686 ** in assert() statements to ensure that the optimized code in
3687 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
3689 ** Return true if the result of comparison is equivalent to desiredResult.
3690 ** Return false if there is a disagreement.
3692 static int vdbeRecordCompareDebug(
3693 int nKey1, const void *pKey1, /* Left key */
3694 const UnpackedRecord *pPKey2, /* Right key */
3695 int desiredResult /* Correct answer */
3697 u32 d1; /* Offset into aKey[] of next data element */
3698 u32 idx1; /* Offset into aKey[] of next header element */
3699 u32 szHdr1; /* Number of bytes in header */
3700 int i = 0;
3701 int rc = 0;
3702 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3703 KeyInfo *pKeyInfo;
3704 Mem mem1;
3706 pKeyInfo = pPKey2->pKeyInfo;
3707 if( pKeyInfo->db==0 ) return 1;
3708 mem1.enc = pKeyInfo->enc;
3709 mem1.db = pKeyInfo->db;
3710 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
3711 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
3713 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3714 ** We could initialize it, as shown here, to silence those complaints.
3715 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3716 ** the unnecessary initialization has a measurable negative performance
3717 ** impact, since this routine is a very high runner. And so, we choose
3718 ** to ignore the compiler warnings and leave this variable uninitialized.
3720 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3722 idx1 = getVarint32(aKey1, szHdr1);
3723 if( szHdr1>98307 ) return SQLITE_CORRUPT;
3724 d1 = szHdr1;
3725 assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
3726 assert( pKeyInfo->aSortOrder!=0 );
3727 assert( pKeyInfo->nKeyField>0 );
3728 assert( idx1<=szHdr1 || CORRUPT_DB );
3730 u32 serial_type1;
3732 /* Read the serial types for the next element in each key. */
3733 idx1 += getVarint32( aKey1+idx1, serial_type1 );
3735 /* Verify that there is enough key space remaining to avoid
3736 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3737 ** always be greater than or equal to the amount of required key space.
3738 ** Use that approximation to avoid the more expensive call to
3739 ** sqlite3VdbeSerialTypeLen() in the common case.
3741 if( d1+serial_type1+2>(u32)nKey1
3742 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3744 break;
3747 /* Extract the values to be compared.
3749 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
3751 /* Do the comparison
3753 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3754 if( rc!=0 ){
3755 assert( mem1.szMalloc==0 ); /* See comment below */
3756 if( pKeyInfo->aSortOrder[i] ){
3757 rc = -rc; /* Invert the result for DESC sort order. */
3759 goto debugCompareEnd;
3761 i++;
3762 }while( idx1<szHdr1 && i<pPKey2->nField );
3764 /* No memory allocation is ever used on mem1. Prove this using
3765 ** the following assert(). If the assert() fails, it indicates a
3766 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3768 assert( mem1.szMalloc==0 );
3770 /* rc==0 here means that one of the keys ran out of fields and
3771 ** all the fields up to that point were equal. Return the default_rc
3772 ** value. */
3773 rc = pPKey2->default_rc;
3775 debugCompareEnd:
3776 if( desiredResult==0 && rc==0 ) return 1;
3777 if( desiredResult<0 && rc<0 ) return 1;
3778 if( desiredResult>0 && rc>0 ) return 1;
3779 if( CORRUPT_DB ) return 1;
3780 if( pKeyInfo->db->mallocFailed ) return 1;
3781 return 0;
3783 #endif
3785 #ifdef SQLITE_DEBUG
3787 ** Count the number of fields (a.k.a. columns) in the record given by
3788 ** pKey,nKey. The verify that this count is less than or equal to the
3789 ** limit given by pKeyInfo->nAllField.
3791 ** If this constraint is not satisfied, it means that the high-speed
3792 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3793 ** not work correctly. If this assert() ever fires, it probably means
3794 ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
3795 ** incorrectly.
3797 static void vdbeAssertFieldCountWithinLimits(
3798 int nKey, const void *pKey, /* The record to verify */
3799 const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
3801 int nField = 0;
3802 u32 szHdr;
3803 u32 idx;
3804 u32 notUsed;
3805 const unsigned char *aKey = (const unsigned char*)pKey;
3807 if( CORRUPT_DB ) return;
3808 idx = getVarint32(aKey, szHdr);
3809 assert( nKey>=0 );
3810 assert( szHdr<=(u32)nKey );
3811 while( idx<szHdr ){
3812 idx += getVarint32(aKey+idx, notUsed);
3813 nField++;
3815 assert( nField <= pKeyInfo->nAllField );
3817 #else
3818 # define vdbeAssertFieldCountWithinLimits(A,B,C)
3819 #endif
3822 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
3823 ** using the collation sequence pColl. As usual, return a negative , zero
3824 ** or positive value if *pMem1 is less than, equal to or greater than
3825 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3827 static int vdbeCompareMemString(
3828 const Mem *pMem1,
3829 const Mem *pMem2,
3830 const CollSeq *pColl,
3831 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
3833 if( pMem1->enc==pColl->enc ){
3834 /* The strings are already in the correct encoding. Call the
3835 ** comparison function directly */
3836 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3837 }else{
3838 int rc;
3839 const void *v1, *v2;
3840 Mem c1;
3841 Mem c2;
3842 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3843 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
3844 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3845 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3846 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3847 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3848 if( (v1==0 || v2==0) ){
3849 if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
3850 rc = 0;
3851 }else{
3852 rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
3854 sqlite3VdbeMemRelease(&c1);
3855 sqlite3VdbeMemRelease(&c2);
3856 return rc;
3861 ** The input pBlob is guaranteed to be a Blob that is not marked
3862 ** with MEM_Zero. Return true if it could be a zero-blob.
3864 static int isAllZero(const char *z, int n){
3865 int i;
3866 for(i=0; i<n; i++){
3867 if( z[i] ) return 0;
3869 return 1;
3873 ** Compare two blobs. Return negative, zero, or positive if the first
3874 ** is less than, equal to, or greater than the second, respectively.
3875 ** If one blob is a prefix of the other, then the shorter is the lessor.
3877 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3878 int c;
3879 int n1 = pB1->n;
3880 int n2 = pB2->n;
3882 /* It is possible to have a Blob value that has some non-zero content
3883 ** followed by zero content. But that only comes up for Blobs formed
3884 ** by the OP_MakeRecord opcode, and such Blobs never get passed into
3885 ** sqlite3MemCompare(). */
3886 assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
3887 assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
3889 if( (pB1->flags|pB2->flags) & MEM_Zero ){
3890 if( pB1->flags & pB2->flags & MEM_Zero ){
3891 return pB1->u.nZero - pB2->u.nZero;
3892 }else if( pB1->flags & MEM_Zero ){
3893 if( !isAllZero(pB2->z, pB2->n) ) return -1;
3894 return pB1->u.nZero - n2;
3895 }else{
3896 if( !isAllZero(pB1->z, pB1->n) ) return +1;
3897 return n1 - pB2->u.nZero;
3900 c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
3901 if( c ) return c;
3902 return n1 - n2;
3906 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
3907 ** number. Return negative, zero, or positive if the first (i64) is less than,
3908 ** equal to, or greater than the second (double).
3910 static int sqlite3IntFloatCompare(i64 i, double r){
3911 if( sizeof(LONGDOUBLE_TYPE)>8 ){
3912 LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
3913 if( x<r ) return -1;
3914 if( x>r ) return +1;
3915 return 0;
3916 }else{
3917 i64 y;
3918 double s;
3919 if( r<-9223372036854775808.0 ) return +1;
3920 if( r>=9223372036854775808.0 ) return -1;
3921 y = (i64)r;
3922 if( i<y ) return -1;
3923 if( i>y ) return +1;
3924 s = (double)i;
3925 if( s<r ) return -1;
3926 if( s>r ) return +1;
3927 return 0;
3932 ** Compare the values contained by the two memory cells, returning
3933 ** negative, zero or positive if pMem1 is less than, equal to, or greater
3934 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3935 ** and reals) sorted numerically, followed by text ordered by the collating
3936 ** sequence pColl and finally blob's ordered by memcmp().
3938 ** Two NULL values are considered equal by this function.
3940 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
3941 int f1, f2;
3942 int combined_flags;
3944 f1 = pMem1->flags;
3945 f2 = pMem2->flags;
3946 combined_flags = f1|f2;
3947 assert( (combined_flags & MEM_RowSet)==0 );
3949 /* If one value is NULL, it is less than the other. If both values
3950 ** are NULL, return 0.
3952 if( combined_flags&MEM_Null ){
3953 return (f2&MEM_Null) - (f1&MEM_Null);
3956 /* At least one of the two values is a number
3958 if( combined_flags&(MEM_Int|MEM_Real) ){
3959 if( (f1 & f2 & MEM_Int)!=0 ){
3960 if( pMem1->u.i < pMem2->u.i ) return -1;
3961 if( pMem1->u.i > pMem2->u.i ) return +1;
3962 return 0;
3964 if( (f1 & f2 & MEM_Real)!=0 ){
3965 if( pMem1->u.r < pMem2->u.r ) return -1;
3966 if( pMem1->u.r > pMem2->u.r ) return +1;
3967 return 0;
3969 if( (f1&MEM_Int)!=0 ){
3970 if( (f2&MEM_Real)!=0 ){
3971 return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
3972 }else{
3973 return -1;
3976 if( (f1&MEM_Real)!=0 ){
3977 if( (f2&MEM_Int)!=0 ){
3978 return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
3979 }else{
3980 return -1;
3983 return +1;
3986 /* If one value is a string and the other is a blob, the string is less.
3987 ** If both are strings, compare using the collating functions.
3989 if( combined_flags&MEM_Str ){
3990 if( (f1 & MEM_Str)==0 ){
3991 return 1;
3993 if( (f2 & MEM_Str)==0 ){
3994 return -1;
3997 assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
3998 assert( pMem1->enc==SQLITE_UTF8 ||
3999 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
4001 /* The collation sequence must be defined at this point, even if
4002 ** the user deletes the collation sequence after the vdbe program is
4003 ** compiled (this was not always the case).
4005 assert( !pColl || pColl->xCmp );
4007 if( pColl ){
4008 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
4010 /* If a NULL pointer was passed as the collate function, fall through
4011 ** to the blob case and use memcmp(). */
4014 /* Both values must be blobs. Compare using memcmp(). */
4015 return sqlite3BlobCompare(pMem1, pMem2);
4020 ** The first argument passed to this function is a serial-type that
4021 ** corresponds to an integer - all values between 1 and 9 inclusive
4022 ** except 7. The second points to a buffer containing an integer value
4023 ** serialized according to serial_type. This function deserializes
4024 ** and returns the value.
4026 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
4027 u32 y;
4028 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
4029 switch( serial_type ){
4030 case 0:
4031 case 1:
4032 testcase( aKey[0]&0x80 );
4033 return ONE_BYTE_INT(aKey);
4034 case 2:
4035 testcase( aKey[0]&0x80 );
4036 return TWO_BYTE_INT(aKey);
4037 case 3:
4038 testcase( aKey[0]&0x80 );
4039 return THREE_BYTE_INT(aKey);
4040 case 4: {
4041 testcase( aKey[0]&0x80 );
4042 y = FOUR_BYTE_UINT(aKey);
4043 return (i64)*(int*)&y;
4045 case 5: {
4046 testcase( aKey[0]&0x80 );
4047 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4049 case 6: {
4050 u64 x = FOUR_BYTE_UINT(aKey);
4051 testcase( aKey[0]&0x80 );
4052 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4053 return (i64)*(i64*)&x;
4057 return (serial_type - 8);
4061 ** This function compares the two table rows or index records
4062 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
4063 ** or positive integer if key1 is less than, equal to or
4064 ** greater than key2. The {nKey1, pKey1} key must be a blob
4065 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
4066 ** key must be a parsed key such as obtained from
4067 ** sqlite3VdbeParseRecord.
4069 ** If argument bSkip is non-zero, it is assumed that the caller has already
4070 ** determined that the first fields of the keys are equal.
4072 ** Key1 and Key2 do not have to contain the same number of fields. If all
4073 ** fields that appear in both keys are equal, then pPKey2->default_rc is
4074 ** returned.
4076 ** If database corruption is discovered, set pPKey2->errCode to
4077 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
4078 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
4079 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
4081 int sqlite3VdbeRecordCompareWithSkip(
4082 int nKey1, const void *pKey1, /* Left key */
4083 UnpackedRecord *pPKey2, /* Right key */
4084 int bSkip /* If true, skip the first field */
4086 u32 d1; /* Offset into aKey[] of next data element */
4087 int i; /* Index of next field to compare */
4088 u32 szHdr1; /* Size of record header in bytes */
4089 u32 idx1; /* Offset of first type in header */
4090 int rc = 0; /* Return value */
4091 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
4092 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
4093 const unsigned char *aKey1 = (const unsigned char *)pKey1;
4094 Mem mem1;
4096 /* If bSkip is true, then the caller has already determined that the first
4097 ** two elements in the keys are equal. Fix the various stack variables so
4098 ** that this routine begins comparing at the second field. */
4099 if( bSkip ){
4100 u32 s1;
4101 idx1 = 1 + getVarint32(&aKey1[1], s1);
4102 szHdr1 = aKey1[0];
4103 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
4104 i = 1;
4105 pRhs++;
4106 }else{
4107 idx1 = getVarint32(aKey1, szHdr1);
4108 d1 = szHdr1;
4109 if( d1>(unsigned)nKey1 ){
4110 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4111 return 0; /* Corruption */
4113 i = 0;
4116 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
4117 assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
4118 || CORRUPT_DB );
4119 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
4120 assert( pPKey2->pKeyInfo->nKeyField>0 );
4121 assert( idx1<=szHdr1 || CORRUPT_DB );
4123 u32 serial_type;
4125 /* RHS is an integer */
4126 if( pRhs->flags & MEM_Int ){
4127 serial_type = aKey1[idx1];
4128 testcase( serial_type==12 );
4129 if( serial_type>=10 ){
4130 rc = +1;
4131 }else if( serial_type==0 ){
4132 rc = -1;
4133 }else if( serial_type==7 ){
4134 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4135 rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
4136 }else{
4137 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
4138 i64 rhs = pRhs->u.i;
4139 if( lhs<rhs ){
4140 rc = -1;
4141 }else if( lhs>rhs ){
4142 rc = +1;
4147 /* RHS is real */
4148 else if( pRhs->flags & MEM_Real ){
4149 serial_type = aKey1[idx1];
4150 if( serial_type>=10 ){
4151 /* Serial types 12 or greater are strings and blobs (greater than
4152 ** numbers). Types 10 and 11 are currently "reserved for future
4153 ** use", so it doesn't really matter what the results of comparing
4154 ** them to numberic values are. */
4155 rc = +1;
4156 }else if( serial_type==0 ){
4157 rc = -1;
4158 }else{
4159 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
4160 if( serial_type==7 ){
4161 if( mem1.u.r<pRhs->u.r ){
4162 rc = -1;
4163 }else if( mem1.u.r>pRhs->u.r ){
4164 rc = +1;
4166 }else{
4167 rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
4172 /* RHS is a string */
4173 else if( pRhs->flags & MEM_Str ){
4174 getVarint32(&aKey1[idx1], serial_type);
4175 testcase( serial_type==12 );
4176 if( serial_type<12 ){
4177 rc = -1;
4178 }else if( !(serial_type & 0x01) ){
4179 rc = +1;
4180 }else{
4181 mem1.n = (serial_type - 12) / 2;
4182 testcase( (d1+mem1.n)==(unsigned)nKey1 );
4183 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
4184 if( (d1+mem1.n) > (unsigned)nKey1 ){
4185 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4186 return 0; /* Corruption */
4187 }else if( pKeyInfo->aColl[i] ){
4188 mem1.enc = pKeyInfo->enc;
4189 mem1.db = pKeyInfo->db;
4190 mem1.flags = MEM_Str;
4191 mem1.z = (char*)&aKey1[d1];
4192 rc = vdbeCompareMemString(
4193 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
4195 }else{
4196 int nCmp = MIN(mem1.n, pRhs->n);
4197 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4198 if( rc==0 ) rc = mem1.n - pRhs->n;
4203 /* RHS is a blob */
4204 else if( pRhs->flags & MEM_Blob ){
4205 assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
4206 getVarint32(&aKey1[idx1], serial_type);
4207 testcase( serial_type==12 );
4208 if( serial_type<12 || (serial_type & 0x01) ){
4209 rc = -1;
4210 }else{
4211 int nStr = (serial_type - 12) / 2;
4212 testcase( (d1+nStr)==(unsigned)nKey1 );
4213 testcase( (d1+nStr+1)==(unsigned)nKey1 );
4214 if( (d1+nStr) > (unsigned)nKey1 ){
4215 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4216 return 0; /* Corruption */
4217 }else if( pRhs->flags & MEM_Zero ){
4218 if( !isAllZero((const char*)&aKey1[d1],nStr) ){
4219 rc = 1;
4220 }else{
4221 rc = nStr - pRhs->u.nZero;
4223 }else{
4224 int nCmp = MIN(nStr, pRhs->n);
4225 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
4226 if( rc==0 ) rc = nStr - pRhs->n;
4231 /* RHS is null */
4232 else{
4233 serial_type = aKey1[idx1];
4234 rc = (serial_type!=0);
4237 if( rc!=0 ){
4238 if( pKeyInfo->aSortOrder[i] ){
4239 rc = -rc;
4241 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
4242 assert( mem1.szMalloc==0 ); /* See comment below */
4243 return rc;
4246 i++;
4247 pRhs++;
4248 d1 += sqlite3VdbeSerialTypeLen(serial_type);
4249 idx1 += sqlite3VarintLen(serial_type);
4250 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
4252 /* No memory allocation is ever used on mem1. Prove this using
4253 ** the following assert(). If the assert() fails, it indicates a
4254 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
4255 assert( mem1.szMalloc==0 );
4257 /* rc==0 here means that one or both of the keys ran out of fields and
4258 ** all the fields up to that point were equal. Return the default_rc
4259 ** value. */
4260 assert( CORRUPT_DB
4261 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
4262 || pKeyInfo->db->mallocFailed
4264 pPKey2->eqSeen = 1;
4265 return pPKey2->default_rc;
4267 int sqlite3VdbeRecordCompare(
4268 int nKey1, const void *pKey1, /* Left key */
4269 UnpackedRecord *pPKey2 /* Right key */
4271 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
4276 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4277 ** that (a) the first field of pPKey2 is an integer, and (b) the
4278 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
4279 ** byte (i.e. is less than 128).
4281 ** To avoid concerns about buffer overreads, this routine is only used
4282 ** on schemas where the maximum valid header size is 63 bytes or less.
4284 static int vdbeRecordCompareInt(
4285 int nKey1, const void *pKey1, /* Left key */
4286 UnpackedRecord *pPKey2 /* Right key */
4288 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
4289 int serial_type = ((const u8*)pKey1)[1];
4290 int res;
4291 u32 y;
4292 u64 x;
4293 i64 v;
4294 i64 lhs;
4296 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4297 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
4298 switch( serial_type ){
4299 case 1: { /* 1-byte signed integer */
4300 lhs = ONE_BYTE_INT(aKey);
4301 testcase( lhs<0 );
4302 break;
4304 case 2: { /* 2-byte signed integer */
4305 lhs = TWO_BYTE_INT(aKey);
4306 testcase( lhs<0 );
4307 break;
4309 case 3: { /* 3-byte signed integer */
4310 lhs = THREE_BYTE_INT(aKey);
4311 testcase( lhs<0 );
4312 break;
4314 case 4: { /* 4-byte signed integer */
4315 y = FOUR_BYTE_UINT(aKey);
4316 lhs = (i64)*(int*)&y;
4317 testcase( lhs<0 );
4318 break;
4320 case 5: { /* 6-byte signed integer */
4321 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4322 testcase( lhs<0 );
4323 break;
4325 case 6: { /* 8-byte signed integer */
4326 x = FOUR_BYTE_UINT(aKey);
4327 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4328 lhs = *(i64*)&x;
4329 testcase( lhs<0 );
4330 break;
4332 case 8:
4333 lhs = 0;
4334 break;
4335 case 9:
4336 lhs = 1;
4337 break;
4339 /* This case could be removed without changing the results of running
4340 ** this code. Including it causes gcc to generate a faster switch
4341 ** statement (since the range of switch targets now starts at zero and
4342 ** is contiguous) but does not cause any duplicate code to be generated
4343 ** (as gcc is clever enough to combine the two like cases). Other
4344 ** compilers might be similar. */
4345 case 0: case 7:
4346 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4348 default:
4349 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4352 v = pPKey2->aMem[0].u.i;
4353 if( v>lhs ){
4354 res = pPKey2->r1;
4355 }else if( v<lhs ){
4356 res = pPKey2->r2;
4357 }else if( pPKey2->nField>1 ){
4358 /* The first fields of the two keys are equal. Compare the trailing
4359 ** fields. */
4360 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4361 }else{
4362 /* The first fields of the two keys are equal and there are no trailing
4363 ** fields. Return pPKey2->default_rc in this case. */
4364 res = pPKey2->default_rc;
4365 pPKey2->eqSeen = 1;
4368 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
4369 return res;
4373 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4374 ** that (a) the first field of pPKey2 is a string, that (b) the first field
4375 ** uses the collation sequence BINARY and (c) that the size-of-header varint
4376 ** at the start of (pKey1/nKey1) fits in a single byte.
4378 static int vdbeRecordCompareString(
4379 int nKey1, const void *pKey1, /* Left key */
4380 UnpackedRecord *pPKey2 /* Right key */
4382 const u8 *aKey1 = (const u8*)pKey1;
4383 int serial_type;
4384 int res;
4386 assert( pPKey2->aMem[0].flags & MEM_Str );
4387 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4388 getVarint32(&aKey1[1], serial_type);
4389 if( serial_type<12 ){
4390 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
4391 }else if( !(serial_type & 0x01) ){
4392 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
4393 }else{
4394 int nCmp;
4395 int nStr;
4396 int szHdr = aKey1[0];
4398 nStr = (serial_type-12) / 2;
4399 if( (szHdr + nStr) > nKey1 ){
4400 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4401 return 0; /* Corruption */
4403 nCmp = MIN( pPKey2->aMem[0].n, nStr );
4404 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
4406 if( res==0 ){
4407 res = nStr - pPKey2->aMem[0].n;
4408 if( res==0 ){
4409 if( pPKey2->nField>1 ){
4410 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
4411 }else{
4412 res = pPKey2->default_rc;
4413 pPKey2->eqSeen = 1;
4415 }else if( res>0 ){
4416 res = pPKey2->r2;
4417 }else{
4418 res = pPKey2->r1;
4420 }else if( res>0 ){
4421 res = pPKey2->r2;
4422 }else{
4423 res = pPKey2->r1;
4427 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
4428 || CORRUPT_DB
4429 || pPKey2->pKeyInfo->db->mallocFailed
4431 return res;
4435 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
4436 ** suitable for comparing serialized records to the unpacked record passed
4437 ** as the only argument.
4439 RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
4440 /* varintRecordCompareInt() and varintRecordCompareString() both assume
4441 ** that the size-of-header varint that occurs at the start of each record
4442 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
4443 ** also assumes that it is safe to overread a buffer by at least the
4444 ** maximum possible legal header size plus 8 bytes. Because there is
4445 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
4446 ** buffer passed to varintRecordCompareInt() this makes it convenient to
4447 ** limit the size of the header to 64 bytes in cases where the first field
4448 ** is an integer.
4450 ** The easiest way to enforce this limit is to consider only records with
4451 ** 13 fields or less. If the first field is an integer, the maximum legal
4452 ** header size is (12*5 + 1 + 1) bytes. */
4453 if( p->pKeyInfo->nAllField<=13 ){
4454 int flags = p->aMem[0].flags;
4455 if( p->pKeyInfo->aSortOrder[0] ){
4456 p->r1 = 1;
4457 p->r2 = -1;
4458 }else{
4459 p->r1 = -1;
4460 p->r2 = 1;
4462 if( (flags & MEM_Int) ){
4463 return vdbeRecordCompareInt;
4465 testcase( flags & MEM_Real );
4466 testcase( flags & MEM_Null );
4467 testcase( flags & MEM_Blob );
4468 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
4469 assert( flags & MEM_Str );
4470 return vdbeRecordCompareString;
4474 return sqlite3VdbeRecordCompare;
4478 ** pCur points at an index entry created using the OP_MakeRecord opcode.
4479 ** Read the rowid (the last field in the record) and store it in *rowid.
4480 ** Return SQLITE_OK if everything works, or an error code otherwise.
4482 ** pCur might be pointing to text obtained from a corrupt database file.
4483 ** So the content cannot be trusted. Do appropriate checks on the content.
4485 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
4486 i64 nCellKey = 0;
4487 int rc;
4488 u32 szHdr; /* Size of the header */
4489 u32 typeRowid; /* Serial type of the rowid */
4490 u32 lenRowid; /* Size of the rowid */
4491 Mem m, v;
4493 /* Get the size of the index entry. Only indices entries of less
4494 ** than 2GiB are support - anything large must be database corruption.
4495 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4496 ** this code can safely assume that nCellKey is 32-bits
4498 assert( sqlite3BtreeCursorIsValid(pCur) );
4499 nCellKey = sqlite3BtreePayloadSize(pCur);
4500 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
4502 /* Read in the complete content of the index entry */
4503 sqlite3VdbeMemInit(&m, db, 0);
4504 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4505 if( rc ){
4506 return rc;
4509 /* The index entry must begin with a header size */
4510 (void)getVarint32((u8*)m.z, szHdr);
4511 testcase( szHdr==3 );
4512 testcase( szHdr==m.n );
4513 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
4514 goto idx_rowid_corruption;
4517 /* The last field of the index should be an integer - the ROWID.
4518 ** Verify that the last entry really is an integer. */
4519 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
4520 testcase( typeRowid==1 );
4521 testcase( typeRowid==2 );
4522 testcase( typeRowid==3 );
4523 testcase( typeRowid==4 );
4524 testcase( typeRowid==5 );
4525 testcase( typeRowid==6 );
4526 testcase( typeRowid==8 );
4527 testcase( typeRowid==9 );
4528 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
4529 goto idx_rowid_corruption;
4531 lenRowid = sqlite3SmallTypeSizes[typeRowid];
4532 testcase( (u32)m.n==szHdr+lenRowid );
4533 if( unlikely((u32)m.n<szHdr+lenRowid) ){
4534 goto idx_rowid_corruption;
4537 /* Fetch the integer off the end of the index record */
4538 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
4539 *rowid = v.u.i;
4540 sqlite3VdbeMemRelease(&m);
4541 return SQLITE_OK;
4543 /* Jump here if database corruption is detected after m has been
4544 ** allocated. Free the m object and return SQLITE_CORRUPT. */
4545 idx_rowid_corruption:
4546 testcase( m.szMalloc!=0 );
4547 sqlite3VdbeMemRelease(&m);
4548 return SQLITE_CORRUPT_BKPT;
4552 ** Compare the key of the index entry that cursor pC is pointing to against
4553 ** the key string in pUnpacked. Write into *pRes a number
4554 ** that is negative, zero, or positive if pC is less than, equal to,
4555 ** or greater than pUnpacked. Return SQLITE_OK on success.
4557 ** pUnpacked is either created without a rowid or is truncated so that it
4558 ** omits the rowid at the end. The rowid at the end of the index entry
4559 ** is ignored as well. Hence, this routine only compares the prefixes
4560 ** of the keys prior to the final rowid, not the entire key.
4562 int sqlite3VdbeIdxKeyCompare(
4563 sqlite3 *db, /* Database connection */
4564 VdbeCursor *pC, /* The cursor to compare against */
4565 UnpackedRecord *pUnpacked, /* Unpacked version of key */
4566 int *res /* Write the comparison result here */
4568 i64 nCellKey = 0;
4569 int rc;
4570 BtCursor *pCur;
4571 Mem m;
4573 assert( pC->eCurType==CURTYPE_BTREE );
4574 pCur = pC->uc.pCursor;
4575 assert( sqlite3BtreeCursorIsValid(pCur) );
4576 nCellKey = sqlite3BtreePayloadSize(pCur);
4577 /* nCellKey will always be between 0 and 0xffffffff because of the way
4578 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
4579 if( nCellKey<=0 || nCellKey>0x7fffffff ){
4580 *res = 0;
4581 return SQLITE_CORRUPT_BKPT;
4583 sqlite3VdbeMemInit(&m, db, 0);
4584 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
4585 if( rc ){
4586 return rc;
4588 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
4589 sqlite3VdbeMemRelease(&m);
4590 return SQLITE_OK;
4594 ** This routine sets the value to be returned by subsequent calls to
4595 ** sqlite3_changes() on the database handle 'db'.
4597 void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
4598 assert( sqlite3_mutex_held(db->mutex) );
4599 db->nChange = nChange;
4600 db->nTotalChange += nChange;
4604 ** Set a flag in the vdbe to update the change counter when it is finalised
4605 ** or reset.
4607 void sqlite3VdbeCountChanges(Vdbe *v){
4608 v->changeCntOn = 1;
4612 ** Mark every prepared statement associated with a database connection
4613 ** as expired.
4615 ** An expired statement means that recompilation of the statement is
4616 ** recommend. Statements expire when things happen that make their
4617 ** programs obsolete. Removing user-defined functions or collating
4618 ** sequences, or changing an authorization function are the types of
4619 ** things that make prepared statements obsolete.
4621 void sqlite3ExpirePreparedStatements(sqlite3 *db){
4622 Vdbe *p;
4623 for(p = db->pVdbe; p; p=p->pNext){
4624 p->expired = 1;
4629 ** Return the database associated with the Vdbe.
4631 sqlite3 *sqlite3VdbeDb(Vdbe *v){
4632 return v->db;
4636 ** Return the SQLITE_PREPARE flags for a Vdbe.
4638 u8 sqlite3VdbePrepareFlags(Vdbe *v){
4639 return v->prepFlags;
4643 ** Return a pointer to an sqlite3_value structure containing the value bound
4644 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4645 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4646 ** constants) to the value before returning it.
4648 ** The returned value must be freed by the caller using sqlite3ValueFree().
4650 sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
4651 assert( iVar>0 );
4652 if( v ){
4653 Mem *pMem = &v->aVar[iVar-1];
4654 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
4655 if( 0==(pMem->flags & MEM_Null) ){
4656 sqlite3_value *pRet = sqlite3ValueNew(v->db);
4657 if( pRet ){
4658 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4659 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
4661 return pRet;
4664 return 0;
4668 ** Configure SQL variable iVar so that binding a new value to it signals
4669 ** to sqlite3_reoptimize() that re-preparing the statement may result
4670 ** in a better query plan.
4672 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
4673 assert( iVar>0 );
4674 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
4675 if( iVar>=32 ){
4676 v->expmask |= 0x80000000;
4677 }else{
4678 v->expmask |= ((u32)1 << (iVar-1));
4683 ** Cause a function to throw an error if it was call from OP_PureFunc
4684 ** rather than OP_Function.
4686 ** OP_PureFunc means that the function must be deterministic, and should
4687 ** throw an error if it is given inputs that would make it non-deterministic.
4688 ** This routine is invoked by date/time functions that use non-deterministic
4689 ** features such as 'now'.
4691 int sqlite3NotPureFunc(sqlite3_context *pCtx){
4692 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4693 if( pCtx->pVdbe==0 ) return 1;
4694 #endif
4695 if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
4696 sqlite3_result_error(pCtx,
4697 "non-deterministic function in index expression or CHECK constraint",
4698 -1);
4699 return 0;
4701 return 1;
4704 #ifndef SQLITE_OMIT_VIRTUALTABLE
4706 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4707 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4708 ** in memory obtained from sqlite3DbMalloc).
4710 void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4711 if( pVtab->zErrMsg ){
4712 sqlite3 *db = p->db;
4713 sqlite3DbFree(db, p->zErrMsg);
4714 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4715 sqlite3_free(pVtab->zErrMsg);
4716 pVtab->zErrMsg = 0;
4719 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4721 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4724 ** If the second argument is not NULL, release any allocations associated
4725 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
4726 ** structure itself, using sqlite3DbFree().
4728 ** This function is used to free UnpackedRecord structures allocated by
4729 ** the vdbeUnpackRecord() function found in vdbeapi.c.
4731 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
4732 if( p ){
4733 int i;
4734 for(i=0; i<nField; i++){
4735 Mem *pMem = &p->aMem[i];
4736 if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
4738 sqlite3DbFreeNN(db, p);
4741 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4743 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4745 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
4746 ** then cursor passed as the second argument should point to the row about
4747 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
4748 ** the required value will be read from the row the cursor points to.
4750 void sqlite3VdbePreUpdateHook(
4751 Vdbe *v, /* Vdbe pre-update hook is invoked by */
4752 VdbeCursor *pCsr, /* Cursor to grab old.* values from */
4753 int op, /* SQLITE_INSERT, UPDATE or DELETE */
4754 const char *zDb, /* Database name */
4755 Table *pTab, /* Modified table */
4756 i64 iKey1, /* Initial key value */
4757 int iReg /* Register for new.* record */
4759 sqlite3 *db = v->db;
4760 i64 iKey2;
4761 PreUpdate preupdate;
4762 const char *zTbl = pTab->zName;
4763 static const u8 fakeSortOrder = 0;
4765 assert( db->pPreUpdate==0 );
4766 memset(&preupdate, 0, sizeof(PreUpdate));
4767 if( HasRowid(pTab)==0 ){
4768 iKey1 = iKey2 = 0;
4769 preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
4770 }else{
4771 if( op==SQLITE_UPDATE ){
4772 iKey2 = v->aMem[iReg].u.i;
4773 }else{
4774 iKey2 = iKey1;
4778 assert( pCsr->nField==pTab->nCol
4779 || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
4782 preupdate.v = v;
4783 preupdate.pCsr = pCsr;
4784 preupdate.op = op;
4785 preupdate.iNewReg = iReg;
4786 preupdate.keyinfo.db = db;
4787 preupdate.keyinfo.enc = ENC(db);
4788 preupdate.keyinfo.nKeyField = pTab->nCol;
4789 preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
4790 preupdate.iKey1 = iKey1;
4791 preupdate.iKey2 = iKey2;
4792 preupdate.pTab = pTab;
4794 db->pPreUpdate = &preupdate;
4795 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
4796 db->pPreUpdate = 0;
4797 sqlite3DbFree(db, preupdate.aRecord);
4798 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
4799 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
4800 if( preupdate.aNew ){
4801 int i;
4802 for(i=0; i<pCsr->nField; i++){
4803 sqlite3VdbeMemRelease(&preupdate.aNew[i]);
4805 sqlite3DbFreeNN(db, preupdate.aNew);
4808 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */