4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code used for creating, destroying, and populating
13 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
15 #include "sqliteInt.h"
19 ** Create a new virtual database engine.
21 Vdbe
*sqlite3VdbeCreate(Parse
*pParse
){
22 sqlite3
*db
= pParse
->db
;
24 p
= sqlite3DbMallocRawNN(db
, sizeof(Vdbe
) );
26 memset(&p
->aOp
, 0, sizeof(Vdbe
)-offsetof(Vdbe
,aOp
));
34 p
->magic
= VDBE_MAGIC_INIT
;
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);
46 ** Change the error string stored in Vdbe.zErrMsg
48 void sqlite3VdbeError(Vdbe
*p
, const char *zFormat
, ...){
50 sqlite3DbFree(p
->db
, p
->zErrMsg
);
51 va_start(ap
, zFormat
);
52 p
->zErrMsg
= sqlite3VMPrintf(p
->db
, zFormat
, ap
);
57 ** Remember the SQL string for a prepared statement.
59 void sqlite3VdbeSetSql(Vdbe
*p
, const char *z
, int n
, u8 prepFlags
){
61 p
->prepFlags
= prepFlags
;
62 if( (prepFlags
& SQLITE_PREPARE_SAVESQL
)==0 ){
66 p
->zSql
= sqlite3DbStrNDup(p
->db
, z
, n
);
70 ** Swap all content between two VDBE structures.
72 void sqlite3VdbeSwap(Vdbe
*pA
, Vdbe
*pB
){
75 assert( pA
->db
==pB
->db
);
80 pA
->pNext
= pB
->pNext
;
83 pA
->pPrev
= pB
->pPrev
;
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
){
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
);
118 int nNew
= (p
->nOpAlloc
? p
->nOpAlloc
*2 : (int)(1024/sizeof(Op
)));
119 UNUSED_PARAMETER(nOp
);
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
);
128 assert( nOp
<=(1024/sizeof(Op
)) );
129 assert( nNew
>=(p
->nOpAlloc
+nOp
) );
130 pNew
= sqlite3DbRealloc(p
->db
, v
->aOp
, nNew
*sizeof(Op
));
132 p
->szOpAlloc
= sqlite3DbMallocSize(p
->db
, pNew
);
133 p
->nOpAlloc
= p
->szOpAlloc
/sizeof(Op
);
136 return (pNew
? SQLITE_OK
: SQLITE_NOMEM_BKPT
);
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){
151 ** Add a new instruction to the list of instructions current in the
152 ** VDBE. Return the address of the new instruction.
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
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
){
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
);
184 pOp
->opcode
= (u8
)op
;
190 pOp
->p4type
= P4_NOTUSED
;
191 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
195 if( p
->db
->flags
& SQLITE_VdbeAddopTrace
){
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
);
203 if( kk
) printf("\n");
204 sqlite3VdbePrintOp(0, i
, &p
->aOp
[i
]);
205 test_addop_breakpoint();
212 #ifdef SQLITE_VDBE_COVERAGE
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
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
, ...){
255 va_start(ap
, zTypes
);
256 for(i
=0; (c
= zTypes
[i
])!=0; i
++){
258 const char *z
= va_arg(ap
, const char*);
259 sqlite3VdbeAddOp4(p
, z
==0 ? OP_Null
: OP_String8
, 0, iDest
+i
, 0, z
, 0);
261 sqlite3VdbeAddOp2(p
, OP_Integer
, va_arg(ap
, int), iDest
+i
);
263 goto skip_op_resultrow
;
266 sqlite3VdbeAddOp2(p
, OP_ResultRow
, iDest
, i
);
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
);
289 ** Add an opcode that includes the p4 value with a P4_INT64 or
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.
311 int sqlite3VdbeExplainParent(Parse
*pParse
){
313 if( pParse
->addrExplain
==0 ) return 0;
314 pOp
= sqlite3VdbeGetOp(pParse
->pVdbe
, pParse
->addrExplain
);
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 ){
327 Vdbe
*v
= pParse
->pVdbe
;
331 zMsg
= sqlite3VMPrintf(pParse
->db
, zFmt
, ap
);
335 sqlite3VdbeAddOp4(v
, OP_Explain
, iThis
, pParse
->addrExplain
, 0,
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
){
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
;
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
;
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]));
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
;
434 assert( v
->magic
==VDBE_MAGIC_INIT
);
435 assert( j
<p
->nLabel
);
439 if( p
->db
->flags
& SQLITE_VdbeAddopTrace
){
440 printf("RESOLVE LABEL %d to %d\n", x
, v
->nOp
);
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
){
469 ** Mark the VDBE as one that can only be run multiple times.
471 void sqlite3VdbeReusable(Vdbe
*p
){
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:
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
490 ** sqlite3DbFree(v->db, sIter.apSub);
493 typedef struct VdbeOpIter 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
){
507 if( p
->iSub
<=p
->nSub
){
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
];
525 if( pRet
->p4type
==P4_SUBPROGRAM
){
526 int nByte
= (p
->nSub
+1)*sizeof(SubProgram
*);
528 for(j
=0; j
<p
->nSub
; j
++){
529 if( p
->apSub
[j
]==pRet
->p4
.pProgram
) break;
532 p
->apSub
= sqlite3DbReallocOrFree(v
->db
, p
->apSub
, nByte
);
536 p
->apSub
[p
->nSub
++] = pRet
->p4
.pProgram
;
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.
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
){
569 int hasFkCounter
= 0;
570 int hasCreateTable
= 0;
571 int hasInitCoroutine
= 0;
574 memset(&sIter
, 0, sizeof(sIter
));
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
))
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 ){
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
601 return ( v
->db
->mallocFailed
|| hasAbort
==mayAbort
|| hasFkCounter
602 || (hasCreateTable
&& hasInitCoroutine
) );
604 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
608 ** Increment the nWrite counter in the VDBE if the cursor is not an
609 ** ephemeral cursor, or if the cursor argument is NULL.
611 void sqlite3VdbeIncrWriteCounter(Vdbe
*p
, VdbeCursor
*pC
){
613 || (pC
->eCurType
!=CURTYPE_SORTER
614 && pC
->eCurType
!=CURTYPE_PSEUDO
624 ** Assert if an Abort at this point in time might result in a corrupt
627 void sqlite3VdbeAssertAbortable(Vdbe
*p
){
628 assert( p
->nWrite
==0 || p
->usesStmtJournal
);
633 ** This routine is called after all opcodes have been inserted. It loops
634 ** through all the opcodes and fixes up some details.
636 ** (1) For each jump instruction with a negative P2 value (a label)
637 ** resolve the P2 value to an actual address.
639 ** (2) Compute the maximum number of arguments used by any SQL function
640 ** and store that value in *pMaxFuncArgs.
642 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
643 ** indicate what the prepared statement actually does.
645 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
647 ** (5) Reclaim the memory allocated for storing labels.
649 ** This routine will only function correctly if the mkopcodeh.tcl generator
650 ** script numbers the opcodes correctly. Changes to this routine must be
651 ** coordinated with changes to mkopcodeh.tcl.
653 static void resolveP2Values(Vdbe
*p
, int *pMaxFuncArgs
){
654 int nMaxArgs
= *pMaxFuncArgs
;
656 Parse
*pParse
= p
->pParse
;
657 int *aLabel
= pParse
->aLabel
;
660 pOp
= &p
->aOp
[p
->nOp
-1];
663 /* Only JUMP opcodes and the short list of special opcodes in the switch
664 ** below need to be considered. The mkopcodeh.tcl generator script groups
665 ** all these opcodes together near the front of the opcode list. Skip
666 ** any opcode that does not need processing by virtual of the fact that
667 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
669 if( pOp
->opcode
<=SQLITE_MX_JUMP_OPCODE
){
670 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
671 ** cases from this switch! */
672 switch( pOp
->opcode
){
673 case OP_Transaction
: {
674 if( pOp
->p2
!=0 ) p
->readOnly
= 0;
682 #ifndef SQLITE_OMIT_WAL
686 case OP_JournalMode
: {
692 case OP_SorterNext
: {
693 pOp
->p4
.xAdvance
= sqlite3BtreeNext
;
694 pOp
->p4type
= P4_ADVANCE
;
695 /* The code generator never codes any of these opcodes as a jump
696 ** to a label. They are always coded as a jump backwards to a
698 assert( pOp
->p2
>=0 );
702 pOp
->p4
.xAdvance
= sqlite3BtreePrevious
;
703 pOp
->p4type
= P4_ADVANCE
;
704 /* The code generator never codes any of these opcodes as a jump
705 ** to a label. They are always coded as a jump backwards to a
707 assert( pOp
->p2
>=0 );
710 #ifndef SQLITE_OMIT_VIRTUALTABLE
712 if( pOp
->p2
>nMaxArgs
) nMaxArgs
= pOp
->p2
;
717 assert( (pOp
- p
->aOp
) >= 3 );
718 assert( pOp
[-1].opcode
==OP_Integer
);
720 if( n
>nMaxArgs
) nMaxArgs
= n
;
721 /* Fall through into the default case */
726 /* The mkopcodeh.tcl script has so arranged things that the only
727 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
728 ** have non-negative values for P2. */
729 assert( (sqlite3OpcodeProperty
[pOp
->opcode
] & OPFLG_JUMP
)!=0 );
730 assert( ADDR(pOp
->p2
)<pParse
->nLabel
);
731 pOp
->p2
= aLabel
[ADDR(pOp
->p2
)];
736 /* The mkopcodeh.tcl script has so arranged things that the only
737 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
738 ** have non-negative values for P2. */
739 assert( (sqlite3OpcodeProperty
[pOp
->opcode
]&OPFLG_JUMP
)==0 || pOp
->p2
>=0);
741 if( pOp
==p
->aOp
) break;
744 sqlite3DbFree(p
->db
, pParse
->aLabel
);
747 *pMaxFuncArgs
= nMaxArgs
;
748 assert( p
->bIsReader
!=0 || DbMaskAllZero(p
->btreeMask
) );
752 ** Return the address of the next instruction to be inserted.
754 int sqlite3VdbeCurrentAddr(Vdbe
*p
){
755 assert( p
->magic
==VDBE_MAGIC_INIT
);
760 ** Verify that at least N opcode slots are available in p without
761 ** having to malloc for more space (except when compiled using
762 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
763 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
764 ** fail due to a OOM fault and hence that the return value from
765 ** sqlite3VdbeAddOpList() will always be non-NULL.
767 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
768 void sqlite3VdbeVerifyNoMallocRequired(Vdbe
*p
, int N
){
769 assert( p
->nOp
+ N
<= p
->pParse
->nOpAlloc
);
774 ** Verify that the VM passed as the only argument does not contain
775 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
776 ** by code in pragma.c to ensure that the implementation of certain
777 ** pragmas comports with the flags specified in the mkpragmatab.tcl
780 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
781 void sqlite3VdbeVerifyNoResultRow(Vdbe
*p
){
783 for(i
=0; i
<p
->nOp
; i
++){
784 assert( p
->aOp
[i
].opcode
!=OP_ResultRow
);
790 ** Generate code (a single OP_Abortable opcode) that will
791 ** verify that the VDBE program can safely call Abort in the current
794 #if defined(SQLITE_DEBUG)
795 void sqlite3VdbeVerifyAbortable(Vdbe
*p
, int onError
){
796 if( onError
==OE_Abort
) sqlite3VdbeAddOp0(p
, OP_Abortable
);
801 ** This function returns a pointer to the array of opcodes associated with
802 ** the Vdbe passed as the first argument. It is the callers responsibility
803 ** to arrange for the returned array to be eventually freed using the
804 ** vdbeFreeOpArray() function.
806 ** Before returning, *pnOp is set to the number of entries in the returned
807 ** array. Also, *pnMaxArg is set to the larger of its current value and
808 ** the number of entries in the Vdbe.apArg[] array required to execute the
811 VdbeOp
*sqlite3VdbeTakeOpArray(Vdbe
*p
, int *pnOp
, int *pnMaxArg
){
812 VdbeOp
*aOp
= p
->aOp
;
813 assert( aOp
&& !p
->db
->mallocFailed
);
815 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
816 assert( DbMaskAllZero(p
->btreeMask
) );
818 resolveP2Values(p
, pnMaxArg
);
825 ** Add a whole list of operations to the operation stack. Return a
826 ** pointer to the first operation inserted.
828 ** Non-zero P2 arguments to jump instructions are automatically adjusted
829 ** so that the jump target is relative to the first operation inserted.
831 VdbeOp
*sqlite3VdbeAddOpList(
832 Vdbe
*p
, /* Add opcodes to the prepared statement */
833 int nOp
, /* Number of opcodes to add */
834 VdbeOpList
const *aOp
, /* The opcodes to be added */
835 int iLineno
/* Source-file line number of first opcode */
838 VdbeOp
*pOut
, *pFirst
;
840 assert( p
->magic
==VDBE_MAGIC_INIT
);
841 if( p
->nOp
+ nOp
> p
->pParse
->nOpAlloc
&& growOpArray(p
, nOp
) ){
844 pFirst
= pOut
= &p
->aOp
[p
->nOp
];
845 for(i
=0; i
<nOp
; i
++, aOp
++, pOut
++){
846 pOut
->opcode
= aOp
->opcode
;
849 assert( aOp
->p2
>=0 );
850 if( (sqlite3OpcodeProperty
[aOp
->opcode
] & OPFLG_JUMP
)!=0 && aOp
->p2
>0 ){
854 pOut
->p4type
= P4_NOTUSED
;
857 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
860 #ifdef SQLITE_VDBE_COVERAGE
861 pOut
->iSrcLine
= iLineno
+i
;
866 if( p
->db
->flags
& SQLITE_VdbeAddopTrace
){
867 sqlite3VdbePrintOp(0, i
+p
->nOp
, &p
->aOp
[i
+p
->nOp
]);
875 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
877 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
879 void sqlite3VdbeScanStatus(
880 Vdbe
*p
, /* VM to add scanstatus() to */
881 int addrExplain
, /* Address of OP_Explain (or 0) */
882 int addrLoop
, /* Address of loop counter */
883 int addrVisit
, /* Address of rows visited counter */
884 LogEst nEst
, /* Estimated number of output rows */
885 const char *zName
/* Name of table or index being scanned */
887 int nByte
= (p
->nScan
+1) * sizeof(ScanStatus
);
889 aNew
= (ScanStatus
*)sqlite3DbRealloc(p
->db
, p
->aScan
, nByte
);
891 ScanStatus
*pNew
= &aNew
[p
->nScan
++];
892 pNew
->addrExplain
= addrExplain
;
893 pNew
->addrLoop
= addrLoop
;
894 pNew
->addrVisit
= addrVisit
;
896 pNew
->zName
= sqlite3DbStrDup(p
->db
, zName
);
904 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
905 ** for a specific instruction.
907 void sqlite3VdbeChangeOpcode(Vdbe
*p
, u32 addr
, u8 iNewOpcode
){
908 sqlite3VdbeGetOp(p
,addr
)->opcode
= iNewOpcode
;
910 void sqlite3VdbeChangeP1(Vdbe
*p
, u32 addr
, int val
){
911 sqlite3VdbeGetOp(p
,addr
)->p1
= val
;
913 void sqlite3VdbeChangeP2(Vdbe
*p
, u32 addr
, int val
){
914 sqlite3VdbeGetOp(p
,addr
)->p2
= val
;
916 void sqlite3VdbeChangeP3(Vdbe
*p
, u32 addr
, int val
){
917 sqlite3VdbeGetOp(p
,addr
)->p3
= val
;
919 void sqlite3VdbeChangeP5(Vdbe
*p
, u16 p5
){
920 assert( p
->nOp
>0 || p
->db
->mallocFailed
);
921 if( p
->nOp
>0 ) p
->aOp
[p
->nOp
-1].p5
= p5
;
925 ** Change the P2 operand of instruction addr so that it points to
926 ** the address of the next instruction to be coded.
928 void sqlite3VdbeJumpHere(Vdbe
*p
, int addr
){
929 sqlite3VdbeChangeP2(p
, addr
, p
->nOp
);
934 ** If the input FuncDef structure is ephemeral, then free it. If
935 ** the FuncDef is not ephermal, then do nothing.
937 static void freeEphemeralFunction(sqlite3
*db
, FuncDef
*pDef
){
938 if( (pDef
->funcFlags
& SQLITE_FUNC_EPHEM
)!=0 ){
939 sqlite3DbFreeNN(db
, pDef
);
943 static void vdbeFreeOpArray(sqlite3
*, Op
*, int);
946 ** Delete a P4 value if necessary.
948 static SQLITE_NOINLINE
void freeP4Mem(sqlite3
*db
, Mem
*p
){
949 if( p
->szMalloc
) sqlite3DbFree(db
, p
->zMalloc
);
950 sqlite3DbFreeNN(db
, p
);
952 static SQLITE_NOINLINE
void freeP4FuncCtx(sqlite3
*db
, sqlite3_context
*p
){
953 freeEphemeralFunction(db
, p
->pFunc
);
954 sqlite3DbFreeNN(db
, p
);
956 static void freeP4(sqlite3
*db
, int p4type
, void *p4
){
960 freeP4FuncCtx(db
, (sqlite3_context
*)p4
);
968 sqlite3DbFree(db
, p4
);
972 if( db
->pnBytesFreed
==0 ) sqlite3KeyInfoUnref((KeyInfo
*)p4
);
975 #ifdef SQLITE_ENABLE_CURSOR_HINTS
977 sqlite3ExprDelete(db
, (Expr
*)p4
);
982 freeEphemeralFunction(db
, (FuncDef
*)p4
);
986 if( db
->pnBytesFreed
==0 ){
987 sqlite3ValueFree((sqlite3_value
*)p4
);
989 freeP4Mem(db
, (Mem
*)p4
);
994 if( db
->pnBytesFreed
==0 ) sqlite3VtabUnlock((VTable
*)p4
);
1001 ** Free the space allocated for aOp and any p4 values allocated for the
1002 ** opcodes contained within. If aOp is not NULL it is assumed to contain
1005 static void vdbeFreeOpArray(sqlite3
*db
, Op
*aOp
, int nOp
){
1008 for(pOp
=&aOp
[nOp
-1]; pOp
>=aOp
; pOp
--){
1009 if( pOp
->p4type
<= P4_FREE_IF_LE
) freeP4(db
, pOp
->p4type
, pOp
->p4
.p
);
1010 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1011 sqlite3DbFree(db
, pOp
->zComment
);
1014 sqlite3DbFreeNN(db
, aOp
);
1019 ** Link the SubProgram object passed as the second argument into the linked
1020 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
1021 ** objects when the VM is no longer required.
1023 void sqlite3VdbeLinkSubProgram(Vdbe
*pVdbe
, SubProgram
*p
){
1024 p
->pNext
= pVdbe
->pProgram
;
1025 pVdbe
->pProgram
= p
;
1029 ** Change the opcode at addr into OP_Noop
1031 int sqlite3VdbeChangeToNoop(Vdbe
*p
, int addr
){
1033 if( p
->db
->mallocFailed
) return 0;
1034 assert( addr
>=0 && addr
<p
->nOp
);
1035 pOp
= &p
->aOp
[addr
];
1036 freeP4(p
->db
, pOp
->p4type
, pOp
->p4
.p
);
1037 pOp
->p4type
= P4_NOTUSED
;
1039 pOp
->opcode
= OP_Noop
;
1044 ** If the last opcode is "op" and it is not a jump destination,
1045 ** then remove it. Return true if and only if an opcode was removed.
1047 int sqlite3VdbeDeletePriorOpcode(Vdbe
*p
, u8 op
){
1048 if( p
->nOp
>0 && p
->aOp
[p
->nOp
-1].opcode
==op
){
1049 return sqlite3VdbeChangeToNoop(p
, p
->nOp
-1);
1056 ** Change the value of the P4 operand for a specific instruction.
1057 ** This routine is useful when a large program is loaded from a
1058 ** static array using sqlite3VdbeAddOpList but we want to make a
1059 ** few minor changes to the program.
1061 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
1062 ** the string is made into memory obtained from sqlite3_malloc().
1063 ** A value of n==0 means copy bytes of zP4 up to and including the
1064 ** first null byte. If n>0 then copy n+1 bytes of zP4.
1066 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
1067 ** to a string or structure that is guaranteed to exist for the lifetime of
1068 ** the Vdbe. In these cases we can just copy the pointer.
1070 ** If addr<0 then change P4 on the most recently inserted instruction.
1072 static void SQLITE_NOINLINE
vdbeChangeP4Full(
1079 freeP4(p
->db
, pOp
->p4type
, pOp
->p4
.p
);
1084 sqlite3VdbeChangeP4(p
, (int)(pOp
- p
->aOp
), zP4
, n
);
1086 if( n
==0 ) n
= sqlite3Strlen30(zP4
);
1087 pOp
->p4
.z
= sqlite3DbStrNDup(p
->db
, zP4
, n
);
1088 pOp
->p4type
= P4_DYNAMIC
;
1091 void sqlite3VdbeChangeP4(Vdbe
*p
, int addr
, const char *zP4
, int n
){
1096 assert( p
->magic
==VDBE_MAGIC_INIT
);
1097 assert( p
->aOp
!=0 || db
->mallocFailed
);
1098 if( db
->mallocFailed
){
1099 if( n
!=P4_VTAB
) freeP4(db
, n
, (void*)*(char**)&zP4
);
1103 assert( addr
<p
->nOp
);
1107 pOp
= &p
->aOp
[addr
];
1108 if( n
>=0 || pOp
->p4type
){
1109 vdbeChangeP4Full(p
, pOp
, zP4
, n
);
1113 /* Note: this cast is safe, because the origin data point was an int
1114 ** that was cast to a (const char *). */
1115 pOp
->p4
.i
= SQLITE_PTR_TO_INT(zP4
);
1116 pOp
->p4type
= P4_INT32
;
1119 pOp
->p4
.p
= (void*)zP4
;
1120 pOp
->p4type
= (signed char)n
;
1121 if( n
==P4_VTAB
) sqlite3VtabLock((VTable
*)zP4
);
1126 ** Change the P4 operand of the most recently coded instruction
1127 ** to the value defined by the arguments. This is a high-speed
1128 ** version of sqlite3VdbeChangeP4().
1130 ** The P4 operand must not have been previously defined. And the new
1131 ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
1134 void sqlite3VdbeAppendP4(Vdbe
*p
, void *pP4
, int n
){
1136 assert( n
!=P4_INT32
&& n
!=P4_VTAB
);
1138 if( p
->db
->mallocFailed
){
1139 freeP4(p
->db
, n
, pP4
);
1143 pOp
= &p
->aOp
[p
->nOp
-1];
1144 assert( pOp
->p4type
==P4_NOTUSED
);
1151 ** Set the P4 on the most recently added opcode to the KeyInfo for the
1154 void sqlite3VdbeSetP4KeyInfo(Parse
*pParse
, Index
*pIdx
){
1155 Vdbe
*v
= pParse
->pVdbe
;
1159 pKeyInfo
= sqlite3KeyInfoOfIndex(pParse
, pIdx
);
1160 if( pKeyInfo
) sqlite3VdbeAppendP4(v
, pKeyInfo
, P4_KEYINFO
);
1163 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1165 ** Change the comment on the most recently coded instruction. Or
1166 ** insert a No-op and add the comment to that new instruction. This
1167 ** makes the code easier to read during debugging. None of this happens
1168 ** in a production build.
1170 static void vdbeVComment(Vdbe
*p
, const char *zFormat
, va_list ap
){
1171 assert( p
->nOp
>0 || p
->aOp
==0 );
1172 assert( p
->aOp
==0 || p
->aOp
[p
->nOp
-1].zComment
==0 || p
->db
->mallocFailed
);
1175 sqlite3DbFree(p
->db
, p
->aOp
[p
->nOp
-1].zComment
);
1176 p
->aOp
[p
->nOp
-1].zComment
= sqlite3VMPrintf(p
->db
, zFormat
, ap
);
1179 void sqlite3VdbeComment(Vdbe
*p
, const char *zFormat
, ...){
1182 va_start(ap
, zFormat
);
1183 vdbeVComment(p
, zFormat
, ap
);
1187 void sqlite3VdbeNoopComment(Vdbe
*p
, const char *zFormat
, ...){
1190 sqlite3VdbeAddOp0(p
, OP_Noop
);
1191 va_start(ap
, zFormat
);
1192 vdbeVComment(p
, zFormat
, ap
);
1198 #ifdef SQLITE_VDBE_COVERAGE
1200 ** Set the value if the iSrcLine field for the previously coded instruction.
1202 void sqlite3VdbeSetLineNumber(Vdbe
*v
, int iLine
){
1203 sqlite3VdbeGetOp(v
,-1)->iSrcLine
= iLine
;
1205 #endif /* SQLITE_VDBE_COVERAGE */
1208 ** Return the opcode for a given address. If the address is -1, then
1209 ** return the most recently inserted opcode.
1211 ** If a memory allocation error has occurred prior to the calling of this
1212 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
1213 ** is readable but not writable, though it is cast to a writable value.
1214 ** The return of a dummy opcode allows the call to continue functioning
1215 ** after an OOM fault without having to check to see if the return from
1216 ** this routine is a valid pointer. But because the dummy.opcode is 0,
1217 ** dummy will never be written to. This is verified by code inspection and
1218 ** by running with Valgrind.
1220 VdbeOp
*sqlite3VdbeGetOp(Vdbe
*p
, int addr
){
1221 /* C89 specifies that the constant "dummy" will be initialized to all
1222 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
1223 static VdbeOp dummy
; /* Ignore the MSVC warning about no initializer */
1224 assert( p
->magic
==VDBE_MAGIC_INIT
);
1228 assert( (addr
>=0 && addr
<p
->nOp
) || p
->db
->mallocFailed
);
1229 if( p
->db
->mallocFailed
){
1230 return (VdbeOp
*)&dummy
;
1232 return &p
->aOp
[addr
];
1236 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
1238 ** Return an integer value for one of the parameters to the opcode pOp
1239 ** determined by character c.
1241 static int translateP(char c
, const Op
*pOp
){
1242 if( c
=='1' ) return pOp
->p1
;
1243 if( c
=='2' ) return pOp
->p2
;
1244 if( c
=='3' ) return pOp
->p3
;
1245 if( c
=='4' ) return pOp
->p4
.i
;
1250 ** Compute a string for the "comment" field of a VDBE opcode listing.
1252 ** The Synopsis: field in comments in the vdbe.c source file gets converted
1253 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
1254 ** absence of other comments, this synopsis becomes the comment on the opcode.
1255 ** Some translation occurs:
1258 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
1259 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
1260 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
1262 static int displayComment(
1263 const Op
*pOp
, /* The opcode to be commented */
1264 const char *zP4
, /* Previously obtained value for P4 */
1265 char *zTemp
, /* Write result here */
1266 int nTemp
/* Space available in zTemp[] */
1268 const char *zOpName
;
1269 const char *zSynopsis
;
1273 zOpName
= sqlite3OpcodeName(pOp
->opcode
);
1274 nOpName
= sqlite3Strlen30(zOpName
);
1275 if( zOpName
[nOpName
+1] ){
1278 zSynopsis
= zOpName
+= nOpName
+ 1;
1279 if( strncmp(zSynopsis
,"IF ",3)==0 ){
1280 if( pOp
->p5
& SQLITE_STOREP2
){
1281 sqlite3_snprintf(sizeof(zAlt
), zAlt
, "r[P2] = (%s)", zSynopsis
+3);
1283 sqlite3_snprintf(sizeof(zAlt
), zAlt
, "if %s goto P2", zSynopsis
+3);
1287 for(ii
=jj
=0; jj
<nTemp
-1 && (c
= zSynopsis
[ii
])!=0; ii
++){
1289 c
= zSynopsis
[++ii
];
1291 sqlite3_snprintf(nTemp
-jj
, zTemp
+jj
, "%s", zP4
);
1293 sqlite3_snprintf(nTemp
-jj
, zTemp
+jj
, "%s", pOp
->zComment
);
1296 int v1
= translateP(c
, pOp
);
1298 sqlite3_snprintf(nTemp
-jj
, zTemp
+jj
, "%d", v1
);
1299 if( strncmp(zSynopsis
+ii
+1, "@P", 2)==0 ){
1301 jj
+= sqlite3Strlen30(zTemp
+jj
);
1302 v2
= translateP(zSynopsis
[ii
], pOp
);
1303 if( strncmp(zSynopsis
+ii
+1,"+1",2)==0 ){
1308 sqlite3_snprintf(nTemp
-jj
, zTemp
+jj
, "..%d", v1
+v2
-1);
1310 }else if( strncmp(zSynopsis
+ii
+1, "..P3", 4)==0 && pOp
->p3
==0 ){
1314 jj
+= sqlite3Strlen30(zTemp
+jj
);
1319 if( !seenCom
&& jj
<nTemp
-5 && pOp
->zComment
){
1320 sqlite3_snprintf(nTemp
-jj
, zTemp
+jj
, "; %s", pOp
->zComment
);
1321 jj
+= sqlite3Strlen30(zTemp
+jj
);
1323 if( jj
<nTemp
) zTemp
[jj
] = 0;
1324 }else if( pOp
->zComment
){
1325 sqlite3_snprintf(nTemp
, zTemp
, "%s", pOp
->zComment
);
1326 jj
= sqlite3Strlen30(zTemp
);
1333 #endif /* SQLITE_DEBUG */
1335 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
1337 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
1338 ** that can be displayed in the P4 column of EXPLAIN output.
1340 static void displayP4Expr(StrAccum
*p
, Expr
*pExpr
){
1341 const char *zOp
= 0;
1342 switch( pExpr
->op
){
1344 sqlite3_str_appendf(p
, "%Q", pExpr
->u
.zToken
);
1347 sqlite3_str_appendf(p
, "%d", pExpr
->u
.iValue
);
1350 sqlite3_str_appendf(p
, "NULL");
1353 sqlite3_str_appendf(p
, "r[%d]", pExpr
->iTable
);
1357 if( pExpr
->iColumn
<0 ){
1358 sqlite3_str_appendf(p
, "rowid");
1360 sqlite3_str_appendf(p
, "c%d", (int)pExpr
->iColumn
);
1364 case TK_LT
: zOp
= "LT"; break;
1365 case TK_LE
: zOp
= "LE"; break;
1366 case TK_GT
: zOp
= "GT"; break;
1367 case TK_GE
: zOp
= "GE"; break;
1368 case TK_NE
: zOp
= "NE"; break;
1369 case TK_EQ
: zOp
= "EQ"; break;
1370 case TK_IS
: zOp
= "IS"; break;
1371 case TK_ISNOT
: zOp
= "ISNOT"; break;
1372 case TK_AND
: zOp
= "AND"; break;
1373 case TK_OR
: zOp
= "OR"; break;
1374 case TK_PLUS
: zOp
= "ADD"; break;
1375 case TK_STAR
: zOp
= "MUL"; break;
1376 case TK_MINUS
: zOp
= "SUB"; break;
1377 case TK_REM
: zOp
= "REM"; break;
1378 case TK_BITAND
: zOp
= "BITAND"; break;
1379 case TK_BITOR
: zOp
= "BITOR"; break;
1380 case TK_SLASH
: zOp
= "DIV"; break;
1381 case TK_LSHIFT
: zOp
= "LSHIFT"; break;
1382 case TK_RSHIFT
: zOp
= "RSHIFT"; break;
1383 case TK_CONCAT
: zOp
= "CONCAT"; break;
1384 case TK_UMINUS
: zOp
= "MINUS"; break;
1385 case TK_UPLUS
: zOp
= "PLUS"; break;
1386 case TK_BITNOT
: zOp
= "BITNOT"; break;
1387 case TK_NOT
: zOp
= "NOT"; break;
1388 case TK_ISNULL
: zOp
= "ISNULL"; break;
1389 case TK_NOTNULL
: zOp
= "NOTNULL"; break;
1392 sqlite3_str_appendf(p
, "%s", "expr");
1397 sqlite3_str_appendf(p
, "%s(", zOp
);
1398 displayP4Expr(p
, pExpr
->pLeft
);
1399 if( pExpr
->pRight
){
1400 sqlite3_str_append(p
, ",", 1);
1401 displayP4Expr(p
, pExpr
->pRight
);
1403 sqlite3_str_append(p
, ")", 1);
1406 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
1411 ** Compute a string that describes the P4 parameter for an opcode.
1412 ** Use zTemp for any required temporary buffer space.
1414 static char *displayP4(Op
*pOp
, char *zTemp
, int nTemp
){
1417 assert( nTemp
>=20 );
1418 sqlite3StrAccumInit(&x
, 0, zTemp
, nTemp
, 0);
1419 switch( pOp
->p4type
){
1422 KeyInfo
*pKeyInfo
= pOp
->p4
.pKeyInfo
;
1423 assert( pKeyInfo
->aSortOrder
!=0 );
1424 sqlite3_str_appendf(&x
, "k(%d", pKeyInfo
->nKeyField
);
1425 for(j
=0; j
<pKeyInfo
->nKeyField
; j
++){
1426 CollSeq
*pColl
= pKeyInfo
->aColl
[j
];
1427 const char *zColl
= pColl
? pColl
->zName
: "";
1428 if( strcmp(zColl
, "BINARY")==0 ) zColl
= "B";
1429 sqlite3_str_appendf(&x
, ",%s%s",
1430 pKeyInfo
->aSortOrder
[j
] ? "-" : "", zColl
);
1432 sqlite3_str_append(&x
, ")", 1);
1435 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1437 displayP4Expr(&x
, pOp
->p4
.pExpr
);
1442 CollSeq
*pColl
= pOp
->p4
.pColl
;
1443 sqlite3_str_appendf(&x
, "(%.20s)", pColl
->zName
);
1447 FuncDef
*pDef
= pOp
->p4
.pFunc
;
1448 sqlite3_str_appendf(&x
, "%s(%d)", pDef
->zName
, pDef
->nArg
);
1451 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1453 FuncDef
*pDef
= pOp
->p4
.pCtx
->pFunc
;
1454 sqlite3_str_appendf(&x
, "%s(%d)", pDef
->zName
, pDef
->nArg
);
1459 sqlite3_str_appendf(&x
, "%lld", *pOp
->p4
.pI64
);
1463 sqlite3_str_appendf(&x
, "%d", pOp
->p4
.i
);
1467 sqlite3_str_appendf(&x
, "%.16g", *pOp
->p4
.pReal
);
1471 Mem
*pMem
= pOp
->p4
.pMem
;
1472 if( pMem
->flags
& MEM_Str
){
1474 }else if( pMem
->flags
& MEM_Int
){
1475 sqlite3_str_appendf(&x
, "%lld", pMem
->u
.i
);
1476 }else if( pMem
->flags
& MEM_Real
){
1477 sqlite3_str_appendf(&x
, "%.16g", pMem
->u
.r
);
1478 }else if( pMem
->flags
& MEM_Null
){
1481 assert( pMem
->flags
& MEM_Blob
);
1486 #ifndef SQLITE_OMIT_VIRTUALTABLE
1488 sqlite3_vtab
*pVtab
= pOp
->p4
.pVtab
->pVtab
;
1489 sqlite3_str_appendf(&x
, "vtab:%p", pVtab
);
1495 int *ai
= pOp
->p4
.ai
;
1496 int n
= ai
[0]; /* The first element of an INTARRAY is always the
1497 ** count of the number of elements to follow */
1498 for(i
=1; i
<=n
; i
++){
1499 sqlite3_str_appendf(&x
, ",%d", ai
[i
]);
1502 sqlite3_str_append(&x
, "]", 1);
1505 case P4_SUBPROGRAM
: {
1506 sqlite3_str_appendf(&x
, "program");
1515 sqlite3_str_appendf(&x
, "%s", pOp
->p4
.pTab
->zName
);
1526 sqlite3StrAccumFinish(&x
);
1530 #endif /* VDBE_DISPLAY_P4 */
1533 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
1535 ** The prepared statements need to know in advance the complete set of
1536 ** attached databases that will be use. A mask of these databases
1537 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
1538 ** p->btreeMask of databases that will require a lock.
1540 void sqlite3VdbeUsesBtree(Vdbe
*p
, int i
){
1541 assert( i
>=0 && i
<p
->db
->nDb
&& i
<(int)sizeof(yDbMask
)*8 );
1542 assert( i
<(int)sizeof(p
->btreeMask
)*8 );
1543 DbMaskSet(p
->btreeMask
, i
);
1544 if( i
!=1 && sqlite3BtreeSharable(p
->db
->aDb
[i
].pBt
) ){
1545 DbMaskSet(p
->lockMask
, i
);
1549 #if !defined(SQLITE_OMIT_SHARED_CACHE)
1551 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1552 ** this routine obtains the mutex associated with each BtShared structure
1553 ** that may be accessed by the VM passed as an argument. In doing so it also
1554 ** sets the BtShared.db member of each of the BtShared structures, ensuring
1555 ** that the correct busy-handler callback is invoked if required.
1557 ** If SQLite is not threadsafe but does support shared-cache mode, then
1558 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1559 ** of all of BtShared structures accessible via the database handle
1560 ** associated with the VM.
1562 ** If SQLite is not threadsafe and does not support shared-cache mode, this
1563 ** function is a no-op.
1565 ** The p->btreeMask field is a bitmask of all btrees that the prepared
1566 ** statement p will ever use. Let N be the number of bits in p->btreeMask
1567 ** corresponding to btrees that use shared cache. Then the runtime of
1568 ** this routine is N*N. But as N is rarely more than 1, this should not
1571 void sqlite3VdbeEnter(Vdbe
*p
){
1576 if( DbMaskAllZero(p
->lockMask
) ) return; /* The common case */
1580 for(i
=0; i
<nDb
; i
++){
1581 if( i
!=1 && DbMaskTest(p
->lockMask
,i
) && ALWAYS(aDb
[i
].pBt
!=0) ){
1582 sqlite3BtreeEnter(aDb
[i
].pBt
);
1588 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1590 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1592 static SQLITE_NOINLINE
void vdbeLeave(Vdbe
*p
){
1600 for(i
=0; i
<nDb
; i
++){
1601 if( i
!=1 && DbMaskTest(p
->lockMask
,i
) && ALWAYS(aDb
[i
].pBt
!=0) ){
1602 sqlite3BtreeLeave(aDb
[i
].pBt
);
1606 void sqlite3VdbeLeave(Vdbe
*p
){
1607 if( DbMaskAllZero(p
->lockMask
) ) return; /* The common case */
1612 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
1614 ** Print a single opcode. This routine is used for debugging only.
1616 void sqlite3VdbePrintOp(FILE *pOut
, int pc
, VdbeOp
*pOp
){
1620 static const char *zFormat1
= "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
1621 if( pOut
==0 ) pOut
= stdout
;
1622 zP4
= displayP4(pOp
, zPtr
, sizeof(zPtr
));
1623 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1624 displayComment(pOp
, zP4
, zCom
, sizeof(zCom
));
1628 /* NB: The sqlite3OpcodeName() function is implemented by code created
1629 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1630 ** information from the vdbe.c source text */
1631 fprintf(pOut
, zFormat1
, pc
,
1632 sqlite3OpcodeName(pOp
->opcode
), pOp
->p1
, pOp
->p2
, pOp
->p3
, zP4
, pOp
->p5
,
1640 ** Initialize an array of N Mem element.
1642 static void initMemArray(Mem
*p
, int N
, sqlite3
*db
, u16 flags
){
1650 #ifdef SQLITE_DEBUG_COLUMNCACHE
1658 ** Release an array of N Mem elements
1660 static void releaseMemArray(Mem
*p
, int N
){
1663 sqlite3
*db
= p
->db
;
1664 if( db
->pnBytesFreed
){
1666 if( p
->szMalloc
) sqlite3DbFree(db
, p
->zMalloc
);
1667 }while( (++p
)<pEnd
);
1671 assert( (&p
[1])==pEnd
|| p
[0].db
==p
[1].db
);
1672 assert( sqlite3VdbeCheckMemInvariants(p
) );
1674 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1675 ** that takes advantage of the fact that the memory cell value is
1676 ** being set to NULL after releasing any dynamic resources.
1678 ** The justification for duplicating code is that according to
1679 ** callgrind, this causes a certain test case to hit the CPU 4.7
1680 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1681 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1682 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1683 ** with no indexes using a single prepared INSERT statement, bind()
1684 ** and reset(). Inserts are grouped into a transaction.
1686 testcase( p
->flags
& MEM_Agg
);
1687 testcase( p
->flags
& MEM_Dyn
);
1688 testcase( p
->flags
& MEM_Frame
);
1689 testcase( p
->flags
& MEM_RowSet
);
1690 if( p
->flags
&(MEM_Agg
|MEM_Dyn
|MEM_Frame
|MEM_RowSet
) ){
1691 sqlite3VdbeMemRelease(p
);
1692 }else if( p
->szMalloc
){
1693 sqlite3DbFreeNN(db
, p
->zMalloc
);
1697 p
->flags
= MEM_Undefined
;
1698 }while( (++p
)<pEnd
);
1703 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1704 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
1706 void sqlite3VdbeFrameDelete(VdbeFrame
*p
){
1708 Mem
*aMem
= VdbeFrameMem(p
);
1709 VdbeCursor
**apCsr
= (VdbeCursor
**)&aMem
[p
->nChildMem
];
1710 for(i
=0; i
<p
->nChildCsr
; i
++){
1711 sqlite3VdbeFreeCursor(p
->v
, apCsr
[i
]);
1713 releaseMemArray(aMem
, p
->nChildMem
);
1714 sqlite3VdbeDeleteAuxData(p
->v
->db
, &p
->pAuxData
, -1, 0);
1715 sqlite3DbFree(p
->v
->db
, p
);
1718 #ifndef SQLITE_OMIT_EXPLAIN
1720 ** Give a listing of the program in the virtual machine.
1722 ** The interface is the same as sqlite3VdbeExec(). But instead of
1723 ** running the code, it invokes the callback once for each instruction.
1724 ** This feature is used to implement "EXPLAIN".
1726 ** When p->explain==1, each instruction is listed. When
1727 ** p->explain==2, only OP_Explain instructions are listed and these
1728 ** are shown in a different format. p->explain==2 is used to implement
1729 ** EXPLAIN QUERY PLAN.
1730 ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
1731 ** are also shown, so that the boundaries between the main program and
1732 ** each trigger are clear.
1734 ** When p->explain==1, first the main program is listed, then each of
1735 ** the trigger subprograms are listed one by one.
1737 int sqlite3VdbeList(
1738 Vdbe
*p
/* The VDBE */
1740 int nRow
; /* Stop when row count reaches this */
1741 int nSub
= 0; /* Number of sub-vdbes seen so far */
1742 SubProgram
**apSub
= 0; /* Array of sub-vdbes */
1743 Mem
*pSub
= 0; /* Memory cell hold array of subprogs */
1744 sqlite3
*db
= p
->db
; /* The database connection */
1745 int i
; /* Loop counter */
1746 int rc
= SQLITE_OK
; /* Return code */
1747 Mem
*pMem
= &p
->aMem
[1]; /* First Mem of result set */
1748 int bListSubprogs
= (p
->explain
==1 || (db
->flags
& SQLITE_TriggerEQP
)!=0);
1751 assert( p
->explain
);
1752 assert( p
->magic
==VDBE_MAGIC_RUN
);
1753 assert( p
->rc
==SQLITE_OK
|| p
->rc
==SQLITE_BUSY
|| p
->rc
==SQLITE_NOMEM
);
1755 /* Even though this opcode does not use dynamic strings for
1756 ** the result, result columns may become dynamic if the user calls
1757 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
1759 releaseMemArray(pMem
, 8);
1762 if( p
->rc
==SQLITE_NOMEM
){
1763 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1764 ** sqlite3_column_text16() failed. */
1765 sqlite3OomFault(db
);
1766 return SQLITE_ERROR
;
1769 /* When the number of output rows reaches nRow, that means the
1770 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1771 ** nRow is the sum of the number of rows in the main program, plus
1772 ** the sum of the number of rows in all trigger subprograms encountered
1773 ** so far. The nRow value will increase as new trigger subprograms are
1774 ** encountered, but p->pc will eventually catch up to nRow.
1777 if( bListSubprogs
){
1778 /* The first 8 memory cells are used for the result set. So we will
1779 ** commandeer the 9th cell to use as storage for an array of pointers
1780 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1782 assert( p
->nMem
>9 );
1784 if( pSub
->flags
&MEM_Blob
){
1785 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1786 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
1787 nSub
= pSub
->n
/sizeof(Vdbe
*);
1788 apSub
= (SubProgram
**)pSub
->z
;
1790 for(i
=0; i
<nSub
; i
++){
1791 nRow
+= apSub
[i
]->nOp
;
1795 while(1){ /* Loop exits via break */
1803 /* The output line number is small enough that we are still in the
1807 /* We are currently listing subprograms. Figure out which one and
1808 ** pick up the appropriate opcode. */
1811 for(j
=0; i
>=apSub
[j
]->nOp
; j
++){
1814 pOp
= &apSub
[j
]->aOp
[i
];
1817 /* When an OP_Program opcode is encounter (the only opcode that has
1818 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1819 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1820 ** has not already been seen.
1822 if( bListSubprogs
&& pOp
->p4type
==P4_SUBPROGRAM
){
1823 int nByte
= (nSub
+1)*sizeof(SubProgram
*);
1825 for(j
=0; j
<nSub
; j
++){
1826 if( apSub
[j
]==pOp
->p4
.pProgram
) break;
1829 p
->rc
= sqlite3VdbeMemGrow(pSub
, nByte
, nSub
!=0);
1830 if( p
->rc
!=SQLITE_OK
){
1834 apSub
= (SubProgram
**)pSub
->z
;
1835 apSub
[nSub
++] = pOp
->p4
.pProgram
;
1836 pSub
->flags
|= MEM_Blob
;
1837 pSub
->n
= nSub
*sizeof(SubProgram
*);
1838 nRow
+= pOp
->p4
.pProgram
->nOp
;
1841 if( p
->explain
<2 ) break;
1842 if( pOp
->opcode
==OP_Explain
) break;
1843 if( pOp
->opcode
==OP_Init
&& p
->pc
>1 ) break;
1846 if( rc
==SQLITE_OK
){
1847 if( db
->u1
.isInterrupted
){
1848 p
->rc
= SQLITE_INTERRUPT
;
1850 sqlite3VdbeError(p
, sqlite3ErrStr(p
->rc
));
1853 if( p
->explain
==1 ){
1854 pMem
->flags
= MEM_Int
;
1855 pMem
->u
.i
= i
; /* Program counter */
1858 pMem
->flags
= MEM_Static
|MEM_Str
|MEM_Term
;
1859 pMem
->z
= (char*)sqlite3OpcodeName(pOp
->opcode
); /* Opcode */
1860 assert( pMem
->z
!=0 );
1861 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1862 pMem
->enc
= SQLITE_UTF8
;
1866 pMem
->flags
= MEM_Int
;
1867 pMem
->u
.i
= pOp
->p1
; /* P1 */
1870 pMem
->flags
= MEM_Int
;
1871 pMem
->u
.i
= pOp
->p2
; /* P2 */
1874 pMem
->flags
= MEM_Int
;
1875 pMem
->u
.i
= pOp
->p3
; /* P3 */
1878 if( sqlite3VdbeMemClearAndResize(pMem
, 100) ){ /* P4 */
1879 assert( p
->db
->mallocFailed
);
1880 return SQLITE_ERROR
;
1882 pMem
->flags
= MEM_Str
|MEM_Term
;
1883 zP4
= displayP4(pOp
, pMem
->z
, pMem
->szMalloc
);
1886 sqlite3VdbeMemSetStr(pMem
, zP4
, -1, SQLITE_UTF8
, 0);
1888 assert( pMem
->z
!=0 );
1889 pMem
->n
= sqlite3Strlen30(pMem
->z
);
1890 pMem
->enc
= SQLITE_UTF8
;
1894 if( p
->explain
==1 ){
1895 if( sqlite3VdbeMemClearAndResize(pMem
, 4) ){
1896 assert( p
->db
->mallocFailed
);
1897 return SQLITE_ERROR
;
1899 pMem
->flags
= MEM_Str
|MEM_Term
;
1901 sqlite3_snprintf(3, pMem
->z
, "%.2x", pOp
->p5
); /* P5 */
1902 pMem
->enc
= SQLITE_UTF8
;
1905 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1906 if( sqlite3VdbeMemClearAndResize(pMem
, 500) ){
1907 assert( p
->db
->mallocFailed
);
1908 return SQLITE_ERROR
;
1910 pMem
->flags
= MEM_Str
|MEM_Term
;
1911 pMem
->n
= displayComment(pOp
, zP4
, pMem
->z
, 500);
1912 pMem
->enc
= SQLITE_UTF8
;
1914 pMem
->flags
= MEM_Null
; /* Comment */
1918 p
->nResColumn
= 8 - 4*(p
->explain
-1);
1919 p
->pResultSet
= &p
->aMem
[1];
1926 #endif /* SQLITE_OMIT_EXPLAIN */
1930 ** Print the SQL that was used to generate a VDBE program.
1932 void sqlite3VdbePrintSql(Vdbe
*p
){
1936 }else if( p
->nOp
>=1 ){
1937 const VdbeOp
*pOp
= &p
->aOp
[0];
1938 if( pOp
->opcode
==OP_Init
&& pOp
->p4
.z
!=0 ){
1940 while( sqlite3Isspace(*z
) ) z
++;
1943 if( z
) printf("SQL: [%s]\n", z
);
1947 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1949 ** Print an IOTRACE message showing SQL content.
1951 void sqlite3VdbeIOTraceSql(Vdbe
*p
){
1954 if( sqlite3IoTrace
==0 ) return;
1957 if( pOp
->opcode
==OP_Init
&& pOp
->p4
.z
!=0 ){
1960 sqlite3_snprintf(sizeof(z
), z
, "%s", pOp
->p4
.z
);
1961 for(i
=0; sqlite3Isspace(z
[i
]); i
++){}
1962 for(j
=0; z
[i
]; i
++){
1963 if( sqlite3Isspace(z
[i
]) ){
1972 sqlite3IoTrace("SQL %s\n", z
);
1975 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1977 /* An instance of this object describes bulk memory available for use
1978 ** by subcomponents of a prepared statement. Space is allocated out
1979 ** of a ReusableSpace object by the allocSpace() routine below.
1981 struct ReusableSpace
{
1982 u8
*pSpace
; /* Available memory */
1983 int nFree
; /* Bytes of available memory */
1984 int nNeeded
; /* Total bytes that could not be allocated */
1987 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
1988 ** from the ReusableSpace object. Return a pointer to the allocated
1989 ** memory on success. If insufficient memory is available in the
1990 ** ReusableSpace object, increase the ReusableSpace.nNeeded
1991 ** value by the amount needed and return NULL.
1993 ** If pBuf is not initially NULL, that means that the memory has already
1994 ** been allocated by a prior call to this routine, so just return a copy
1995 ** of pBuf and leave ReusableSpace unchanged.
1997 ** This allocator is employed to repurpose unused slots at the end of the
1998 ** opcode array of prepared state for other memory needs of the prepared
2001 static void *allocSpace(
2002 struct ReusableSpace
*p
, /* Bulk memory available for allocation */
2003 void *pBuf
, /* Pointer to a prior allocation */
2004 int nByte
/* Bytes of memory needed */
2006 assert( EIGHT_BYTE_ALIGNMENT(p
->pSpace
) );
2008 nByte
= ROUND8(nByte
);
2009 if( nByte
<= p
->nFree
){
2011 pBuf
= &p
->pSpace
[p
->nFree
];
2013 p
->nNeeded
+= nByte
;
2016 assert( EIGHT_BYTE_ALIGNMENT(pBuf
) );
2021 ** Rewind the VDBE back to the beginning in preparation for
2024 void sqlite3VdbeRewind(Vdbe
*p
){
2025 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
2029 assert( p
->magic
==VDBE_MAGIC_INIT
|| p
->magic
==VDBE_MAGIC_RESET
);
2031 /* There should be at least one opcode.
2035 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
2036 p
->magic
= VDBE_MAGIC_RUN
;
2039 for(i
=0; i
<p
->nMem
; i
++){
2040 assert( p
->aMem
[i
].db
==p
->db
);
2045 p
->errorAction
= OE_Abort
;
2048 p
->minWriteFileFormat
= 255;
2050 p
->nFkConstraint
= 0;
2052 for(i
=0; i
<p
->nOp
; i
++){
2054 p
->aOp
[i
].cycles
= 0;
2060 ** Prepare a virtual machine for execution for the first time after
2061 ** creating the virtual machine. This involves things such
2062 ** as allocating registers and initializing the program counter.
2063 ** After the VDBE has be prepped, it can be executed by one or more
2064 ** calls to sqlite3VdbeExec().
2066 ** This function may be called exactly once on each virtual machine.
2067 ** After this routine is called the VM has been "packaged" and is ready
2068 ** to run. After this routine is called, further calls to
2069 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
2070 ** the Vdbe from the Parse object that helped generate it so that the
2071 ** the Vdbe becomes an independent entity and the Parse object can be
2074 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
2075 ** to its initial state after it has been run.
2077 void sqlite3VdbeMakeReady(
2078 Vdbe
*p
, /* The VDBE */
2079 Parse
*pParse
/* Parsing context */
2081 sqlite3
*db
; /* The database connection */
2082 int nVar
; /* Number of parameters */
2083 int nMem
; /* Number of VM memory registers */
2084 int nCursor
; /* Number of cursors required */
2085 int nArg
; /* Number of arguments in subprograms */
2086 int n
; /* Loop counter */
2087 struct ReusableSpace x
; /* Reusable bulk memory */
2091 assert( pParse
!=0 );
2092 assert( p
->magic
==VDBE_MAGIC_INIT
);
2093 assert( pParse
==p
->pParse
);
2095 assert( db
->mallocFailed
==0 );
2096 nVar
= pParse
->nVar
;
2097 nMem
= pParse
->nMem
;
2098 nCursor
= pParse
->nTab
;
2099 nArg
= pParse
->nMaxArg
;
2101 /* Each cursor uses a memory cell. The first cursor (cursor 0) can
2102 ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
2103 ** space at the end of aMem[] for cursors 1 and greater.
2104 ** See also: allocateCursor().
2107 if( nCursor
==0 && nMem
>0 ) nMem
++; /* Space for aMem[0] even if not used */
2109 /* Figure out how much reusable memory is available at the end of the
2110 ** opcode array. This extra memory will be reallocated for other elements
2111 ** of the prepared statement.
2113 n
= ROUND8(sizeof(Op
)*p
->nOp
); /* Bytes of opcode memory used */
2114 x
.pSpace
= &((u8
*)p
->aOp
)[n
]; /* Unused opcode memory */
2115 assert( EIGHT_BYTE_ALIGNMENT(x
.pSpace
) );
2116 x
.nFree
= ROUNDDOWN8(pParse
->szOpAlloc
- n
); /* Bytes of unused memory */
2117 assert( x
.nFree
>=0 );
2118 assert( EIGHT_BYTE_ALIGNMENT(&x
.pSpace
[x
.nFree
]) );
2120 resolveP2Values(p
, &nArg
);
2121 p
->usesStmtJournal
= (u8
)(pParse
->isMultiWrite
&& pParse
->mayAbort
);
2122 if( pParse
->explain
&& nMem
<10 ){
2127 /* Memory for registers, parameters, cursor, etc, is allocated in one or two
2128 ** passes. On the first pass, we try to reuse unused memory at the
2129 ** end of the opcode array. If we are unable to satisfy all memory
2130 ** requirements by reusing the opcode array tail, then the second
2131 ** pass will fill in the remainder using a fresh memory allocation.
2133 ** This two-pass approach that reuses as much memory as possible from
2134 ** the leftover memory at the end of the opcode array. This can significantly
2135 ** reduce the amount of memory held by a prepared statement.
2139 p
->aMem
= allocSpace(&x
, p
->aMem
, nMem
*sizeof(Mem
));
2140 p
->aVar
= allocSpace(&x
, p
->aVar
, nVar
*sizeof(Mem
));
2141 p
->apArg
= allocSpace(&x
, p
->apArg
, nArg
*sizeof(Mem
*));
2142 p
->apCsr
= allocSpace(&x
, p
->apCsr
, nCursor
*sizeof(VdbeCursor
*));
2143 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2144 p
->anExec
= allocSpace(&x
, p
->anExec
, p
->nOp
*sizeof(i64
));
2146 if( x
.nNeeded
==0 ) break;
2147 x
.pSpace
= p
->pFree
= sqlite3DbMallocRawNN(db
, x
.nNeeded
);
2148 x
.nFree
= x
.nNeeded
;
2149 }while( !db
->mallocFailed
);
2151 p
->pVList
= pParse
->pVList
;
2153 p
->explain
= pParse
->explain
;
2154 if( db
->mallocFailed
){
2159 p
->nCursor
= nCursor
;
2160 p
->nVar
= (ynVar
)nVar
;
2161 initMemArray(p
->aVar
, nVar
, db
, MEM_Null
);
2163 initMemArray(p
->aMem
, nMem
, db
, MEM_Undefined
);
2164 memset(p
->apCsr
, 0, nCursor
*sizeof(VdbeCursor
*));
2165 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2166 memset(p
->anExec
, 0, p
->nOp
*sizeof(i64
));
2169 sqlite3VdbeRewind(p
);
2173 ** Close a VDBE cursor and release all the resources that cursor
2176 void sqlite3VdbeFreeCursor(Vdbe
*p
, VdbeCursor
*pCx
){
2180 assert( pCx
->pBtx
==0 || pCx
->eCurType
==CURTYPE_BTREE
);
2181 switch( pCx
->eCurType
){
2182 case CURTYPE_SORTER
: {
2183 sqlite3VdbeSorterClose(p
->db
, pCx
);
2186 case CURTYPE_BTREE
: {
2187 if( pCx
->isEphemeral
){
2188 if( pCx
->pBtx
) sqlite3BtreeClose(pCx
->pBtx
);
2189 /* The pCx->pCursor will be close automatically, if it exists, by
2190 ** the call above. */
2192 assert( pCx
->uc
.pCursor
!=0 );
2193 sqlite3BtreeCloseCursor(pCx
->uc
.pCursor
);
2197 #ifndef SQLITE_OMIT_VIRTUALTABLE
2198 case CURTYPE_VTAB
: {
2199 sqlite3_vtab_cursor
*pVCur
= pCx
->uc
.pVCur
;
2200 const sqlite3_module
*pModule
= pVCur
->pVtab
->pModule
;
2201 assert( pVCur
->pVtab
->nRef
>0 );
2202 pVCur
->pVtab
->nRef
--;
2203 pModule
->xClose(pVCur
);
2211 ** Close all cursors in the current frame.
2213 static void closeCursorsInFrame(Vdbe
*p
){
2216 for(i
=0; i
<p
->nCursor
; i
++){
2217 VdbeCursor
*pC
= p
->apCsr
[i
];
2219 sqlite3VdbeFreeCursor(p
, pC
);
2227 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
2228 ** is used, for example, when a trigger sub-program is halted to restore
2229 ** control to the main program.
2231 int sqlite3VdbeFrameRestore(VdbeFrame
*pFrame
){
2232 Vdbe
*v
= pFrame
->v
;
2233 closeCursorsInFrame(v
);
2234 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2235 v
->anExec
= pFrame
->anExec
;
2237 v
->aOp
= pFrame
->aOp
;
2238 v
->nOp
= pFrame
->nOp
;
2239 v
->aMem
= pFrame
->aMem
;
2240 v
->nMem
= pFrame
->nMem
;
2241 v
->apCsr
= pFrame
->apCsr
;
2242 v
->nCursor
= pFrame
->nCursor
;
2243 v
->db
->lastRowid
= pFrame
->lastRowid
;
2244 v
->nChange
= pFrame
->nChange
;
2245 v
->db
->nChange
= pFrame
->nDbChange
;
2246 sqlite3VdbeDeleteAuxData(v
->db
, &v
->pAuxData
, -1, 0);
2247 v
->pAuxData
= pFrame
->pAuxData
;
2248 pFrame
->pAuxData
= 0;
2253 ** Close all cursors.
2255 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
2256 ** cell array. This is necessary as the memory cell array may contain
2257 ** pointers to VdbeFrame objects, which may in turn contain pointers to
2260 static void closeAllCursors(Vdbe
*p
){
2263 for(pFrame
=p
->pFrame
; pFrame
->pParent
; pFrame
=pFrame
->pParent
);
2264 sqlite3VdbeFrameRestore(pFrame
);
2268 assert( p
->nFrame
==0 );
2269 closeCursorsInFrame(p
);
2271 releaseMemArray(p
->aMem
, p
->nMem
);
2273 while( p
->pDelFrame
){
2274 VdbeFrame
*pDel
= p
->pDelFrame
;
2275 p
->pDelFrame
= pDel
->pParent
;
2276 sqlite3VdbeFrameDelete(pDel
);
2279 /* Delete any auxdata allocations made by the VM */
2280 if( p
->pAuxData
) sqlite3VdbeDeleteAuxData(p
->db
, &p
->pAuxData
, -1, 0);
2281 assert( p
->pAuxData
==0 );
2285 ** Set the number of result columns that will be returned by this SQL
2286 ** statement. This is now set at compile time, rather than during
2287 ** execution of the vdbe program so that sqlite3_column_count() can
2288 ** be called on an SQL statement before sqlite3_step().
2290 void sqlite3VdbeSetNumCols(Vdbe
*p
, int nResColumn
){
2292 sqlite3
*db
= p
->db
;
2294 if( p
->nResColumn
){
2295 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
2296 sqlite3DbFree(db
, p
->aColName
);
2298 n
= nResColumn
*COLNAME_N
;
2299 p
->nResColumn
= (u16
)nResColumn
;
2300 p
->aColName
= (Mem
*)sqlite3DbMallocRawNN(db
, sizeof(Mem
)*n
);
2301 if( p
->aColName
==0 ) return;
2302 initMemArray(p
->aColName
, n
, db
, MEM_Null
);
2306 ** Set the name of the idx'th column to be returned by the SQL statement.
2307 ** zName must be a pointer to a nul terminated string.
2309 ** This call must be made after a call to sqlite3VdbeSetNumCols().
2311 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
2312 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
2313 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
2315 int sqlite3VdbeSetColName(
2316 Vdbe
*p
, /* Vdbe being configured */
2317 int idx
, /* Index of column zName applies to */
2318 int var
, /* One of the COLNAME_* constants */
2319 const char *zName
, /* Pointer to buffer containing name */
2320 void (*xDel
)(void*) /* Memory management strategy for zName */
2324 assert( idx
<p
->nResColumn
);
2325 assert( var
<COLNAME_N
);
2326 if( p
->db
->mallocFailed
){
2327 assert( !zName
|| xDel
!=SQLITE_DYNAMIC
);
2328 return SQLITE_NOMEM_BKPT
;
2330 assert( p
->aColName
!=0 );
2331 pColName
= &(p
->aColName
[idx
+var
*p
->nResColumn
]);
2332 rc
= sqlite3VdbeMemSetStr(pColName
, zName
, -1, SQLITE_UTF8
, xDel
);
2333 assert( rc
!=0 || !zName
|| (pColName
->flags
&MEM_Term
)!=0 );
2338 ** A read or write transaction may or may not be active on database handle
2339 ** db. If a transaction is active, commit it. If there is a
2340 ** write-transaction spanning more than one database file, this routine
2341 ** takes care of the master journal trickery.
2343 static int vdbeCommit(sqlite3
*db
, Vdbe
*p
){
2345 int nTrans
= 0; /* Number of databases with an active write-transaction
2346 ** that are candidates for a two-phase commit using a
2347 ** master-journal */
2349 int needXcommit
= 0;
2351 #ifdef SQLITE_OMIT_VIRTUALTABLE
2352 /* With this option, sqlite3VtabSync() is defined to be simply
2353 ** SQLITE_OK so p is not used.
2355 UNUSED_PARAMETER(p
);
2358 /* Before doing anything else, call the xSync() callback for any
2359 ** virtual module tables written in this transaction. This has to
2360 ** be done before determining whether a master journal file is
2361 ** required, as an xSync() callback may add an attached database
2362 ** to the transaction.
2364 rc
= sqlite3VtabSync(db
, p
);
2366 /* This loop determines (a) if the commit hook should be invoked and
2367 ** (b) how many database files have open write transactions, not
2368 ** including the temp database. (b) is important because if more than
2369 ** one database file has an open write transaction, a master journal
2370 ** file is required for an atomic commit.
2372 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
2373 Btree
*pBt
= db
->aDb
[i
].pBt
;
2374 if( sqlite3BtreeIsInTrans(pBt
) ){
2375 /* Whether or not a database might need a master journal depends upon
2376 ** its journal mode (among other things). This matrix determines which
2377 ** journal modes use a master journal and which do not */
2378 static const u8 aMJNeeded
[] = {
2386 Pager
*pPager
; /* Pager associated with pBt */
2388 sqlite3BtreeEnter(pBt
);
2389 pPager
= sqlite3BtreePager(pBt
);
2390 if( db
->aDb
[i
].safety_level
!=PAGER_SYNCHRONOUS_OFF
2391 && aMJNeeded
[sqlite3PagerGetJournalMode(pPager
)]
2392 && sqlite3PagerIsMemdb(pPager
)==0
2397 rc
= sqlite3PagerExclusiveLock(pPager
);
2398 sqlite3BtreeLeave(pBt
);
2401 if( rc
!=SQLITE_OK
){
2405 /* If there are any write-transactions at all, invoke the commit hook */
2406 if( needXcommit
&& db
->xCommitCallback
){
2407 rc
= db
->xCommitCallback(db
->pCommitArg
);
2409 return SQLITE_CONSTRAINT_COMMITHOOK
;
2413 /* The simple case - no more than one database file (not counting the
2414 ** TEMP database) has a transaction active. There is no need for the
2417 ** If the return value of sqlite3BtreeGetFilename() is a zero length
2418 ** string, it means the main database is :memory: or a temp file. In
2419 ** that case we do not support atomic multi-file commits, so use the
2420 ** simple case then too.
2422 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db
->aDb
[0].pBt
))
2425 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
2426 Btree
*pBt
= db
->aDb
[i
].pBt
;
2428 rc
= sqlite3BtreeCommitPhaseOne(pBt
, 0);
2432 /* Do the commit only if all databases successfully complete phase 1.
2433 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2434 ** IO error while deleting or truncating a journal file. It is unlikely,
2435 ** but could happen. In this case abandon processing and return the error.
2437 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
2438 Btree
*pBt
= db
->aDb
[i
].pBt
;
2440 rc
= sqlite3BtreeCommitPhaseTwo(pBt
, 0);
2443 if( rc
==SQLITE_OK
){
2444 sqlite3VtabCommit(db
);
2448 /* The complex case - There is a multi-file write-transaction active.
2449 ** This requires a master journal file to ensure the transaction is
2450 ** committed atomically.
2452 #ifndef SQLITE_OMIT_DISKIO
2454 sqlite3_vfs
*pVfs
= db
->pVfs
;
2455 char *zMaster
= 0; /* File-name for the master journal */
2456 char const *zMainFile
= sqlite3BtreeGetFilename(db
->aDb
[0].pBt
);
2457 sqlite3_file
*pMaster
= 0;
2463 /* Select a master journal file name */
2464 nMainFile
= sqlite3Strlen30(zMainFile
);
2465 zMaster
= sqlite3MPrintf(db
, "%s-mjXXXXXX9XXz", zMainFile
);
2466 if( zMaster
==0 ) return SQLITE_NOMEM_BKPT
;
2470 if( retryCount
>100 ){
2471 sqlite3_log(SQLITE_FULL
, "MJ delete: %s", zMaster
);
2472 sqlite3OsDelete(pVfs
, zMaster
, 0);
2474 }else if( retryCount
==1 ){
2475 sqlite3_log(SQLITE_FULL
, "MJ collide: %s", zMaster
);
2479 sqlite3_randomness(sizeof(iRandom
), &iRandom
);
2480 sqlite3_snprintf(13, &zMaster
[nMainFile
], "-mj%06X9%02X",
2481 (iRandom
>>8)&0xffffff, iRandom
&0xff);
2482 /* The antipenultimate character of the master journal name must
2483 ** be "9" to avoid name collisions when using 8+3 filenames. */
2484 assert( zMaster
[sqlite3Strlen30(zMaster
)-3]=='9' );
2485 sqlite3FileSuffix3(zMainFile
, zMaster
);
2486 rc
= sqlite3OsAccess(pVfs
, zMaster
, SQLITE_ACCESS_EXISTS
, &res
);
2487 }while( rc
==SQLITE_OK
&& res
);
2488 if( rc
==SQLITE_OK
){
2489 /* Open the master journal. */
2490 rc
= sqlite3OsOpenMalloc(pVfs
, zMaster
, &pMaster
,
2491 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
|
2492 SQLITE_OPEN_EXCLUSIVE
|SQLITE_OPEN_MASTER_JOURNAL
, 0
2495 if( rc
!=SQLITE_OK
){
2496 sqlite3DbFree(db
, zMaster
);
2500 /* Write the name of each database file in the transaction into the new
2501 ** master journal file. If an error occurs at this point close
2502 ** and delete the master journal file. All the individual journal files
2503 ** still have 'null' as the master journal pointer, so they will roll
2504 ** back independently if a failure occurs.
2506 for(i
=0; i
<db
->nDb
; i
++){
2507 Btree
*pBt
= db
->aDb
[i
].pBt
;
2508 if( sqlite3BtreeIsInTrans(pBt
) ){
2509 char const *zFile
= sqlite3BtreeGetJournalname(pBt
);
2511 continue; /* Ignore TEMP and :memory: databases */
2513 assert( zFile
[0]!=0 );
2514 rc
= sqlite3OsWrite(pMaster
, zFile
, sqlite3Strlen30(zFile
)+1, offset
);
2515 offset
+= sqlite3Strlen30(zFile
)+1;
2516 if( rc
!=SQLITE_OK
){
2517 sqlite3OsCloseFree(pMaster
);
2518 sqlite3OsDelete(pVfs
, zMaster
, 0);
2519 sqlite3DbFree(db
, zMaster
);
2525 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2526 ** flag is set this is not required.
2528 if( 0==(sqlite3OsDeviceCharacteristics(pMaster
)&SQLITE_IOCAP_SEQUENTIAL
)
2529 && SQLITE_OK
!=(rc
= sqlite3OsSync(pMaster
, SQLITE_SYNC_NORMAL
))
2531 sqlite3OsCloseFree(pMaster
);
2532 sqlite3OsDelete(pVfs
, zMaster
, 0);
2533 sqlite3DbFree(db
, zMaster
);
2537 /* Sync all the db files involved in the transaction. The same call
2538 ** sets the master journal pointer in each individual journal. If
2539 ** an error occurs here, do not delete the master journal file.
2541 ** If the error occurs during the first call to
2542 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2543 ** master journal file will be orphaned. But we cannot delete it,
2544 ** in case the master journal file name was written into the journal
2545 ** file before the failure occurred.
2547 for(i
=0; rc
==SQLITE_OK
&& i
<db
->nDb
; i
++){
2548 Btree
*pBt
= db
->aDb
[i
].pBt
;
2550 rc
= sqlite3BtreeCommitPhaseOne(pBt
, zMaster
);
2553 sqlite3OsCloseFree(pMaster
);
2554 assert( rc
!=SQLITE_BUSY
);
2555 if( rc
!=SQLITE_OK
){
2556 sqlite3DbFree(db
, zMaster
);
2560 /* Delete the master journal file. This commits the transaction. After
2561 ** doing this the directory is synced again before any individual
2562 ** transaction files are deleted.
2564 rc
= sqlite3OsDelete(pVfs
, zMaster
, 1);
2565 sqlite3DbFree(db
, zMaster
);
2571 /* All files and directories have already been synced, so the following
2572 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2573 ** deleting or truncating journals. If something goes wrong while
2574 ** this is happening we don't really care. The integrity of the
2575 ** transaction is already guaranteed, but some stray 'cold' journals
2576 ** may be lying around. Returning an error code won't help matters.
2578 disable_simulated_io_errors();
2579 sqlite3BeginBenignMalloc();
2580 for(i
=0; i
<db
->nDb
; i
++){
2581 Btree
*pBt
= db
->aDb
[i
].pBt
;
2583 sqlite3BtreeCommitPhaseTwo(pBt
, 1);
2586 sqlite3EndBenignMalloc();
2587 enable_simulated_io_errors();
2589 sqlite3VtabCommit(db
);
2597 ** This routine checks that the sqlite3.nVdbeActive count variable
2598 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
2599 ** currently active. An assertion fails if the two counts do not match.
2600 ** This is an internal self-check only - it is not an essential processing
2603 ** This is a no-op if NDEBUG is defined.
2606 static void checkActiveVdbeCnt(sqlite3
*db
){
2613 if( sqlite3_stmt_busy((sqlite3_stmt
*)p
) ){
2615 if( p
->readOnly
==0 ) nWrite
++;
2616 if( p
->bIsReader
) nRead
++;
2620 assert( cnt
==db
->nVdbeActive
);
2621 assert( nWrite
==db
->nVdbeWrite
);
2622 assert( nRead
==db
->nVdbeRead
);
2625 #define checkActiveVdbeCnt(x)
2629 ** If the Vdbe passed as the first argument opened a statement-transaction,
2630 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2631 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2632 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
2633 ** statement transaction is committed.
2635 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2636 ** Otherwise SQLITE_OK.
2638 static SQLITE_NOINLINE
int vdbeCloseStatement(Vdbe
*p
, int eOp
){
2639 sqlite3
*const db
= p
->db
;
2642 const int iSavepoint
= p
->iStatement
-1;
2644 assert( eOp
==SAVEPOINT_ROLLBACK
|| eOp
==SAVEPOINT_RELEASE
);
2645 assert( db
->nStatement
>0 );
2646 assert( p
->iStatement
==(db
->nStatement
+db
->nSavepoint
) );
2648 for(i
=0; i
<db
->nDb
; i
++){
2649 int rc2
= SQLITE_OK
;
2650 Btree
*pBt
= db
->aDb
[i
].pBt
;
2652 if( eOp
==SAVEPOINT_ROLLBACK
){
2653 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2655 if( rc2
==SQLITE_OK
){
2656 rc2
= sqlite3BtreeSavepoint(pBt
, SAVEPOINT_RELEASE
, iSavepoint
);
2658 if( rc
==SQLITE_OK
){
2666 if( rc
==SQLITE_OK
){
2667 if( eOp
==SAVEPOINT_ROLLBACK
){
2668 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_ROLLBACK
, iSavepoint
);
2670 if( rc
==SQLITE_OK
){
2671 rc
= sqlite3VtabSavepoint(db
, SAVEPOINT_RELEASE
, iSavepoint
);
2675 /* If the statement transaction is being rolled back, also restore the
2676 ** database handles deferred constraint counter to the value it had when
2677 ** the statement transaction was opened. */
2678 if( eOp
==SAVEPOINT_ROLLBACK
){
2679 db
->nDeferredCons
= p
->nStmtDefCons
;
2680 db
->nDeferredImmCons
= p
->nStmtDefImmCons
;
2684 int sqlite3VdbeCloseStatement(Vdbe
*p
, int eOp
){
2685 if( p
->db
->nStatement
&& p
->iStatement
){
2686 return vdbeCloseStatement(p
, eOp
);
2693 ** This function is called when a transaction opened by the database
2694 ** handle associated with the VM passed as an argument is about to be
2695 ** committed. If there are outstanding deferred foreign key constraint
2696 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2698 ** If there are outstanding FK violations and this function returns
2699 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2700 ** and write an error message to it. Then return SQLITE_ERROR.
2702 #ifndef SQLITE_OMIT_FOREIGN_KEY
2703 int sqlite3VdbeCheckFk(Vdbe
*p
, int deferred
){
2704 sqlite3
*db
= p
->db
;
2705 if( (deferred
&& (db
->nDeferredCons
+db
->nDeferredImmCons
)>0)
2706 || (!deferred
&& p
->nFkConstraint
>0)
2708 p
->rc
= SQLITE_CONSTRAINT_FOREIGNKEY
;
2709 p
->errorAction
= OE_Abort
;
2710 sqlite3VdbeError(p
, "FOREIGN KEY constraint failed");
2711 return SQLITE_ERROR
;
2718 ** This routine is called the when a VDBE tries to halt. If the VDBE
2719 ** has made changes and is in autocommit mode, then commit those
2720 ** changes. If a rollback is needed, then do the rollback.
2722 ** This routine is the only way to move the state of a VM from
2723 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2724 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
2726 ** Return an error code. If the commit could not complete because of
2727 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2728 ** means the close did not happen and needs to be repeated.
2730 int sqlite3VdbeHalt(Vdbe
*p
){
2731 int rc
; /* Used to store transient return codes */
2732 sqlite3
*db
= p
->db
;
2734 /* This function contains the logic that determines if a statement or
2735 ** transaction will be committed or rolled back as a result of the
2736 ** execution of this virtual machine.
2738 ** If any of the following errors occur:
2745 ** Then the internal cache might have been left in an inconsistent
2746 ** state. We need to rollback the statement transaction, if there is
2747 ** one, or the complete transaction if there is no statement transaction.
2750 if( p
->magic
!=VDBE_MAGIC_RUN
){
2753 if( db
->mallocFailed
){
2754 p
->rc
= SQLITE_NOMEM_BKPT
;
2757 checkActiveVdbeCnt(db
);
2759 /* No commit or rollback needed if the program never started or if the
2760 ** SQL statement does not read or write a database file. */
2761 if( p
->pc
>=0 && p
->bIsReader
){
2762 int mrc
; /* Primary error code from p->rc */
2763 int eStatementOp
= 0;
2764 int isSpecialError
; /* Set to true if a 'special' error */
2766 /* Lock all btrees used by the statement */
2767 sqlite3VdbeEnter(p
);
2769 /* Check for one of the special errors */
2771 isSpecialError
= mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_IOERR
2772 || mrc
==SQLITE_INTERRUPT
|| mrc
==SQLITE_FULL
;
2773 if( isSpecialError
){
2774 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2775 ** no rollback is necessary. Otherwise, at least a savepoint
2776 ** transaction must be rolled back to restore the database to a
2777 ** consistent state.
2779 ** Even if the statement is read-only, it is important to perform
2780 ** a statement or transaction rollback operation. If the error
2781 ** occurred while writing to the journal, sub-journal or database
2782 ** file as part of an effort to free up cache space (see function
2783 ** pagerStress() in pager.c), the rollback is required to restore
2784 ** the pager to a consistent state.
2786 if( !p
->readOnly
|| mrc
!=SQLITE_INTERRUPT
){
2787 if( (mrc
==SQLITE_NOMEM
|| mrc
==SQLITE_FULL
) && p
->usesStmtJournal
){
2788 eStatementOp
= SAVEPOINT_ROLLBACK
;
2790 /* We are forced to roll back the active transaction. Before doing
2791 ** so, abort any other statements this handle currently has active.
2793 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2794 sqlite3CloseSavepoints(db
);
2801 /* Check for immediate foreign key violations. */
2802 if( p
->rc
==SQLITE_OK
){
2803 sqlite3VdbeCheckFk(p
, 0);
2806 /* If the auto-commit flag is set and this is the only active writer
2807 ** VM, then we do either a commit or rollback of the current transaction.
2809 ** Note: This block also runs if one of the special errors handled
2810 ** above has occurred.
2812 if( !sqlite3VtabInSync(db
)
2814 && db
->nVdbeWrite
==(p
->readOnly
==0)
2816 if( p
->rc
==SQLITE_OK
|| (p
->errorAction
==OE_Fail
&& !isSpecialError
) ){
2817 rc
= sqlite3VdbeCheckFk(p
, 1);
2818 if( rc
!=SQLITE_OK
){
2819 if( NEVER(p
->readOnly
) ){
2820 sqlite3VdbeLeave(p
);
2821 return SQLITE_ERROR
;
2823 rc
= SQLITE_CONSTRAINT_FOREIGNKEY
;
2825 /* The auto-commit flag is true, the vdbe program was successful
2826 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2827 ** key constraints to hold up the transaction. This means a commit
2829 rc
= vdbeCommit(db
, p
);
2831 if( rc
==SQLITE_BUSY
&& p
->readOnly
){
2832 sqlite3VdbeLeave(p
);
2834 }else if( rc
!=SQLITE_OK
){
2836 sqlite3RollbackAll(db
, SQLITE_OK
);
2839 db
->nDeferredCons
= 0;
2840 db
->nDeferredImmCons
= 0;
2841 db
->flags
&= ~SQLITE_DeferFKs
;
2842 sqlite3CommitInternalChanges(db
);
2845 sqlite3RollbackAll(db
, SQLITE_OK
);
2849 }else if( eStatementOp
==0 ){
2850 if( p
->rc
==SQLITE_OK
|| p
->errorAction
==OE_Fail
){
2851 eStatementOp
= SAVEPOINT_RELEASE
;
2852 }else if( p
->errorAction
==OE_Abort
){
2853 eStatementOp
= SAVEPOINT_ROLLBACK
;
2855 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2856 sqlite3CloseSavepoints(db
);
2862 /* If eStatementOp is non-zero, then a statement transaction needs to
2863 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2864 ** do so. If this operation returns an error, and the current statement
2865 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2866 ** current statement error code.
2869 rc
= sqlite3VdbeCloseStatement(p
, eStatementOp
);
2871 if( p
->rc
==SQLITE_OK
|| (p
->rc
&0xff)==SQLITE_CONSTRAINT
){
2873 sqlite3DbFree(db
, p
->zErrMsg
);
2876 sqlite3RollbackAll(db
, SQLITE_ABORT_ROLLBACK
);
2877 sqlite3CloseSavepoints(db
);
2883 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2884 ** has been rolled back, update the database connection change-counter.
2886 if( p
->changeCntOn
){
2887 if( eStatementOp
!=SAVEPOINT_ROLLBACK
){
2888 sqlite3VdbeSetChanges(db
, p
->nChange
);
2890 sqlite3VdbeSetChanges(db
, 0);
2895 /* Release the locks */
2896 sqlite3VdbeLeave(p
);
2899 /* We have successfully halted and closed the VM. Record this fact. */
2902 if( !p
->readOnly
) db
->nVdbeWrite
--;
2903 if( p
->bIsReader
) db
->nVdbeRead
--;
2904 assert( db
->nVdbeActive
>=db
->nVdbeRead
);
2905 assert( db
->nVdbeRead
>=db
->nVdbeWrite
);
2906 assert( db
->nVdbeWrite
>=0 );
2908 p
->magic
= VDBE_MAGIC_HALT
;
2909 checkActiveVdbeCnt(db
);
2910 if( db
->mallocFailed
){
2911 p
->rc
= SQLITE_NOMEM_BKPT
;
2914 /* If the auto-commit flag is set to true, then any locks that were held
2915 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2916 ** to invoke any required unlock-notify callbacks.
2918 if( db
->autoCommit
){
2919 sqlite3ConnectionUnlocked(db
);
2922 assert( db
->nVdbeActive
>0 || db
->autoCommit
==0 || db
->nStatement
==0 );
2923 return (p
->rc
==SQLITE_BUSY
? SQLITE_BUSY
: SQLITE_OK
);
2928 ** Each VDBE holds the result of the most recent sqlite3_step() call
2929 ** in p->rc. This routine sets that result back to SQLITE_OK.
2931 void sqlite3VdbeResetStepResult(Vdbe
*p
){
2936 ** Copy the error code and error message belonging to the VDBE passed
2937 ** as the first argument to its database handle (so that they will be
2938 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2940 ** This function does not clear the VDBE error code or message, just
2941 ** copies them to the database handle.
2943 int sqlite3VdbeTransferError(Vdbe
*p
){
2944 sqlite3
*db
= p
->db
;
2947 db
->bBenignMalloc
++;
2948 sqlite3BeginBenignMalloc();
2949 if( db
->pErr
==0 ) db
->pErr
= sqlite3ValueNew(db
);
2950 sqlite3ValueSetStr(db
->pErr
, -1, p
->zErrMsg
, SQLITE_UTF8
, SQLITE_TRANSIENT
);
2951 sqlite3EndBenignMalloc();
2952 db
->bBenignMalloc
--;
2953 }else if( db
->pErr
){
2954 sqlite3ValueSetNull(db
->pErr
);
2960 #ifdef SQLITE_ENABLE_SQLLOG
2962 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2965 static void vdbeInvokeSqllog(Vdbe
*v
){
2966 if( sqlite3GlobalConfig
.xSqllog
&& v
->rc
==SQLITE_OK
&& v
->zSql
&& v
->pc
>=0 ){
2967 char *zExpanded
= sqlite3VdbeExpandSql(v
, v
->zSql
);
2968 assert( v
->db
->init
.busy
==0 );
2970 sqlite3GlobalConfig
.xSqllog(
2971 sqlite3GlobalConfig
.pSqllogArg
, v
->db
, zExpanded
, 1
2973 sqlite3DbFree(v
->db
, zExpanded
);
2978 # define vdbeInvokeSqllog(x)
2982 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
2983 ** Write any error messages into *pzErrMsg. Return the result code.
2985 ** After this routine is run, the VDBE should be ready to be executed
2988 ** To look at it another way, this routine resets the state of the
2989 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2992 int sqlite3VdbeReset(Vdbe
*p
){
2993 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
3000 /* If the VM did not run to completion or if it encountered an
3001 ** error, then it might not have been halted properly. So halt
3006 /* If the VDBE has be run even partially, then transfer the error code
3007 ** and error message from the VDBE into the main database structure. But
3008 ** if the VDBE has just been set to run but has not actually executed any
3009 ** instructions yet, leave the main database error information unchanged.
3012 vdbeInvokeSqllog(p
);
3013 sqlite3VdbeTransferError(p
);
3014 if( p
->runOnlyOnce
) p
->expired
= 1;
3015 }else if( p
->rc
&& p
->expired
){
3016 /* The expired flag was set on the VDBE before the first call
3017 ** to sqlite3_step(). For consistency (since sqlite3_step() was
3018 ** called), set the database error in this case as well.
3020 sqlite3ErrorWithMsg(db
, p
->rc
, p
->zErrMsg
? "%s" : 0, p
->zErrMsg
);
3023 /* Reset register contents and reclaim error message memory.
3026 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
3027 ** Vdbe.aMem[] arrays have already been cleaned up. */
3028 if( p
->apCsr
) for(i
=0; i
<p
->nCursor
; i
++) assert( p
->apCsr
[i
]==0 );
3030 for(i
=0; i
<p
->nMem
; i
++) assert( p
->aMem
[i
].flags
==MEM_Undefined
);
3033 sqlite3DbFree(db
, p
->zErrMsg
);
3040 /* Save profiling information from this VDBE run.
3044 FILE *out
= fopen("vdbe_profile.out", "a");
3046 fprintf(out
, "---- ");
3047 for(i
=0; i
<p
->nOp
; i
++){
3048 fprintf(out
, "%02x", p
->aOp
[i
].opcode
);
3053 fprintf(out
, "-- ");
3054 for(i
=0; (c
= p
->zSql
[i
])!=0; i
++){
3055 if( pc
=='\n' ) fprintf(out
, "-- ");
3059 if( pc
!='\n' ) fprintf(out
, "\n");
3061 for(i
=0; i
<p
->nOp
; i
++){
3063 sqlite3_snprintf(sizeof(zHdr
), zHdr
, "%6u %12llu %8llu ",
3066 p
->aOp
[i
].cnt
>0 ? p
->aOp
[i
].cycles
/p
->aOp
[i
].cnt
: 0
3068 fprintf(out
, "%s", zHdr
);
3069 sqlite3VdbePrintOp(out
, i
, &p
->aOp
[i
]);
3075 p
->magic
= VDBE_MAGIC_RESET
;
3076 return p
->rc
& db
->errMask
;
3080 ** Clean up and delete a VDBE after execution. Return an integer which is
3081 ** the result code. Write any error message text into *pzErrMsg.
3083 int sqlite3VdbeFinalize(Vdbe
*p
){
3085 if( p
->magic
==VDBE_MAGIC_RUN
|| p
->magic
==VDBE_MAGIC_HALT
){
3086 rc
= sqlite3VdbeReset(p
);
3087 assert( (rc
& p
->db
->errMask
)==rc
);
3089 sqlite3VdbeDelete(p
);
3094 ** If parameter iOp is less than zero, then invoke the destructor for
3095 ** all auxiliary data pointers currently cached by the VM passed as
3096 ** the first argument.
3098 ** Or, if iOp is greater than or equal to zero, then the destructor is
3099 ** only invoked for those auxiliary data pointers created by the user
3100 ** function invoked by the OP_Function opcode at instruction iOp of
3101 ** VM pVdbe, and only then if:
3103 ** * the associated function parameter is the 32nd or later (counting
3104 ** from left to right), or
3106 ** * the corresponding bit in argument mask is clear (where the first
3107 ** function parameter corresponds to bit 0 etc.).
3109 void sqlite3VdbeDeleteAuxData(sqlite3
*db
, AuxData
**pp
, int iOp
, int mask
){
3111 AuxData
*pAux
= *pp
;
3113 || (pAux
->iAuxOp
==iOp
3115 && (pAux
->iAuxArg
>31 || !(mask
& MASKBIT32(pAux
->iAuxArg
))))
3117 testcase( pAux
->iAuxArg
==31 );
3118 if( pAux
->xDeleteAux
){
3119 pAux
->xDeleteAux(pAux
->pAux
);
3121 *pp
= pAux
->pNextAux
;
3122 sqlite3DbFree(db
, pAux
);
3124 pp
= &pAux
->pNextAux
;
3130 ** Free all memory associated with the Vdbe passed as the second argument,
3131 ** except for object itself, which is preserved.
3133 ** The difference between this function and sqlite3VdbeDelete() is that
3134 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
3135 ** the database connection and frees the object itself.
3137 void sqlite3VdbeClearObject(sqlite3
*db
, Vdbe
*p
){
3138 SubProgram
*pSub
, *pNext
;
3139 assert( p
->db
==0 || p
->db
==db
);
3140 releaseMemArray(p
->aColName
, p
->nResColumn
*COLNAME_N
);
3141 for(pSub
=p
->pProgram
; pSub
; pSub
=pNext
){
3142 pNext
= pSub
->pNext
;
3143 vdbeFreeOpArray(db
, pSub
->aOp
, pSub
->nOp
);
3144 sqlite3DbFree(db
, pSub
);
3146 if( p
->magic
!=VDBE_MAGIC_INIT
){
3147 releaseMemArray(p
->aVar
, p
->nVar
);
3148 sqlite3DbFree(db
, p
->pVList
);
3149 sqlite3DbFree(db
, p
->pFree
);
3151 vdbeFreeOpArray(db
, p
->aOp
, p
->nOp
);
3152 sqlite3DbFree(db
, p
->aColName
);
3153 sqlite3DbFree(db
, p
->zSql
);
3154 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3157 for(i
=0; i
<p
->nScan
; i
++){
3158 sqlite3DbFree(db
, p
->aScan
[i
].zName
);
3160 sqlite3DbFree(db
, p
->aScan
);
3166 ** Delete an entire VDBE.
3168 void sqlite3VdbeDelete(Vdbe
*p
){
3173 assert( sqlite3_mutex_held(db
->mutex
) );
3174 sqlite3VdbeClearObject(db
, p
);
3176 p
->pPrev
->pNext
= p
->pNext
;
3178 assert( db
->pVdbe
==p
);
3179 db
->pVdbe
= p
->pNext
;
3182 p
->pNext
->pPrev
= p
->pPrev
;
3184 p
->magic
= VDBE_MAGIC_DEAD
;
3186 sqlite3DbFreeNN(db
, p
);
3190 ** The cursor "p" has a pending seek operation that has not yet been
3191 ** carried out. Seek the cursor now. If an error occurs, return
3192 ** the appropriate error code.
3194 static int SQLITE_NOINLINE
handleDeferredMoveto(VdbeCursor
*p
){
3197 extern int sqlite3_search_count
;
3199 assert( p
->deferredMoveto
);
3200 assert( p
->isTable
);
3201 assert( p
->eCurType
==CURTYPE_BTREE
);
3202 rc
= sqlite3BtreeMovetoUnpacked(p
->uc
.pCursor
, 0, p
->movetoTarget
, 0, &res
);
3204 if( res
!=0 ) return SQLITE_CORRUPT_BKPT
;
3206 sqlite3_search_count
++;
3208 p
->deferredMoveto
= 0;
3209 p
->cacheStatus
= CACHE_STALE
;
3214 ** Something has moved cursor "p" out of place. Maybe the row it was
3215 ** pointed to was deleted out from under it. Or maybe the btree was
3216 ** rebalanced. Whatever the cause, try to restore "p" to the place it
3217 ** is supposed to be pointing. If the row was deleted out from under the
3218 ** cursor, set the cursor to point to a NULL row.
3220 static int SQLITE_NOINLINE
handleMovedCursor(VdbeCursor
*p
){
3221 int isDifferentRow
, rc
;
3222 assert( p
->eCurType
==CURTYPE_BTREE
);
3223 assert( p
->uc
.pCursor
!=0 );
3224 assert( sqlite3BtreeCursorHasMoved(p
->uc
.pCursor
) );
3225 rc
= sqlite3BtreeCursorRestore(p
->uc
.pCursor
, &isDifferentRow
);
3226 p
->cacheStatus
= CACHE_STALE
;
3227 if( isDifferentRow
) p
->nullRow
= 1;
3232 ** Check to ensure that the cursor is valid. Restore the cursor
3233 ** if need be. Return any I/O error from the restore operation.
3235 int sqlite3VdbeCursorRestore(VdbeCursor
*p
){
3236 assert( p
->eCurType
==CURTYPE_BTREE
);
3237 if( sqlite3BtreeCursorHasMoved(p
->uc
.pCursor
) ){
3238 return handleMovedCursor(p
);
3244 ** Make sure the cursor p is ready to read or write the row to which it
3245 ** was last positioned. Return an error code if an OOM fault or I/O error
3246 ** prevents us from positioning the cursor to its correct position.
3248 ** If a MoveTo operation is pending on the given cursor, then do that
3249 ** MoveTo now. If no move is pending, check to see if the row has been
3250 ** deleted out from under the cursor and if it has, mark the row as
3253 ** If the cursor is already pointing to the correct row and that row has
3254 ** not been deleted out from under the cursor, then this routine is a no-op.
3256 int sqlite3VdbeCursorMoveto(VdbeCursor
**pp
, int *piCol
){
3257 VdbeCursor
*p
= *pp
;
3258 assert( p
->eCurType
==CURTYPE_BTREE
|| p
->eCurType
==CURTYPE_PSEUDO
);
3259 if( p
->deferredMoveto
){
3261 if( p
->aAltMap
&& (iMap
= p
->aAltMap
[1+*piCol
])>0 ){
3262 *pp
= p
->pAltCursor
;
3266 return handleDeferredMoveto(p
);
3268 if( sqlite3BtreeCursorHasMoved(p
->uc
.pCursor
) ){
3269 return handleMovedCursor(p
);
3275 ** The following functions:
3277 ** sqlite3VdbeSerialType()
3278 ** sqlite3VdbeSerialTypeLen()
3279 ** sqlite3VdbeSerialLen()
3280 ** sqlite3VdbeSerialPut()
3281 ** sqlite3VdbeSerialGet()
3283 ** encapsulate the code that serializes values for storage in SQLite
3284 ** data and index records. Each serialized value consists of a
3285 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3286 ** integer, stored as a varint.
3288 ** In an SQLite index record, the serial type is stored directly before
3289 ** the blob of data that it corresponds to. In a table record, all serial
3290 ** types are stored at the start of the record, and the blobs of data at
3291 ** the end. Hence these functions allow the caller to handle the
3292 ** serial-type and data blob separately.
3294 ** The following table describes the various storage classes for data:
3296 ** serial type bytes of data type
3297 ** -------------- --------------- ---------------
3299 ** 1 1 signed integer
3300 ** 2 2 signed integer
3301 ** 3 3 signed integer
3302 ** 4 4 signed integer
3303 ** 5 6 signed integer
3304 ** 6 8 signed integer
3306 ** 8 0 Integer constant 0
3307 ** 9 0 Integer constant 1
3308 ** 10,11 reserved for expansion
3309 ** N>=12 and even (N-12)/2 BLOB
3310 ** N>=13 and odd (N-13)/2 text
3312 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
3313 ** of SQLite will not understand those serial types.
3317 ** Return the serial-type for the value stored in pMem.
3319 u32
sqlite3VdbeSerialType(Mem
*pMem
, int file_format
, u32
*pLen
){
3320 int flags
= pMem
->flags
;
3324 if( flags
&MEM_Null
){
3328 if( flags
&MEM_Int
){
3329 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3330 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
3339 if( (i
&1)==i
&& file_format
>=4 ){
3347 if( u
<=32767 ){ *pLen
= 2; return 2; }
3348 if( u
<=8388607 ){ *pLen
= 3; return 3; }
3349 if( u
<=2147483647 ){ *pLen
= 4; return 4; }
3350 if( u
<=MAX_6BYTE
){ *pLen
= 6; return 5; }
3354 if( flags
&MEM_Real
){
3358 assert( pMem
->db
->mallocFailed
|| flags
&(MEM_Str
|MEM_Blob
) );
3359 assert( pMem
->n
>=0 );
3361 if( flags
& MEM_Zero
){
3365 return ((n
*2) + 12 + ((flags
&MEM_Str
)!=0));
3369 ** The sizes for serial types less than 128
3371 static const u8 sqlite3SmallTypeSizes
[] = {
3372 /* 0 1 2 3 4 5 6 7 8 9 */
3373 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
3374 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
3375 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
3376 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
3377 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3378 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3379 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3380 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3381 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3382 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3383 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3384 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3385 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
3389 ** Return the length of the data corresponding to the supplied serial-type.
3391 u32
sqlite3VdbeSerialTypeLen(u32 serial_type
){
3392 if( serial_type
>=128 ){
3393 return (serial_type
-12)/2;
3395 assert( serial_type
<12
3396 || sqlite3SmallTypeSizes
[serial_type
]==(serial_type
- 12)/2 );
3397 return sqlite3SmallTypeSizes
[serial_type
];
3400 u8
sqlite3VdbeOneByteSerialTypeLen(u8 serial_type
){
3401 assert( serial_type
<128 );
3402 return sqlite3SmallTypeSizes
[serial_type
];
3406 ** If we are on an architecture with mixed-endian floating
3407 ** points (ex: ARM7) then swap the lower 4 bytes with the
3408 ** upper 4 bytes. Return the result.
3410 ** For most architectures, this is a no-op.
3412 ** (later): It is reported to me that the mixed-endian problem
3413 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
3414 ** that early versions of GCC stored the two words of a 64-bit
3415 ** float in the wrong order. And that error has been propagated
3416 ** ever since. The blame is not necessarily with GCC, though.
3417 ** GCC might have just copying the problem from a prior compiler.
3418 ** I am also told that newer versions of GCC that follow a different
3419 ** ABI get the byte order right.
3421 ** Developers using SQLite on an ARM7 should compile and run their
3422 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
3423 ** enabled, some asserts below will ensure that the byte order of
3424 ** floating point values is correct.
3426 ** (2007-08-30) Frank van Vugt has studied this problem closely
3427 ** and has send his findings to the SQLite developers. Frank
3428 ** writes that some Linux kernels offer floating point hardware
3429 ** emulation that uses only 32-bit mantissas instead of a full
3430 ** 48-bits as required by the IEEE standard. (This is the
3431 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
3432 ** byte swapping becomes very complicated. To avoid problems,
3433 ** the necessary byte swapping is carried out using a 64-bit integer
3434 ** rather than a 64-bit float. Frank assures us that the code here
3435 ** works for him. We, the developers, have no way to independently
3436 ** verify this, but Frank seems to know what he is talking about
3439 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
3440 static u64
floatSwap(u64 in
){
3453 # define swapMixedEndianFloat(X) X = floatSwap(X)
3455 # define swapMixedEndianFloat(X)
3459 ** Write the serialized data blob for the value stored in pMem into
3460 ** buf. It is assumed that the caller has allocated sufficient space.
3461 ** Return the number of bytes written.
3463 ** nBuf is the amount of space left in buf[]. The caller is responsible
3464 ** for allocating enough space to buf[] to hold the entire field, exclusive
3465 ** of the pMem->u.nZero bytes for a MEM_Zero value.
3467 ** Return the number of bytes actually written into buf[]. The number
3468 ** of bytes in the zero-filled tail is included in the return value only
3469 ** if those bytes were zeroed in buf[].
3471 u32
sqlite3VdbeSerialPut(u8
*buf
, Mem
*pMem
, u32 serial_type
){
3474 /* Integer and Real */
3475 if( serial_type
<=7 && serial_type
>0 ){
3478 if( serial_type
==7 ){
3479 assert( sizeof(v
)==sizeof(pMem
->u
.r
) );
3480 memcpy(&v
, &pMem
->u
.r
, sizeof(v
));
3481 swapMixedEndianFloat(v
);
3485 len
= i
= sqlite3SmallTypeSizes
[serial_type
];
3488 buf
[--i
] = (u8
)(v
&0xFF);
3494 /* String or blob */
3495 if( serial_type
>=12 ){
3496 assert( pMem
->n
+ ((pMem
->flags
& MEM_Zero
)?pMem
->u
.nZero
:0)
3497 == (int)sqlite3VdbeSerialTypeLen(serial_type
) );
3499 if( len
>0 ) memcpy(buf
, pMem
->z
, len
);
3503 /* NULL or constants 0 or 1 */
3507 /* Input "x" is a sequence of unsigned characters that represent a
3508 ** big-endian integer. Return the equivalent native integer
3510 #define ONE_BYTE_INT(x) ((i8)(x)[0])
3511 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
3512 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3513 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3514 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3517 ** Deserialize the data blob pointed to by buf as serial type serial_type
3518 ** and store the result in pMem. Return the number of bytes read.
3520 ** This function is implemented as two separate routines for performance.
3521 ** The few cases that require local variables are broken out into a separate
3522 ** routine so that in most cases the overhead of moving the stack pointer
3525 static u32 SQLITE_NOINLINE
serialGet(
3526 const unsigned char *buf
, /* Buffer to deserialize from */
3527 u32 serial_type
, /* Serial type to deserialize */
3528 Mem
*pMem
/* Memory cell to write value into */
3530 u64 x
= FOUR_BYTE_UINT(buf
);
3531 u32 y
= FOUR_BYTE_UINT(buf
+4);
3533 if( serial_type
==6 ){
3534 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3535 ** twos-complement integer. */
3536 pMem
->u
.i
= *(i64
*)&x
;
3537 pMem
->flags
= MEM_Int
;
3538 testcase( pMem
->u
.i
<0 );
3540 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3541 ** floating point number. */
3542 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3543 /* Verify that integers and floating point values use the same
3544 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3545 ** defined that 64-bit floating point values really are mixed
3548 static const u64 t1
= ((u64
)0x3ff00000)<<32;
3549 static const double r1
= 1.0;
3551 swapMixedEndianFloat(t2
);
3552 assert( sizeof(r1
)==sizeof(t2
) && memcmp(&r1
, &t2
, sizeof(r1
))==0 );
3554 assert( sizeof(x
)==8 && sizeof(pMem
->u
.r
)==8 );
3555 swapMixedEndianFloat(x
);
3556 memcpy(&pMem
->u
.r
, &x
, sizeof(x
));
3557 pMem
->flags
= sqlite3IsNaN(pMem
->u
.r
) ? MEM_Null
: MEM_Real
;
3561 u32
sqlite3VdbeSerialGet(
3562 const unsigned char *buf
, /* Buffer to deserialize from */
3563 u32 serial_type
, /* Serial type to deserialize */
3564 Mem
*pMem
/* Memory cell to write value into */
3566 switch( serial_type
){
3567 case 10: { /* Internal use only: NULL with virtual table
3568 ** UPDATE no-change flag set */
3569 pMem
->flags
= MEM_Null
|MEM_Zero
;
3574 case 11: /* Reserved for future use */
3575 case 0: { /* Null */
3576 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3577 pMem
->flags
= MEM_Null
;
3581 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3583 pMem
->u
.i
= ONE_BYTE_INT(buf
);
3584 pMem
->flags
= MEM_Int
;
3585 testcase( pMem
->u
.i
<0 );
3588 case 2: { /* 2-byte signed integer */
3589 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3590 ** twos-complement integer. */
3591 pMem
->u
.i
= TWO_BYTE_INT(buf
);
3592 pMem
->flags
= MEM_Int
;
3593 testcase( pMem
->u
.i
<0 );
3596 case 3: { /* 3-byte signed integer */
3597 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3598 ** twos-complement integer. */
3599 pMem
->u
.i
= THREE_BYTE_INT(buf
);
3600 pMem
->flags
= MEM_Int
;
3601 testcase( pMem
->u
.i
<0 );
3604 case 4: { /* 4-byte signed integer */
3605 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3606 ** twos-complement integer. */
3607 pMem
->u
.i
= FOUR_BYTE_INT(buf
);
3609 /* Work around a sign-extension bug in the HP compiler for HP/UX */
3610 if( buf
[0]&0x80 ) pMem
->u
.i
|= 0xffffffff80000000LL
;
3612 pMem
->flags
= MEM_Int
;
3613 testcase( pMem
->u
.i
<0 );
3616 case 5: { /* 6-byte signed integer */
3617 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3618 ** twos-complement integer. */
3619 pMem
->u
.i
= FOUR_BYTE_UINT(buf
+2) + (((i64
)1)<<32)*TWO_BYTE_INT(buf
);
3620 pMem
->flags
= MEM_Int
;
3621 testcase( pMem
->u
.i
<0 );
3624 case 6: /* 8-byte signed integer */
3625 case 7: { /* IEEE floating point */
3626 /* These use local variables, so do them in a separate routine
3627 ** to avoid having to move the frame pointer in the common case */
3628 return serialGet(buf
,serial_type
,pMem
);
3630 case 8: /* Integer 0 */
3631 case 9: { /* Integer 1 */
3632 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3633 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
3634 pMem
->u
.i
= serial_type
-8;
3635 pMem
->flags
= MEM_Int
;
3639 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3641 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3642 ** (N-13)/2 bytes in length. */
3643 static const u16 aFlag
[] = { MEM_Blob
|MEM_Ephem
, MEM_Str
|MEM_Ephem
};
3644 pMem
->z
= (char *)buf
;
3645 pMem
->n
= (serial_type
-12)/2;
3646 pMem
->flags
= aFlag
[serial_type
&1];
3653 ** This routine is used to allocate sufficient space for an UnpackedRecord
3654 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3655 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
3657 ** The space is either allocated using sqlite3DbMallocRaw() or from within
3658 ** the unaligned buffer passed via the second and third arguments (presumably
3659 ** stack space). If the former, then *ppFree is set to a pointer that should
3660 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3661 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3662 ** before returning.
3664 ** If an OOM error occurs, NULL is returned.
3666 UnpackedRecord
*sqlite3VdbeAllocUnpackedRecord(
3667 KeyInfo
*pKeyInfo
/* Description of the record */
3669 UnpackedRecord
*p
; /* Unpacked record to return */
3670 int nByte
; /* Number of bytes required for *p */
3671 nByte
= ROUND8(sizeof(UnpackedRecord
)) + sizeof(Mem
)*(pKeyInfo
->nKeyField
+1);
3672 p
= (UnpackedRecord
*)sqlite3DbMallocRaw(pKeyInfo
->db
, nByte
);
3674 p
->aMem
= (Mem
*)&((char*)p
)[ROUND8(sizeof(UnpackedRecord
))];
3675 assert( pKeyInfo
->aSortOrder
!=0 );
3676 p
->pKeyInfo
= pKeyInfo
;
3677 p
->nField
= pKeyInfo
->nKeyField
+ 1;
3682 ** Given the nKey-byte encoding of a record in pKey[], populate the
3683 ** UnpackedRecord structure indicated by the fourth argument with the
3684 ** contents of the decoded record.
3686 void sqlite3VdbeRecordUnpack(
3687 KeyInfo
*pKeyInfo
, /* Information about the record format */
3688 int nKey
, /* Size of the binary record */
3689 const void *pKey
, /* The binary record */
3690 UnpackedRecord
*p
/* Populate this structure before returning. */
3692 const unsigned char *aKey
= (const unsigned char *)pKey
;
3694 u32 idx
; /* Offset in aKey[] to read from */
3695 u16 u
; /* Unsigned loop counter */
3697 Mem
*pMem
= p
->aMem
;
3700 assert( EIGHT_BYTE_ALIGNMENT(pMem
) );
3701 idx
= getVarint32(aKey
, szHdr
);
3704 while( idx
<szHdr
&& d
<=nKey
){
3707 idx
+= getVarint32(&aKey
[idx
], serial_type
);
3708 pMem
->enc
= pKeyInfo
->enc
;
3709 pMem
->db
= pKeyInfo
->db
;
3710 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
3713 d
+= sqlite3VdbeSerialGet(&aKey
[d
], serial_type
, pMem
);
3715 if( (++u
)>=p
->nField
) break;
3717 assert( u
<=pKeyInfo
->nKeyField
+ 1 );
3723 ** This function compares two index or table record keys in the same way
3724 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3725 ** this function deserializes and compares values using the
3726 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3727 ** in assert() statements to ensure that the optimized code in
3728 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
3730 ** Return true if the result of comparison is equivalent to desiredResult.
3731 ** Return false if there is a disagreement.
3733 static int vdbeRecordCompareDebug(
3734 int nKey1
, const void *pKey1
, /* Left key */
3735 const UnpackedRecord
*pPKey2
, /* Right key */
3736 int desiredResult
/* Correct answer */
3738 u32 d1
; /* Offset into aKey[] of next data element */
3739 u32 idx1
; /* Offset into aKey[] of next header element */
3740 u32 szHdr1
; /* Number of bytes in header */
3743 const unsigned char *aKey1
= (const unsigned char *)pKey1
;
3747 pKeyInfo
= pPKey2
->pKeyInfo
;
3748 if( pKeyInfo
->db
==0 ) return 1;
3749 mem1
.enc
= pKeyInfo
->enc
;
3750 mem1
.db
= pKeyInfo
->db
;
3751 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
3752 VVA_ONLY( mem1
.szMalloc
= 0; ) /* Only needed by assert() statements */
3754 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3755 ** We could initialize it, as shown here, to silence those complaints.
3756 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3757 ** the unnecessary initialization has a measurable negative performance
3758 ** impact, since this routine is a very high runner. And so, we choose
3759 ** to ignore the compiler warnings and leave this variable uninitialized.
3761 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3763 idx1
= getVarint32(aKey1
, szHdr1
);
3764 if( szHdr1
>98307 ) return SQLITE_CORRUPT
;
3766 assert( pKeyInfo
->nAllField
>=pPKey2
->nField
|| CORRUPT_DB
);
3767 assert( pKeyInfo
->aSortOrder
!=0 );
3768 assert( pKeyInfo
->nKeyField
>0 );
3769 assert( idx1
<=szHdr1
|| CORRUPT_DB
);
3773 /* Read the serial types for the next element in each key. */
3774 idx1
+= getVarint32( aKey1
+idx1
, serial_type1
);
3776 /* Verify that there is enough key space remaining to avoid
3777 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3778 ** always be greater than or equal to the amount of required key space.
3779 ** Use that approximation to avoid the more expensive call to
3780 ** sqlite3VdbeSerialTypeLen() in the common case.
3782 if( d1
+serial_type1
+2>(u32
)nKey1
3783 && d1
+sqlite3VdbeSerialTypeLen(serial_type1
)>(u32
)nKey1
3788 /* Extract the values to be compared.
3790 d1
+= sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type1
, &mem1
);
3792 /* Do the comparison
3794 rc
= sqlite3MemCompare(&mem1
, &pPKey2
->aMem
[i
], pKeyInfo
->aColl
[i
]);
3796 assert( mem1
.szMalloc
==0 ); /* See comment below */
3797 if( pKeyInfo
->aSortOrder
[i
] ){
3798 rc
= -rc
; /* Invert the result for DESC sort order. */
3800 goto debugCompareEnd
;
3803 }while( idx1
<szHdr1
&& i
<pPKey2
->nField
);
3805 /* No memory allocation is ever used on mem1. Prove this using
3806 ** the following assert(). If the assert() fails, it indicates a
3807 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3809 assert( mem1
.szMalloc
==0 );
3811 /* rc==0 here means that one of the keys ran out of fields and
3812 ** all the fields up to that point were equal. Return the default_rc
3814 rc
= pPKey2
->default_rc
;
3817 if( desiredResult
==0 && rc
==0 ) return 1;
3818 if( desiredResult
<0 && rc
<0 ) return 1;
3819 if( desiredResult
>0 && rc
>0 ) return 1;
3820 if( CORRUPT_DB
) return 1;
3821 if( pKeyInfo
->db
->mallocFailed
) return 1;
3828 ** Count the number of fields (a.k.a. columns) in the record given by
3829 ** pKey,nKey. The verify that this count is less than or equal to the
3830 ** limit given by pKeyInfo->nAllField.
3832 ** If this constraint is not satisfied, it means that the high-speed
3833 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3834 ** not work correctly. If this assert() ever fires, it probably means
3835 ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
3838 static void vdbeAssertFieldCountWithinLimits(
3839 int nKey
, const void *pKey
, /* The record to verify */
3840 const KeyInfo
*pKeyInfo
/* Compare size with this KeyInfo */
3846 const unsigned char *aKey
= (const unsigned char*)pKey
;
3848 if( CORRUPT_DB
) return;
3849 idx
= getVarint32(aKey
, szHdr
);
3851 assert( szHdr
<=(u32
)nKey
);
3853 idx
+= getVarint32(aKey
+idx
, notUsed
);
3856 assert( nField
<= pKeyInfo
->nAllField
);
3859 # define vdbeAssertFieldCountWithinLimits(A,B,C)
3863 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
3864 ** using the collation sequence pColl. As usual, return a negative , zero
3865 ** or positive value if *pMem1 is less than, equal to or greater than
3866 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3868 static int vdbeCompareMemString(
3871 const CollSeq
*pColl
,
3872 u8
*prcErr
/* If an OOM occurs, set to SQLITE_NOMEM */
3874 if( pMem1
->enc
==pColl
->enc
){
3875 /* The strings are already in the correct encoding. Call the
3876 ** comparison function directly */
3877 return pColl
->xCmp(pColl
->pUser
,pMem1
->n
,pMem1
->z
,pMem2
->n
,pMem2
->z
);
3880 const void *v1
, *v2
;
3883 sqlite3VdbeMemInit(&c1
, pMem1
->db
, MEM_Null
);
3884 sqlite3VdbeMemInit(&c2
, pMem1
->db
, MEM_Null
);
3885 sqlite3VdbeMemShallowCopy(&c1
, pMem1
, MEM_Ephem
);
3886 sqlite3VdbeMemShallowCopy(&c2
, pMem2
, MEM_Ephem
);
3887 v1
= sqlite3ValueText((sqlite3_value
*)&c1
, pColl
->enc
);
3888 v2
= sqlite3ValueText((sqlite3_value
*)&c2
, pColl
->enc
);
3889 if( (v1
==0 || v2
==0) ){
3890 if( prcErr
) *prcErr
= SQLITE_NOMEM_BKPT
;
3893 rc
= pColl
->xCmp(pColl
->pUser
, c1
.n
, v1
, c2
.n
, v2
);
3895 sqlite3VdbeMemRelease(&c1
);
3896 sqlite3VdbeMemRelease(&c2
);
3902 ** The input pBlob is guaranteed to be a Blob that is not marked
3903 ** with MEM_Zero. Return true if it could be a zero-blob.
3905 static int isAllZero(const char *z
, int n
){
3908 if( z
[i
] ) return 0;
3914 ** Compare two blobs. Return negative, zero, or positive if the first
3915 ** is less than, equal to, or greater than the second, respectively.
3916 ** If one blob is a prefix of the other, then the shorter is the lessor.
3918 SQLITE_NOINLINE
int sqlite3BlobCompare(const Mem
*pB1
, const Mem
*pB2
){
3923 /* It is possible to have a Blob value that has some non-zero content
3924 ** followed by zero content. But that only comes up for Blobs formed
3925 ** by the OP_MakeRecord opcode, and such Blobs never get passed into
3926 ** sqlite3MemCompare(). */
3927 assert( (pB1
->flags
& MEM_Zero
)==0 || n1
==0 );
3928 assert( (pB2
->flags
& MEM_Zero
)==0 || n2
==0 );
3930 if( (pB1
->flags
|pB2
->flags
) & MEM_Zero
){
3931 if( pB1
->flags
& pB2
->flags
& MEM_Zero
){
3932 return pB1
->u
.nZero
- pB2
->u
.nZero
;
3933 }else if( pB1
->flags
& MEM_Zero
){
3934 if( !isAllZero(pB2
->z
, pB2
->n
) ) return -1;
3935 return pB1
->u
.nZero
- n2
;
3937 if( !isAllZero(pB1
->z
, pB1
->n
) ) return +1;
3938 return n1
- pB2
->u
.nZero
;
3941 c
= memcmp(pB1
->z
, pB2
->z
, n1
>n2
? n2
: n1
);
3947 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
3948 ** number. Return negative, zero, or positive if the first (i64) is less than,
3949 ** equal to, or greater than the second (double).
3951 static int sqlite3IntFloatCompare(i64 i
, double r
){
3952 if( sizeof(LONGDOUBLE_TYPE
)>8 ){
3953 LONGDOUBLE_TYPE x
= (LONGDOUBLE_TYPE
)i
;
3954 if( x
<r
) return -1;
3955 if( x
>r
) return +1;
3960 if( r
<-9223372036854775808.0 ) return +1;
3961 if( r
>=9223372036854775808.0 ) return -1;
3963 if( i
<y
) return -1;
3964 if( i
>y
) return +1;
3966 if( s
<r
) return -1;
3967 if( s
>r
) return +1;
3973 ** Compare the values contained by the two memory cells, returning
3974 ** negative, zero or positive if pMem1 is less than, equal to, or greater
3975 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3976 ** and reals) sorted numerically, followed by text ordered by the collating
3977 ** sequence pColl and finally blob's ordered by memcmp().
3979 ** Two NULL values are considered equal by this function.
3981 int sqlite3MemCompare(const Mem
*pMem1
, const Mem
*pMem2
, const CollSeq
*pColl
){
3987 combined_flags
= f1
|f2
;
3988 assert( (combined_flags
& MEM_RowSet
)==0 );
3990 /* If one value is NULL, it is less than the other. If both values
3991 ** are NULL, return 0.
3993 if( combined_flags
&MEM_Null
){
3994 return (f2
&MEM_Null
) - (f1
&MEM_Null
);
3997 /* At least one of the two values is a number
3999 if( combined_flags
&(MEM_Int
|MEM_Real
) ){
4000 if( (f1
& f2
& MEM_Int
)!=0 ){
4001 if( pMem1
->u
.i
< pMem2
->u
.i
) return -1;
4002 if( pMem1
->u
.i
> pMem2
->u
.i
) return +1;
4005 if( (f1
& f2
& MEM_Real
)!=0 ){
4006 if( pMem1
->u
.r
< pMem2
->u
.r
) return -1;
4007 if( pMem1
->u
.r
> pMem2
->u
.r
) return +1;
4010 if( (f1
&MEM_Int
)!=0 ){
4011 if( (f2
&MEM_Real
)!=0 ){
4012 return sqlite3IntFloatCompare(pMem1
->u
.i
, pMem2
->u
.r
);
4017 if( (f1
&MEM_Real
)!=0 ){
4018 if( (f2
&MEM_Int
)!=0 ){
4019 return -sqlite3IntFloatCompare(pMem2
->u
.i
, pMem1
->u
.r
);
4027 /* If one value is a string and the other is a blob, the string is less.
4028 ** If both are strings, compare using the collating functions.
4030 if( combined_flags
&MEM_Str
){
4031 if( (f1
& MEM_Str
)==0 ){
4034 if( (f2
& MEM_Str
)==0 ){
4038 assert( pMem1
->enc
==pMem2
->enc
|| pMem1
->db
->mallocFailed
);
4039 assert( pMem1
->enc
==SQLITE_UTF8
||
4040 pMem1
->enc
==SQLITE_UTF16LE
|| pMem1
->enc
==SQLITE_UTF16BE
);
4042 /* The collation sequence must be defined at this point, even if
4043 ** the user deletes the collation sequence after the vdbe program is
4044 ** compiled (this was not always the case).
4046 assert( !pColl
|| pColl
->xCmp
);
4049 return vdbeCompareMemString(pMem1
, pMem2
, pColl
, 0);
4051 /* If a NULL pointer was passed as the collate function, fall through
4052 ** to the blob case and use memcmp(). */
4055 /* Both values must be blobs. Compare using memcmp(). */
4056 return sqlite3BlobCompare(pMem1
, pMem2
);
4061 ** The first argument passed to this function is a serial-type that
4062 ** corresponds to an integer - all values between 1 and 9 inclusive
4063 ** except 7. The second points to a buffer containing an integer value
4064 ** serialized according to serial_type. This function deserializes
4065 ** and returns the value.
4067 static i64
vdbeRecordDecodeInt(u32 serial_type
, const u8
*aKey
){
4069 assert( CORRUPT_DB
|| (serial_type
>=1 && serial_type
<=9 && serial_type
!=7) );
4070 switch( serial_type
){
4073 testcase( aKey
[0]&0x80 );
4074 return ONE_BYTE_INT(aKey
);
4076 testcase( aKey
[0]&0x80 );
4077 return TWO_BYTE_INT(aKey
);
4079 testcase( aKey
[0]&0x80 );
4080 return THREE_BYTE_INT(aKey
);
4082 testcase( aKey
[0]&0x80 );
4083 y
= FOUR_BYTE_UINT(aKey
);
4084 return (i64
)*(int*)&y
;
4087 testcase( aKey
[0]&0x80 );
4088 return FOUR_BYTE_UINT(aKey
+2) + (((i64
)1)<<32)*TWO_BYTE_INT(aKey
);
4091 u64 x
= FOUR_BYTE_UINT(aKey
);
4092 testcase( aKey
[0]&0x80 );
4093 x
= (x
<<32) | FOUR_BYTE_UINT(aKey
+4);
4094 return (i64
)*(i64
*)&x
;
4098 return (serial_type
- 8);
4102 ** This function compares the two table rows or index records
4103 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
4104 ** or positive integer if key1 is less than, equal to or
4105 ** greater than key2. The {nKey1, pKey1} key must be a blob
4106 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
4107 ** key must be a parsed key such as obtained from
4108 ** sqlite3VdbeParseRecord.
4110 ** If argument bSkip is non-zero, it is assumed that the caller has already
4111 ** determined that the first fields of the keys are equal.
4113 ** Key1 and Key2 do not have to contain the same number of fields. If all
4114 ** fields that appear in both keys are equal, then pPKey2->default_rc is
4117 ** If database corruption is discovered, set pPKey2->errCode to
4118 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
4119 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
4120 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
4122 int sqlite3VdbeRecordCompareWithSkip(
4123 int nKey1
, const void *pKey1
, /* Left key */
4124 UnpackedRecord
*pPKey2
, /* Right key */
4125 int bSkip
/* If true, skip the first field */
4127 u32 d1
; /* Offset into aKey[] of next data element */
4128 int i
; /* Index of next field to compare */
4129 u32 szHdr1
; /* Size of record header in bytes */
4130 u32 idx1
; /* Offset of first type in header */
4131 int rc
= 0; /* Return value */
4132 Mem
*pRhs
= pPKey2
->aMem
; /* Next field of pPKey2 to compare */
4134 const unsigned char *aKey1
= (const unsigned char *)pKey1
;
4137 /* If bSkip is true, then the caller has already determined that the first
4138 ** two elements in the keys are equal. Fix the various stack variables so
4139 ** that this routine begins comparing at the second field. */
4142 idx1
= 1 + getVarint32(&aKey1
[1], s1
);
4144 d1
= szHdr1
+ sqlite3VdbeSerialTypeLen(s1
);
4148 idx1
= getVarint32(aKey1
, szHdr1
);
4150 if( d1
>(unsigned)nKey1
){
4151 pPKey2
->errCode
= (u8
)SQLITE_CORRUPT_BKPT
;
4152 return 0; /* Corruption */
4157 VVA_ONLY( mem1
.szMalloc
= 0; ) /* Only needed by assert() statements */
4158 assert( pPKey2
->pKeyInfo
->nAllField
>=pPKey2
->nField
4160 assert( pPKey2
->pKeyInfo
->aSortOrder
!=0 );
4161 assert( pPKey2
->pKeyInfo
->nKeyField
>0 );
4162 assert( idx1
<=szHdr1
|| CORRUPT_DB
);
4166 /* RHS is an integer */
4167 if( pRhs
->flags
& MEM_Int
){
4168 serial_type
= aKey1
[idx1
];
4169 testcase( serial_type
==12 );
4170 if( serial_type
>=10 ){
4172 }else if( serial_type
==0 ){
4174 }else if( serial_type
==7 ){
4175 sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type
, &mem1
);
4176 rc
= -sqlite3IntFloatCompare(pRhs
->u
.i
, mem1
.u
.r
);
4178 i64 lhs
= vdbeRecordDecodeInt(serial_type
, &aKey1
[d1
]);
4179 i64 rhs
= pRhs
->u
.i
;
4182 }else if( lhs
>rhs
){
4189 else if( pRhs
->flags
& MEM_Real
){
4190 serial_type
= aKey1
[idx1
];
4191 if( serial_type
>=10 ){
4192 /* Serial types 12 or greater are strings and blobs (greater than
4193 ** numbers). Types 10 and 11 are currently "reserved for future
4194 ** use", so it doesn't really matter what the results of comparing
4195 ** them to numberic values are. */
4197 }else if( serial_type
==0 ){
4200 sqlite3VdbeSerialGet(&aKey1
[d1
], serial_type
, &mem1
);
4201 if( serial_type
==7 ){
4202 if( mem1
.u
.r
<pRhs
->u
.r
){
4204 }else if( mem1
.u
.r
>pRhs
->u
.r
){
4208 rc
= sqlite3IntFloatCompare(mem1
.u
.i
, pRhs
->u
.r
);
4213 /* RHS is a string */
4214 else if( pRhs
->flags
& MEM_Str
){
4215 getVarint32(&aKey1
[idx1
], serial_type
);
4216 testcase( serial_type
==12 );
4217 if( serial_type
<12 ){
4219 }else if( !(serial_type
& 0x01) ){
4222 mem1
.n
= (serial_type
- 12) / 2;
4223 testcase( (d1
+mem1
.n
)==(unsigned)nKey1
);
4224 testcase( (d1
+mem1
.n
+1)==(unsigned)nKey1
);
4225 if( (d1
+mem1
.n
) > (unsigned)nKey1
){
4226 pPKey2
->errCode
= (u8
)SQLITE_CORRUPT_BKPT
;
4227 return 0; /* Corruption */
4228 }else if( (pKeyInfo
= pPKey2
->pKeyInfo
)->aColl
[i
] ){
4229 mem1
.enc
= pKeyInfo
->enc
;
4230 mem1
.db
= pKeyInfo
->db
;
4231 mem1
.flags
= MEM_Str
;
4232 mem1
.z
= (char*)&aKey1
[d1
];
4233 rc
= vdbeCompareMemString(
4234 &mem1
, pRhs
, pKeyInfo
->aColl
[i
], &pPKey2
->errCode
4237 int nCmp
= MIN(mem1
.n
, pRhs
->n
);
4238 rc
= memcmp(&aKey1
[d1
], pRhs
->z
, nCmp
);
4239 if( rc
==0 ) rc
= mem1
.n
- pRhs
->n
;
4245 else if( pRhs
->flags
& MEM_Blob
){
4246 assert( (pRhs
->flags
& MEM_Zero
)==0 || pRhs
->n
==0 );
4247 getVarint32(&aKey1
[idx1
], serial_type
);
4248 testcase( serial_type
==12 );
4249 if( serial_type
<12 || (serial_type
& 0x01) ){
4252 int nStr
= (serial_type
- 12) / 2;
4253 testcase( (d1
+nStr
)==(unsigned)nKey1
);
4254 testcase( (d1
+nStr
+1)==(unsigned)nKey1
);
4255 if( (d1
+nStr
) > (unsigned)nKey1
){
4256 pPKey2
->errCode
= (u8
)SQLITE_CORRUPT_BKPT
;
4257 return 0; /* Corruption */
4258 }else if( pRhs
->flags
& MEM_Zero
){
4259 if( !isAllZero((const char*)&aKey1
[d1
],nStr
) ){
4262 rc
= nStr
- pRhs
->u
.nZero
;
4265 int nCmp
= MIN(nStr
, pRhs
->n
);
4266 rc
= memcmp(&aKey1
[d1
], pRhs
->z
, nCmp
);
4267 if( rc
==0 ) rc
= nStr
- pRhs
->n
;
4274 serial_type
= aKey1
[idx1
];
4275 rc
= (serial_type
!=0);
4279 if( pPKey2
->pKeyInfo
->aSortOrder
[i
] ){
4282 assert( vdbeRecordCompareDebug(nKey1
, pKey1
, pPKey2
, rc
) );
4283 assert( mem1
.szMalloc
==0 ); /* See comment below */
4288 if( i
==pPKey2
->nField
) break;
4290 d1
+= sqlite3VdbeSerialTypeLen(serial_type
);
4291 idx1
+= sqlite3VarintLen(serial_type
);
4292 }while( idx1
<(unsigned)szHdr1
&& d1
<=(unsigned)nKey1
);
4294 /* No memory allocation is ever used on mem1. Prove this using
4295 ** the following assert(). If the assert() fails, it indicates a
4296 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
4297 assert( mem1
.szMalloc
==0 );
4299 /* rc==0 here means that one or both of the keys ran out of fields and
4300 ** all the fields up to that point were equal. Return the default_rc
4303 || vdbeRecordCompareDebug(nKey1
, pKey1
, pPKey2
, pPKey2
->default_rc
)
4304 || pPKey2
->pKeyInfo
->db
->mallocFailed
4307 return pPKey2
->default_rc
;
4309 int sqlite3VdbeRecordCompare(
4310 int nKey1
, const void *pKey1
, /* Left key */
4311 UnpackedRecord
*pPKey2
/* Right key */
4313 return sqlite3VdbeRecordCompareWithSkip(nKey1
, pKey1
, pPKey2
, 0);
4318 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4319 ** that (a) the first field of pPKey2 is an integer, and (b) the
4320 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
4321 ** byte (i.e. is less than 128).
4323 ** To avoid concerns about buffer overreads, this routine is only used
4324 ** on schemas where the maximum valid header size is 63 bytes or less.
4326 static int vdbeRecordCompareInt(
4327 int nKey1
, const void *pKey1
, /* Left key */
4328 UnpackedRecord
*pPKey2
/* Right key */
4330 const u8
*aKey
= &((const u8
*)pKey1
)[*(const u8
*)pKey1
& 0x3F];
4331 int serial_type
= ((const u8
*)pKey1
)[1];
4338 vdbeAssertFieldCountWithinLimits(nKey1
, pKey1
, pPKey2
->pKeyInfo
);
4339 assert( (*(u8
*)pKey1
)<=0x3F || CORRUPT_DB
);
4340 switch( serial_type
){
4341 case 1: { /* 1-byte signed integer */
4342 lhs
= ONE_BYTE_INT(aKey
);
4346 case 2: { /* 2-byte signed integer */
4347 lhs
= TWO_BYTE_INT(aKey
);
4351 case 3: { /* 3-byte signed integer */
4352 lhs
= THREE_BYTE_INT(aKey
);
4356 case 4: { /* 4-byte signed integer */
4357 y
= FOUR_BYTE_UINT(aKey
);
4358 lhs
= (i64
)*(int*)&y
;
4362 case 5: { /* 6-byte signed integer */
4363 lhs
= FOUR_BYTE_UINT(aKey
+2) + (((i64
)1)<<32)*TWO_BYTE_INT(aKey
);
4367 case 6: { /* 8-byte signed integer */
4368 x
= FOUR_BYTE_UINT(aKey
);
4369 x
= (x
<<32) | FOUR_BYTE_UINT(aKey
+4);
4381 /* This case could be removed without changing the results of running
4382 ** this code. Including it causes gcc to generate a faster switch
4383 ** statement (since the range of switch targets now starts at zero and
4384 ** is contiguous) but does not cause any duplicate code to be generated
4385 ** (as gcc is clever enough to combine the two like cases). Other
4386 ** compilers might be similar. */
4388 return sqlite3VdbeRecordCompare(nKey1
, pKey1
, pPKey2
);
4391 return sqlite3VdbeRecordCompare(nKey1
, pKey1
, pPKey2
);
4394 v
= pPKey2
->aMem
[0].u
.i
;
4399 }else if( pPKey2
->nField
>1 ){
4400 /* The first fields of the two keys are equal. Compare the trailing
4402 res
= sqlite3VdbeRecordCompareWithSkip(nKey1
, pKey1
, pPKey2
, 1);
4404 /* The first fields of the two keys are equal and there are no trailing
4405 ** fields. Return pPKey2->default_rc in this case. */
4406 res
= pPKey2
->default_rc
;
4410 assert( vdbeRecordCompareDebug(nKey1
, pKey1
, pPKey2
, res
) );
4415 ** This function is an optimized version of sqlite3VdbeRecordCompare()
4416 ** that (a) the first field of pPKey2 is a string, that (b) the first field
4417 ** uses the collation sequence BINARY and (c) that the size-of-header varint
4418 ** at the start of (pKey1/nKey1) fits in a single byte.
4420 static int vdbeRecordCompareString(
4421 int nKey1
, const void *pKey1
, /* Left key */
4422 UnpackedRecord
*pPKey2
/* Right key */
4424 const u8
*aKey1
= (const u8
*)pKey1
;
4428 assert( pPKey2
->aMem
[0].flags
& MEM_Str
);
4429 vdbeAssertFieldCountWithinLimits(nKey1
, pKey1
, pPKey2
->pKeyInfo
);
4430 getVarint32(&aKey1
[1], serial_type
);
4431 if( serial_type
<12 ){
4432 res
= pPKey2
->r1
; /* (pKey1/nKey1) is a number or a null */
4433 }else if( !(serial_type
& 0x01) ){
4434 res
= pPKey2
->r2
; /* (pKey1/nKey1) is a blob */
4438 int szHdr
= aKey1
[0];
4440 nStr
= (serial_type
-12) / 2;
4441 if( (szHdr
+ nStr
) > nKey1
){
4442 pPKey2
->errCode
= (u8
)SQLITE_CORRUPT_BKPT
;
4443 return 0; /* Corruption */
4445 nCmp
= MIN( pPKey2
->aMem
[0].n
, nStr
);
4446 res
= memcmp(&aKey1
[szHdr
], pPKey2
->aMem
[0].z
, nCmp
);
4449 res
= nStr
- pPKey2
->aMem
[0].n
;
4451 if( pPKey2
->nField
>1 ){
4452 res
= sqlite3VdbeRecordCompareWithSkip(nKey1
, pKey1
, pPKey2
, 1);
4454 res
= pPKey2
->default_rc
;
4469 assert( vdbeRecordCompareDebug(nKey1
, pKey1
, pPKey2
, res
)
4471 || pPKey2
->pKeyInfo
->db
->mallocFailed
4477 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
4478 ** suitable for comparing serialized records to the unpacked record passed
4479 ** as the only argument.
4481 RecordCompare
sqlite3VdbeFindCompare(UnpackedRecord
*p
){
4482 /* varintRecordCompareInt() and varintRecordCompareString() both assume
4483 ** that the size-of-header varint that occurs at the start of each record
4484 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
4485 ** also assumes that it is safe to overread a buffer by at least the
4486 ** maximum possible legal header size plus 8 bytes. Because there is
4487 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
4488 ** buffer passed to varintRecordCompareInt() this makes it convenient to
4489 ** limit the size of the header to 64 bytes in cases where the first field
4492 ** The easiest way to enforce this limit is to consider only records with
4493 ** 13 fields or less. If the first field is an integer, the maximum legal
4494 ** header size is (12*5 + 1 + 1) bytes. */
4495 if( p
->pKeyInfo
->nAllField
<=13 ){
4496 int flags
= p
->aMem
[0].flags
;
4497 if( p
->pKeyInfo
->aSortOrder
[0] ){
4504 if( (flags
& MEM_Int
) ){
4505 return vdbeRecordCompareInt
;
4507 testcase( flags
& MEM_Real
);
4508 testcase( flags
& MEM_Null
);
4509 testcase( flags
& MEM_Blob
);
4510 if( (flags
& (MEM_Real
|MEM_Null
|MEM_Blob
))==0 && p
->pKeyInfo
->aColl
[0]==0 ){
4511 assert( flags
& MEM_Str
);
4512 return vdbeRecordCompareString
;
4516 return sqlite3VdbeRecordCompare
;
4520 ** pCur points at an index entry created using the OP_MakeRecord opcode.
4521 ** Read the rowid (the last field in the record) and store it in *rowid.
4522 ** Return SQLITE_OK if everything works, or an error code otherwise.
4524 ** pCur might be pointing to text obtained from a corrupt database file.
4525 ** So the content cannot be trusted. Do appropriate checks on the content.
4527 int sqlite3VdbeIdxRowid(sqlite3
*db
, BtCursor
*pCur
, i64
*rowid
){
4530 u32 szHdr
; /* Size of the header */
4531 u32 typeRowid
; /* Serial type of the rowid */
4532 u32 lenRowid
; /* Size of the rowid */
4535 /* Get the size of the index entry. Only indices entries of less
4536 ** than 2GiB are support - anything large must be database corruption.
4537 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4538 ** this code can safely assume that nCellKey is 32-bits
4540 assert( sqlite3BtreeCursorIsValid(pCur
) );
4541 nCellKey
= sqlite3BtreePayloadSize(pCur
);
4542 assert( (nCellKey
& SQLITE_MAX_U32
)==(u64
)nCellKey
);
4544 /* Read in the complete content of the index entry */
4545 sqlite3VdbeMemInit(&m
, db
, 0);
4546 rc
= sqlite3VdbeMemFromBtree(pCur
, 0, (u32
)nCellKey
, &m
);
4551 /* The index entry must begin with a header size */
4552 (void)getVarint32((u8
*)m
.z
, szHdr
);
4553 testcase( szHdr
==3 );
4554 testcase( szHdr
==m
.n
);
4555 if( unlikely(szHdr
<3 || (int)szHdr
>m
.n
) ){
4556 goto idx_rowid_corruption
;
4559 /* The last field of the index should be an integer - the ROWID.
4560 ** Verify that the last entry really is an integer. */
4561 (void)getVarint32((u8
*)&m
.z
[szHdr
-1], typeRowid
);
4562 testcase( typeRowid
==1 );
4563 testcase( typeRowid
==2 );
4564 testcase( typeRowid
==3 );
4565 testcase( typeRowid
==4 );
4566 testcase( typeRowid
==5 );
4567 testcase( typeRowid
==6 );
4568 testcase( typeRowid
==8 );
4569 testcase( typeRowid
==9 );
4570 if( unlikely(typeRowid
<1 || typeRowid
>9 || typeRowid
==7) ){
4571 goto idx_rowid_corruption
;
4573 lenRowid
= sqlite3SmallTypeSizes
[typeRowid
];
4574 testcase( (u32
)m
.n
==szHdr
+lenRowid
);
4575 if( unlikely((u32
)m
.n
<szHdr
+lenRowid
) ){
4576 goto idx_rowid_corruption
;
4579 /* Fetch the integer off the end of the index record */
4580 sqlite3VdbeSerialGet((u8
*)&m
.z
[m
.n
-lenRowid
], typeRowid
, &v
);
4582 sqlite3VdbeMemRelease(&m
);
4585 /* Jump here if database corruption is detected after m has been
4586 ** allocated. Free the m object and return SQLITE_CORRUPT. */
4587 idx_rowid_corruption
:
4588 testcase( m
.szMalloc
!=0 );
4589 sqlite3VdbeMemRelease(&m
);
4590 return SQLITE_CORRUPT_BKPT
;
4594 ** Compare the key of the index entry that cursor pC is pointing to against
4595 ** the key string in pUnpacked. Write into *pRes a number
4596 ** that is negative, zero, or positive if pC is less than, equal to,
4597 ** or greater than pUnpacked. Return SQLITE_OK on success.
4599 ** pUnpacked is either created without a rowid or is truncated so that it
4600 ** omits the rowid at the end. The rowid at the end of the index entry
4601 ** is ignored as well. Hence, this routine only compares the prefixes
4602 ** of the keys prior to the final rowid, not the entire key.
4604 int sqlite3VdbeIdxKeyCompare(
4605 sqlite3
*db
, /* Database connection */
4606 VdbeCursor
*pC
, /* The cursor to compare against */
4607 UnpackedRecord
*pUnpacked
, /* Unpacked version of key */
4608 int *res
/* Write the comparison result here */
4615 assert( pC
->eCurType
==CURTYPE_BTREE
);
4616 pCur
= pC
->uc
.pCursor
;
4617 assert( sqlite3BtreeCursorIsValid(pCur
) );
4618 nCellKey
= sqlite3BtreePayloadSize(pCur
);
4619 /* nCellKey will always be between 0 and 0xffffffff because of the way
4620 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
4621 if( nCellKey
<=0 || nCellKey
>0x7fffffff ){
4623 return SQLITE_CORRUPT_BKPT
;
4625 sqlite3VdbeMemInit(&m
, db
, 0);
4626 rc
= sqlite3VdbeMemFromBtree(pCur
, 0, (u32
)nCellKey
, &m
);
4630 *res
= sqlite3VdbeRecordCompareWithSkip(m
.n
, m
.z
, pUnpacked
, 0);
4631 sqlite3VdbeMemRelease(&m
);
4636 ** This routine sets the value to be returned by subsequent calls to
4637 ** sqlite3_changes() on the database handle 'db'.
4639 void sqlite3VdbeSetChanges(sqlite3
*db
, int nChange
){
4640 assert( sqlite3_mutex_held(db
->mutex
) );
4641 db
->nChange
= nChange
;
4642 db
->nTotalChange
+= nChange
;
4646 ** Set a flag in the vdbe to update the change counter when it is finalised
4649 void sqlite3VdbeCountChanges(Vdbe
*v
){
4654 ** Mark every prepared statement associated with a database connection
4657 ** An expired statement means that recompilation of the statement is
4658 ** recommend. Statements expire when things happen that make their
4659 ** programs obsolete. Removing user-defined functions or collating
4660 ** sequences, or changing an authorization function are the types of
4661 ** things that make prepared statements obsolete.
4663 void sqlite3ExpirePreparedStatements(sqlite3
*db
){
4665 for(p
= db
->pVdbe
; p
; p
=p
->pNext
){
4671 ** Return the database associated with the Vdbe.
4673 sqlite3
*sqlite3VdbeDb(Vdbe
*v
){
4678 ** Return the SQLITE_PREPARE flags for a Vdbe.
4680 u8
sqlite3VdbePrepareFlags(Vdbe
*v
){
4681 return v
->prepFlags
;
4685 ** Return a pointer to an sqlite3_value structure containing the value bound
4686 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4687 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4688 ** constants) to the value before returning it.
4690 ** The returned value must be freed by the caller using sqlite3ValueFree().
4692 sqlite3_value
*sqlite3VdbeGetBoundValue(Vdbe
*v
, int iVar
, u8 aff
){
4695 Mem
*pMem
= &v
->aVar
[iVar
-1];
4696 assert( (v
->db
->flags
& SQLITE_EnableQPSG
)==0 );
4697 if( 0==(pMem
->flags
& MEM_Null
) ){
4698 sqlite3_value
*pRet
= sqlite3ValueNew(v
->db
);
4700 sqlite3VdbeMemCopy((Mem
*)pRet
, pMem
);
4701 sqlite3ValueApplyAffinity(pRet
, aff
, SQLITE_UTF8
);
4710 ** Configure SQL variable iVar so that binding a new value to it signals
4711 ** to sqlite3_reoptimize() that re-preparing the statement may result
4712 ** in a better query plan.
4714 void sqlite3VdbeSetVarmask(Vdbe
*v
, int iVar
){
4716 assert( (v
->db
->flags
& SQLITE_EnableQPSG
)==0 );
4718 v
->expmask
|= 0x80000000;
4720 v
->expmask
|= ((u32
)1 << (iVar
-1));
4725 ** Cause a function to throw an error if it was call from OP_PureFunc
4726 ** rather than OP_Function.
4728 ** OP_PureFunc means that the function must be deterministic, and should
4729 ** throw an error if it is given inputs that would make it non-deterministic.
4730 ** This routine is invoked by date/time functions that use non-deterministic
4731 ** features such as 'now'.
4733 int sqlite3NotPureFunc(sqlite3_context
*pCtx
){
4734 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4735 if( pCtx
->pVdbe
==0 ) return 1;
4737 if( pCtx
->pVdbe
->aOp
[pCtx
->iOp
].opcode
==OP_PureFunc
){
4738 sqlite3_result_error(pCtx
,
4739 "non-deterministic function in index expression or CHECK constraint",
4746 #ifndef SQLITE_OMIT_VIRTUALTABLE
4748 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4749 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4750 ** in memory obtained from sqlite3DbMalloc).
4752 void sqlite3VtabImportErrmsg(Vdbe
*p
, sqlite3_vtab
*pVtab
){
4753 if( pVtab
->zErrMsg
){
4754 sqlite3
*db
= p
->db
;
4755 sqlite3DbFree(db
, p
->zErrMsg
);
4756 p
->zErrMsg
= sqlite3DbStrDup(db
, pVtab
->zErrMsg
);
4757 sqlite3_free(pVtab
->zErrMsg
);
4761 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4763 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4766 ** If the second argument is not NULL, release any allocations associated
4767 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
4768 ** structure itself, using sqlite3DbFree().
4770 ** This function is used to free UnpackedRecord structures allocated by
4771 ** the vdbeUnpackRecord() function found in vdbeapi.c.
4773 static void vdbeFreeUnpacked(sqlite3
*db
, int nField
, UnpackedRecord
*p
){
4776 for(i
=0; i
<nField
; i
++){
4777 Mem
*pMem
= &p
->aMem
[i
];
4778 if( pMem
->zMalloc
) sqlite3VdbeMemRelease(pMem
);
4780 sqlite3DbFreeNN(db
, p
);
4783 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4785 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4787 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
4788 ** then cursor passed as the second argument should point to the row about
4789 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
4790 ** the required value will be read from the row the cursor points to.
4792 void sqlite3VdbePreUpdateHook(
4793 Vdbe
*v
, /* Vdbe pre-update hook is invoked by */
4794 VdbeCursor
*pCsr
, /* Cursor to grab old.* values from */
4795 int op
, /* SQLITE_INSERT, UPDATE or DELETE */
4796 const char *zDb
, /* Database name */
4797 Table
*pTab
, /* Modified table */
4798 i64 iKey1
, /* Initial key value */
4799 int iReg
/* Register for new.* record */
4801 sqlite3
*db
= v
->db
;
4803 PreUpdate preupdate
;
4804 const char *zTbl
= pTab
->zName
;
4805 static const u8 fakeSortOrder
= 0;
4807 assert( db
->pPreUpdate
==0 );
4808 memset(&preupdate
, 0, sizeof(PreUpdate
));
4809 if( HasRowid(pTab
)==0 ){
4811 preupdate
.pPk
= sqlite3PrimaryKeyIndex(pTab
);
4813 if( op
==SQLITE_UPDATE
){
4814 iKey2
= v
->aMem
[iReg
].u
.i
;
4820 assert( pCsr
->nField
==pTab
->nCol
4821 || (pCsr
->nField
==pTab
->nCol
+1 && op
==SQLITE_DELETE
&& iReg
==-1)
4825 preupdate
.pCsr
= pCsr
;
4827 preupdate
.iNewReg
= iReg
;
4828 preupdate
.keyinfo
.db
= db
;
4829 preupdate
.keyinfo
.enc
= ENC(db
);
4830 preupdate
.keyinfo
.nKeyField
= pTab
->nCol
;
4831 preupdate
.keyinfo
.aSortOrder
= (u8
*)&fakeSortOrder
;
4832 preupdate
.iKey1
= iKey1
;
4833 preupdate
.iKey2
= iKey2
;
4834 preupdate
.pTab
= pTab
;
4836 db
->pPreUpdate
= &preupdate
;
4837 db
->xPreUpdateCallback(db
->pPreUpdateArg
, db
, op
, zDb
, zTbl
, iKey1
, iKey2
);
4839 sqlite3DbFree(db
, preupdate
.aRecord
);
4840 vdbeFreeUnpacked(db
, preupdate
.keyinfo
.nKeyField
+1, preupdate
.pUnpacked
);
4841 vdbeFreeUnpacked(db
, preupdate
.keyinfo
.nKeyField
+1, preupdate
.pNewUnpacked
);
4842 if( preupdate
.aNew
){
4844 for(i
=0; i
<pCsr
->nField
; i
++){
4845 sqlite3VdbeMemRelease(&preupdate
.aNew
[i
]);
4847 sqlite3DbFreeNN(db
, preupdate
.aNew
);
4850 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */