blob: f990c40d4166a4075de1883cf6c054b0943444ce [file] [log] [blame]
drh9a324642003-09-06 20:12:01 +00001/*
2** 2003 September 6
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code used for creating, destroying, and populating
danielk1977fc57d7b2004-05-26 02:04:57 +000013** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
drh9a324642003-09-06 20:12:01 +000014** to version 2.8.7, all this code was combined into the vdbe.c source file.
15** But that file was getting too big so this subroutines were split out.
16*/
17#include "sqliteInt.h"
drh9a324642003-09-06 20:12:01 +000018#include "vdbeInt.h"
19
drh9a324642003-09-06 20:12:01 +000020/*
21** Create a new virtual database engine.
22*/
drh9ac79622013-12-18 15:11:47 +000023Vdbe *sqlite3VdbeCreate(Parse *pParse){
24 sqlite3 *db = pParse->db;
drh9a324642003-09-06 20:12:01 +000025 Vdbe *p;
drh17435752007-08-16 04:30:38 +000026 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
drh9a324642003-09-06 20:12:01 +000027 if( p==0 ) return 0;
28 p->db = db;
29 if( db->pVdbe ){
30 db->pVdbe->pPrev = p;
31 }
32 p->pNext = db->pVdbe;
33 p->pPrev = 0;
34 db->pVdbe = p;
35 p->magic = VDBE_MAGIC_INIT;
drh9ac79622013-12-18 15:11:47 +000036 p->pParse = pParse;
drh73d5b8f2013-12-23 19:09:07 +000037 assert( pParse->aLabel==0 );
38 assert( pParse->nLabel==0 );
39 assert( pParse->nOpAlloc==0 );
drh9a324642003-09-06 20:12:01 +000040 return p;
41}
42
43/*
drhb900aaf2006-11-09 00:24:53 +000044** Remember the SQL string for a prepared statement.
45*/
danielk19776ab3a2e2009-02-19 14:39:25 +000046void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
dan1d2ce4f2009-10-19 18:11:09 +000047 assert( isPrepareV2==1 || isPrepareV2==0 );
drhb900aaf2006-11-09 00:24:53 +000048 if( p==0 ) return;
danac455932012-11-26 19:50:41 +000049#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
danielk19776ab3a2e2009-02-19 14:39:25 +000050 if( !isPrepareV2 ) return;
51#endif
drhb900aaf2006-11-09 00:24:53 +000052 assert( p->zSql==0 );
drh17435752007-08-16 04:30:38 +000053 p->zSql = sqlite3DbStrNDup(p->db, z, n);
shanef639c402009-11-03 19:42:30 +000054 p->isPrepareV2 = (u8)isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000055}
56
57/*
58** Return the SQL associated with a prepared statement
59*/
danielk1977d0e2a852007-11-14 06:48:48 +000060const char *sqlite3_sql(sqlite3_stmt *pStmt){
danielk19776ab3a2e2009-02-19 14:39:25 +000061 Vdbe *p = (Vdbe *)pStmt;
drh87f5c5f2010-01-20 01:20:56 +000062 return (p && p->isPrepareV2) ? p->zSql : 0;
drhb900aaf2006-11-09 00:24:53 +000063}
64
65/*
drhc5155252007-01-08 21:07:17 +000066** Swap all content between two VDBE structures.
drhb900aaf2006-11-09 00:24:53 +000067*/
drhc5155252007-01-08 21:07:17 +000068void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
69 Vdbe tmp, *pTmp;
70 char *zTmp;
drhc5155252007-01-08 21:07:17 +000071 tmp = *pA;
72 *pA = *pB;
73 *pB = tmp;
74 pTmp = pA->pNext;
75 pA->pNext = pB->pNext;
76 pB->pNext = pTmp;
77 pTmp = pA->pPrev;
78 pA->pPrev = pB->pPrev;
79 pB->pPrev = pTmp;
80 zTmp = pA->zSql;
81 pA->zSql = pB->zSql;
82 pB->zSql = zTmp;
danielk19776ab3a2e2009-02-19 14:39:25 +000083 pB->isPrepareV2 = pA->isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000084}
85
drh9a324642003-09-06 20:12:01 +000086/*
dan76ccd892014-08-12 13:38:52 +000087** Resize the Vdbe.aOp array so that it is at least nOp elements larger
drh81e069e2014-08-12 14:29:20 +000088** than its current size. nOp is guaranteed to be less than or equal
89** to 1024/sizeof(Op).
danielk1977ace3eb22006-01-26 10:35:04 +000090**
danielk197700e13612008-11-17 19:18:54 +000091** If an out-of-memory error occurs while resizing the array, return
dan76ccd892014-08-12 13:38:52 +000092** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
danielk197700e13612008-11-17 19:18:54 +000093** unchanged (this is so that any opcodes already allocated can be
94** correctly deallocated along with the rest of the Vdbe).
drh76ff3a02004-09-24 22:32:30 +000095*/
dan76ccd892014-08-12 13:38:52 +000096static int growOpArray(Vdbe *v, int nOp){
drha4e5d582007-10-20 15:41:57 +000097 VdbeOp *pNew;
drh73d5b8f2013-12-23 19:09:07 +000098 Parse *p = v->pParse;
dan76ccd892014-08-12 13:38:52 +000099
drh81e069e2014-08-12 14:29:20 +0000100 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
101 ** more frequent reallocs and hence provide more opportunities for
102 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
103 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
104 ** by the minimum* amount required until the size reaches 512. Normal
105 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
106 ** size of the op array or add 1KB of space, whichever is smaller. */
dan76ccd892014-08-12 13:38:52 +0000107#ifdef SQLITE_TEST_REALLOC_STRESS
108 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
109#else
danielk197700e13612008-11-17 19:18:54 +0000110 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
dan76ccd892014-08-12 13:38:52 +0000111 UNUSED_PARAMETER(nOp);
112#endif
113
drh81e069e2014-08-12 14:29:20 +0000114 assert( nOp<=(1024/sizeof(Op)) );
dan76ccd892014-08-12 13:38:52 +0000115 assert( nNew>=(p->nOpAlloc+nOp) );
drh73d5b8f2013-12-23 19:09:07 +0000116 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
drha4e5d582007-10-20 15:41:57 +0000117 if( pNew ){
drhb45f65d2009-03-01 19:42:11 +0000118 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
drh73d5b8f2013-12-23 19:09:07 +0000119 v->aOp = pNew;
drh76ff3a02004-09-24 22:32:30 +0000120 }
danielk197700e13612008-11-17 19:18:54 +0000121 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
drh76ff3a02004-09-24 22:32:30 +0000122}
123
drh313619f2013-10-31 20:34:06 +0000124#ifdef SQLITE_DEBUG
125/* This routine is just a convenient place to set a breakpoint that will
126** fire after each opcode is inserted and displayed using
127** "PRAGMA vdbe_addoptrace=on".
128*/
129static void test_addop_breakpoint(void){
130 static int n = 0;
131 n++;
132}
133#endif
134
drh76ff3a02004-09-24 22:32:30 +0000135/*
drh9a324642003-09-06 20:12:01 +0000136** Add a new instruction to the list of instructions current in the
137** VDBE. Return the address of the new instruction.
138**
139** Parameters:
140**
141** p Pointer to the VDBE
142**
143** op The opcode for this instruction
144**
drh66a51672008-01-03 00:01:23 +0000145** p1, p2, p3 Operands
drh9a324642003-09-06 20:12:01 +0000146**
danielk19774adee202004-05-08 08:23:19 +0000147** Use the sqlite3VdbeResolveLabel() function to fix an address and
drh66a51672008-01-03 00:01:23 +0000148** the sqlite3VdbeChangeP4() function to change the value of the P4
drh9a324642003-09-06 20:12:01 +0000149** operand.
150*/
drh66a51672008-01-03 00:01:23 +0000151int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
drh9a324642003-09-06 20:12:01 +0000152 int i;
drh701a0ae2004-02-22 20:05:00 +0000153 VdbeOp *pOp;
drh9a324642003-09-06 20:12:01 +0000154
155 i = p->nOp;
drh9a324642003-09-06 20:12:01 +0000156 assert( p->magic==VDBE_MAGIC_INIT );
drh8df32842008-12-09 02:51:23 +0000157 assert( op>0 && op<0xff );
drh73d5b8f2013-12-23 19:09:07 +0000158 if( p->pParse->nOpAlloc<=i ){
dan76ccd892014-08-12 13:38:52 +0000159 if( growOpArray(p, 1) ){
drhc42ed162009-06-26 14:04:51 +0000160 return 1;
drhfd2d26b2006-03-15 22:44:36 +0000161 }
drh9a324642003-09-06 20:12:01 +0000162 }
danielk197701256832007-04-18 14:24:32 +0000163 p->nOp++;
drh701a0ae2004-02-22 20:05:00 +0000164 pOp = &p->aOp[i];
drh8df32842008-12-09 02:51:23 +0000165 pOp->opcode = (u8)op;
drh26c9b5e2008-04-11 14:56:53 +0000166 pOp->p5 = 0;
drh701a0ae2004-02-22 20:05:00 +0000167 pOp->p1 = p1;
drh701a0ae2004-02-22 20:05:00 +0000168 pOp->p2 = p2;
drh66a51672008-01-03 00:01:23 +0000169 pOp->p3 = p3;
170 pOp->p4.p = 0;
171 pOp->p4type = P4_NOTUSED;
drhc7379ce2013-10-30 02:28:23 +0000172#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000173 pOp->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000174#endif
175#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000176 if( p->db->flags & SQLITE_VdbeAddopTrace ){
drh9ac79622013-12-18 15:11:47 +0000177 int jj, kk;
178 Parse *pParse = p->pParse;
179 for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
180 struct yColCache *x = pParse->aColCache + jj;
181 if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
182 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
183 kk++;
184 }
185 if( kk ) printf("\n");
drhe0962052013-01-29 19:14:31 +0000186 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
drh313619f2013-10-31 20:34:06 +0000187 test_addop_breakpoint();
drhe0962052013-01-29 19:14:31 +0000188 }
drh9a324642003-09-06 20:12:01 +0000189#endif
drh26c9b5e2008-04-11 14:56:53 +0000190#ifdef VDBE_PROFILE
191 pOp->cycles = 0;
192 pOp->cnt = 0;
193#endif
drh688852a2014-02-17 22:40:43 +0000194#ifdef SQLITE_VDBE_COVERAGE
195 pOp->iSrcLine = 0;
196#endif
drh9a324642003-09-06 20:12:01 +0000197 return i;
198}
drh66a51672008-01-03 00:01:23 +0000199int sqlite3VdbeAddOp0(Vdbe *p, int op){
200 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
201}
202int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
203 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
204}
205int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
206 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
drh701a0ae2004-02-22 20:05:00 +0000207}
208
drh66a51672008-01-03 00:01:23 +0000209
drh701a0ae2004-02-22 20:05:00 +0000210/*
drh66a51672008-01-03 00:01:23 +0000211** Add an opcode that includes the p4 value as a pointer.
drhd4e70eb2008-01-02 00:34:36 +0000212*/
drh66a51672008-01-03 00:01:23 +0000213int sqlite3VdbeAddOp4(
drhd4e70eb2008-01-02 00:34:36 +0000214 Vdbe *p, /* Add the opcode to this VM */
215 int op, /* The new opcode */
drh66a51672008-01-03 00:01:23 +0000216 int p1, /* The P1 operand */
217 int p2, /* The P2 operand */
218 int p3, /* The P3 operand */
219 const char *zP4, /* The P4 operand */
220 int p4type /* P4 operand type */
drhd4e70eb2008-01-02 00:34:36 +0000221){
drh66a51672008-01-03 00:01:23 +0000222 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
223 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
drhd4e70eb2008-01-02 00:34:36 +0000224 return addr;
225}
226
227/*
drh5d9c9da2011-06-03 20:11:17 +0000228** Add an OP_ParseSchema opcode. This routine is broken out from
drhe4c88c02012-01-04 12:57:45 +0000229** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
230** as having been used.
drh5d9c9da2011-06-03 20:11:17 +0000231**
232** The zWhere string must have been obtained from sqlite3_malloc().
233** This routine will take ownership of the allocated memory.
234*/
235void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
236 int j;
237 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
238 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
239 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
240}
241
242/*
drh8cff69d2009-11-12 19:59:44 +0000243** Add an opcode that includes the p4 value as an integer.
244*/
245int sqlite3VdbeAddOp4Int(
246 Vdbe *p, /* Add the opcode to this VM */
247 int op, /* The new opcode */
248 int p1, /* The P1 operand */
249 int p2, /* The P2 operand */
250 int p3, /* The P3 operand */
251 int p4 /* The P4 operand as an integer */
252){
253 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
254 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
255 return addr;
256}
257
258/*
drh9a324642003-09-06 20:12:01 +0000259** Create a new symbolic label for an instruction that has yet to be
260** coded. The symbolic label is really just a negative number. The
261** label can be used as the P2 value of an operation. Later, when
262** the label is resolved to a specific address, the VDBE will scan
263** through its operation list and change all values of P2 which match
264** the label into the resolved address.
265**
266** The VDBE knows that a P2 value is a label because labels are
267** always negative and P2 values are suppose to be non-negative.
268** Hence, a negative P2 value is a label that has yet to be resolved.
danielk1977b5548a82004-06-26 13:51:33 +0000269**
270** Zero is returned if a malloc() fails.
drh9a324642003-09-06 20:12:01 +0000271*/
drh73d5b8f2013-12-23 19:09:07 +0000272int sqlite3VdbeMakeLabel(Vdbe *v){
273 Parse *p = v->pParse;
drhc35f3d52012-02-01 19:03:38 +0000274 int i = p->nLabel++;
drh73d5b8f2013-12-23 19:09:07 +0000275 assert( v->magic==VDBE_MAGIC_INIT );
drhc35f3d52012-02-01 19:03:38 +0000276 if( (i & (i-1))==0 ){
277 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
278 (i*2+1)*sizeof(p->aLabel[0]));
drh9a324642003-09-06 20:12:01 +0000279 }
drh76ff3a02004-09-24 22:32:30 +0000280 if( p->aLabel ){
281 p->aLabel[i] = -1;
drh9a324642003-09-06 20:12:01 +0000282 }
drh9a324642003-09-06 20:12:01 +0000283 return -1-i;
284}
285
286/*
287** Resolve label "x" to be the address of the next instruction to
288** be inserted. The parameter "x" must have been obtained from
danielk19774adee202004-05-08 08:23:19 +0000289** a prior call to sqlite3VdbeMakeLabel().
drh9a324642003-09-06 20:12:01 +0000290*/
drh73d5b8f2013-12-23 19:09:07 +0000291void sqlite3VdbeResolveLabel(Vdbe *v, int x){
292 Parse *p = v->pParse;
drh76ff3a02004-09-24 22:32:30 +0000293 int j = -1-x;
drh73d5b8f2013-12-23 19:09:07 +0000294 assert( v->magic==VDBE_MAGIC_INIT );
drhb2b9d3d2013-08-01 01:14:43 +0000295 assert( j<p->nLabel );
drhd2490902014-04-13 19:28:15 +0000296 if( ALWAYS(j>=0) && p->aLabel ){
drh73d5b8f2013-12-23 19:09:07 +0000297 p->aLabel[j] = v->nOp;
drh9a324642003-09-06 20:12:01 +0000298 }
drh61019c72014-01-04 16:49:02 +0000299 p->iFixedOp = v->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000300}
301
drh4611d922010-02-25 14:47:01 +0000302/*
303** Mark the VDBE as one that can only be run one time.
304*/
305void sqlite3VdbeRunOnlyOnce(Vdbe *p){
306 p->runOnlyOnce = 1;
307}
308
drhff738bc2009-09-24 00:09:58 +0000309#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
dan144926d2009-09-09 11:37:20 +0000310
311/*
312** The following type and function are used to iterate through all opcodes
313** in a Vdbe main program and each of the sub-programs (triggers) it may
314** invoke directly or indirectly. It should be used as follows:
315**
316** Op *pOp;
317** VdbeOpIter sIter;
318**
319** memset(&sIter, 0, sizeof(sIter));
320** sIter.v = v; // v is of type Vdbe*
321** while( (pOp = opIterNext(&sIter)) ){
322** // Do something with pOp
323** }
324** sqlite3DbFree(v->db, sIter.apSub);
325**
326*/
327typedef struct VdbeOpIter VdbeOpIter;
328struct VdbeOpIter {
329 Vdbe *v; /* Vdbe to iterate through the opcodes of */
330 SubProgram **apSub; /* Array of subprograms */
331 int nSub; /* Number of entries in apSub */
332 int iAddr; /* Address of next instruction to return */
333 int iSub; /* 0 = main program, 1 = first sub-program etc. */
334};
335static Op *opIterNext(VdbeOpIter *p){
336 Vdbe *v = p->v;
337 Op *pRet = 0;
338 Op *aOp;
339 int nOp;
340
341 if( p->iSub<=p->nSub ){
342
343 if( p->iSub==0 ){
344 aOp = v->aOp;
345 nOp = v->nOp;
346 }else{
347 aOp = p->apSub[p->iSub-1]->aOp;
348 nOp = p->apSub[p->iSub-1]->nOp;
349 }
350 assert( p->iAddr<nOp );
351
352 pRet = &aOp[p->iAddr];
353 p->iAddr++;
354 if( p->iAddr==nOp ){
355 p->iSub++;
356 p->iAddr = 0;
357 }
358
359 if( pRet->p4type==P4_SUBPROGRAM ){
360 int nByte = (p->nSub+1)*sizeof(SubProgram*);
361 int j;
362 for(j=0; j<p->nSub; j++){
363 if( p->apSub[j]==pRet->p4.pProgram ) break;
364 }
365 if( j==p->nSub ){
366 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
367 if( !p->apSub ){
368 pRet = 0;
369 }else{
370 p->apSub[p->nSub++] = pRet->p4.pProgram;
371 }
372 }
373 }
374 }
375
376 return pRet;
377}
378
379/*
danf3677212009-09-10 16:14:50 +0000380** Check if the program stored in the VM associated with pParse may
drhff738bc2009-09-24 00:09:58 +0000381** throw an ABORT exception (causing the statement, but not entire transaction
dan144926d2009-09-09 11:37:20 +0000382** to be rolled back). This condition is true if the main program or any
383** sub-programs contains any of the following:
384**
385** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
386** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
387** * OP_Destroy
388** * OP_VUpdate
389** * OP_VRename
dan32b09f22009-09-23 17:29:59 +0000390** * OP_FkCounter with P2==0 (immediate foreign key constraint)
dan144926d2009-09-09 11:37:20 +0000391**
danf3677212009-09-10 16:14:50 +0000392** Then check that the value of Parse.mayAbort is true if an
393** ABORT may be thrown, or false otherwise. Return true if it does
394** match, or false otherwise. This function is intended to be used as
395** part of an assert statement in the compiler. Similar to:
396**
397** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
dan144926d2009-09-09 11:37:20 +0000398*/
danf3677212009-09-10 16:14:50 +0000399int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
400 int hasAbort = 0;
dan144926d2009-09-09 11:37:20 +0000401 Op *pOp;
402 VdbeOpIter sIter;
403 memset(&sIter, 0, sizeof(sIter));
404 sIter.v = v;
405
406 while( (pOp = opIterNext(&sIter))!=0 ){
407 int opcode = pOp->opcode;
408 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
dan32b09f22009-09-23 17:29:59 +0000409#ifndef SQLITE_OMIT_FOREIGN_KEY
dan0ff297e2009-09-25 17:03:14 +0000410 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
dan32b09f22009-09-23 17:29:59 +0000411#endif
dan144926d2009-09-09 11:37:20 +0000412 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
drhd91c1a12013-02-09 13:58:25 +0000413 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
dan144926d2009-09-09 11:37:20 +0000414 ){
danf3677212009-09-10 16:14:50 +0000415 hasAbort = 1;
dan144926d2009-09-09 11:37:20 +0000416 break;
417 }
418 }
dan144926d2009-09-09 11:37:20 +0000419 sqlite3DbFree(v->db, sIter.apSub);
danf3677212009-09-10 16:14:50 +0000420
mistachkin48864df2013-03-21 21:20:32 +0000421 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
danf3677212009-09-10 16:14:50 +0000422 ** If malloc failed, then the while() loop above may not have iterated
423 ** through all opcodes and hasAbort may be set incorrectly. Return
424 ** true for this case to prevent the assert() in the callers frame
425 ** from failing. */
426 return ( v->db->mallocFailed || hasAbort==mayAbort );
dan144926d2009-09-09 11:37:20 +0000427}
drhff738bc2009-09-24 00:09:58 +0000428#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
dan144926d2009-09-09 11:37:20 +0000429
drh9a324642003-09-06 20:12:01 +0000430/*
drh9cbf3422008-01-17 16:22:13 +0000431** Loop through the program looking for P2 values that are negative
432** on jump instructions. Each such value is a label. Resolve the
433** label by setting the P2 value to its correct non-zero value.
drh76ff3a02004-09-24 22:32:30 +0000434**
435** This routine is called once after all opcodes have been inserted.
danielk1977634f2982005-03-28 08:44:07 +0000436**
drh13449892005-09-07 21:22:45 +0000437** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
danielk1977399918f2006-06-14 13:03:23 +0000438** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
danielk1977634f2982005-03-28 08:44:07 +0000439** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
drha6c2ed92009-11-14 23:22:23 +0000440**
441** The Op.opflags field is set on all opcodes.
drh76ff3a02004-09-24 22:32:30 +0000442*/
drh9cbf3422008-01-17 16:22:13 +0000443static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
drh76ff3a02004-09-24 22:32:30 +0000444 int i;
dan165921a2009-08-28 18:53:45 +0000445 int nMaxArgs = *pMaxFuncArgs;
drh76ff3a02004-09-24 22:32:30 +0000446 Op *pOp;
drh73d5b8f2013-12-23 19:09:07 +0000447 Parse *pParse = p->pParse;
448 int *aLabel = pParse->aLabel;
drhad4a4b82008-11-05 16:37:34 +0000449 p->readOnly = 1;
drh1713afb2013-06-28 01:24:57 +0000450 p->bIsReader = 0;
drh76ff3a02004-09-24 22:32:30 +0000451 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
danielk1977634f2982005-03-28 08:44:07 +0000452 u8 opcode = pOp->opcode;
453
drh8c8a8c42013-08-06 07:45:08 +0000454 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
455 ** cases from this switch! */
456 switch( opcode ){
457 case OP_Function:
458 case OP_AggStep: {
459 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
460 break;
461 }
462 case OP_Transaction: {
463 if( pOp->p2!=0 ) p->readOnly = 0;
464 /* fall thru */
465 }
466 case OP_AutoCommit:
467 case OP_Savepoint: {
468 p->bIsReader = 1;
469 break;
470 }
dand9031542013-07-05 16:54:30 +0000471#ifndef SQLITE_OMIT_WAL
drh8c8a8c42013-08-06 07:45:08 +0000472 case OP_Checkpoint:
drh9e92a472013-06-27 17:40:30 +0000473#endif
drh8c8a8c42013-08-06 07:45:08 +0000474 case OP_Vacuum:
475 case OP_JournalMode: {
476 p->readOnly = 0;
477 p->bIsReader = 1;
478 break;
479 }
danielk1977182c4ba2007-06-27 15:53:34 +0000480#ifndef SQLITE_OMIT_VIRTUALTABLE
drh8c8a8c42013-08-06 07:45:08 +0000481 case OP_VUpdate: {
482 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
483 break;
484 }
485 case OP_VFilter: {
486 int n;
487 assert( p->nOp - i >= 3 );
488 assert( pOp[-1].opcode==OP_Integer );
489 n = pOp[-1].p1;
490 if( n>nMaxArgs ) nMaxArgs = n;
491 break;
492 }
danielk1977182c4ba2007-06-27 15:53:34 +0000493#endif
drh8c8a8c42013-08-06 07:45:08 +0000494 case OP_Next:
drhf93cd942013-11-21 03:12:25 +0000495 case OP_NextIfOpen:
drh8c8a8c42013-08-06 07:45:08 +0000496 case OP_SorterNext: {
497 pOp->p4.xAdvance = sqlite3BtreeNext;
498 pOp->p4type = P4_ADVANCE;
499 break;
500 }
drhf93cd942013-11-21 03:12:25 +0000501 case OP_Prev:
502 case OP_PrevIfOpen: {
drh8c8a8c42013-08-06 07:45:08 +0000503 pOp->p4.xAdvance = sqlite3BtreePrevious;
504 pOp->p4type = P4_ADVANCE;
505 break;
506 }
danielk1977bc04f852005-03-29 08:26:13 +0000507 }
danielk1977634f2982005-03-28 08:44:07 +0000508
drh8c8a8c42013-08-06 07:45:08 +0000509 pOp->opflags = sqlite3OpcodeProperty[opcode];
drha6c2ed92009-11-14 23:22:23 +0000510 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
drh73d5b8f2013-12-23 19:09:07 +0000511 assert( -1-pOp->p2<pParse->nLabel );
drhd2981512008-01-04 19:33:49 +0000512 pOp->p2 = aLabel[-1-pOp->p2];
513 }
drh76ff3a02004-09-24 22:32:30 +0000514 }
drh73d5b8f2013-12-23 19:09:07 +0000515 sqlite3DbFree(p->db, pParse->aLabel);
516 pParse->aLabel = 0;
517 pParse->nLabel = 0;
danielk1977bc04f852005-03-29 08:26:13 +0000518 *pMaxFuncArgs = nMaxArgs;
drha7ab6d82014-07-21 15:44:39 +0000519 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
drh76ff3a02004-09-24 22:32:30 +0000520}
521
522/*
drh9a324642003-09-06 20:12:01 +0000523** Return the address of the next instruction to be inserted.
524*/
danielk19774adee202004-05-08 08:23:19 +0000525int sqlite3VdbeCurrentAddr(Vdbe *p){
drh9a324642003-09-06 20:12:01 +0000526 assert( p->magic==VDBE_MAGIC_INIT );
527 return p->nOp;
528}
529
dan65a7cd12009-09-01 12:16:01 +0000530/*
531** This function returns a pointer to the array of opcodes associated with
532** the Vdbe passed as the first argument. It is the callers responsibility
533** to arrange for the returned array to be eventually freed using the
534** vdbeFreeOpArray() function.
535**
536** Before returning, *pnOp is set to the number of entries in the returned
537** array. Also, *pnMaxArg is set to the larger of its current value and
538** the number of entries in the Vdbe.apArg[] array required to execute the
539** returned program.
540*/
dan165921a2009-08-28 18:53:45 +0000541VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
542 VdbeOp *aOp = p->aOp;
dan523a0872009-08-31 05:23:32 +0000543 assert( aOp && !p->db->mallocFailed );
dan65a7cd12009-09-01 12:16:01 +0000544
545 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
drha7ab6d82014-07-21 15:44:39 +0000546 assert( DbMaskAllZero(p->btreeMask) );
dan65a7cd12009-09-01 12:16:01 +0000547
dan165921a2009-08-28 18:53:45 +0000548 resolveP2Values(p, pnMaxArg);
549 *pnOp = p->nOp;
550 p->aOp = 0;
551 return aOp;
552}
553
drh9a324642003-09-06 20:12:01 +0000554/*
555** Add a whole list of operations to the operation stack. Return the
556** address of the first operation added.
557*/
drh688852a2014-02-17 22:40:43 +0000558int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
drh9a324642003-09-06 20:12:01 +0000559 int addr;
560 assert( p->magic==VDBE_MAGIC_INIT );
dan76ccd892014-08-12 13:38:52 +0000561 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
drh76ff3a02004-09-24 22:32:30 +0000562 return 0;
drh9a324642003-09-06 20:12:01 +0000563 }
564 addr = p->nOp;
drh7b746032009-06-26 12:15:22 +0000565 if( ALWAYS(nOp>0) ){
drh9a324642003-09-06 20:12:01 +0000566 int i;
drh905793e2004-02-21 13:31:09 +0000567 VdbeOpList const *pIn = aOp;
568 for(i=0; i<nOp; i++, pIn++){
569 int p2 = pIn->p2;
570 VdbeOp *pOut = &p->aOp[i+addr];
571 pOut->opcode = pIn->opcode;
572 pOut->p1 = pIn->p1;
drh4308e342013-11-11 16:55:52 +0000573 if( p2<0 ){
574 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
drh8558cde2008-01-05 05:20:10 +0000575 pOut->p2 = addr + ADDR(p2);
576 }else{
577 pOut->p2 = p2;
578 }
drh24003452008-01-03 01:28:59 +0000579 pOut->p3 = pIn->p3;
580 pOut->p4type = P4_NOTUSED;
581 pOut->p4.p = 0;
582 pOut->p5 = 0;
drhc7379ce2013-10-30 02:28:23 +0000583#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000584 pOut->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000585#endif
drh688852a2014-02-17 22:40:43 +0000586#ifdef SQLITE_VDBE_COVERAGE
587 pOut->iSrcLine = iLineno+i;
588#else
589 (void)iLineno;
590#endif
drhc7379ce2013-10-30 02:28:23 +0000591#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000592 if( p->db->flags & SQLITE_VdbeAddopTrace ){
danielk19774adee202004-05-08 08:23:19 +0000593 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
drh9a324642003-09-06 20:12:01 +0000594 }
595#endif
596 }
597 p->nOp += nOp;
598 }
599 return addr;
600}
601
602/*
603** Change the value of the P1 operand for a specific instruction.
604** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000605** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000606** few minor changes to the program.
607*/
drh88caeac2011-08-24 15:12:08 +0000608void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000609 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000610 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000611 p->aOp[addr].p1 = val;
612 }
613}
614
615/*
616** Change the value of the P2 operand for a specific instruction.
617** This routine is useful for setting a jump destination.
618*/
drh88caeac2011-08-24 15:12:08 +0000619void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000620 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000621 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000622 p->aOp[addr].p2 = val;
623 }
624}
625
drhd654be82005-09-20 17:42:23 +0000626/*
danielk19771f4aa332008-01-03 09:51:55 +0000627** Change the value of the P3 operand for a specific instruction.
danielk1977207872a2008-01-03 07:54:23 +0000628*/
drh88caeac2011-08-24 15:12:08 +0000629void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000630 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000631 if( ((u32)p->nOp)>addr ){
danielk1977207872a2008-01-03 07:54:23 +0000632 p->aOp[addr].p3 = val;
633 }
634}
635
636/*
drh35573352008-01-08 23:54:25 +0000637** Change the value of the P5 operand for the most recently
638** added operation.
danielk19771f4aa332008-01-03 09:51:55 +0000639*/
drh35573352008-01-08 23:54:25 +0000640void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
drh7b746032009-06-26 12:15:22 +0000641 assert( p!=0 );
642 if( p->aOp ){
drh35573352008-01-08 23:54:25 +0000643 assert( p->nOp>0 );
644 p->aOp[p->nOp-1].p5 = val;
danielk19771f4aa332008-01-03 09:51:55 +0000645 }
646}
647
648/*
drhf8875402006-03-17 13:56:34 +0000649** Change the P2 operand of instruction addr so that it points to
drhd654be82005-09-20 17:42:23 +0000650** the address of the next instruction to be coded.
651*/
652void sqlite3VdbeJumpHere(Vdbe *p, int addr){
drh61019c72014-01-04 16:49:02 +0000653 sqlite3VdbeChangeP2(p, addr, p->nOp);
654 p->pParse->iFixedOp = p->nOp - 1;
drhd654be82005-09-20 17:42:23 +0000655}
drhb38ad992005-09-16 00:27:01 +0000656
drhb7f6f682006-07-08 17:06:43 +0000657
658/*
659** If the input FuncDef structure is ephemeral, then free it. If
660** the FuncDef is not ephermal, then do nothing.
661*/
drh633e6d52008-07-28 19:34:53 +0000662static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
drhd36e1042013-09-06 13:10:12 +0000663 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
drh633e6d52008-07-28 19:34:53 +0000664 sqlite3DbFree(db, pDef);
drhb7f6f682006-07-08 17:06:43 +0000665 }
666}
667
dand46def72010-07-24 11:28:28 +0000668static void vdbeFreeOpArray(sqlite3 *, Op *, int);
669
drhb38ad992005-09-16 00:27:01 +0000670/*
drh66a51672008-01-03 00:01:23 +0000671** Delete a P4 value if necessary.
drhb38ad992005-09-16 00:27:01 +0000672*/
drh633e6d52008-07-28 19:34:53 +0000673static void freeP4(sqlite3 *db, int p4type, void *p4){
drh0acb7e42008-06-25 00:12:41 +0000674 if( p4 ){
dand46def72010-07-24 11:28:28 +0000675 assert( db );
drh66a51672008-01-03 00:01:23 +0000676 switch( p4type ){
677 case P4_REAL:
678 case P4_INT64:
drh66a51672008-01-03 00:01:23 +0000679 case P4_DYNAMIC:
drh2ec2fb22013-11-06 19:59:23 +0000680 case P4_INTARRAY: {
drh633e6d52008-07-28 19:34:53 +0000681 sqlite3DbFree(db, p4);
drhac1733d2005-09-17 17:58:22 +0000682 break;
683 }
drh2ec2fb22013-11-06 19:59:23 +0000684 case P4_KEYINFO: {
685 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
686 break;
687 }
drhb9755982010-07-24 16:34:37 +0000688 case P4_MPRINTF: {
drh7043db92010-07-26 12:38:12 +0000689 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
drhb9755982010-07-24 16:34:37 +0000690 break;
691 }
drh66a51672008-01-03 00:01:23 +0000692 case P4_FUNCDEF: {
drh633e6d52008-07-28 19:34:53 +0000693 freeEphemeralFunction(db, (FuncDef*)p4);
drhb7f6f682006-07-08 17:06:43 +0000694 break;
695 }
drh66a51672008-01-03 00:01:23 +0000696 case P4_MEM: {
drhc176c272010-07-26 13:57:59 +0000697 if( db->pnBytesFreed==0 ){
698 sqlite3ValueFree((sqlite3_value*)p4);
699 }else{
drhf37c68e2010-07-26 14:20:06 +0000700 Mem *p = (Mem*)p4;
drh17bcb102014-09-18 21:25:33 +0000701 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
drhf37c68e2010-07-26 14:20:06 +0000702 sqlite3DbFree(db, p);
drhc176c272010-07-26 13:57:59 +0000703 }
drhac1733d2005-09-17 17:58:22 +0000704 break;
705 }
danielk1977595a5232009-07-24 17:58:53 +0000706 case P4_VTAB : {
dand46def72010-07-24 11:28:28 +0000707 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
danielk1977595a5232009-07-24 17:58:53 +0000708 break;
709 }
drhb38ad992005-09-16 00:27:01 +0000710 }
711 }
712}
713
dan65a7cd12009-09-01 12:16:01 +0000714/*
715** Free the space allocated for aOp and any p4 values allocated for the
716** opcodes contained within. If aOp is not NULL it is assumed to contain
717** nOp entries.
718*/
dan165921a2009-08-28 18:53:45 +0000719static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
720 if( aOp ){
721 Op *pOp;
722 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
723 freeP4(db, pOp->p4type, pOp->p4.p);
drhc7379ce2013-10-30 02:28:23 +0000724#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
dan165921a2009-08-28 18:53:45 +0000725 sqlite3DbFree(db, pOp->zComment);
726#endif
727 }
728 }
729 sqlite3DbFree(db, aOp);
730}
731
dan65a7cd12009-09-01 12:16:01 +0000732/*
dand19c9332010-07-26 12:05:17 +0000733** Link the SubProgram object passed as the second argument into the linked
734** list at Vdbe.pSubProgram. This list is used to delete all sub-program
735** objects when the VM is no longer required.
dan65a7cd12009-09-01 12:16:01 +0000736*/
dand19c9332010-07-26 12:05:17 +0000737void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
738 p->pNext = pVdbe->pProgram;
739 pVdbe->pProgram = p;
dan165921a2009-08-28 18:53:45 +0000740}
741
drh9a324642003-09-06 20:12:01 +0000742/*
drh48f2d3b2011-09-16 01:34:43 +0000743** Change the opcode at addr into OP_Noop
drhf8875402006-03-17 13:56:34 +0000744*/
drh48f2d3b2011-09-16 01:34:43 +0000745void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
dan76ccd892014-08-12 13:38:52 +0000746 if( addr<p->nOp ){
danielk197792d4d7a2007-05-04 12:05:56 +0000747 VdbeOp *pOp = &p->aOp[addr];
drh633e6d52008-07-28 19:34:53 +0000748 sqlite3 *db = p->db;
drh48f2d3b2011-09-16 01:34:43 +0000749 freeP4(db, pOp->p4type, pOp->p4.p);
750 memset(pOp, 0, sizeof(pOp[0]));
751 pOp->opcode = OP_Noop;
drh313619f2013-10-31 20:34:06 +0000752 if( addr==p->nOp-1 ) p->nOp--;
drhf8875402006-03-17 13:56:34 +0000753 }
754}
755
756/*
drh762c1c42014-01-02 19:35:30 +0000757** Remove the last opcode inserted
758*/
drh61019c72014-01-04 16:49:02 +0000759int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
760 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
761 sqlite3VdbeChangeToNoop(p, p->nOp-1);
762 return 1;
763 }else{
764 return 0;
765 }
drh762c1c42014-01-02 19:35:30 +0000766}
767
768/*
drh66a51672008-01-03 00:01:23 +0000769** Change the value of the P4 operand for a specific instruction.
drh9a324642003-09-06 20:12:01 +0000770** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000771** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000772** few minor changes to the program.
773**
drh66a51672008-01-03 00:01:23 +0000774** If n>=0 then the P4 operand is dynamic, meaning that a copy of
drh17435752007-08-16 04:30:38 +0000775** the string is made into memory obtained from sqlite3_malloc().
drh66a51672008-01-03 00:01:23 +0000776** A value of n==0 means copy bytes of zP4 up to and including the
777** first null byte. If n>0 then copy n+1 bytes of zP4.
danielk19771f55c052005-05-19 08:42:59 +0000778**
drh66a51672008-01-03 00:01:23 +0000779** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
danielk19771f55c052005-05-19 08:42:59 +0000780** to a string or structure that is guaranteed to exist for the lifetime of
781** the Vdbe. In these cases we can just copy the pointer.
drh9a324642003-09-06 20:12:01 +0000782**
drh66a51672008-01-03 00:01:23 +0000783** If addr<0 then change P4 on the most recently inserted instruction.
drh9a324642003-09-06 20:12:01 +0000784*/
drh66a51672008-01-03 00:01:23 +0000785void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
drh9a324642003-09-06 20:12:01 +0000786 Op *pOp;
drh633e6d52008-07-28 19:34:53 +0000787 sqlite3 *db;
drh91fd4d42008-01-19 20:11:25 +0000788 assert( p!=0 );
drh633e6d52008-07-28 19:34:53 +0000789 db = p->db;
drh91fd4d42008-01-19 20:11:25 +0000790 assert( p->magic==VDBE_MAGIC_INIT );
drh633e6d52008-07-28 19:34:53 +0000791 if( p->aOp==0 || db->mallocFailed ){
drh2ec2fb22013-11-06 19:59:23 +0000792 if( n!=P4_VTAB ){
drh633e6d52008-07-28 19:34:53 +0000793 freeP4(db, n, (void*)*(char**)&zP4);
danielk1977261919c2005-12-06 12:52:59 +0000794 }
danielk1977d5d56522005-03-16 12:15:20 +0000795 return;
796 }
drh7b746032009-06-26 12:15:22 +0000797 assert( p->nOp>0 );
drh91fd4d42008-01-19 20:11:25 +0000798 assert( addr<p->nOp );
799 if( addr<0 ){
drh9a324642003-09-06 20:12:01 +0000800 addr = p->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000801 }
802 pOp = &p->aOp[addr];
drh079a3072014-03-19 14:10:55 +0000803 assert( pOp->p4type==P4_NOTUSED
804 || pOp->p4type==P4_INT32
805 || pOp->p4type==P4_KEYINFO );
drh633e6d52008-07-28 19:34:53 +0000806 freeP4(db, pOp->p4type, pOp->p4.p);
drh66a51672008-01-03 00:01:23 +0000807 pOp->p4.p = 0;
drh98757152008-01-09 23:04:12 +0000808 if( n==P4_INT32 ){
mlcreech12d40822008-03-06 07:35:21 +0000809 /* Note: this cast is safe, because the origin data point was an int
810 ** that was cast to a (const char *). */
shane1fc41292008-07-08 22:28:48 +0000811 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
drh8df32842008-12-09 02:51:23 +0000812 pOp->p4type = P4_INT32;
drh98757152008-01-09 23:04:12 +0000813 }else if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +0000814 pOp->p4.p = 0;
815 pOp->p4type = P4_NOTUSED;
816 }else if( n==P4_KEYINFO ){
danielk19772dca4ac2008-01-03 11:50:29 +0000817 pOp->p4.p = (void*)zP4;
drh66a51672008-01-03 00:01:23 +0000818 pOp->p4type = P4_KEYINFO;
danielk1977595a5232009-07-24 17:58:53 +0000819 }else if( n==P4_VTAB ){
820 pOp->p4.p = (void*)zP4;
821 pOp->p4type = P4_VTAB;
822 sqlite3VtabLock((VTable *)zP4);
823 assert( ((VTable *)zP4)->db==p->db );
drh9a324642003-09-06 20:12:01 +0000824 }else if( n<0 ){
danielk19772dca4ac2008-01-03 11:50:29 +0000825 pOp->p4.p = (void*)zP4;
drh8df32842008-12-09 02:51:23 +0000826 pOp->p4type = (signed char)n;
drh9a324642003-09-06 20:12:01 +0000827 }else{
drhea678832008-12-10 19:26:22 +0000828 if( n==0 ) n = sqlite3Strlen30(zP4);
danielk19772dca4ac2008-01-03 11:50:29 +0000829 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
drh66a51672008-01-03 00:01:23 +0000830 pOp->p4type = P4_DYNAMIC;
drh9a324642003-09-06 20:12:01 +0000831 }
832}
833
drh2ec2fb22013-11-06 19:59:23 +0000834/*
835** Set the P4 on the most recently added opcode to the KeyInfo for the
836** index given.
837*/
838void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
839 Vdbe *v = pParse->pVdbe;
840 assert( v!=0 );
841 assert( pIdx!=0 );
842 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
843 P4_KEYINFO);
844}
845
drhc7379ce2013-10-30 02:28:23 +0000846#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drhad6d9462004-09-19 02:15:24 +0000847/*
mistachkind5578432012-08-25 10:01:29 +0000848** Change the comment on the most recently coded instruction. Or
drh16ee60f2008-06-20 18:13:25 +0000849** insert a No-op and add the comment to that new instruction. This
850** makes the code easier to read during debugging. None of this happens
851** in a production build.
drhad6d9462004-09-19 02:15:24 +0000852*/
drhb07028f2011-10-14 21:49:18 +0000853static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
danielk197701256832007-04-18 14:24:32 +0000854 assert( p->nOp>0 || p->aOp==0 );
drhd4e70eb2008-01-02 00:34:36 +0000855 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
danielk1977dba01372008-01-05 18:44:29 +0000856 if( p->nOp ){
drhb07028f2011-10-14 21:49:18 +0000857 assert( p->aOp );
858 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
859 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
860 }
861}
862void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
863 va_list ap;
864 if( p ){
danielk1977dba01372008-01-05 18:44:29 +0000865 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000866 vdbeVComment(p, zFormat, ap);
danielk1977dba01372008-01-05 18:44:29 +0000867 va_end(ap);
868 }
drhad6d9462004-09-19 02:15:24 +0000869}
drh16ee60f2008-06-20 18:13:25 +0000870void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
871 va_list ap;
drhb07028f2011-10-14 21:49:18 +0000872 if( p ){
873 sqlite3VdbeAddOp0(p, OP_Noop);
drh16ee60f2008-06-20 18:13:25 +0000874 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000875 vdbeVComment(p, zFormat, ap);
drh16ee60f2008-06-20 18:13:25 +0000876 va_end(ap);
877 }
878}
879#endif /* NDEBUG */
drhad6d9462004-09-19 02:15:24 +0000880
drh688852a2014-02-17 22:40:43 +0000881#ifdef SQLITE_VDBE_COVERAGE
882/*
883** Set the value if the iSrcLine field for the previously coded instruction.
884*/
885void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
886 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
887}
888#endif /* SQLITE_VDBE_COVERAGE */
889
drh9a324642003-09-06 20:12:01 +0000890/*
drh20411ea2009-05-29 19:00:12 +0000891** Return the opcode for a given address. If the address is -1, then
892** return the most recently inserted opcode.
893**
894** If a memory allocation error has occurred prior to the calling of this
895** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
drhf83dc1e2010-06-03 12:09:52 +0000896** is readable but not writable, though it is cast to a writable value.
897** The return of a dummy opcode allows the call to continue functioning
peter.d.reid60ec9142014-09-06 16:39:46 +0000898** after an OOM fault without having to check to see if the return from
drhf83dc1e2010-06-03 12:09:52 +0000899** this routine is a valid pointer. But because the dummy.opcode is 0,
900** dummy will never be written to. This is verified by code inspection and
901** by running with Valgrind.
drh9a324642003-09-06 20:12:01 +0000902*/
danielk19774adee202004-05-08 08:23:19 +0000903VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
drha0b75da2010-07-02 18:44:37 +0000904 /* C89 specifies that the constant "dummy" will be initialized to all
905 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
mistachkin0fe5f952011-09-14 18:19:08 +0000906 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
drh9a324642003-09-06 20:12:01 +0000907 assert( p->magic==VDBE_MAGIC_INIT );
drh37b89a02009-06-19 00:33:31 +0000908 if( addr<0 ){
drh37b89a02009-06-19 00:33:31 +0000909 addr = p->nOp - 1;
910 }
drh17435752007-08-16 04:30:38 +0000911 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +0000912 if( p->db->mallocFailed ){
drhf83dc1e2010-06-03 12:09:52 +0000913 return (VdbeOp*)&dummy;
drh20411ea2009-05-29 19:00:12 +0000914 }else{
915 return &p->aOp[addr];
916 }
drh9a324642003-09-06 20:12:01 +0000917}
918
drhc7379ce2013-10-30 02:28:23 +0000919#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
drh81316f82013-10-29 20:40:47 +0000920/*
drhf63552b2013-10-30 00:25:03 +0000921** Return an integer value for one of the parameters to the opcode pOp
922** determined by character c.
923*/
924static int translateP(char c, const Op *pOp){
925 if( c=='1' ) return pOp->p1;
926 if( c=='2' ) return pOp->p2;
927 if( c=='3' ) return pOp->p3;
928 if( c=='4' ) return pOp->p4.i;
929 return pOp->p5;
930}
931
drh81316f82013-10-29 20:40:47 +0000932/*
drh4eded602013-12-20 15:59:20 +0000933** Compute a string for the "comment" field of a VDBE opcode listing.
934**
935** The Synopsis: field in comments in the vdbe.c source file gets converted
936** to an extra string that is appended to the sqlite3OpcodeName(). In the
937** absence of other comments, this synopsis becomes the comment on the opcode.
938** Some translation occurs:
939**
940** "PX" -> "r[X]"
941** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
942** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
943** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
drh81316f82013-10-29 20:40:47 +0000944*/
drhf63552b2013-10-30 00:25:03 +0000945static int displayComment(
946 const Op *pOp, /* The opcode to be commented */
947 const char *zP4, /* Previously obtained value for P4 */
948 char *zTemp, /* Write result here */
949 int nTemp /* Space available in zTemp[] */
950){
drh81316f82013-10-29 20:40:47 +0000951 const char *zOpName;
952 const char *zSynopsis;
953 int nOpName;
954 int ii, jj;
955 zOpName = sqlite3OpcodeName(pOp->opcode);
956 nOpName = sqlite3Strlen30(zOpName);
957 if( zOpName[nOpName+1] ){
958 int seenCom = 0;
drhf63552b2013-10-30 00:25:03 +0000959 char c;
drh81316f82013-10-29 20:40:47 +0000960 zSynopsis = zOpName += nOpName + 1;
drhf63552b2013-10-30 00:25:03 +0000961 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
962 if( c=='P' ){
963 c = zSynopsis[++ii];
964 if( c=='4' ){
965 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
966 }else if( c=='X' ){
967 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
968 seenCom = 1;
drh81316f82013-10-29 20:40:47 +0000969 }else{
drhf63552b2013-10-30 00:25:03 +0000970 int v1 = translateP(c, pOp);
971 int v2;
972 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
973 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
974 ii += 3;
975 jj += sqlite3Strlen30(zTemp+jj);
976 v2 = translateP(zSynopsis[ii], pOp);
drh4eded602013-12-20 15:59:20 +0000977 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
978 ii += 2;
979 v2++;
980 }
981 if( v2>1 ){
982 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
983 }
drhf63552b2013-10-30 00:25:03 +0000984 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
985 ii += 4;
986 }
drh81316f82013-10-29 20:40:47 +0000987 }
988 jj += sqlite3Strlen30(zTemp+jj);
989 }else{
drhf63552b2013-10-30 00:25:03 +0000990 zTemp[jj++] = c;
drh81316f82013-10-29 20:40:47 +0000991 }
992 }
993 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
994 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
995 jj += sqlite3Strlen30(zTemp+jj);
996 }
997 if( jj<nTemp ) zTemp[jj] = 0;
998 }else if( pOp->zComment ){
999 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1000 jj = sqlite3Strlen30(zTemp);
1001 }else{
1002 zTemp[0] = 0;
1003 jj = 0;
1004 }
1005 return jj;
1006}
1007#endif /* SQLITE_DEBUG */
1008
1009
drhb7f91642004-10-31 02:22:47 +00001010#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
1011 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001012/*
drh66a51672008-01-03 00:01:23 +00001013** Compute a string that describes the P4 parameter for an opcode.
drhd3d39e92004-05-20 22:16:29 +00001014** Use zTemp for any required temporary buffer space.
1015*/
drh66a51672008-01-03 00:01:23 +00001016static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1017 char *zP4 = zTemp;
drhd3d39e92004-05-20 22:16:29 +00001018 assert( nTemp>=20 );
drh66a51672008-01-03 00:01:23 +00001019 switch( pOp->p4type ){
1020 case P4_KEYINFO: {
drhd3d39e92004-05-20 22:16:29 +00001021 int i, j;
danielk19772dca4ac2008-01-03 11:50:29 +00001022 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
drhe1a022e2012-09-17 17:16:53 +00001023 assert( pKeyInfo->aSortOrder!=0 );
drh5b843aa2013-10-30 13:46:01 +00001024 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
drhea678832008-12-10 19:26:22 +00001025 i = sqlite3Strlen30(zTemp);
drhd3d39e92004-05-20 22:16:29 +00001026 for(j=0; j<pKeyInfo->nField; j++){
1027 CollSeq *pColl = pKeyInfo->aColl[j];
drh261d8a52012-12-08 21:36:26 +00001028 const char *zColl = pColl ? pColl->zName : "nil";
1029 int n = sqlite3Strlen30(zColl);
drh5b843aa2013-10-30 13:46:01 +00001030 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
1031 zColl = "B";
1032 n = 1;
1033 }
drh261d8a52012-12-08 21:36:26 +00001034 if( i+n>nTemp-6 ){
1035 memcpy(&zTemp[i],",...",4);
1036 break;
drhd3d39e92004-05-20 22:16:29 +00001037 }
drh261d8a52012-12-08 21:36:26 +00001038 zTemp[i++] = ',';
1039 if( pKeyInfo->aSortOrder[j] ){
1040 zTemp[i++] = '-';
1041 }
1042 memcpy(&zTemp[i], zColl, n+1);
1043 i += n;
drhd3d39e92004-05-20 22:16:29 +00001044 }
1045 zTemp[i++] = ')';
1046 zTemp[i] = 0;
1047 assert( i<nTemp );
drhd3d39e92004-05-20 22:16:29 +00001048 break;
1049 }
drh66a51672008-01-03 00:01:23 +00001050 case P4_COLLSEQ: {
danielk19772dca4ac2008-01-03 11:50:29 +00001051 CollSeq *pColl = pOp->p4.pColl;
drh5e6790c2013-11-12 20:18:14 +00001052 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
drhd3d39e92004-05-20 22:16:29 +00001053 break;
1054 }
drh66a51672008-01-03 00:01:23 +00001055 case P4_FUNCDEF: {
danielk19772dca4ac2008-01-03 11:50:29 +00001056 FuncDef *pDef = pOp->p4.pFunc;
drha967e882006-06-13 01:04:52 +00001057 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
drhf9b596e2004-05-26 16:54:42 +00001058 break;
1059 }
drh66a51672008-01-03 00:01:23 +00001060 case P4_INT64: {
danielk19772dca4ac2008-01-03 11:50:29 +00001061 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
drhd4e70eb2008-01-02 00:34:36 +00001062 break;
1063 }
drh66a51672008-01-03 00:01:23 +00001064 case P4_INT32: {
1065 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
drh598f1342007-10-23 15:39:45 +00001066 break;
1067 }
drh66a51672008-01-03 00:01:23 +00001068 case P4_REAL: {
danielk19772dca4ac2008-01-03 11:50:29 +00001069 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
drhd4e70eb2008-01-02 00:34:36 +00001070 break;
1071 }
drh66a51672008-01-03 00:01:23 +00001072 case P4_MEM: {
danielk19772dca4ac2008-01-03 11:50:29 +00001073 Mem *pMem = pOp->p4.pMem;
drhd4e70eb2008-01-02 00:34:36 +00001074 if( pMem->flags & MEM_Str ){
drh66a51672008-01-03 00:01:23 +00001075 zP4 = pMem->z;
drhd4e70eb2008-01-02 00:34:36 +00001076 }else if( pMem->flags & MEM_Int ){
1077 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
1078 }else if( pMem->flags & MEM_Real ){
drh74eaba42014-09-18 17:52:15 +00001079 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
drhb8475df2011-12-09 16:21:19 +00001080 }else if( pMem->flags & MEM_Null ){
1081 sqlite3_snprintf(nTemp, zTemp, "NULL");
drh56016892009-08-25 14:24:04 +00001082 }else{
1083 assert( pMem->flags & MEM_Blob );
1084 zP4 = "(blob)";
drhd4e70eb2008-01-02 00:34:36 +00001085 }
drh598f1342007-10-23 15:39:45 +00001086 break;
1087 }
drha967e882006-06-13 01:04:52 +00001088#ifndef SQLITE_OMIT_VIRTUALTABLE
drh66a51672008-01-03 00:01:23 +00001089 case P4_VTAB: {
danielk1977595a5232009-07-24 17:58:53 +00001090 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
drh19146192006-06-26 19:10:32 +00001091 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
drha967e882006-06-13 01:04:52 +00001092 break;
1093 }
1094#endif
drh0acb7e42008-06-25 00:12:41 +00001095 case P4_INTARRAY: {
1096 sqlite3_snprintf(nTemp, zTemp, "intarray");
1097 break;
1098 }
dan165921a2009-08-28 18:53:45 +00001099 case P4_SUBPROGRAM: {
1100 sqlite3_snprintf(nTemp, zTemp, "program");
1101 break;
1102 }
drh4a6f3aa2011-08-28 00:19:26 +00001103 case P4_ADVANCE: {
1104 zTemp[0] = 0;
1105 break;
1106 }
drhd3d39e92004-05-20 22:16:29 +00001107 default: {
danielk19772dca4ac2008-01-03 11:50:29 +00001108 zP4 = pOp->p4.z;
drh949f9cd2008-01-12 21:35:57 +00001109 if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +00001110 zP4 = zTemp;
drhd4e70eb2008-01-02 00:34:36 +00001111 zTemp[0] = 0;
drhd3d39e92004-05-20 22:16:29 +00001112 }
1113 }
1114 }
drh66a51672008-01-03 00:01:23 +00001115 assert( zP4!=0 );
drh66a51672008-01-03 00:01:23 +00001116 return zP4;
drhd3d39e92004-05-20 22:16:29 +00001117}
drhb7f91642004-10-31 02:22:47 +00001118#endif
drhd3d39e92004-05-20 22:16:29 +00001119
drh900b31e2007-08-28 02:27:51 +00001120/*
drhd0679ed2007-08-28 22:24:34 +00001121** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
drh3ebaee92010-05-06 21:37:22 +00001122**
drhbdaec522011-04-04 00:14:43 +00001123** The prepared statements need to know in advance the complete set of
drhe4c88c02012-01-04 12:57:45 +00001124** attached databases that will be use. A mask of these databases
1125** is maintained in p->btreeMask. The p->lockMask value is the subset of
1126** p->btreeMask of databases that will require a lock.
drh900b31e2007-08-28 02:27:51 +00001127*/
drhfb982642007-08-30 01:19:59 +00001128void sqlite3VdbeUsesBtree(Vdbe *p, int i){
drhfcd71b62011-04-05 22:08:24 +00001129 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
danielk197700e13612008-11-17 19:18:54 +00001130 assert( i<(int)sizeof(p->btreeMask)*8 );
drha7ab6d82014-07-21 15:44:39 +00001131 DbMaskSet(p->btreeMask, i);
drhdc5b0472011-04-06 22:05:53 +00001132 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
drha7ab6d82014-07-21 15:44:39 +00001133 DbMaskSet(p->lockMask, i);
drhdc5b0472011-04-06 22:05:53 +00001134 }
drh900b31e2007-08-28 02:27:51 +00001135}
1136
drhe54e0512011-04-05 17:31:56 +00001137#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001138/*
1139** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1140** this routine obtains the mutex associated with each BtShared structure
1141** that may be accessed by the VM passed as an argument. In doing so it also
1142** sets the BtShared.db member of each of the BtShared structures, ensuring
1143** that the correct busy-handler callback is invoked if required.
1144**
1145** If SQLite is not threadsafe but does support shared-cache mode, then
1146** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1147** of all of BtShared structures accessible via the database handle
1148** associated with the VM.
1149**
1150** If SQLite is not threadsafe and does not support shared-cache mode, this
1151** function is a no-op.
1152**
1153** The p->btreeMask field is a bitmask of all btrees that the prepared
1154** statement p will ever use. Let N be the number of bits in p->btreeMask
1155** corresponding to btrees that use shared cache. Then the runtime of
1156** this routine is N*N. But as N is rarely more than 1, this should not
1157** be a problem.
1158*/
1159void sqlite3VdbeEnter(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001160 int i;
drhdc5b0472011-04-06 22:05:53 +00001161 sqlite3 *db;
1162 Db *aDb;
1163 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001164 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001165 db = p->db;
1166 aDb = db->aDb;
1167 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001168 for(i=0; i<nDb; i++){
1169 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001170 sqlite3BtreeEnter(aDb[i].pBt);
1171 }
1172 }
drhbdaec522011-04-04 00:14:43 +00001173}
drhe54e0512011-04-05 17:31:56 +00001174#endif
drhbdaec522011-04-04 00:14:43 +00001175
drhe54e0512011-04-05 17:31:56 +00001176#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001177/*
1178** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1179*/
1180void sqlite3VdbeLeave(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001181 int i;
drhdc5b0472011-04-06 22:05:53 +00001182 sqlite3 *db;
1183 Db *aDb;
1184 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001185 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001186 db = p->db;
1187 aDb = db->aDb;
1188 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001189 for(i=0; i<nDb; i++){
1190 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001191 sqlite3BtreeLeave(aDb[i].pBt);
1192 }
1193 }
drhbdaec522011-04-04 00:14:43 +00001194}
drhbdaec522011-04-04 00:14:43 +00001195#endif
drhd3d39e92004-05-20 22:16:29 +00001196
danielk19778b60e0f2005-01-12 09:10:39 +00001197#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001198/*
1199** Print a single opcode. This routine is used for debugging only.
1200*/
danielk19774adee202004-05-08 08:23:19 +00001201void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
drh66a51672008-01-03 00:01:23 +00001202 char *zP4;
drhd3d39e92004-05-20 22:16:29 +00001203 char zPtr[50];
drh81316f82013-10-29 20:40:47 +00001204 char zCom[100];
drh26198bb2013-10-31 11:15:09 +00001205 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
drh9a324642003-09-06 20:12:01 +00001206 if( pOut==0 ) pOut = stdout;
drh66a51672008-01-03 00:01:23 +00001207 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
drhc7379ce2013-10-30 02:28:23 +00001208#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001209 displayComment(pOp, zP4, zCom, sizeof(zCom));
1210#else
drh2926f962014-02-17 01:13:28 +00001211 zCom[0] = 0;
drh81316f82013-10-29 20:40:47 +00001212#endif
drh4eded602013-12-20 15:59:20 +00001213 /* NB: The sqlite3OpcodeName() function is implemented by code created
1214 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1215 ** information from the vdbe.c source text */
danielk197711641c12008-01-03 08:18:30 +00001216 fprintf(pOut, zFormat1, pc,
drh1db639c2008-01-17 02:36:28 +00001217 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
drh81316f82013-10-29 20:40:47 +00001218 zCom
drh1db639c2008-01-17 02:36:28 +00001219 );
drh9a324642003-09-06 20:12:01 +00001220 fflush(pOut);
1221}
1222#endif
1223
1224/*
drh76ff3a02004-09-24 22:32:30 +00001225** Release an array of N Mem elements
1226*/
drhc890fec2008-08-01 20:10:08 +00001227static void releaseMemArray(Mem *p, int N){
danielk1977a7a8e142008-02-13 18:25:27 +00001228 if( p && N ){
danielk1977e972e032008-09-19 18:32:26 +00001229 Mem *pEnd;
danielk1977a7a8e142008-02-13 18:25:27 +00001230 sqlite3 *db = p->db;
drh8df32842008-12-09 02:51:23 +00001231 u8 malloc_failed = db->mallocFailed;
dand46def72010-07-24 11:28:28 +00001232 if( db->pnBytesFreed ){
1233 for(pEnd=&p[N]; p<pEnd; p++){
drh17bcb102014-09-18 21:25:33 +00001234 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
dand46def72010-07-24 11:28:28 +00001235 }
drhc176c272010-07-26 13:57:59 +00001236 return;
1237 }
danielk1977e972e032008-09-19 18:32:26 +00001238 for(pEnd=&p[N]; p<pEnd; p++){
1239 assert( (&p[1])==pEnd || p[0].db==p[1].db );
drh75fd0542014-03-01 16:24:44 +00001240 assert( sqlite3VdbeCheckMemInvariants(p) );
danielk1977e972e032008-09-19 18:32:26 +00001241
1242 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1243 ** that takes advantage of the fact that the memory cell value is
1244 ** being set to NULL after releasing any dynamic resources.
1245 **
1246 ** The justification for duplicating code is that according to
1247 ** callgrind, this causes a certain test case to hit the CPU 4.7
1248 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1249 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1250 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1251 ** with no indexes using a single prepared INSERT statement, bind()
1252 ** and reset(). Inserts are grouped into a transaction.
1253 */
drhb6e8fd12014-03-06 01:56:33 +00001254 testcase( p->flags & MEM_Agg );
1255 testcase( p->flags & MEM_Dyn );
1256 testcase( p->flags & MEM_Frame );
1257 testcase( p->flags & MEM_RowSet );
dan165921a2009-08-28 18:53:45 +00001258 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
danielk1977e972e032008-09-19 18:32:26 +00001259 sqlite3VdbeMemRelease(p);
drh17bcb102014-09-18 21:25:33 +00001260 }else if( p->szMalloc ){
danielk1977e972e032008-09-19 18:32:26 +00001261 sqlite3DbFree(db, p->zMalloc);
drh17bcb102014-09-18 21:25:33 +00001262 p->szMalloc = 0;
danielk1977e972e032008-09-19 18:32:26 +00001263 }
1264
drha5750cf2014-02-07 13:20:31 +00001265 p->flags = MEM_Undefined;
drh76ff3a02004-09-24 22:32:30 +00001266 }
danielk1977a7a8e142008-02-13 18:25:27 +00001267 db->mallocFailed = malloc_failed;
drh76ff3a02004-09-24 22:32:30 +00001268 }
1269}
1270
dan65a7cd12009-09-01 12:16:01 +00001271/*
1272** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1273** allocated by the OP_Program opcode in sqlite3VdbeExec().
1274*/
dan165921a2009-08-28 18:53:45 +00001275void sqlite3VdbeFrameDelete(VdbeFrame *p){
1276 int i;
1277 Mem *aMem = VdbeFrameMem(p);
1278 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1279 for(i=0; i<p->nChildCsr; i++){
1280 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1281 }
1282 releaseMemArray(aMem, p->nChildMem);
1283 sqlite3DbFree(p->v->db, p);
1284}
1285
drhb7f91642004-10-31 02:22:47 +00001286#ifndef SQLITE_OMIT_EXPLAIN
drh76ff3a02004-09-24 22:32:30 +00001287/*
drh9a324642003-09-06 20:12:01 +00001288** Give a listing of the program in the virtual machine.
1289**
danielk19774adee202004-05-08 08:23:19 +00001290** The interface is the same as sqlite3VdbeExec(). But instead of
drh9a324642003-09-06 20:12:01 +00001291** running the code, it invokes the callback once for each instruction.
1292** This feature is used to implement "EXPLAIN".
drh9cbf3422008-01-17 16:22:13 +00001293**
1294** When p->explain==1, each instruction is listed. When
1295** p->explain==2, only OP_Explain instructions are listed and these
1296** are shown in a different format. p->explain==2 is used to implement
1297** EXPLAIN QUERY PLAN.
drh5cfa5842009-12-31 20:35:08 +00001298**
1299** When p->explain==1, first the main program is listed, then each of
1300** the trigger subprograms are listed one by one.
drh9a324642003-09-06 20:12:01 +00001301*/
danielk19774adee202004-05-08 08:23:19 +00001302int sqlite3VdbeList(
drh9a324642003-09-06 20:12:01 +00001303 Vdbe *p /* The VDBE */
1304){
drh5cfa5842009-12-31 20:35:08 +00001305 int nRow; /* Stop when row count reaches this */
dan165921a2009-08-28 18:53:45 +00001306 int nSub = 0; /* Number of sub-vdbes seen so far */
1307 SubProgram **apSub = 0; /* Array of sub-vdbes */
drh5cfa5842009-12-31 20:35:08 +00001308 Mem *pSub = 0; /* Memory cell hold array of subprogs */
1309 sqlite3 *db = p->db; /* The database connection */
1310 int i; /* Loop counter */
1311 int rc = SQLITE_OK; /* Return code */
drh9734e6e2011-10-07 18:24:25 +00001312 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
drh9a324642003-09-06 20:12:01 +00001313
drh9a324642003-09-06 20:12:01 +00001314 assert( p->explain );
drh5f82e3c2009-07-06 00:44:08 +00001315 assert( p->magic==VDBE_MAGIC_RUN );
danielk19776c359f02008-11-21 16:58:03 +00001316 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
danielk197718f41892004-05-22 07:27:46 +00001317
drh9cbf3422008-01-17 16:22:13 +00001318 /* Even though this opcode does not use dynamic strings for
1319 ** the result, result columns may become dynamic if the user calls
drh4f26d6c2004-05-26 23:25:30 +00001320 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
danielk197718f41892004-05-22 07:27:46 +00001321 */
dan165921a2009-08-28 18:53:45 +00001322 releaseMemArray(pMem, 8);
drh9734e6e2011-10-07 18:24:25 +00001323 p->pResultSet = 0;
danielk197718f41892004-05-22 07:27:46 +00001324
danielk19776c359f02008-11-21 16:58:03 +00001325 if( p->rc==SQLITE_NOMEM ){
1326 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1327 ** sqlite3_column_text16() failed. */
1328 db->mallocFailed = 1;
1329 return SQLITE_ERROR;
1330 }
1331
drh5cfa5842009-12-31 20:35:08 +00001332 /* When the number of output rows reaches nRow, that means the
1333 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1334 ** nRow is the sum of the number of rows in the main program, plus
1335 ** the sum of the number of rows in all trigger subprograms encountered
1336 ** so far. The nRow value will increase as new trigger subprograms are
1337 ** encountered, but p->pc will eventually catch up to nRow.
1338 */
dan165921a2009-08-28 18:53:45 +00001339 nRow = p->nOp;
1340 if( p->explain==1 ){
drh5cfa5842009-12-31 20:35:08 +00001341 /* The first 8 memory cells are used for the result set. So we will
1342 ** commandeer the 9th cell to use as storage for an array of pointers
1343 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1344 ** cells. */
1345 assert( p->nMem>9 );
dan165921a2009-08-28 18:53:45 +00001346 pSub = &p->aMem[9];
1347 if( pSub->flags&MEM_Blob ){
drh5cfa5842009-12-31 20:35:08 +00001348 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1349 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
dan165921a2009-08-28 18:53:45 +00001350 nSub = pSub->n/sizeof(Vdbe*);
1351 apSub = (SubProgram **)pSub->z;
1352 }
1353 for(i=0; i<nSub; i++){
1354 nRow += apSub[i]->nOp;
1355 }
1356 }
1357
drhecc92422005-09-10 16:46:12 +00001358 do{
1359 i = p->pc++;
dan165921a2009-08-28 18:53:45 +00001360 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1361 if( i>=nRow ){
drh826fb5a2004-02-14 23:59:57 +00001362 p->rc = SQLITE_OK;
1363 rc = SQLITE_DONE;
drh881feaa2006-07-26 01:39:30 +00001364 }else if( db->u1.isInterrupted ){
drhc5cdca62005-01-11 16:54:14 +00001365 p->rc = SQLITE_INTERRUPT;
drh826fb5a2004-02-14 23:59:57 +00001366 rc = SQLITE_ERROR;
drhf089aa42008-07-08 19:34:06 +00001367 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
drh826fb5a2004-02-14 23:59:57 +00001368 }else{
drh81316f82013-10-29 20:40:47 +00001369 char *zP4;
dan165921a2009-08-28 18:53:45 +00001370 Op *pOp;
1371 if( i<p->nOp ){
drh5cfa5842009-12-31 20:35:08 +00001372 /* The output line number is small enough that we are still in the
1373 ** main program. */
dan165921a2009-08-28 18:53:45 +00001374 pOp = &p->aOp[i];
1375 }else{
drh5cfa5842009-12-31 20:35:08 +00001376 /* We are currently listing subprograms. Figure out which one and
1377 ** pick up the appropriate opcode. */
dan165921a2009-08-28 18:53:45 +00001378 int j;
1379 i -= p->nOp;
1380 for(j=0; i>=apSub[j]->nOp; j++){
1381 i -= apSub[j]->nOp;
1382 }
1383 pOp = &apSub[j]->aOp[i];
1384 }
danielk19770d78bae2008-01-03 07:09:48 +00001385 if( p->explain==1 ){
1386 pMem->flags = MEM_Int;
danielk19770d78bae2008-01-03 07:09:48 +00001387 pMem->u.i = i; /* Program counter */
1388 pMem++;
1389
1390 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001391 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
danielk19770d78bae2008-01-03 07:09:48 +00001392 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001393 pMem->n = sqlite3Strlen30(pMem->z);
danielk19770d78bae2008-01-03 07:09:48 +00001394 pMem->enc = SQLITE_UTF8;
1395 pMem++;
dan165921a2009-08-28 18:53:45 +00001396
drh5cfa5842009-12-31 20:35:08 +00001397 /* When an OP_Program opcode is encounter (the only opcode that has
1398 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1399 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1400 ** has not already been seen.
1401 */
dan165921a2009-08-28 18:53:45 +00001402 if( pOp->p4type==P4_SUBPROGRAM ){
1403 int nByte = (nSub+1)*sizeof(SubProgram*);
1404 int j;
1405 for(j=0; j<nSub; j++){
1406 if( apSub[j]==pOp->p4.pProgram ) break;
1407 }
dan2b9ee772012-03-31 09:59:44 +00001408 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
dan165921a2009-08-28 18:53:45 +00001409 apSub = (SubProgram **)pSub->z;
1410 apSub[nSub++] = pOp->p4.pProgram;
1411 pSub->flags |= MEM_Blob;
1412 pSub->n = nSub*sizeof(SubProgram*);
1413 }
1414 }
danielk19770d78bae2008-01-03 07:09:48 +00001415 }
drheb2e1762004-05-27 01:53:56 +00001416
1417 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001418 pMem->u.i = pOp->p1; /* P1 */
drheb2e1762004-05-27 01:53:56 +00001419 pMem++;
1420
1421 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001422 pMem->u.i = pOp->p2; /* P2 */
drheb2e1762004-05-27 01:53:56 +00001423 pMem++;
1424
dan2ce22452010-11-08 19:01:16 +00001425 pMem->flags = MEM_Int;
1426 pMem->u.i = pOp->p3; /* P3 */
dan2ce22452010-11-08 19:01:16 +00001427 pMem++;
danielk19770d78bae2008-01-03 07:09:48 +00001428
danielk1977a7a8e142008-02-13 18:25:27 +00001429 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
danielk1977357864e2009-03-25 15:43:08 +00001430 assert( p->db->mallocFailed );
1431 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001432 }
drhc91b2fd2014-03-01 18:13:23 +00001433 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001434 zP4 = displayP4(pOp, pMem->z, 32);
1435 if( zP4!=pMem->z ){
1436 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
danielk1977a7a8e142008-02-13 18:25:27 +00001437 }else{
1438 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001439 pMem->n = sqlite3Strlen30(pMem->z);
danielk1977a7a8e142008-02-13 18:25:27 +00001440 pMem->enc = SQLITE_UTF8;
1441 }
danielk19770d78bae2008-01-03 07:09:48 +00001442 pMem++;
drheb2e1762004-05-27 01:53:56 +00001443
danielk19770d78bae2008-01-03 07:09:48 +00001444 if( p->explain==1 ){
drh85e5f0d2008-02-19 18:28:13 +00001445 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
danielk1977357864e2009-03-25 15:43:08 +00001446 assert( p->db->mallocFailed );
1447 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001448 }
drhc91b2fd2014-03-01 18:13:23 +00001449 pMem->flags = MEM_Str|MEM_Term;
drh85e5f0d2008-02-19 18:28:13 +00001450 pMem->n = 2;
1451 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
danielk19770d78bae2008-01-03 07:09:48 +00001452 pMem->enc = SQLITE_UTF8;
1453 pMem++;
1454
drhc7379ce2013-10-30 02:28:23 +00001455#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001456 if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
1457 assert( p->db->mallocFailed );
1458 return SQLITE_ERROR;
drh52391cb2008-02-14 23:44:13 +00001459 }
drhc91b2fd2014-03-01 18:13:23 +00001460 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001461 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
drh81316f82013-10-29 20:40:47 +00001462 pMem->enc = SQLITE_UTF8;
1463#else
1464 pMem->flags = MEM_Null; /* Comment */
drh81316f82013-10-29 20:40:47 +00001465#endif
danielk19770d78bae2008-01-03 07:09:48 +00001466 }
1467
dan2ce22452010-11-08 19:01:16 +00001468 p->nResColumn = 8 - 4*(p->explain-1);
drh9734e6e2011-10-07 18:24:25 +00001469 p->pResultSet = &p->aMem[1];
drh826fb5a2004-02-14 23:59:57 +00001470 p->rc = SQLITE_OK;
1471 rc = SQLITE_ROW;
drh9a324642003-09-06 20:12:01 +00001472 }
drh826fb5a2004-02-14 23:59:57 +00001473 return rc;
drh9a324642003-09-06 20:12:01 +00001474}
drhb7f91642004-10-31 02:22:47 +00001475#endif /* SQLITE_OMIT_EXPLAIN */
drh9a324642003-09-06 20:12:01 +00001476
drh7c4ac0c2007-04-05 11:25:58 +00001477#ifdef SQLITE_DEBUG
drh9a324642003-09-06 20:12:01 +00001478/*
drh3f7d4e42004-07-24 14:35:58 +00001479** Print the SQL that was used to generate a VDBE program.
1480*/
1481void sqlite3VdbePrintSql(Vdbe *p){
drh84e55a82013-11-13 17:58:23 +00001482 const char *z = 0;
1483 if( p->zSql ){
1484 z = p->zSql;
1485 }else if( p->nOp>=1 ){
1486 const VdbeOp *pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001487 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh84e55a82013-11-13 17:58:23 +00001488 z = pOp->p4.z;
1489 while( sqlite3Isspace(*z) ) z++;
1490 }
drh3f7d4e42004-07-24 14:35:58 +00001491 }
drh84e55a82013-11-13 17:58:23 +00001492 if( z ) printf("SQL: [%s]\n", z);
drh3f7d4e42004-07-24 14:35:58 +00001493}
drh7c4ac0c2007-04-05 11:25:58 +00001494#endif
drh3f7d4e42004-07-24 14:35:58 +00001495
drh602c2372007-03-01 00:29:13 +00001496#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1497/*
1498** Print an IOTRACE message showing SQL content.
1499*/
1500void sqlite3VdbeIOTraceSql(Vdbe *p){
1501 int nOp = p->nOp;
1502 VdbeOp *pOp;
mlcreech3a00f902008-03-04 17:45:01 +00001503 if( sqlite3IoTrace==0 ) return;
drh602c2372007-03-01 00:29:13 +00001504 if( nOp<1 ) return;
drh949f9cd2008-01-12 21:35:57 +00001505 pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001506 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh602c2372007-03-01 00:29:13 +00001507 int i, j;
drh00a18e42007-08-13 11:10:34 +00001508 char z[1000];
drh949f9cd2008-01-12 21:35:57 +00001509 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
danielk197778ca0e72009-01-20 16:53:39 +00001510 for(i=0; sqlite3Isspace(z[i]); i++){}
drh602c2372007-03-01 00:29:13 +00001511 for(j=0; z[i]; i++){
danielk197778ca0e72009-01-20 16:53:39 +00001512 if( sqlite3Isspace(z[i]) ){
drh602c2372007-03-01 00:29:13 +00001513 if( z[i-1]!=' ' ){
1514 z[j++] = ' ';
1515 }
1516 }else{
1517 z[j++] = z[i];
1518 }
1519 }
1520 z[j] = 0;
mlcreech3a00f902008-03-04 17:45:01 +00001521 sqlite3IoTrace("SQL %s\n", z);
drh602c2372007-03-01 00:29:13 +00001522 }
1523}
1524#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1525
drhb2771ce2009-02-20 01:28:59 +00001526/*
drh4800b2e2009-12-08 15:35:22 +00001527** Allocate space from a fixed size buffer and return a pointer to
1528** that space. If insufficient space is available, return NULL.
1529**
1530** The pBuf parameter is the initial value of a pointer which will
1531** receive the new memory. pBuf is normally NULL. If pBuf is not
1532** NULL, it means that memory space has already been allocated and that
1533** this routine should not allocate any new memory. When pBuf is not
1534** NULL simply return pBuf. Only allocate new memory space when pBuf
1535** is NULL.
drhb2771ce2009-02-20 01:28:59 +00001536**
1537** nByte is the number of bytes of space needed.
1538**
drh19875c82009-12-08 19:58:19 +00001539** *ppFrom points to available space and pEnd points to the end of the
1540** available space. When space is allocated, *ppFrom is advanced past
1541** the end of the allocated space.
drhb2771ce2009-02-20 01:28:59 +00001542**
1543** *pnByte is a counter of the number of bytes of space that have failed
1544** to allocate. If there is insufficient space in *ppFrom to satisfy the
danielk1977d336e222009-02-20 10:58:41 +00001545** request, then increment *pnByte by the amount of the request.
drhb2771ce2009-02-20 01:28:59 +00001546*/
drh4800b2e2009-12-08 15:35:22 +00001547static void *allocSpace(
1548 void *pBuf, /* Where return pointer will be stored */
drhb2771ce2009-02-20 01:28:59 +00001549 int nByte, /* Number of bytes to allocate */
1550 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
danielk1977d336e222009-02-20 10:58:41 +00001551 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
drhb2771ce2009-02-20 01:28:59 +00001552 int *pnByte /* If allocation cannot be made, increment *pnByte */
1553){
drhea598cb2009-04-05 12:22:08 +00001554 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
drh4800b2e2009-12-08 15:35:22 +00001555 if( pBuf ) return pBuf;
1556 nByte = ROUND8(nByte);
1557 if( &(*ppFrom)[nByte] <= pEnd ){
1558 pBuf = (void*)*ppFrom;
1559 *ppFrom += nByte;
1560 }else{
1561 *pnByte += nByte;
drhb2771ce2009-02-20 01:28:59 +00001562 }
drh4800b2e2009-12-08 15:35:22 +00001563 return pBuf;
drhb2771ce2009-02-20 01:28:59 +00001564}
drh602c2372007-03-01 00:29:13 +00001565
drh3f7d4e42004-07-24 14:35:58 +00001566/*
drh124c0b42011-06-01 18:15:55 +00001567** Rewind the VDBE back to the beginning in preparation for
1568** running it.
drh9a324642003-09-06 20:12:01 +00001569*/
drh124c0b42011-06-01 18:15:55 +00001570void sqlite3VdbeRewind(Vdbe *p){
1571#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1572 int i;
1573#endif
drh9a324642003-09-06 20:12:01 +00001574 assert( p!=0 );
drh9a324642003-09-06 20:12:01 +00001575 assert( p->magic==VDBE_MAGIC_INIT );
1576
drhc16a03b2004-09-15 13:38:10 +00001577 /* There should be at least one opcode.
drh9a324642003-09-06 20:12:01 +00001578 */
drhc16a03b2004-09-15 13:38:10 +00001579 assert( p->nOp>0 );
drh9a324642003-09-06 20:12:01 +00001580
danielk197700e13612008-11-17 19:18:54 +00001581 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
danielk1977634f2982005-03-28 08:44:07 +00001582 p->magic = VDBE_MAGIC_RUN;
1583
drh124c0b42011-06-01 18:15:55 +00001584#ifdef SQLITE_DEBUG
1585 for(i=1; i<p->nMem; i++){
1586 assert( p->aMem[i].db==p->db );
1587 }
1588#endif
1589 p->pc = -1;
1590 p->rc = SQLITE_OK;
1591 p->errorAction = OE_Abort;
1592 p->magic = VDBE_MAGIC_RUN;
1593 p->nChange = 0;
1594 p->cacheCtr = 1;
1595 p->minWriteFileFormat = 255;
1596 p->iStatement = 0;
1597 p->nFkConstraint = 0;
1598#ifdef VDBE_PROFILE
1599 for(i=0; i<p->nOp; i++){
1600 p->aOp[i].cnt = 0;
1601 p->aOp[i].cycles = 0;
1602 }
1603#endif
1604}
1605
1606/*
1607** Prepare a virtual machine for execution for the first time after
1608** creating the virtual machine. This involves things such
1609** as allocating stack space and initializing the program counter.
1610** After the VDBE has be prepped, it can be executed by one or more
1611** calls to sqlite3VdbeExec().
1612**
peter.d.reid60ec9142014-09-06 16:39:46 +00001613** This function may be called exactly once on each virtual machine.
drh124c0b42011-06-01 18:15:55 +00001614** After this routine is called the VM has been "packaged" and is ready
peter.d.reid60ec9142014-09-06 16:39:46 +00001615** to run. After this routine is called, further calls to
drh124c0b42011-06-01 18:15:55 +00001616** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1617** the Vdbe from the Parse object that helped generate it so that the
1618** the Vdbe becomes an independent entity and the Parse object can be
1619** destroyed.
1620**
1621** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1622** to its initial state after it has been run.
1623*/
1624void sqlite3VdbeMakeReady(
1625 Vdbe *p, /* The VDBE */
1626 Parse *pParse /* Parsing context */
1627){
1628 sqlite3 *db; /* The database connection */
1629 int nVar; /* Number of parameters */
1630 int nMem; /* Number of VM memory registers */
1631 int nCursor; /* Number of cursors required */
1632 int nArg; /* Number of arguments in subprograms */
dan1d8cb212011-12-09 13:24:16 +00001633 int nOnce; /* Number of OP_Once instructions */
drh124c0b42011-06-01 18:15:55 +00001634 int n; /* Loop counter */
1635 u8 *zCsr; /* Memory available for allocation */
1636 u8 *zEnd; /* First byte past allocated memory */
1637 int nByte; /* How much extra memory is needed */
1638
1639 assert( p!=0 );
1640 assert( p->nOp>0 );
1641 assert( pParse!=0 );
1642 assert( p->magic==VDBE_MAGIC_INIT );
drh73d5b8f2013-12-23 19:09:07 +00001643 assert( pParse==p->pParse );
drh124c0b42011-06-01 18:15:55 +00001644 db = p->db;
1645 assert( db->mallocFailed==0 );
1646 nVar = pParse->nVar;
1647 nMem = pParse->nMem;
1648 nCursor = pParse->nTab;
1649 nArg = pParse->nMaxArg;
dan1d8cb212011-12-09 13:24:16 +00001650 nOnce = pParse->nOnce;
drh20e226d2012-01-01 13:58:53 +00001651 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
drh124c0b42011-06-01 18:15:55 +00001652
danielk1977cd3e8f72008-03-25 09:47:35 +00001653 /* For each cursor required, also allocate a memory cell. Memory
1654 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1655 ** the vdbe program. Instead they are used to allocate space for
drhdfe88ec2008-11-03 20:55:06 +00001656 ** VdbeCursor/BtCursor structures. The blob of memory associated with
danielk1977cd3e8f72008-03-25 09:47:35 +00001657 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1658 ** stores the blob of memory associated with cursor 1, etc.
1659 **
1660 ** See also: allocateCursor().
1661 */
1662 nMem += nCursor;
1663
danielk19776ab3a2e2009-02-19 14:39:25 +00001664 /* Allocate space for memory registers, SQL variables, VDBE cursors and
drh124c0b42011-06-01 18:15:55 +00001665 ** an array to marshal SQL function arguments in.
drh9a324642003-09-06 20:12:01 +00001666 */
drh73d5b8f2013-12-23 19:09:07 +00001667 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
1668 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
drh19875c82009-12-08 19:58:19 +00001669
drh124c0b42011-06-01 18:15:55 +00001670 resolveP2Values(p, &nArg);
1671 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1672 if( pParse->explain && nMem<10 ){
1673 nMem = 10;
1674 }
1675 memset(zCsr, 0, zEnd-zCsr);
1676 zCsr += (zCsr - (u8*)0)&7;
1677 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
drhaab910c2011-06-27 00:01:22 +00001678 p->expired = 0;
drh124c0b42011-06-01 18:15:55 +00001679
1680 /* Memory for registers, parameters, cursor, etc, is allocated in two
1681 ** passes. On the first pass, we try to reuse unused space at the
1682 ** end of the opcode array. If we are unable to satisfy all memory
1683 ** requirements by reusing the opcode array tail, then the second
1684 ** pass will fill in the rest using a fresh allocation.
1685 **
1686 ** This two-pass approach that reuses as much memory as possible from
1687 ** the leftover space at the end of the opcode array can significantly
1688 ** reduce the amount of memory held by a prepared statement.
1689 */
1690 do {
1691 nByte = 0;
1692 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
1693 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
1694 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
1695 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
1696 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
1697 &zCsr, zEnd, &nByte);
drhb8475df2011-12-09 16:21:19 +00001698 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
drh124c0b42011-06-01 18:15:55 +00001699 if( nByte ){
1700 p->pFree = sqlite3DbMallocZero(db, nByte);
drh0f7eb612006-08-08 13:51:43 +00001701 }
drh124c0b42011-06-01 18:15:55 +00001702 zCsr = p->pFree;
1703 zEnd = &zCsr[nByte];
1704 }while( nByte && !db->mallocFailed );
drhb2771ce2009-02-20 01:28:59 +00001705
drhd2a56232013-01-28 19:00:20 +00001706 p->nCursor = nCursor;
dan1d8cb212011-12-09 13:24:16 +00001707 p->nOnceFlag = nOnce;
drh124c0b42011-06-01 18:15:55 +00001708 if( p->aVar ){
1709 p->nVar = (ynVar)nVar;
1710 for(n=0; n<nVar; n++){
1711 p->aVar[n].flags = MEM_Null;
1712 p->aVar[n].db = db;
danielk197754db47e2004-05-19 10:36:43 +00001713 }
drh82a48512003-09-06 22:45:20 +00001714 }
drh124c0b42011-06-01 18:15:55 +00001715 if( p->azVar ){
1716 p->nzVar = pParse->nzVar;
1717 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
1718 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
danielk1977b3bce662005-01-29 08:32:43 +00001719 }
drh124c0b42011-06-01 18:15:55 +00001720 if( p->aMem ){
1721 p->aMem--; /* aMem[] goes from 1..nMem */
1722 p->nMem = nMem; /* not from 0..nMem-1 */
1723 for(n=1; n<=nMem; n++){
drha5750cf2014-02-07 13:20:31 +00001724 p->aMem[n].flags = MEM_Undefined;
drh124c0b42011-06-01 18:15:55 +00001725 p->aMem[n].db = db;
drhcf64d8b2003-12-31 17:57:10 +00001726 }
drh9a324642003-09-06 20:12:01 +00001727 }
drh124c0b42011-06-01 18:15:55 +00001728 p->explain = pParse->explain;
1729 sqlite3VdbeRewind(p);
drh9a324642003-09-06 20:12:01 +00001730}
1731
drh9a324642003-09-06 20:12:01 +00001732/*
danielk1977cd3e8f72008-03-25 09:47:35 +00001733** Close a VDBE cursor and release all the resources that cursor
1734** happens to hold.
drh9a324642003-09-06 20:12:01 +00001735*/
drhdfe88ec2008-11-03 20:55:06 +00001736void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
drh4774b132004-06-12 20:12:51 +00001737 if( pCx==0 ){
1738 return;
1739 }
dana20fde62011-07-12 14:28:05 +00001740 sqlite3VdbeSorterClose(p->db, pCx);
drh9a324642003-09-06 20:12:01 +00001741 if( pCx->pBt ){
danielk19774adee202004-05-08 08:23:19 +00001742 sqlite3BtreeClose(pCx->pBt);
drh34004ce2008-07-11 16:15:17 +00001743 /* The pCx->pCursor will be close automatically, if it exists, by
1744 ** the call above. */
1745 }else if( pCx->pCursor ){
1746 sqlite3BtreeCloseCursor(pCx->pCursor);
drh9a324642003-09-06 20:12:01 +00001747 }
drh9eff6162006-06-12 21:59:13 +00001748#ifndef SQLITE_OMIT_VIRTUALTABLE
1749 if( pCx->pVtabCursor ){
1750 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
drh5cc10232013-11-21 01:04:02 +00001751 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
danielk1977be718892006-06-23 08:05:19 +00001752 p->inVtabMethod = 1;
drh9eff6162006-06-12 21:59:13 +00001753 pModule->xClose(pVtabCursor);
danielk1977be718892006-06-23 08:05:19 +00001754 p->inVtabMethod = 0;
drh9eff6162006-06-12 21:59:13 +00001755 }
1756#endif
drh9a324642003-09-06 20:12:01 +00001757}
1758
dan65a7cd12009-09-01 12:16:01 +00001759/*
1760** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1761** is used, for example, when a trigger sub-program is halted to restore
1762** control to the main program.
1763*/
dan165921a2009-08-28 18:53:45 +00001764int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
1765 Vdbe *v = pFrame->v;
dan1d8cb212011-12-09 13:24:16 +00001766 v->aOnceFlag = pFrame->aOnceFlag;
1767 v->nOnceFlag = pFrame->nOnceFlag;
dan165921a2009-08-28 18:53:45 +00001768 v->aOp = pFrame->aOp;
1769 v->nOp = pFrame->nOp;
1770 v->aMem = pFrame->aMem;
1771 v->nMem = pFrame->nMem;
1772 v->apCsr = pFrame->apCsr;
1773 v->nCursor = pFrame->nCursor;
dan76d462e2009-08-30 11:42:51 +00001774 v->db->lastRowid = pFrame->lastRowid;
1775 v->nChange = pFrame->nChange;
dan165921a2009-08-28 18:53:45 +00001776 return pFrame->pc;
1777}
1778
drh9a324642003-09-06 20:12:01 +00001779/*
drh5f82e3c2009-07-06 00:44:08 +00001780** Close all cursors.
dan165921a2009-08-28 18:53:45 +00001781**
1782** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1783** cell array. This is necessary as the memory cell array may contain
1784** pointers to VdbeFrame objects, which may in turn contain pointers to
1785** open cursors.
drh9a324642003-09-06 20:12:01 +00001786*/
drh5f82e3c2009-07-06 00:44:08 +00001787static void closeAllCursors(Vdbe *p){
dan165921a2009-08-28 18:53:45 +00001788 if( p->pFrame ){
drh23272752011-03-06 21:54:33 +00001789 VdbeFrame *pFrame;
dan165921a2009-08-28 18:53:45 +00001790 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
1791 sqlite3VdbeFrameRestore(pFrame);
1792 }
1793 p->pFrame = 0;
1794 p->nFrame = 0;
1795
dan523a0872009-08-31 05:23:32 +00001796 if( p->apCsr ){
1797 int i;
1798 for(i=0; i<p->nCursor; i++){
1799 VdbeCursor *pC = p->apCsr[i];
1800 if( pC ){
1801 sqlite3VdbeFreeCursor(p, pC);
1802 p->apCsr[i] = 0;
1803 }
danielk1977be718892006-06-23 08:05:19 +00001804 }
drh9a324642003-09-06 20:12:01 +00001805 }
dan523a0872009-08-31 05:23:32 +00001806 if( p->aMem ){
1807 releaseMemArray(&p->aMem[1], p->nMem);
1808 }
dan27106572010-12-01 08:04:47 +00001809 while( p->pDelFrame ){
1810 VdbeFrame *pDel = p->pDelFrame;
1811 p->pDelFrame = pDel->pParent;
1812 sqlite3VdbeFrameDelete(pDel);
1813 }
dan0c547792013-07-18 17:12:08 +00001814
1815 /* Delete any auxdata allocations made by the VM */
1816 sqlite3VdbeDeleteAuxData(p, -1, 0);
1817 assert( p->pAuxData==0 );
drh9a324642003-09-06 20:12:01 +00001818}
1819
1820/*
drh9a324642003-09-06 20:12:01 +00001821** Clean up the VM after execution.
1822**
1823** This routine will automatically close any cursors, lists, and/or
1824** sorters that were left open. It also deletes the values of
drh5a12e682004-05-19 11:24:25 +00001825** variables in the aVar[] array.
drh9a324642003-09-06 20:12:01 +00001826*/
drhc890fec2008-08-01 20:10:08 +00001827static void Cleanup(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00001828 sqlite3 *db = p->db;
dan165921a2009-08-28 18:53:45 +00001829
1830#ifdef SQLITE_DEBUG
1831 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1832 ** Vdbe.aMem[] arrays have already been cleaned up. */
1833 int i;
drhb8475df2011-12-09 16:21:19 +00001834 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
1835 if( p->aMem ){
drha5750cf2014-02-07 13:20:31 +00001836 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
drhb8475df2011-12-09 16:21:19 +00001837 }
dan165921a2009-08-28 18:53:45 +00001838#endif
1839
drh633e6d52008-07-28 19:34:53 +00001840 sqlite3DbFree(db, p->zErrMsg);
drh9a324642003-09-06 20:12:01 +00001841 p->zErrMsg = 0;
drhd4e70eb2008-01-02 00:34:36 +00001842 p->pResultSet = 0;
drh9a324642003-09-06 20:12:01 +00001843}
1844
1845/*
danielk197722322fd2004-05-25 23:35:17 +00001846** Set the number of result columns that will be returned by this SQL
1847** statement. This is now set at compile time, rather than during
1848** execution of the vdbe program so that sqlite3_column_count() can
1849** be called on an SQL statement before sqlite3_step().
1850*/
1851void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
drh76ff3a02004-09-24 22:32:30 +00001852 Mem *pColName;
1853 int n;
drh633e6d52008-07-28 19:34:53 +00001854 sqlite3 *db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001855
drhc890fec2008-08-01 20:10:08 +00001856 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
drh633e6d52008-07-28 19:34:53 +00001857 sqlite3DbFree(db, p->aColName);
danielk1977955de522006-02-10 02:27:42 +00001858 n = nResColumn*COLNAME_N;
shane36840fd2009-06-26 16:32:13 +00001859 p->nResColumn = (u16)nResColumn;
drh633e6d52008-07-28 19:34:53 +00001860 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
drh76ff3a02004-09-24 22:32:30 +00001861 if( p->aColName==0 ) return;
1862 while( n-- > 0 ){
drh4a50aac2007-08-23 02:47:53 +00001863 pColName->flags = MEM_Null;
drh153c62c2007-08-24 03:51:33 +00001864 pColName->db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001865 pColName++;
drh76ff3a02004-09-24 22:32:30 +00001866 }
danielk197722322fd2004-05-25 23:35:17 +00001867}
1868
1869/*
danielk19773cf86062004-05-26 10:11:05 +00001870** Set the name of the idx'th column to be returned by the SQL statement.
1871** zName must be a pointer to a nul terminated string.
1872**
1873** This call must be made after a call to sqlite3VdbeSetNumCols().
1874**
danielk197710fb7492008-10-31 10:53:22 +00001875** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1876** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1877** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
danielk19773cf86062004-05-26 10:11:05 +00001878*/
danielk197710fb7492008-10-31 10:53:22 +00001879int sqlite3VdbeSetColName(
1880 Vdbe *p, /* Vdbe being configured */
1881 int idx, /* Index of column zName applies to */
1882 int var, /* One of the COLNAME_* constants */
1883 const char *zName, /* Pointer to buffer containing name */
1884 void (*xDel)(void*) /* Memory management strategy for zName */
1885){
danielk19773cf86062004-05-26 10:11:05 +00001886 int rc;
1887 Mem *pColName;
danielk1977955de522006-02-10 02:27:42 +00001888 assert( idx<p->nResColumn );
1889 assert( var<COLNAME_N );
danielk197710fb7492008-10-31 10:53:22 +00001890 if( p->db->mallocFailed ){
1891 assert( !zName || xDel!=SQLITE_DYNAMIC );
1892 return SQLITE_NOMEM;
1893 }
drh76ff3a02004-09-24 22:32:30 +00001894 assert( p->aColName!=0 );
danielk1977955de522006-02-10 02:27:42 +00001895 pColName = &(p->aColName[idx+var*p->nResColumn]);
danielk197710fb7492008-10-31 10:53:22 +00001896 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
drh0793f1b2008-11-05 17:41:19 +00001897 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
danielk19773cf86062004-05-26 10:11:05 +00001898 return rc;
1899}
1900
danielk197713adf8a2004-06-03 16:08:41 +00001901/*
1902** A read or write transaction may or may not be active on database handle
1903** db. If a transaction is active, commit it. If there is a
1904** write-transaction spanning more than one database file, this routine
1905** takes care of the master journal trickery.
1906*/
danielk19773e3a84d2008-08-01 17:37:40 +00001907static int vdbeCommit(sqlite3 *db, Vdbe *p){
danielk197713adf8a2004-06-03 16:08:41 +00001908 int i;
1909 int nTrans = 0; /* Number of databases with an active write-transaction */
1910 int rc = SQLITE_OK;
1911 int needXcommit = 0;
1912
shane36840fd2009-06-26 16:32:13 +00001913#ifdef SQLITE_OMIT_VIRTUALTABLE
1914 /* With this option, sqlite3VtabSync() is defined to be simply
1915 ** SQLITE_OK so p is not used.
1916 */
1917 UNUSED_PARAMETER(p);
1918#endif
1919
danielk19775bd270b2006-07-25 15:14:52 +00001920 /* Before doing anything else, call the xSync() callback for any
1921 ** virtual module tables written in this transaction. This has to
1922 ** be done before determining whether a master journal file is
1923 ** required, as an xSync() callback may add an attached database
1924 ** to the transaction.
1925 */
dan016f7812013-08-21 17:35:48 +00001926 rc = sqlite3VtabSync(db, p);
danielk19775bd270b2006-07-25 15:14:52 +00001927
1928 /* This loop determines (a) if the commit hook should be invoked and
1929 ** (b) how many database files have open write transactions, not
1930 ** including the temp database. (b) is important because if more than
1931 ** one database file has an open write transaction, a master journal
1932 ** file is required for an atomic commit.
1933 */
drhabfb62f2010-07-30 11:20:35 +00001934 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001935 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00001936 if( sqlite3BtreeIsInTrans(pBt) ){
danielk197713adf8a2004-06-03 16:08:41 +00001937 needXcommit = 1;
1938 if( i!=1 ) nTrans++;
dan6b9bb592012-10-05 19:43:02 +00001939 sqlite3BtreeEnter(pBt);
drhabfb62f2010-07-30 11:20:35 +00001940 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
dan6b9bb592012-10-05 19:43:02 +00001941 sqlite3BtreeLeave(pBt);
danielk197713adf8a2004-06-03 16:08:41 +00001942 }
1943 }
drhabfb62f2010-07-30 11:20:35 +00001944 if( rc!=SQLITE_OK ){
1945 return rc;
1946 }
danielk197713adf8a2004-06-03 16:08:41 +00001947
1948 /* If there are any write-transactions at all, invoke the commit hook */
1949 if( needXcommit && db->xCommitCallback ){
drh92f02c32004-09-02 14:57:08 +00001950 rc = db->xCommitCallback(db->pCommitArg);
drh92f02c32004-09-02 14:57:08 +00001951 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00001952 return SQLITE_CONSTRAINT_COMMITHOOK;
danielk197713adf8a2004-06-03 16:08:41 +00001953 }
1954 }
1955
danielk197740b38dc2004-06-26 08:38:24 +00001956 /* The simple case - no more than one database file (not counting the
1957 ** TEMP database) has a transaction active. There is no need for the
drh2ac3ee92004-06-07 16:27:46 +00001958 ** master-journal.
drhc9e06862004-06-09 20:03:08 +00001959 **
danielk197740b38dc2004-06-26 08:38:24 +00001960 ** If the return value of sqlite3BtreeGetFilename() is a zero length
danielk197717b90b52008-06-06 11:11:25 +00001961 ** string, it means the main database is :memory: or a temp file. In
1962 ** that case we do not support atomic multi-file commits, so use the
1963 ** simple case then too.
danielk197713adf8a2004-06-03 16:08:41 +00001964 */
drhea678832008-12-10 19:26:22 +00001965 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
1966 || nTrans<=1
1967 ){
danielk197704103022009-02-03 16:51:24 +00001968 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001969 Btree *pBt = db->aDb[i].pBt;
1970 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00001971 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
drh2ac3ee92004-06-07 16:27:46 +00001972 }
1973 }
1974
drh80e35f42007-03-30 14:06:34 +00001975 /* Do the commit only if all databases successfully complete phase 1.
1976 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1977 ** IO error while deleting or truncating a journal file. It is unlikely,
1978 ** but could happen. In this case abandon processing and return the error.
danielk1977979f38e2007-03-27 16:19:51 +00001979 */
1980 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1981 Btree *pBt = db->aDb[i].pBt;
1982 if( pBt ){
dan60939d02011-03-29 15:40:55 +00001983 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
danielk197713adf8a2004-06-03 16:08:41 +00001984 }
danielk1977979f38e2007-03-27 16:19:51 +00001985 }
1986 if( rc==SQLITE_OK ){
danielk1977f9e7dda2006-06-16 16:08:53 +00001987 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00001988 }
1989 }
1990
1991 /* The complex case - There is a multi-file write-transaction active.
1992 ** This requires a master journal file to ensure the transaction is
peter.d.reid60ec9142014-09-06 16:39:46 +00001993 ** committed atomically.
danielk197713adf8a2004-06-03 16:08:41 +00001994 */
danielk197744ee5bf2005-05-27 09:41:12 +00001995#ifndef SQLITE_OMIT_DISKIO
danielk197713adf8a2004-06-03 16:08:41 +00001996 else{
danielk1977b4b47412007-08-17 15:53:36 +00001997 sqlite3_vfs *pVfs = db->pVfs;
drh2c8997b2005-08-27 16:36:48 +00001998 int needSync = 0;
danielk197713adf8a2004-06-03 16:08:41 +00001999 char *zMaster = 0; /* File-name for the master journal */
2000 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
danielk1977b4b47412007-08-17 15:53:36 +00002001 sqlite3_file *pMaster = 0;
danielk197762079062007-08-15 17:08:46 +00002002 i64 offset = 0;
danielk1977861f7452008-06-05 11:39:11 +00002003 int res;
drhf5808602011-12-16 00:33:04 +00002004 int retryCount = 0;
drh5c531a42011-12-16 01:21:31 +00002005 int nMainFile;
danielk197713adf8a2004-06-03 16:08:41 +00002006
2007 /* Select a master journal file name */
drh5c531a42011-12-16 01:21:31 +00002008 nMainFile = sqlite3Strlen30(zMainFile);
drh52bcde02012-01-03 14:50:45 +00002009 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
drh5c531a42011-12-16 01:21:31 +00002010 if( zMaster==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002011 do {
drhdc5ea5c2008-12-10 17:19:59 +00002012 u32 iRandom;
drh84968c02011-12-16 15:11:39 +00002013 if( retryCount ){
2014 if( retryCount>100 ){
2015 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2016 sqlite3OsDelete(pVfs, zMaster, 0);
2017 break;
2018 }else if( retryCount==1 ){
2019 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2020 }
danielk197713adf8a2004-06-03 16:08:41 +00002021 }
drh84968c02011-12-16 15:11:39 +00002022 retryCount++;
danielk197713adf8a2004-06-03 16:08:41 +00002023 sqlite3_randomness(sizeof(iRandom), &iRandom);
drh5c531a42011-12-16 01:21:31 +00002024 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
drhf5808602011-12-16 00:33:04 +00002025 (iRandom>>8)&0xffffff, iRandom&0xff);
drhf5808602011-12-16 00:33:04 +00002026 /* The antipenultimate character of the master journal name must
2027 ** be "9" to avoid name collisions when using 8+3 filenames. */
drh5c531a42011-12-16 01:21:31 +00002028 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
drh81cc5162011-05-17 20:36:21 +00002029 sqlite3FileSuffix3(zMainFile, zMaster);
danielk1977861f7452008-06-05 11:39:11 +00002030 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2031 }while( rc==SQLITE_OK && res );
2032 if( rc==SQLITE_OK ){
drh19db9352008-03-27 22:42:51 +00002033 /* Open the master journal. */
2034 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2035 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2036 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2037 );
2038 }
danielk197713adf8a2004-06-03 16:08:41 +00002039 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002040 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002041 return rc;
2042 }
2043
2044 /* Write the name of each database file in the transaction into the new
2045 ** master journal file. If an error occurs at this point close
2046 ** and delete the master journal file. All the individual journal files
2047 ** still have 'null' as the master journal pointer, so they will roll
danielk1977aca790a2005-01-13 11:07:52 +00002048 ** back independently if a failure occurs.
danielk197713adf8a2004-06-03 16:08:41 +00002049 */
danielk19771e536952007-08-16 10:09:01 +00002050 for(i=0; i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002051 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002052 if( sqlite3BtreeIsInTrans(pBt) ){
danielk19775865e3d2004-06-14 06:03:57 +00002053 char const *zFile = sqlite3BtreeGetJournalname(pBt);
drh8c96a6e2010-08-31 01:09:15 +00002054 if( zFile==0 ){
drhb290e1c2009-12-08 13:36:55 +00002055 continue; /* Ignore TEMP and :memory: databases */
2056 }
drh8c96a6e2010-08-31 01:09:15 +00002057 assert( zFile[0]!=0 );
drh2c8997b2005-08-27 16:36:48 +00002058 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
2059 needSync = 1;
2060 }
drhea678832008-12-10 19:26:22 +00002061 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2062 offset += sqlite3Strlen30(zFile)+1;
danielk197713adf8a2004-06-03 16:08:41 +00002063 if( rc!=SQLITE_OK ){
danielk1977fee2d252007-08-18 10:59:19 +00002064 sqlite3OsCloseFree(pMaster);
2065 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002066 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002067 return rc;
2068 }
2069 }
2070 }
2071
danielk19779663b8f2007-08-24 11:52:28 +00002072 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2073 ** flag is set this is not required.
2074 */
danielk1977bea2a942009-01-20 17:06:27 +00002075 if( needSync
2076 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2077 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2078 ){
danielk1977fee2d252007-08-18 10:59:19 +00002079 sqlite3OsCloseFree(pMaster);
2080 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002081 sqlite3DbFree(db, zMaster);
danielk19775865e3d2004-06-14 06:03:57 +00002082 return rc;
2083 }
drhc9e06862004-06-09 20:03:08 +00002084
danielk197713adf8a2004-06-03 16:08:41 +00002085 /* Sync all the db files involved in the transaction. The same call
2086 ** sets the master journal pointer in each individual journal. If
2087 ** an error occurs here, do not delete the master journal file.
2088 **
drh80e35f42007-03-30 14:06:34 +00002089 ** If the error occurs during the first call to
2090 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2091 ** master journal file will be orphaned. But we cannot delete it,
2092 ** in case the master journal file name was written into the journal
shanebe217792009-03-05 04:20:31 +00002093 ** file before the failure occurred.
danielk197713adf8a2004-06-03 16:08:41 +00002094 */
danielk19775bd270b2006-07-25 15:14:52 +00002095 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002096 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002097 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002098 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002099 }
2100 }
danielk1977fee2d252007-08-18 10:59:19 +00002101 sqlite3OsCloseFree(pMaster);
drhabfb62f2010-07-30 11:20:35 +00002102 assert( rc!=SQLITE_BUSY );
danielk19775bd270b2006-07-25 15:14:52 +00002103 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002104 sqlite3DbFree(db, zMaster);
danielk19775bd270b2006-07-25 15:14:52 +00002105 return rc;
2106 }
danielk197713adf8a2004-06-03 16:08:41 +00002107
danielk1977962398d2004-06-14 09:35:16 +00002108 /* Delete the master journal file. This commits the transaction. After
2109 ** doing this the directory is synced again before any individual
2110 ** transaction files are deleted.
2111 */
danielk1977fee2d252007-08-18 10:59:19 +00002112 rc = sqlite3OsDelete(pVfs, zMaster, 1);
drh633e6d52008-07-28 19:34:53 +00002113 sqlite3DbFree(db, zMaster);
drhc416ba92007-03-30 18:42:55 +00002114 zMaster = 0;
drh29a01382006-08-13 19:04:18 +00002115 if( rc ){
2116 return rc;
2117 }
danielk197713adf8a2004-06-03 16:08:41 +00002118
2119 /* All files and directories have already been synced, so the following
drh80e35f42007-03-30 14:06:34 +00002120 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2121 ** deleting or truncating journals. If something goes wrong while
2122 ** this is happening we don't really care. The integrity of the
2123 ** transaction is already guaranteed, but some stray 'cold' journals
2124 ** may be lying around. Returning an error code won't help matters.
danielk197713adf8a2004-06-03 16:08:41 +00002125 */
danielk1977979f38e2007-03-27 16:19:51 +00002126 disable_simulated_io_errors();
danielk19772d1d86f2008-06-20 14:59:51 +00002127 sqlite3BeginBenignMalloc();
danielk197713adf8a2004-06-03 16:08:41 +00002128 for(i=0; i<db->nDb; i++){
2129 Btree *pBt = db->aDb[i].pBt;
2130 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002131 sqlite3BtreeCommitPhaseTwo(pBt, 1);
danielk197713adf8a2004-06-03 16:08:41 +00002132 }
2133 }
danielk19772d1d86f2008-06-20 14:59:51 +00002134 sqlite3EndBenignMalloc();
danielk1977979f38e2007-03-27 16:19:51 +00002135 enable_simulated_io_errors();
2136
danielk1977f9e7dda2006-06-16 16:08:53 +00002137 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002138 }
danielk197744ee5bf2005-05-27 09:41:12 +00002139#endif
danielk1977026d2702004-06-14 13:14:59 +00002140
drh2ac3ee92004-06-07 16:27:46 +00002141 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00002142}
2143
danielk19771d850a72004-05-31 08:26:49 +00002144/*
drh4f7d3a52013-06-27 23:54:02 +00002145** This routine checks that the sqlite3.nVdbeActive count variable
danielk19771d850a72004-05-31 08:26:49 +00002146** matches the number of vdbe's in the list sqlite3.pVdbe that are
2147** currently active. An assertion fails if the two counts do not match.
drh92f02c32004-09-02 14:57:08 +00002148** This is an internal self-check only - it is not an essential processing
2149** step.
danielk19771d850a72004-05-31 08:26:49 +00002150**
2151** This is a no-op if NDEBUG is defined.
2152*/
2153#ifndef NDEBUG
drh9bb575f2004-09-06 17:24:11 +00002154static void checkActiveVdbeCnt(sqlite3 *db){
danielk19771d850a72004-05-31 08:26:49 +00002155 Vdbe *p;
2156 int cnt = 0;
drhad4a4b82008-11-05 16:37:34 +00002157 int nWrite = 0;
drh4f7d3a52013-06-27 23:54:02 +00002158 int nRead = 0;
danielk19771d850a72004-05-31 08:26:49 +00002159 p = db->pVdbe;
2160 while( p ){
dan857745c2014-07-19 17:57:10 +00002161 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
danielk19771d850a72004-05-31 08:26:49 +00002162 cnt++;
drhad4a4b82008-11-05 16:37:34 +00002163 if( p->readOnly==0 ) nWrite++;
drh1713afb2013-06-28 01:24:57 +00002164 if( p->bIsReader ) nRead++;
danielk19771d850a72004-05-31 08:26:49 +00002165 }
2166 p = p->pNext;
2167 }
drh4f7d3a52013-06-27 23:54:02 +00002168 assert( cnt==db->nVdbeActive );
2169 assert( nWrite==db->nVdbeWrite );
2170 assert( nRead==db->nVdbeRead );
danielk19771d850a72004-05-31 08:26:49 +00002171}
2172#else
2173#define checkActiveVdbeCnt(x)
2174#endif
2175
danielk19773cf86062004-05-26 10:11:05 +00002176/*
danielk1977bd434552009-03-18 10:33:00 +00002177** If the Vdbe passed as the first argument opened a statement-transaction,
2178** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2179** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2180** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
drhf7b54962013-05-28 12:11:54 +00002181** statement transaction is committed.
danielk1977bd434552009-03-18 10:33:00 +00002182**
2183** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2184** Otherwise SQLITE_OK.
2185*/
2186int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
danielk1977c926b6a2009-03-20 14:42:11 +00002187 sqlite3 *const db = p->db;
danielk1977bd434552009-03-18 10:33:00 +00002188 int rc = SQLITE_OK;
danielk1977ecaecf92009-07-08 08:05:35 +00002189
danielk1977e4948172009-07-17 17:25:43 +00002190 /* If p->iStatement is greater than zero, then this Vdbe opened a
2191 ** statement transaction that should be closed here. The only exception
mistachkin48864df2013-03-21 21:20:32 +00002192 ** is that an IO error may have occurred, causing an emergency rollback.
danielk1977e4948172009-07-17 17:25:43 +00002193 ** In this case (db->nStatement==0), and there is nothing to do.
2194 */
2195 if( db->nStatement && p->iStatement ){
danielk1977bd434552009-03-18 10:33:00 +00002196 int i;
2197 const int iSavepoint = p->iStatement-1;
danielk1977bd434552009-03-18 10:33:00 +00002198
2199 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2200 assert( db->nStatement>0 );
2201 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2202
2203 for(i=0; i<db->nDb; i++){
2204 int rc2 = SQLITE_OK;
2205 Btree *pBt = db->aDb[i].pBt;
2206 if( pBt ){
2207 if( eOp==SAVEPOINT_ROLLBACK ){
2208 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2209 }
2210 if( rc2==SQLITE_OK ){
2211 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2212 }
2213 if( rc==SQLITE_OK ){
2214 rc = rc2;
2215 }
2216 }
2217 }
2218 db->nStatement--;
2219 p->iStatement = 0;
dan1da40a32009-09-19 17:00:31 +00002220
dana311b802011-04-26 19:21:34 +00002221 if( rc==SQLITE_OK ){
2222 if( eOp==SAVEPOINT_ROLLBACK ){
2223 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2224 }
2225 if( rc==SQLITE_OK ){
2226 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2227 }
2228 }
2229
dan1da40a32009-09-19 17:00:31 +00002230 /* If the statement transaction is being rolled back, also restore the
2231 ** database handles deferred constraint counter to the value it had when
2232 ** the statement transaction was opened. */
2233 if( eOp==SAVEPOINT_ROLLBACK ){
2234 db->nDeferredCons = p->nStmtDefCons;
drh648e2642013-07-11 15:03:32 +00002235 db->nDeferredImmCons = p->nStmtDefImmCons;
dan1da40a32009-09-19 17:00:31 +00002236 }
danielk1977bd434552009-03-18 10:33:00 +00002237 }
2238 return rc;
2239}
2240
2241/*
dan1da40a32009-09-19 17:00:31 +00002242** This function is called when a transaction opened by the database
2243** handle associated with the VM passed as an argument is about to be
2244** committed. If there are outstanding deferred foreign key constraint
2245** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2246**
2247** If there are outstanding FK violations and this function returns
drhd91c1a12013-02-09 13:58:25 +00002248** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2249** and write an error message to it. Then return SQLITE_ERROR.
dan1da40a32009-09-19 17:00:31 +00002250*/
2251#ifndef SQLITE_OMIT_FOREIGN_KEY
dan32b09f22009-09-23 17:29:59 +00002252int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
dan1da40a32009-09-19 17:00:31 +00002253 sqlite3 *db = p->db;
drh648e2642013-07-11 15:03:32 +00002254 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2255 || (!deferred && p->nFkConstraint>0)
2256 ){
drhd91c1a12013-02-09 13:58:25 +00002257 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan32b09f22009-09-23 17:29:59 +00002258 p->errorAction = OE_Abort;
drhf9c8ce32013-11-05 13:33:55 +00002259 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
dan1da40a32009-09-19 17:00:31 +00002260 return SQLITE_ERROR;
2261 }
2262 return SQLITE_OK;
2263}
2264#endif
2265
2266/*
drh92f02c32004-09-02 14:57:08 +00002267** This routine is called the when a VDBE tries to halt. If the VDBE
2268** has made changes and is in autocommit mode, then commit those
2269** changes. If a rollback is needed, then do the rollback.
drh9a324642003-09-06 20:12:01 +00002270**
drh92f02c32004-09-02 14:57:08 +00002271** This routine is the only way to move the state of a VM from
drhff0587c2007-08-29 17:43:19 +00002272** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2273** call this on a VM that is in the SQLITE_MAGIC_HALT state.
drh92f02c32004-09-02 14:57:08 +00002274**
2275** Return an error code. If the commit could not complete because of
2276** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2277** means the close did not happen and needs to be repeated.
drh9a324642003-09-06 20:12:01 +00002278*/
drhff0587c2007-08-29 17:43:19 +00002279int sqlite3VdbeHalt(Vdbe *p){
danielk1977bd434552009-03-18 10:33:00 +00002280 int rc; /* Used to store transient return codes */
drh9bb575f2004-09-06 17:24:11 +00002281 sqlite3 *db = p->db;
danielk197707cb5602006-01-20 10:55:05 +00002282
2283 /* This function contains the logic that determines if a statement or
2284 ** transaction will be committed or rolled back as a result of the
2285 ** execution of this virtual machine.
2286 **
drh71b890a2007-10-03 15:30:52 +00002287 ** If any of the following errors occur:
danielk197707cb5602006-01-20 10:55:05 +00002288 **
drh71b890a2007-10-03 15:30:52 +00002289 ** SQLITE_NOMEM
2290 ** SQLITE_IOERR
2291 ** SQLITE_FULL
2292 ** SQLITE_INTERRUPT
danielk197707cb5602006-01-20 10:55:05 +00002293 **
drh71b890a2007-10-03 15:30:52 +00002294 ** Then the internal cache might have been left in an inconsistent
2295 ** state. We need to rollback the statement transaction, if there is
2296 ** one, or the complete transaction if there is no statement transaction.
danielk197707cb5602006-01-20 10:55:05 +00002297 */
drh9a324642003-09-06 20:12:01 +00002298
drh17435752007-08-16 04:30:38 +00002299 if( p->db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002300 p->rc = SQLITE_NOMEM;
2301 }
drh6e856bc2011-12-09 18:06:44 +00002302 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
drh5f82e3c2009-07-06 00:44:08 +00002303 closeAllCursors(p);
drh92f02c32004-09-02 14:57:08 +00002304 if( p->magic!=VDBE_MAGIC_RUN ){
drh92f02c32004-09-02 14:57:08 +00002305 return SQLITE_OK;
drh9a324642003-09-06 20:12:01 +00002306 }
danielk19771d850a72004-05-31 08:26:49 +00002307 checkActiveVdbeCnt(db);
danielk1977261919c2005-12-06 12:52:59 +00002308
danc0537fe2013-06-28 19:41:43 +00002309 /* No commit or rollback needed if the program never started or if the
2310 ** SQL statement does not read or write a database file. */
2311 if( p->pc>=0 && p->bIsReader ){
drhaac2f552006-09-23 21:44:23 +00002312 int mrc; /* Primary error code from p->rc */
danielk1977bd434552009-03-18 10:33:00 +00002313 int eStatementOp = 0;
2314 int isSpecialError; /* Set to true if a 'special' error */
drhff0587c2007-08-29 17:43:19 +00002315
2316 /* Lock all btrees used by the statement */
drhbdaec522011-04-04 00:14:43 +00002317 sqlite3VdbeEnter(p);
drhff0587c2007-08-29 17:43:19 +00002318
drh71b890a2007-10-03 15:30:52 +00002319 /* Check for one of the special errors */
drhaac2f552006-09-23 21:44:23 +00002320 mrc = p->rc & 0xff;
drh71b890a2007-10-03 15:30:52 +00002321 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
drh77658e22007-12-04 16:54:52 +00002322 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
danielk197707cb5602006-01-20 10:55:05 +00002323 if( isSpecialError ){
dan5653e4d2010-08-12 11:25:47 +00002324 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2325 ** no rollback is necessary. Otherwise, at least a savepoint
2326 ** transaction must be rolled back to restore the database to a
2327 ** consistent state.
2328 **
2329 ** Even if the statement is read-only, it is important to perform
2330 ** a statement or transaction rollback operation. If the error
mistachkin48864df2013-03-21 21:20:32 +00002331 ** occurred while writing to the journal, sub-journal or database
dan5653e4d2010-08-12 11:25:47 +00002332 ** file as part of an effort to free up cache space (see function
2333 ** pagerStress() in pager.c), the rollback is required to restore
2334 ** the pager to a consistent state.
danielk197707cb5602006-01-20 10:55:05 +00002335 */
drhad4a4b82008-11-05 16:37:34 +00002336 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
drhfa3be902009-07-07 02:44:07 +00002337 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
danielk1977bd434552009-03-18 10:33:00 +00002338 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002339 }else{
2340 /* We are forced to roll back the active transaction. Before doing
2341 ** so, abort any other statements this handle currently has active.
2342 */
drh21021a52012-02-13 17:01:51 +00002343 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002344 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002345 db->autoCommit = 1;
2346 }
danielk1977261919c2005-12-06 12:52:59 +00002347 }
2348 }
dan32b09f22009-09-23 17:29:59 +00002349
2350 /* Check for immediate foreign key violations. */
2351 if( p->rc==SQLITE_OK ){
2352 sqlite3VdbeCheckFk(p, 0);
2353 }
danielk197707cb5602006-01-20 10:55:05 +00002354
danielk1977bd434552009-03-18 10:33:00 +00002355 /* If the auto-commit flag is set and this is the only active writer
2356 ** VM, then we do either a commit or rollback of the current transaction.
danielk197707cb5602006-01-20 10:55:05 +00002357 **
2358 ** Note: This block also runs if one of the special errors handled
drhad4a4b82008-11-05 16:37:34 +00002359 ** above has occurred.
danielk197707cb5602006-01-20 10:55:05 +00002360 */
danielk1977093e0f62008-11-13 18:00:14 +00002361 if( !sqlite3VtabInSync(db)
2362 && db->autoCommit
drh4f7d3a52013-06-27 23:54:02 +00002363 && db->nVdbeWrite==(p->readOnly==0)
danielk1977093e0f62008-11-13 18:00:14 +00002364 ){
danielk197707cb5602006-01-20 10:55:05 +00002365 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
dan19611b12011-01-24 16:00:58 +00002366 rc = sqlite3VdbeCheckFk(p, 1);
2367 if( rc!=SQLITE_OK ){
drhe9ce5852011-02-11 22:54:28 +00002368 if( NEVER(p->readOnly) ){
drhbdaec522011-04-04 00:14:43 +00002369 sqlite3VdbeLeave(p);
dan19611b12011-01-24 16:00:58 +00002370 return SQLITE_ERROR;
2371 }
drhd91c1a12013-02-09 13:58:25 +00002372 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan19611b12011-01-24 16:00:58 +00002373 }else{
2374 /* The auto-commit flag is true, the vdbe program was successful
2375 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2376 ** key constraints to hold up the transaction. This means a commit
2377 ** is required. */
2378 rc = vdbeCommit(db, p);
dan1da40a32009-09-19 17:00:31 +00002379 }
dan19611b12011-01-24 16:00:58 +00002380 if( rc==SQLITE_BUSY && p->readOnly ){
drhbdaec522011-04-04 00:14:43 +00002381 sqlite3VdbeLeave(p);
danielk197707cb5602006-01-20 10:55:05 +00002382 return SQLITE_BUSY;
2383 }else if( rc!=SQLITE_OK ){
2384 p->rc = rc;
drh0f198a72012-02-13 16:43:16 +00002385 sqlite3RollbackAll(db, SQLITE_OK);
danielk197707cb5602006-01-20 10:55:05 +00002386 }else{
dan1da40a32009-09-19 17:00:31 +00002387 db->nDeferredCons = 0;
drh648e2642013-07-11 15:03:32 +00002388 db->nDeferredImmCons = 0;
2389 db->flags &= ~SQLITE_DeferFKs;
danielk197707cb5602006-01-20 10:55:05 +00002390 sqlite3CommitInternalChanges(db);
2391 }
2392 }else{
drh0f198a72012-02-13 16:43:16 +00002393 sqlite3RollbackAll(db, SQLITE_OK);
danielk197707cb5602006-01-20 10:55:05 +00002394 }
danielk1977bd434552009-03-18 10:33:00 +00002395 db->nStatement = 0;
2396 }else if( eStatementOp==0 ){
danielk197707cb5602006-01-20 10:55:05 +00002397 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
danielk1977bd434552009-03-18 10:33:00 +00002398 eStatementOp = SAVEPOINT_RELEASE;
danielk197707cb5602006-01-20 10:55:05 +00002399 }else if( p->errorAction==OE_Abort ){
danielk1977bd434552009-03-18 10:33:00 +00002400 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002401 }else{
drh21021a52012-02-13 17:01:51 +00002402 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002403 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002404 db->autoCommit = 1;
2405 }
danielk19771d850a72004-05-31 08:26:49 +00002406 }
danielk197707cb5602006-01-20 10:55:05 +00002407
danielk1977bd434552009-03-18 10:33:00 +00002408 /* If eStatementOp is non-zero, then a statement transaction needs to
2409 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2410 ** do so. If this operation returns an error, and the current statement
drh35173242010-03-08 21:40:13 +00002411 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2412 ** current statement error code.
danielk197707cb5602006-01-20 10:55:05 +00002413 */
danielk1977bd434552009-03-18 10:33:00 +00002414 if( eStatementOp ){
2415 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
dan40ad9d22010-06-03 09:17:38 +00002416 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00002417 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
dan40ad9d22010-06-03 09:17:38 +00002418 p->rc = rc;
2419 sqlite3DbFree(db, p->zErrMsg);
2420 p->zErrMsg = 0;
2421 }
drh21021a52012-02-13 17:01:51 +00002422 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
dan40ad9d22010-06-03 09:17:38 +00002423 sqlite3CloseSavepoints(db);
2424 db->autoCommit = 1;
danielk197707cb5602006-01-20 10:55:05 +00002425 }
danielk197777d83ba2004-05-31 10:08:14 +00002426 }
danielk197707cb5602006-01-20 10:55:05 +00002427
danielk1977bd434552009-03-18 10:33:00 +00002428 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2429 ** has been rolled back, update the database connection change-counter.
danielk197707cb5602006-01-20 10:55:05 +00002430 */
drh6be240e2009-07-14 02:33:02 +00002431 if( p->changeCntOn ){
danielk1977bd434552009-03-18 10:33:00 +00002432 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
danielk197707cb5602006-01-20 10:55:05 +00002433 sqlite3VdbeSetChanges(db, p->nChange);
2434 }else{
2435 sqlite3VdbeSetChanges(db, 0);
2436 }
2437 p->nChange = 0;
danielk1977b28af712004-06-21 06:50:26 +00002438 }
drhff0587c2007-08-29 17:43:19 +00002439
2440 /* Release the locks */
drhbdaec522011-04-04 00:14:43 +00002441 sqlite3VdbeLeave(p);
drh9a324642003-09-06 20:12:01 +00002442 }
danielk19771d850a72004-05-31 08:26:49 +00002443
danielk197765fd59f2006-06-24 11:51:33 +00002444 /* We have successfully halted and closed the VM. Record this fact. */
2445 if( p->pc>=0 ){
drh4f7d3a52013-06-27 23:54:02 +00002446 db->nVdbeActive--;
2447 if( !p->readOnly ) db->nVdbeWrite--;
drh1713afb2013-06-28 01:24:57 +00002448 if( p->bIsReader ) db->nVdbeRead--;
drh4f7d3a52013-06-27 23:54:02 +00002449 assert( db->nVdbeActive>=db->nVdbeRead );
2450 assert( db->nVdbeRead>=db->nVdbeWrite );
2451 assert( db->nVdbeWrite>=0 );
drh9a324642003-09-06 20:12:01 +00002452 }
drh92f02c32004-09-02 14:57:08 +00002453 p->magic = VDBE_MAGIC_HALT;
2454 checkActiveVdbeCnt(db);
drhff0587c2007-08-29 17:43:19 +00002455 if( p->db->mallocFailed ){
2456 p->rc = SQLITE_NOMEM;
2457 }
danielk19771d850a72004-05-31 08:26:49 +00002458
danielk1977404ca072009-03-16 13:19:36 +00002459 /* If the auto-commit flag is set to true, then any locks that were held
2460 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2461 ** to invoke any required unlock-notify callbacks.
2462 */
2463 if( db->autoCommit ){
2464 sqlite3ConnectionUnlocked(db);
2465 }
2466
drh4f7d3a52013-06-27 23:54:02 +00002467 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
dan19611b12011-01-24 16:00:58 +00002468 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
drh92f02c32004-09-02 14:57:08 +00002469}
drh4cf7c7f2007-08-28 23:28:07 +00002470
drh92f02c32004-09-02 14:57:08 +00002471
2472/*
drh3c23a882007-01-09 14:01:13 +00002473** Each VDBE holds the result of the most recent sqlite3_step() call
2474** in p->rc. This routine sets that result back to SQLITE_OK.
2475*/
2476void sqlite3VdbeResetStepResult(Vdbe *p){
2477 p->rc = SQLITE_OK;
2478}
2479
2480/*
dan029ead62011-10-27 15:19:58 +00002481** Copy the error code and error message belonging to the VDBE passed
2482** as the first argument to its database handle (so that they will be
2483** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2484**
2485** This function does not clear the VDBE error code or message, just
2486** copies them to the database handle.
2487*/
2488int sqlite3VdbeTransferError(Vdbe *p){
2489 sqlite3 *db = p->db;
2490 int rc = p->rc;
2491 if( p->zErrMsg ){
drh81bdd6d2011-10-29 01:33:24 +00002492 u8 mallocFailed = db->mallocFailed;
dan029ead62011-10-27 15:19:58 +00002493 sqlite3BeginBenignMalloc();
drha3cc0072013-12-13 16:23:55 +00002494 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
dan029ead62011-10-27 15:19:58 +00002495 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2496 sqlite3EndBenignMalloc();
drh81bdd6d2011-10-29 01:33:24 +00002497 db->mallocFailed = mallocFailed;
dan029ead62011-10-27 15:19:58 +00002498 db->errCode = rc;
2499 }else{
drh13f40da2014-08-22 18:00:11 +00002500 sqlite3Error(db, rc);
dan029ead62011-10-27 15:19:58 +00002501 }
2502 return rc;
2503}
2504
danac455932012-11-26 19:50:41 +00002505#ifdef SQLITE_ENABLE_SQLLOG
2506/*
2507** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2508** invoke it.
2509*/
2510static void vdbeInvokeSqllog(Vdbe *v){
2511 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2512 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2513 assert( v->db->init.busy==0 );
2514 if( zExpanded ){
2515 sqlite3GlobalConfig.xSqllog(
2516 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2517 );
2518 sqlite3DbFree(v->db, zExpanded);
2519 }
2520 }
2521}
2522#else
2523# define vdbeInvokeSqllog(x)
2524#endif
2525
dan029ead62011-10-27 15:19:58 +00002526/*
drh92f02c32004-09-02 14:57:08 +00002527** Clean up a VDBE after execution but do not delete the VDBE just yet.
2528** Write any error messages into *pzErrMsg. Return the result code.
2529**
2530** After this routine is run, the VDBE should be ready to be executed
2531** again.
2532**
2533** To look at it another way, this routine resets the state of the
2534** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2535** VDBE_MAGIC_INIT.
2536*/
drhc890fec2008-08-01 20:10:08 +00002537int sqlite3VdbeReset(Vdbe *p){
drh4ac285a2006-09-15 07:28:50 +00002538 sqlite3 *db;
drh4ac285a2006-09-15 07:28:50 +00002539 db = p->db;
drh92f02c32004-09-02 14:57:08 +00002540
2541 /* If the VM did not run to completion or if it encountered an
2542 ** error, then it might not have been halted properly. So halt
2543 ** it now.
2544 */
2545 sqlite3VdbeHalt(p);
2546
drhfb7e7652005-01-24 00:28:42 +00002547 /* If the VDBE has be run even partially, then transfer the error code
2548 ** and error message from the VDBE into the main database structure. But
2549 ** if the VDBE has just been set to run but has not actually executed any
2550 ** instructions yet, leave the main database error information unchanged.
drh92f02c32004-09-02 14:57:08 +00002551 */
drhfb7e7652005-01-24 00:28:42 +00002552 if( p->pc>=0 ){
danac455932012-11-26 19:50:41 +00002553 vdbeInvokeSqllog(p);
dan029ead62011-10-27 15:19:58 +00002554 sqlite3VdbeTransferError(p);
2555 sqlite3DbFree(db, p->zErrMsg);
2556 p->zErrMsg = 0;
drh4611d922010-02-25 14:47:01 +00002557 if( p->runOnlyOnce ) p->expired = 1;
danielk1977a21c6b62005-01-24 10:25:59 +00002558 }else if( p->rc && p->expired ){
2559 /* The expired flag was set on the VDBE before the first call
2560 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2561 ** called), set the database error in this case as well.
2562 */
drh13f40da2014-08-22 18:00:11 +00002563 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
drh633e6d52008-07-28 19:34:53 +00002564 sqlite3DbFree(db, p->zErrMsg);
danielk19778e556522007-11-13 10:30:24 +00002565 p->zErrMsg = 0;
drh92f02c32004-09-02 14:57:08 +00002566 }
2567
2568 /* Reclaim all memory used by the VDBE
2569 */
drhc890fec2008-08-01 20:10:08 +00002570 Cleanup(p);
drh92f02c32004-09-02 14:57:08 +00002571
2572 /* Save profiling information from this VDBE run.
2573 */
drh9a324642003-09-06 20:12:01 +00002574#ifdef VDBE_PROFILE
2575 {
2576 FILE *out = fopen("vdbe_profile.out", "a");
2577 if( out ){
2578 int i;
2579 fprintf(out, "---- ");
2580 for(i=0; i<p->nOp; i++){
2581 fprintf(out, "%02x", p->aOp[i].opcode);
2582 }
2583 fprintf(out, "\n");
drh2926f962014-02-17 01:13:28 +00002584 if( p->zSql ){
2585 char c, pc = 0;
2586 fprintf(out, "-- ");
2587 for(i=0; (c = p->zSql[i])!=0; i++){
2588 if( pc=='\n' ) fprintf(out, "-- ");
2589 putc(c, out);
2590 pc = c;
2591 }
2592 if( pc!='\n' ) fprintf(out, "\n");
2593 }
drh9a324642003-09-06 20:12:01 +00002594 for(i=0; i<p->nOp; i++){
drh15ab9412014-02-24 14:24:01 +00002595 char zHdr[100];
2596 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
drh9a324642003-09-06 20:12:01 +00002597 p->aOp[i].cnt,
2598 p->aOp[i].cycles,
2599 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2600 );
drh15ab9412014-02-24 14:24:01 +00002601 fprintf(out, "%s", zHdr);
danielk19774adee202004-05-08 08:23:19 +00002602 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
drh9a324642003-09-06 20:12:01 +00002603 }
2604 fclose(out);
2605 }
2606 }
2607#endif
drh7fa20922013-09-17 23:36:33 +00002608 p->iCurrentTime = 0;
drh9a324642003-09-06 20:12:01 +00002609 p->magic = VDBE_MAGIC_INIT;
drh4ac285a2006-09-15 07:28:50 +00002610 return p->rc & db->errMask;
drh9a324642003-09-06 20:12:01 +00002611}
drh92f02c32004-09-02 14:57:08 +00002612
drh9a324642003-09-06 20:12:01 +00002613/*
2614** Clean up and delete a VDBE after execution. Return an integer which is
2615** the result code. Write any error message text into *pzErrMsg.
2616*/
danielk19779e6db7d2004-06-21 08:18:51 +00002617int sqlite3VdbeFinalize(Vdbe *p){
danielk1977b5548a82004-06-26 13:51:33 +00002618 int rc = SQLITE_OK;
danielk1977b5548a82004-06-26 13:51:33 +00002619 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
drhc890fec2008-08-01 20:10:08 +00002620 rc = sqlite3VdbeReset(p);
drh4ac285a2006-09-15 07:28:50 +00002621 assert( (rc & p->db->errMask)==rc );
drh9a324642003-09-06 20:12:01 +00002622 }
danielk19774adee202004-05-08 08:23:19 +00002623 sqlite3VdbeDelete(p);
drh9a324642003-09-06 20:12:01 +00002624 return rc;
2625}
2626
2627/*
dan0c547792013-07-18 17:12:08 +00002628** If parameter iOp is less than zero, then invoke the destructor for
2629** all auxiliary data pointers currently cached by the VM passed as
2630** the first argument.
2631**
2632** Or, if iOp is greater than or equal to zero, then the destructor is
2633** only invoked for those auxiliary data pointers created by the user
2634** function invoked by the OP_Function opcode at instruction iOp of
2635** VM pVdbe, and only then if:
2636**
2637** * the associated function parameter is the 32nd or later (counting
2638** from left to right), or
2639**
2640** * the corresponding bit in argument mask is clear (where the first
peter.d.reid60ec9142014-09-06 16:39:46 +00002641** function parameter corresponds to bit 0 etc.).
drhf92c7ff2004-06-19 15:40:23 +00002642*/
dan0c547792013-07-18 17:12:08 +00002643void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
2644 AuxData **pp = &pVdbe->pAuxData;
2645 while( *pp ){
2646 AuxData *pAux = *pp;
2647 if( (iOp<0)
drh693e6712014-01-24 22:58:00 +00002648 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
dan0c547792013-07-18 17:12:08 +00002649 ){
drh693e6712014-01-24 22:58:00 +00002650 testcase( pAux->iArg==31 );
drhf92c7ff2004-06-19 15:40:23 +00002651 if( pAux->xDelete ){
2652 pAux->xDelete(pAux->pAux);
2653 }
dan0c547792013-07-18 17:12:08 +00002654 *pp = pAux->pNext;
2655 sqlite3DbFree(pVdbe->db, pAux);
2656 }else{
2657 pp= &pAux->pNext;
drhf92c7ff2004-06-19 15:40:23 +00002658 }
2659 }
2660}
2661
2662/*
drhcb103b92012-10-26 00:11:23 +00002663** Free all memory associated with the Vdbe passed as the second argument,
2664** except for object itself, which is preserved.
2665**
dand46def72010-07-24 11:28:28 +00002666** The difference between this function and sqlite3VdbeDelete() is that
2667** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
drhcb103b92012-10-26 00:11:23 +00002668** the database connection and frees the object itself.
dand46def72010-07-24 11:28:28 +00002669*/
drhcb103b92012-10-26 00:11:23 +00002670void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
dand19c9332010-07-26 12:05:17 +00002671 SubProgram *pSub, *pNext;
drh124c0b42011-06-01 18:15:55 +00002672 int i;
dand46def72010-07-24 11:28:28 +00002673 assert( p->db==0 || p->db==db );
2674 releaseMemArray(p->aVar, p->nVar);
2675 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
dand19c9332010-07-26 12:05:17 +00002676 for(pSub=p->pProgram; pSub; pSub=pNext){
2677 pNext = pSub->pNext;
2678 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2679 sqlite3DbFree(db, pSub);
2680 }
drh124c0b42011-06-01 18:15:55 +00002681 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
dand46def72010-07-24 11:28:28 +00002682 vdbeFreeOpArray(db, p->aOp, p->nOp);
dand46def72010-07-24 11:28:28 +00002683 sqlite3DbFree(db, p->aColName);
2684 sqlite3DbFree(db, p->zSql);
2685 sqlite3DbFree(db, p->pFree);
drh678a9aa2011-12-10 15:55:01 +00002686#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
drh25fe97a2013-01-23 18:44:22 +00002687 sqlite3DbFree(db, p->zExplain);
drh678a9aa2011-12-10 15:55:01 +00002688 sqlite3DbFree(db, p->pExplain);
drh7e02e5e2011-12-06 19:44:51 +00002689#endif
dand46def72010-07-24 11:28:28 +00002690}
2691
2692/*
drh9a324642003-09-06 20:12:01 +00002693** Delete an entire VDBE.
2694*/
danielk19774adee202004-05-08 08:23:19 +00002695void sqlite3VdbeDelete(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00002696 sqlite3 *db;
2697
drhfa3be902009-07-07 02:44:07 +00002698 if( NEVER(p==0) ) return;
drh633e6d52008-07-28 19:34:53 +00002699 db = p->db;
drh4245c402012-06-02 14:32:21 +00002700 assert( sqlite3_mutex_held(db->mutex) );
drhcb103b92012-10-26 00:11:23 +00002701 sqlite3VdbeClearObject(db, p);
drh9a324642003-09-06 20:12:01 +00002702 if( p->pPrev ){
2703 p->pPrev->pNext = p->pNext;
2704 }else{
drh633e6d52008-07-28 19:34:53 +00002705 assert( db->pVdbe==p );
2706 db->pVdbe = p->pNext;
drh9a324642003-09-06 20:12:01 +00002707 }
2708 if( p->pNext ){
2709 p->pNext->pPrev = p->pPrev;
2710 }
drh9a324642003-09-06 20:12:01 +00002711 p->magic = VDBE_MAGIC_DEAD;
drh87f5c5f2010-01-20 01:20:56 +00002712 p->db = 0;
drhcb103b92012-10-26 00:11:23 +00002713 sqlite3DbFree(db, p);
drh9a324642003-09-06 20:12:01 +00002714}
drha11846b2004-01-07 18:52:56 +00002715
2716/*
drh6848dad2014-08-22 23:33:03 +00002717** The cursor "p" has a pending seek operation that has not yet been
2718** carried out. Seek the cursor now. If an error occurs, return
2719** the appropriate error code.
2720*/
2721static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
2722 int res, rc;
2723#ifdef SQLITE_TEST
2724 extern int sqlite3_search_count;
2725#endif
2726 assert( p->deferredMoveto );
2727 assert( p->isTable );
2728 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
2729 if( rc ) return rc;
2730 p->lastRowid = p->movetoTarget;
2731 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
2732 p->rowidIsValid = 1;
2733#ifdef SQLITE_TEST
2734 sqlite3_search_count++;
2735#endif
2736 p->deferredMoveto = 0;
2737 p->cacheStatus = CACHE_STALE;
2738 return SQLITE_OK;
2739}
2740
2741/*
2742** Something has moved cursor "p" out of place. Maybe the row it was
2743** pointed to was deleted out from under it. Or maybe the btree was
2744** rebalanced. Whatever the cause, try to restore "p" to the place it
peter.d.reid60ec9142014-09-06 16:39:46 +00002745** is supposed to be pointing. If the row was deleted out from under the
drh6848dad2014-08-22 23:33:03 +00002746** cursor, set the cursor to point to a NULL row.
2747*/
2748static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
2749 int isDifferentRow, rc;
2750 assert( p->pCursor!=0 );
2751 assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
2752 rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
2753 p->cacheStatus = CACHE_STALE;
2754 if( isDifferentRow ) p->nullRow = 1;
2755 return rc;
2756}
2757
2758/*
drh9a65f2c2009-06-22 19:05:40 +00002759** Make sure the cursor p is ready to read or write the row to which it
2760** was last positioned. Return an error code if an OOM fault or I/O error
2761** prevents us from positioning the cursor to its correct position.
2762**
drha11846b2004-01-07 18:52:56 +00002763** If a MoveTo operation is pending on the given cursor, then do that
drh9a65f2c2009-06-22 19:05:40 +00002764** MoveTo now. If no move is pending, check to see if the row has been
2765** deleted out from under the cursor and if it has, mark the row as
2766** a NULL row.
2767**
2768** If the cursor is already pointing to the correct row and that row has
2769** not been deleted out from under the cursor, then this routine is a no-op.
drha11846b2004-01-07 18:52:56 +00002770*/
drhdfe88ec2008-11-03 20:55:06 +00002771int sqlite3VdbeCursorMoveto(VdbeCursor *p){
drha11846b2004-01-07 18:52:56 +00002772 if( p->deferredMoveto ){
drh6848dad2014-08-22 23:33:03 +00002773 return handleDeferredMoveto(p);
2774 }
2775 if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
2776 return handleMovedCursor(p);
drha11846b2004-01-07 18:52:56 +00002777 }
2778 return SQLITE_OK;
2779}
danielk19774adee202004-05-08 08:23:19 +00002780
drhab9f7f12004-05-08 10:56:11 +00002781/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002782** The following functions:
danielk197790e4d952004-05-10 10:05:53 +00002783**
danielk1977cfcdaef2004-05-12 07:33:33 +00002784** sqlite3VdbeSerialType()
2785** sqlite3VdbeSerialTypeLen()
danielk197790e4d952004-05-10 10:05:53 +00002786** sqlite3VdbeSerialLen()
shane92003092008-07-31 01:43:13 +00002787** sqlite3VdbeSerialPut()
2788** sqlite3VdbeSerialGet()
danielk197790e4d952004-05-10 10:05:53 +00002789**
2790** encapsulate the code that serializes values for storage in SQLite
danielk1977cfcdaef2004-05-12 07:33:33 +00002791** data and index records. Each serialized value consists of a
2792** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2793** integer, stored as a varint.
danielk197790e4d952004-05-10 10:05:53 +00002794**
danielk1977cfcdaef2004-05-12 07:33:33 +00002795** In an SQLite index record, the serial type is stored directly before
2796** the blob of data that it corresponds to. In a table record, all serial
2797** types are stored at the start of the record, and the blobs of data at
2798** the end. Hence these functions allow the caller to handle the
mistachkin48864df2013-03-21 21:20:32 +00002799** serial-type and data blob separately.
danielk1977cfcdaef2004-05-12 07:33:33 +00002800**
2801** The following table describes the various storage classes for data:
2802**
2803** serial type bytes of data type
danielk197790e4d952004-05-10 10:05:53 +00002804** -------------- --------------- ---------------
drha19b7752004-05-30 21:14:58 +00002805** 0 0 NULL
danielk197790e4d952004-05-10 10:05:53 +00002806** 1 1 signed integer
2807** 2 2 signed integer
drha19b7752004-05-30 21:14:58 +00002808** 3 3 signed integer
2809** 4 4 signed integer
2810** 5 6 signed integer
2811** 6 8 signed integer
2812** 7 8 IEEE float
drhd946db02005-12-29 19:23:06 +00002813** 8 0 Integer constant 0
2814** 9 0 Integer constant 1
2815** 10,11 reserved for expansion
danielk197790e4d952004-05-10 10:05:53 +00002816** N>=12 and even (N-12)/2 BLOB
2817** N>=13 and odd (N-13)/2 text
2818**
drh35a59652006-01-02 18:24:40 +00002819** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2820** of SQLite will not understand those serial types.
danielk197790e4d952004-05-10 10:05:53 +00002821*/
2822
2823/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002824** Return the serial-type for the value stored in pMem.
danielk1977192ac1d2004-05-10 07:17:30 +00002825*/
drhd946db02005-12-29 19:23:06 +00002826u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
danielk1977cfcdaef2004-05-12 07:33:33 +00002827 int flags = pMem->flags;
drheac5bd72014-07-25 21:35:39 +00002828 u32 n;
danielk1977cfcdaef2004-05-12 07:33:33 +00002829
2830 if( flags&MEM_Null ){
drha19b7752004-05-30 21:14:58 +00002831 return 0;
danielk197790e4d952004-05-10 10:05:53 +00002832 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002833 if( flags&MEM_Int ){
drhfe2093d2005-01-20 22:48:47 +00002834 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
drh5284a052008-05-08 15:18:10 +00002835# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
drh3c024d62007-03-30 11:23:45 +00002836 i64 i = pMem->u.i;
drhd946db02005-12-29 19:23:06 +00002837 u64 u;
drhcfd654b2011-03-05 13:54:15 +00002838 if( i<0 ){
2839 if( i<(-MAX_6BYTE) ) return 6;
2840 /* Previous test prevents: u = -(-9223372036854775808) */
2841 u = -i;
2842 }else{
2843 u = i;
2844 }
drh56690b32012-09-17 15:36:31 +00002845 if( u<=127 ){
2846 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
2847 }
drh5742b632005-01-26 17:47:02 +00002848 if( u<=32767 ) return 2;
2849 if( u<=8388607 ) return 3;
2850 if( u<=2147483647 ) return 4;
2851 if( u<=MAX_6BYTE ) return 5;
drha19b7752004-05-30 21:14:58 +00002852 return 6;
danielk197790e4d952004-05-10 10:05:53 +00002853 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002854 if( flags&MEM_Real ){
drha19b7752004-05-30 21:14:58 +00002855 return 7;
danielk197790e4d952004-05-10 10:05:53 +00002856 }
danielk1977e4359752008-11-03 09:39:45 +00002857 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
drheac5bd72014-07-25 21:35:39 +00002858 assert( pMem->n>=0 );
2859 n = (u32)pMem->n;
drhfdf972a2007-05-02 13:30:27 +00002860 if( flags & MEM_Zero ){
drh8df32842008-12-09 02:51:23 +00002861 n += pMem->u.nZero;
danielk197790e4d952004-05-10 10:05:53 +00002862 }
drhfdf972a2007-05-02 13:30:27 +00002863 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
danielk1977192ac1d2004-05-10 07:17:30 +00002864}
2865
2866/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002867** Return the length of the data corresponding to the supplied serial-type.
danielk1977192ac1d2004-05-10 07:17:30 +00002868*/
drh35cd6432009-06-05 14:17:21 +00002869u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
drha19b7752004-05-30 21:14:58 +00002870 if( serial_type>=12 ){
drh51846b52004-05-28 16:00:21 +00002871 return (serial_type-12)/2;
2872 }else{
drh57196282004-10-06 15:41:16 +00002873 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
drh51846b52004-05-28 16:00:21 +00002874 return aSize[serial_type];
2875 }
danielk1977192ac1d2004-05-10 07:17:30 +00002876}
2877
2878/*
drh110daac2007-05-04 11:59:31 +00002879** If we are on an architecture with mixed-endian floating
drh7a4f5022007-05-23 07:20:08 +00002880** points (ex: ARM7) then swap the lower 4 bytes with the
drh110daac2007-05-04 11:59:31 +00002881** upper 4 bytes. Return the result.
2882**
drh7a4f5022007-05-23 07:20:08 +00002883** For most architectures, this is a no-op.
2884**
2885** (later): It is reported to me that the mixed-endian problem
2886** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2887** that early versions of GCC stored the two words of a 64-bit
2888** float in the wrong order. And that error has been propagated
2889** ever since. The blame is not necessarily with GCC, though.
2890** GCC might have just copying the problem from a prior compiler.
2891** I am also told that newer versions of GCC that follow a different
2892** ABI get the byte order right.
2893**
2894** Developers using SQLite on an ARM7 should compile and run their
2895** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2896** enabled, some asserts below will ensure that the byte order of
2897** floating point values is correct.
drh60d09a72007-08-30 15:05:08 +00002898**
2899** (2007-08-30) Frank van Vugt has studied this problem closely
2900** and has send his findings to the SQLite developers. Frank
2901** writes that some Linux kernels offer floating point hardware
2902** emulation that uses only 32-bit mantissas instead of a full
2903** 48-bits as required by the IEEE standard. (This is the
2904** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2905** byte swapping becomes very complicated. To avoid problems,
2906** the necessary byte swapping is carried out using a 64-bit integer
2907** rather than a 64-bit float. Frank assures us that the code here
2908** works for him. We, the developers, have no way to independently
2909** verify this, but Frank seems to know what he is talking about
2910** so we trust him.
drh110daac2007-05-04 11:59:31 +00002911*/
2912#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
drh60d09a72007-08-30 15:05:08 +00002913static u64 floatSwap(u64 in){
drh110daac2007-05-04 11:59:31 +00002914 union {
drh60d09a72007-08-30 15:05:08 +00002915 u64 r;
drh110daac2007-05-04 11:59:31 +00002916 u32 i[2];
2917 } u;
2918 u32 t;
2919
2920 u.r = in;
2921 t = u.i[0];
2922 u.i[0] = u.i[1];
2923 u.i[1] = t;
2924 return u.r;
2925}
2926# define swapMixedEndianFloat(X) X = floatSwap(X)
2927#else
2928# define swapMixedEndianFloat(X)
2929#endif
2930
2931/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002932** Write the serialized data blob for the value stored in pMem into
2933** buf. It is assumed that the caller has allocated sufficient space.
2934** Return the number of bytes written.
drhfdf972a2007-05-02 13:30:27 +00002935**
drh038b7bc2013-12-09 23:17:22 +00002936** nBuf is the amount of space left in buf[]. The caller is responsible
2937** for allocating enough space to buf[] to hold the entire field, exclusive
2938** of the pMem->u.nZero bytes for a MEM_Zero value.
drhfdf972a2007-05-02 13:30:27 +00002939**
2940** Return the number of bytes actually written into buf[]. The number
2941** of bytes in the zero-filled tail is included in the return value only
2942** if those bytes were zeroed in buf[].
danielk1977cfcdaef2004-05-12 07:33:33 +00002943*/
drha9ab4812013-12-11 11:00:44 +00002944u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
drh35cd6432009-06-05 14:17:21 +00002945 u32 len;
danielk1977183f9f72004-05-13 05:20:26 +00002946
drh1483e142004-05-21 21:12:42 +00002947 /* Integer and Real */
drhd946db02005-12-29 19:23:06 +00002948 if( serial_type<=7 && serial_type>0 ){
drh1483e142004-05-21 21:12:42 +00002949 u64 v;
drh35cd6432009-06-05 14:17:21 +00002950 u32 i;
drha19b7752004-05-30 21:14:58 +00002951 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00002952 assert( sizeof(v)==sizeof(pMem->u.r) );
2953 memcpy(&v, &pMem->u.r, sizeof(v));
drh60d09a72007-08-30 15:05:08 +00002954 swapMixedEndianFloat(v);
drh1483e142004-05-21 21:12:42 +00002955 }else{
drh3c024d62007-03-30 11:23:45 +00002956 v = pMem->u.i;
danielk1977cfcdaef2004-05-12 07:33:33 +00002957 }
drh1483e142004-05-21 21:12:42 +00002958 len = i = sqlite3VdbeSerialTypeLen(serial_type);
drh3f5b1992014-08-22 13:22:32 +00002959 assert( i>0 );
2960 do{
2961 buf[--i] = (u8)(v&0xFF);
drh1483e142004-05-21 21:12:42 +00002962 v >>= 8;
drh3f5b1992014-08-22 13:22:32 +00002963 }while( i );
drh1483e142004-05-21 21:12:42 +00002964 return len;
danielk1977cfcdaef2004-05-12 07:33:33 +00002965 }
drhd946db02005-12-29 19:23:06 +00002966
danielk1977cfcdaef2004-05-12 07:33:33 +00002967 /* String or blob */
drhd946db02005-12-29 19:23:06 +00002968 if( serial_type>=12 ){
drh8df32842008-12-09 02:51:23 +00002969 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
shane75ac1de2009-06-09 18:58:52 +00002970 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
drhfdf972a2007-05-02 13:30:27 +00002971 len = pMem->n;
drhd946db02005-12-29 19:23:06 +00002972 memcpy(buf, pMem->z, len);
2973 return len;
2974 }
2975
2976 /* NULL or constants 0 or 1 */
2977 return 0;
danielk1977cfcdaef2004-05-12 07:33:33 +00002978}
2979
drhf926d1e2014-03-04 04:04:33 +00002980/* Input "x" is a sequence of unsigned characters that represent a
2981** big-endian integer. Return the equivalent native integer
2982*/
2983#define ONE_BYTE_INT(x) ((i8)(x)[0])
2984#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
2985#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
2986#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drh8932bec2014-08-22 14:56:13 +00002987#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drhf926d1e2014-03-04 04:04:33 +00002988
danielk1977cfcdaef2004-05-12 07:33:33 +00002989/*
2990** Deserialize the data blob pointed to by buf as serial type serial_type
2991** and store the result in pMem. Return the number of bytes read.
drh14a924a2014-08-22 14:34:05 +00002992**
2993** This function is implemented as two separate routines for performance.
2994** The few cases that require local variables are broken out into a separate
2995** routine so that in most cases the overhead of moving the stack pointer
2996** is avoided.
danielk1977cfcdaef2004-05-12 07:33:33 +00002997*/
drh14a924a2014-08-22 14:34:05 +00002998static u32 SQLITE_NOINLINE serialGet(
danielk197793d46752004-05-23 13:30:58 +00002999 const unsigned char *buf, /* Buffer to deserialize from */
drh25aa1b42004-05-28 01:39:01 +00003000 u32 serial_type, /* Serial type to deserialize */
3001 Mem *pMem /* Memory cell to write value into */
danielk1977b1bc9532004-05-22 03:05:33 +00003002){
drh8932bec2014-08-22 14:56:13 +00003003 u64 x = FOUR_BYTE_UINT(buf);
3004 u32 y = FOUR_BYTE_UINT(buf+4);
3005 x = (x<<32) + y;
drh14a924a2014-08-22 14:34:05 +00003006 if( serial_type==6 ){
3007 pMem->u.i = *(i64*)&x;
3008 pMem->flags = MEM_Int;
3009 testcase( pMem->u.i<0 );
3010 }else{
3011#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3012 /* Verify that integers and floating point values use the same
3013 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3014 ** defined that 64-bit floating point values really are mixed
3015 ** endian.
3016 */
3017 static const u64 t1 = ((u64)0x3ff00000)<<32;
3018 static const double r1 = 1.0;
3019 u64 t2 = t1;
3020 swapMixedEndianFloat(t2);
3021 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3022#endif
drh74eaba42014-09-18 17:52:15 +00003023 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
drh14a924a2014-08-22 14:34:05 +00003024 swapMixedEndianFloat(x);
drh74eaba42014-09-18 17:52:15 +00003025 memcpy(&pMem->u.r, &x, sizeof(x));
3026 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
drh14a924a2014-08-22 14:34:05 +00003027 }
3028 return 8;
3029}
danielk1977b1bc9532004-05-22 03:05:33 +00003030u32 sqlite3VdbeSerialGet(
3031 const unsigned char *buf, /* Buffer to deserialize from */
3032 u32 serial_type, /* Serial type to deserialize */
3033 Mem *pMem /* Memory cell to write value into */
3034){
drh3c685822005-05-21 18:32:18 +00003035 switch( serial_type ){
drh3c685822005-05-21 18:32:18 +00003036 case 10: /* Reserved for future use */
3037 case 11: /* Reserved for future use */
3038 case 0: { /* NULL */
3039 pMem->flags = MEM_Null;
3040 break;
3041 }
3042 case 1: { /* 1-byte signed integer */
drhf926d1e2014-03-04 04:04:33 +00003043 pMem->u.i = ONE_BYTE_INT(buf);
drh1483e142004-05-21 21:12:42 +00003044 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003045 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003046 return 1;
drh1483e142004-05-21 21:12:42 +00003047 }
drh3c685822005-05-21 18:32:18 +00003048 case 2: { /* 2-byte signed integer */
drhf926d1e2014-03-04 04:04:33 +00003049 pMem->u.i = TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003050 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003051 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003052 return 2;
3053 }
3054 case 3: { /* 3-byte signed integer */
drhf926d1e2014-03-04 04:04:33 +00003055 pMem->u.i = THREE_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003056 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003057 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003058 return 3;
3059 }
3060 case 4: { /* 4-byte signed integer */
drh8932bec2014-08-22 14:56:13 +00003061 pMem->u.i = FOUR_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003062 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003063 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003064 return 4;
3065 }
3066 case 5: { /* 6-byte signed integer */
drhf926d1e2014-03-04 04:04:33 +00003067 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003068 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003069 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003070 return 6;
3071 }
drh91124b32005-08-18 18:15:05 +00003072 case 6: /* 8-byte signed integer */
drh3c685822005-05-21 18:32:18 +00003073 case 7: { /* IEEE floating point */
drh8932bec2014-08-22 14:56:13 +00003074 /* These use local variables, so do them in a separate routine
3075 ** to avoid having to move the frame pointer in the common case */
drh14a924a2014-08-22 14:34:05 +00003076 return serialGet(buf,serial_type,pMem);
drh3c685822005-05-21 18:32:18 +00003077 }
drhd946db02005-12-29 19:23:06 +00003078 case 8: /* Integer 0 */
3079 case 9: { /* Integer 1 */
drh3c024d62007-03-30 11:23:45 +00003080 pMem->u.i = serial_type-8;
drhd946db02005-12-29 19:23:06 +00003081 pMem->flags = MEM_Int;
3082 return 0;
3083 }
drh3c685822005-05-21 18:32:18 +00003084 default: {
drhc138daf2013-11-19 13:55:34 +00003085 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
drh3c685822005-05-21 18:32:18 +00003086 pMem->z = (char *)buf;
drh14a924a2014-08-22 14:34:05 +00003087 pMem->n = (serial_type-12)/2;
drhc138daf2013-11-19 13:55:34 +00003088 pMem->flags = aFlag[serial_type&1];
drh14a924a2014-08-22 14:34:05 +00003089 return pMem->n;
drh696b32f2004-05-30 01:51:52 +00003090 }
danielk1977cfcdaef2004-05-12 07:33:33 +00003091 }
drh3c685822005-05-21 18:32:18 +00003092 return 0;
danielk1977192ac1d2004-05-10 07:17:30 +00003093}
drh1e968a02008-03-25 00:22:21 +00003094/*
dan03e9cfc2011-09-05 14:20:27 +00003095** This routine is used to allocate sufficient space for an UnpackedRecord
3096** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3097** the first argument is a pointer to KeyInfo structure pKeyInfo.
drh1e968a02008-03-25 00:22:21 +00003098**
dan03e9cfc2011-09-05 14:20:27 +00003099** The space is either allocated using sqlite3DbMallocRaw() or from within
3100** the unaligned buffer passed via the second and third arguments (presumably
3101** stack space). If the former, then *ppFree is set to a pointer that should
3102** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3103** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3104** before returning.
drh1e968a02008-03-25 00:22:21 +00003105**
dan03e9cfc2011-09-05 14:20:27 +00003106** If an OOM error occurs, NULL is returned.
3107*/
3108UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3109 KeyInfo *pKeyInfo, /* Description of the record */
3110 char *pSpace, /* Unaligned space available */
3111 int szSpace, /* Size of pSpace[] in bytes */
3112 char **ppFree /* OUT: Caller should free this pointer */
drh1e968a02008-03-25 00:22:21 +00003113){
dan03e9cfc2011-09-05 14:20:27 +00003114 UnpackedRecord *p; /* Unpacked record to return */
3115 int nOff; /* Increment pSpace by nOff to align it */
3116 int nByte; /* Number of bytes required for *p */
3117
3118 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
shane80167bf2009-04-10 15:42:36 +00003119 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
3120 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
3121 */
3122 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
drh8c5d1522009-04-10 00:56:28 +00003123 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
dan42acb3e2011-09-05 20:16:38 +00003124 if( nByte>szSpace+nOff ){
dan03e9cfc2011-09-05 14:20:27 +00003125 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3126 *ppFree = (char *)p;
dan42acb3e2011-09-05 20:16:38 +00003127 if( !p ) return 0;
drh1e968a02008-03-25 00:22:21 +00003128 }else{
dan42acb3e2011-09-05 20:16:38 +00003129 p = (UnpackedRecord*)&pSpace[nOff];
dan03e9cfc2011-09-05 14:20:27 +00003130 *ppFree = 0;
drh1e968a02008-03-25 00:22:21 +00003131 }
dan42acb3e2011-09-05 20:16:38 +00003132
3133 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
drhe1a022e2012-09-17 17:16:53 +00003134 assert( pKeyInfo->aSortOrder!=0 );
drh1e968a02008-03-25 00:22:21 +00003135 p->pKeyInfo = pKeyInfo;
3136 p->nField = pKeyInfo->nField + 1;
dan03e9cfc2011-09-05 14:20:27 +00003137 return p;
3138}
3139
3140/*
3141** Given the nKey-byte encoding of a record in pKey[], populate the
3142** UnpackedRecord structure indicated by the fourth argument with the
3143** contents of the decoded record.
3144*/
3145void sqlite3VdbeRecordUnpack(
3146 KeyInfo *pKeyInfo, /* Information about the record format */
3147 int nKey, /* Size of the binary record */
3148 const void *pKey, /* The binary record */
3149 UnpackedRecord *p /* Populate this structure before returning. */
3150){
3151 const unsigned char *aKey = (const unsigned char *)pKey;
3152 int d;
3153 u32 idx; /* Offset in aKey[] to read from */
3154 u16 u; /* Unsigned loop counter */
3155 u32 szHdr;
dan42acb3e2011-09-05 20:16:38 +00003156 Mem *pMem = p->aMem;
dan03e9cfc2011-09-05 14:20:27 +00003157
dan1fed5da2014-02-25 21:01:25 +00003158 p->default_rc = 0;
drh8c5d1522009-04-10 00:56:28 +00003159 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
shane3f8d5cf2008-04-24 19:15:09 +00003160 idx = getVarint32(aKey, szHdr);
drh1e968a02008-03-25 00:22:21 +00003161 d = szHdr;
shane0b8d2762008-07-22 05:18:00 +00003162 u = 0;
drh7f4b19f2014-09-16 13:30:05 +00003163 while( idx<szHdr && d<=nKey ){
drh1e968a02008-03-25 00:22:21 +00003164 u32 serial_type;
3165
danielk197700e13612008-11-17 19:18:54 +00003166 idx += getVarint32(&aKey[idx], serial_type);
drh1e968a02008-03-25 00:22:21 +00003167 pMem->enc = pKeyInfo->enc;
3168 pMem->db = pKeyInfo->db;
drhc3f1d5f2011-05-30 23:42:16 +00003169 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
drh17bcb102014-09-18 21:25:33 +00003170 pMem->szMalloc = 0;
drh1e968a02008-03-25 00:22:21 +00003171 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
drhe14006d2008-03-25 17:23:32 +00003172 pMem++;
drh7f4b19f2014-09-16 13:30:05 +00003173 if( (++u)>=p->nField ) break;
drh1e968a02008-03-25 00:22:21 +00003174 }
drh7d10d5a2008-08-20 16:35:10 +00003175 assert( u<=pKeyInfo->nField + 1 );
shane0b8d2762008-07-22 05:18:00 +00003176 p->nField = u;
drh1e968a02008-03-25 00:22:21 +00003177}
3178
dan3833e932014-03-01 19:44:56 +00003179#if SQLITE_DEBUG
dan3b9330f2014-02-27 20:44:18 +00003180/*
dan3833e932014-03-01 19:44:56 +00003181** This function compares two index or table record keys in the same way
3182** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3183** this function deserializes and compares values using the
3184** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3185** in assert() statements to ensure that the optimized code in
3186** sqlite3VdbeRecordCompare() returns results with these two primitives.
drh79211e12014-05-02 17:33:16 +00003187**
3188** Return true if the result of comparison is equivalent to desiredResult.
3189** Return false if there is a disagreement.
dan3b9330f2014-02-27 20:44:18 +00003190*/
dan3833e932014-03-01 19:44:56 +00003191static int vdbeRecordCompareDebug(
dan1fed5da2014-02-25 21:01:25 +00003192 int nKey1, const void *pKey1, /* Left key */
drh79211e12014-05-02 17:33:16 +00003193 const UnpackedRecord *pPKey2, /* Right key */
3194 int desiredResult /* Correct answer */
dan1fed5da2014-02-25 21:01:25 +00003195){
dan3b9330f2014-02-27 20:44:18 +00003196 u32 d1; /* Offset into aKey[] of next data element */
3197 u32 idx1; /* Offset into aKey[] of next header element */
3198 u32 szHdr1; /* Number of bytes in header */
3199 int i = 0;
3200 int rc = 0;
3201 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3202 KeyInfo *pKeyInfo;
3203 Mem mem1;
dan1fed5da2014-02-25 21:01:25 +00003204
dan3b9330f2014-02-27 20:44:18 +00003205 pKeyInfo = pPKey2->pKeyInfo;
drh84de6902014-05-02 18:46:52 +00003206 if( pKeyInfo->db==0 ) return 1;
dan3b9330f2014-02-27 20:44:18 +00003207 mem1.enc = pKeyInfo->enc;
3208 mem1.db = pKeyInfo->db;
3209 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
drh17bcb102014-09-18 21:25:33 +00003210 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003211
dan3b9330f2014-02-27 20:44:18 +00003212 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3213 ** We could initialize it, as shown here, to silence those complaints.
3214 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3215 ** the unnecessary initialization has a measurable negative performance
3216 ** impact, since this routine is a very high runner. And so, we choose
3217 ** to ignore the compiler warnings and leave this variable uninitialized.
3218 */
3219 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3220
3221 idx1 = getVarint32(aKey1, szHdr1);
3222 d1 = szHdr1;
3223 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3224 assert( pKeyInfo->aSortOrder!=0 );
3225 assert( pKeyInfo->nField>0 );
3226 assert( idx1<=szHdr1 || CORRUPT_DB );
3227 do{
3228 u32 serial_type1;
dan1fed5da2014-02-25 21:01:25 +00003229
dan3b9330f2014-02-27 20:44:18 +00003230 /* Read the serial types for the next element in each key. */
3231 idx1 += getVarint32( aKey1+idx1, serial_type1 );
dan1fed5da2014-02-25 21:01:25 +00003232
dan3b9330f2014-02-27 20:44:18 +00003233 /* Verify that there is enough key space remaining to avoid
3234 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3235 ** always be greater than or equal to the amount of required key space.
3236 ** Use that approximation to avoid the more expensive call to
3237 ** sqlite3VdbeSerialTypeLen() in the common case.
3238 */
3239 if( d1+serial_type1+2>(u32)nKey1
3240 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3241 ){
3242 break;
dan1fed5da2014-02-25 21:01:25 +00003243 }
dan1fed5da2014-02-25 21:01:25 +00003244
dan3b9330f2014-02-27 20:44:18 +00003245 /* Extract the values to be compared.
3246 */
3247 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
dan1fed5da2014-02-25 21:01:25 +00003248
dan3b9330f2014-02-27 20:44:18 +00003249 /* Do the comparison
3250 */
3251 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3252 if( rc!=0 ){
drh17bcb102014-09-18 21:25:33 +00003253 assert( mem1.szMalloc==0 ); /* See comment below */
dan3b9330f2014-02-27 20:44:18 +00003254 if( pKeyInfo->aSortOrder[i] ){
3255 rc = -rc; /* Invert the result for DESC sort order. */
dan1fed5da2014-02-25 21:01:25 +00003256 }
drh79211e12014-05-02 17:33:16 +00003257 goto debugCompareEnd;
dan1fed5da2014-02-25 21:01:25 +00003258 }
dan3b9330f2014-02-27 20:44:18 +00003259 i++;
3260 }while( idx1<szHdr1 && i<pPKey2->nField );
dan1fed5da2014-02-25 21:01:25 +00003261
dan3b9330f2014-02-27 20:44:18 +00003262 /* No memory allocation is ever used on mem1. Prove this using
3263 ** the following assert(). If the assert() fails, it indicates a
3264 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3265 */
drh17bcb102014-09-18 21:25:33 +00003266 assert( mem1.szMalloc==0 );
dan3b9330f2014-02-27 20:44:18 +00003267
3268 /* rc==0 here means that one of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003269 ** all the fields up to that point were equal. Return the default_rc
dan3b9330f2014-02-27 20:44:18 +00003270 ** value. */
drh79211e12014-05-02 17:33:16 +00003271 rc = pPKey2->default_rc;
3272
3273debugCompareEnd:
3274 if( desiredResult==0 && rc==0 ) return 1;
3275 if( desiredResult<0 && rc<0 ) return 1;
3276 if( desiredResult>0 && rc>0 ) return 1;
3277 if( CORRUPT_DB ) return 1;
3278 if( pKeyInfo->db->mallocFailed ) return 1;
3279 return 0;
dan1fed5da2014-02-25 21:01:25 +00003280}
dan3833e932014-03-01 19:44:56 +00003281#endif
dan1fed5da2014-02-25 21:01:25 +00003282
dan3833e932014-03-01 19:44:56 +00003283/*
3284** Both *pMem1 and *pMem2 contain string values. Compare the two values
3285** using the collation sequence pColl. As usual, return a negative , zero
3286** or positive value if *pMem1 is less than, equal to or greater than
3287** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3288*/
dan1fed5da2014-02-25 21:01:25 +00003289static int vdbeCompareMemString(
dan3833e932014-03-01 19:44:56 +00003290 const Mem *pMem1,
3291 const Mem *pMem2,
dan38fdead2014-04-01 10:19:02 +00003292 const CollSeq *pColl,
3293 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
dan1fed5da2014-02-25 21:01:25 +00003294){
3295 if( pMem1->enc==pColl->enc ){
3296 /* The strings are already in the correct encoding. Call the
3297 ** comparison function directly */
3298 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3299 }else{
3300 int rc;
3301 const void *v1, *v2;
3302 int n1, n2;
3303 Mem c1;
3304 Mem c2;
drh17bcb102014-09-18 21:25:33 +00003305 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3306 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
dan1fed5da2014-02-25 21:01:25 +00003307 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3308 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3309 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3310 n1 = v1==0 ? 0 : c1.n;
3311 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3312 n2 = v2==0 ? 0 : c2.n;
3313 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
3314 sqlite3VdbeMemRelease(&c1);
3315 sqlite3VdbeMemRelease(&c2);
dan38fdead2014-04-01 10:19:02 +00003316 if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
dan1fed5da2014-02-25 21:01:25 +00003317 return rc;
3318 }
3319}
3320
3321/*
drh982ff722014-09-16 03:24:43 +00003322** Compare two blobs. Return negative, zero, or positive if the first
3323** is less than, equal to, or greater than the second, respectively.
3324** If one blob is a prefix of the other, then the shorter is the lessor.
3325*/
3326static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3327 int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
3328 if( c ) return c;
3329 return pB1->n - pB2->n;
3330}
3331
3332
3333/*
dan1fed5da2014-02-25 21:01:25 +00003334** Compare the values contained by the two memory cells, returning
3335** negative, zero or positive if pMem1 is less than, equal to, or greater
3336** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3337** and reals) sorted numerically, followed by text ordered by the collating
3338** sequence pColl and finally blob's ordered by memcmp().
3339**
3340** Two NULL values are considered equal by this function.
3341*/
3342int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
dan1fed5da2014-02-25 21:01:25 +00003343 int f1, f2;
3344 int combined_flags;
3345
3346 f1 = pMem1->flags;
3347 f2 = pMem2->flags;
3348 combined_flags = f1|f2;
3349 assert( (combined_flags & MEM_RowSet)==0 );
3350
3351 /* If one value is NULL, it is less than the other. If both values
3352 ** are NULL, return 0.
3353 */
3354 if( combined_flags&MEM_Null ){
3355 return (f2&MEM_Null) - (f1&MEM_Null);
3356 }
3357
3358 /* If one value is a number and the other is not, the number is less.
3359 ** If both are numbers, compare as reals if one is a real, or as integers
3360 ** if both values are integers.
3361 */
3362 if( combined_flags&(MEM_Int|MEM_Real) ){
3363 double r1, r2;
3364 if( (f1 & f2 & MEM_Int)!=0 ){
3365 if( pMem1->u.i < pMem2->u.i ) return -1;
3366 if( pMem1->u.i > pMem2->u.i ) return 1;
3367 return 0;
3368 }
3369 if( (f1&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003370 r1 = pMem1->u.r;
dan1fed5da2014-02-25 21:01:25 +00003371 }else if( (f1&MEM_Int)!=0 ){
3372 r1 = (double)pMem1->u.i;
3373 }else{
3374 return 1;
3375 }
3376 if( (f2&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003377 r2 = pMem2->u.r;
dan1fed5da2014-02-25 21:01:25 +00003378 }else if( (f2&MEM_Int)!=0 ){
3379 r2 = (double)pMem2->u.i;
3380 }else{
3381 return -1;
3382 }
3383 if( r1<r2 ) return -1;
3384 if( r1>r2 ) return 1;
3385 return 0;
3386 }
3387
3388 /* If one value is a string and the other is a blob, the string is less.
3389 ** If both are strings, compare using the collating functions.
3390 */
3391 if( combined_flags&MEM_Str ){
3392 if( (f1 & MEM_Str)==0 ){
3393 return 1;
3394 }
3395 if( (f2 & MEM_Str)==0 ){
3396 return -1;
3397 }
3398
3399 assert( pMem1->enc==pMem2->enc );
3400 assert( pMem1->enc==SQLITE_UTF8 ||
3401 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3402
3403 /* The collation sequence must be defined at this point, even if
3404 ** the user deletes the collation sequence after the vdbe program is
3405 ** compiled (this was not always the case).
3406 */
3407 assert( !pColl || pColl->xCmp );
3408
3409 if( pColl ){
dan38fdead2014-04-01 10:19:02 +00003410 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
dan1fed5da2014-02-25 21:01:25 +00003411 }
3412 /* If a NULL pointer was passed as the collate function, fall through
3413 ** to the blob case and use memcmp(). */
3414 }
3415
3416 /* Both values must be blobs. Compare using memcmp(). */
drh982ff722014-09-16 03:24:43 +00003417 return sqlite3BlobCompare(pMem1, pMem2);
dan1fed5da2014-02-25 21:01:25 +00003418}
3419
3420
dan3833e932014-03-01 19:44:56 +00003421/*
3422** The first argument passed to this function is a serial-type that
3423** corresponds to an integer - all values between 1 and 9 inclusive
3424** except 7. The second points to a buffer containing an integer value
3425** serialized according to serial_type. This function deserializes
3426** and returns the value.
3427*/
dan3b9330f2014-02-27 20:44:18 +00003428static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
drhf926d1e2014-03-04 04:04:33 +00003429 u32 y;
dan3833e932014-03-01 19:44:56 +00003430 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
dan3b9330f2014-02-27 20:44:18 +00003431 switch( serial_type ){
dan3833e932014-03-01 19:44:56 +00003432 case 0:
dan3b9330f2014-02-27 20:44:18 +00003433 case 1:
drhb6e8fd12014-03-06 01:56:33 +00003434 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003435 return ONE_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003436 case 2:
drhb6e8fd12014-03-06 01:56:33 +00003437 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003438 return TWO_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003439 case 3:
drhb6e8fd12014-03-06 01:56:33 +00003440 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003441 return THREE_BYTE_INT(aKey);
3442 case 4: {
drhb6e8fd12014-03-06 01:56:33 +00003443 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003444 y = FOUR_BYTE_UINT(aKey);
3445 return (i64)*(int*)&y;
3446 }
dan3b9330f2014-02-27 20:44:18 +00003447 case 5: {
drhb6e8fd12014-03-06 01:56:33 +00003448 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003449 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhaf5b2af2013-08-05 15:32:09 +00003450 }
dan3b9330f2014-02-27 20:44:18 +00003451 case 6: {
drhf926d1e2014-03-04 04:04:33 +00003452 u64 x = FOUR_BYTE_UINT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003453 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003454 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3455 return (i64)*(i64*)&x;
drh1e968a02008-03-25 00:22:21 +00003456 }
dan3b9330f2014-02-27 20:44:18 +00003457 }
drh407414c2009-07-14 14:15:27 +00003458
dan3b9330f2014-02-27 20:44:18 +00003459 return (serial_type - 8);
drh1e968a02008-03-25 00:22:21 +00003460}
danielk1977eb015e02004-05-18 01:31:14 +00003461
dan3833e932014-03-01 19:44:56 +00003462/*
3463** This function compares the two table rows or index records
3464** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
3465** or positive integer if key1 is less than, equal to or
3466** greater than key2. The {nKey1, pKey1} key must be a blob
peter.d.reid60ec9142014-09-06 16:39:46 +00003467** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
dan3833e932014-03-01 19:44:56 +00003468** key must be a parsed key such as obtained from
3469** sqlite3VdbeParseRecord.
3470**
3471** If argument bSkip is non-zero, it is assumed that the caller has already
3472** determined that the first fields of the keys are equal.
3473**
3474** Key1 and Key2 do not have to contain the same number of fields. If all
3475** fields that appear in both keys are equal, then pPKey2->default_rc is
3476** returned.
drha1f7c0a2014-03-28 03:12:48 +00003477**
dan38fdead2014-04-01 10:19:02 +00003478** If database corruption is discovered, set pPKey2->errCode to
3479** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3480** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3481** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
dan3833e932014-03-01 19:44:56 +00003482*/
drh75179de2014-09-16 14:37:35 +00003483static int vdbeRecordCompareWithSkip(
dan3833e932014-03-01 19:44:56 +00003484 int nKey1, const void *pKey1, /* Left key */
drha1f7c0a2014-03-28 03:12:48 +00003485 UnpackedRecord *pPKey2, /* Right key */
dan3833e932014-03-01 19:44:56 +00003486 int bSkip /* If true, skip the first field */
dan1fed5da2014-02-25 21:01:25 +00003487){
dan3833e932014-03-01 19:44:56 +00003488 u32 d1; /* Offset into aKey[] of next data element */
3489 int i; /* Index of next field to compare */
mistachkinffe6bc22014-03-04 11:16:20 +00003490 u32 szHdr1; /* Size of record header in bytes */
dan3833e932014-03-01 19:44:56 +00003491 u32 idx1; /* Offset of first type in header */
3492 int rc = 0; /* Return value */
3493 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
dan1fed5da2014-02-25 21:01:25 +00003494 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3495 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3496 Mem mem1;
3497
dan3833e932014-03-01 19:44:56 +00003498 /* If bSkip is true, then the caller has already determined that the first
3499 ** two elements in the keys are equal. Fix the various stack variables so
dan3b9330f2014-02-27 20:44:18 +00003500 ** that this routine begins comparing at the second field. */
dan3833e932014-03-01 19:44:56 +00003501 if( bSkip ){
dan3b9330f2014-02-27 20:44:18 +00003502 u32 s1;
dan3b9330f2014-02-27 20:44:18 +00003503 idx1 = 1 + getVarint32(&aKey1[1], s1);
dan3833e932014-03-01 19:44:56 +00003504 szHdr1 = aKey1[0];
3505 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
dan3b9330f2014-02-27 20:44:18 +00003506 i = 1;
3507 pRhs++;
dan3833e932014-03-01 19:44:56 +00003508 }else{
3509 idx1 = getVarint32(aKey1, szHdr1);
3510 d1 = szHdr1;
drha1f7c0a2014-03-28 03:12:48 +00003511 if( d1>(unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003512 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003513 return 0; /* Corruption */
3514 }
dan3833e932014-03-01 19:44:56 +00003515 i = 0;
dan3b9330f2014-02-27 20:44:18 +00003516 }
3517
drh17bcb102014-09-18 21:25:33 +00003518 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003519 assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
3520 || CORRUPT_DB );
3521 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
3522 assert( pPKey2->pKeyInfo->nField>0 );
3523 assert( idx1<=szHdr1 || CORRUPT_DB );
3524 do{
dan1fed5da2014-02-25 21:01:25 +00003525 u32 serial_type;
3526
3527 /* RHS is an integer */
3528 if( pRhs->flags & MEM_Int ){
3529 serial_type = aKey1[idx1];
drhb6e8fd12014-03-06 01:56:33 +00003530 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003531 if( serial_type>=12 ){
3532 rc = +1;
3533 }else if( serial_type==0 ){
3534 rc = -1;
dan3b9330f2014-02-27 20:44:18 +00003535 }else if( serial_type==7 ){
3536 double rhs = (double)pRhs->u.i;
dan1fed5da2014-02-25 21:01:25 +00003537 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
drh74eaba42014-09-18 17:52:15 +00003538 if( mem1.u.r<rhs ){
dan3b9330f2014-02-27 20:44:18 +00003539 rc = -1;
drh74eaba42014-09-18 17:52:15 +00003540 }else if( mem1.u.r>rhs ){
dan3b9330f2014-02-27 20:44:18 +00003541 rc = +1;
3542 }
3543 }else{
3544 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
3545 i64 rhs = pRhs->u.i;
3546 if( lhs<rhs ){
3547 rc = -1;
3548 }else if( lhs>rhs ){
3549 rc = +1;
dan1fed5da2014-02-25 21:01:25 +00003550 }
3551 }
3552 }
3553
3554 /* RHS is real */
3555 else if( pRhs->flags & MEM_Real ){
3556 serial_type = aKey1[idx1];
3557 if( serial_type>=12 ){
3558 rc = +1;
3559 }else if( serial_type==0 ){
3560 rc = -1;
3561 }else{
drh74eaba42014-09-18 17:52:15 +00003562 double rhs = pRhs->u.r;
dan1fed5da2014-02-25 21:01:25 +00003563 double lhs;
3564 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
3565 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00003566 lhs = mem1.u.r;
dan1fed5da2014-02-25 21:01:25 +00003567 }else{
drh295aedf2014-03-03 18:25:24 +00003568 lhs = (double)mem1.u.i;
dan1fed5da2014-02-25 21:01:25 +00003569 }
3570 if( lhs<rhs ){
3571 rc = -1;
3572 }else if( lhs>rhs ){
3573 rc = +1;
3574 }
3575 }
3576 }
3577
3578 /* RHS is a string */
3579 else if( pRhs->flags & MEM_Str ){
3580 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003581 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003582 if( serial_type<12 ){
3583 rc = -1;
3584 }else if( !(serial_type & 0x01) ){
3585 rc = +1;
3586 }else{
3587 mem1.n = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003588 testcase( (d1+mem1.n)==(unsigned)nKey1 );
3589 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003590 if( (d1+mem1.n) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003591 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003592 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003593 }else if( pKeyInfo->aColl[i] ){
3594 mem1.enc = pKeyInfo->enc;
3595 mem1.db = pKeyInfo->db;
3596 mem1.flags = MEM_Str;
drhfcb44a82014-03-03 15:13:27 +00003597 mem1.z = (char*)&aKey1[d1];
dan38fdead2014-04-01 10:19:02 +00003598 rc = vdbeCompareMemString(
3599 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
3600 );
dan1fed5da2014-02-25 21:01:25 +00003601 }else{
3602 int nCmp = MIN(mem1.n, pRhs->n);
3603 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3604 if( rc==0 ) rc = mem1.n - pRhs->n;
3605 }
3606 }
3607 }
3608
3609 /* RHS is a blob */
3610 else if( pRhs->flags & MEM_Blob ){
3611 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003612 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003613 if( serial_type<12 || (serial_type & 0x01) ){
3614 rc = -1;
3615 }else{
3616 int nStr = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003617 testcase( (d1+nStr)==(unsigned)nKey1 );
3618 testcase( (d1+nStr+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003619 if( (d1+nStr) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003620 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003621 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003622 }else{
3623 int nCmp = MIN(nStr, pRhs->n);
3624 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3625 if( rc==0 ) rc = nStr - pRhs->n;
3626 }
3627 }
3628 }
3629
3630 /* RHS is null */
3631 else{
3632 serial_type = aKey1[idx1];
3633 rc = (serial_type!=0);
3634 }
3635
3636 if( rc!=0 ){
dan1fed5da2014-02-25 21:01:25 +00003637 if( pKeyInfo->aSortOrder[i] ){
3638 rc = -rc;
dan1fed5da2014-02-25 21:01:25 +00003639 }
drh79211e12014-05-02 17:33:16 +00003640 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
drh17bcb102014-09-18 21:25:33 +00003641 assert( mem1.szMalloc==0 ); /* See comment below */
dan1fed5da2014-02-25 21:01:25 +00003642 return rc;
3643 }
3644
3645 i++;
dan3b9330f2014-02-27 20:44:18 +00003646 pRhs++;
dan1fed5da2014-02-25 21:01:25 +00003647 d1 += sqlite3VdbeSerialTypeLen(serial_type);
3648 idx1 += sqlite3VarintLen(serial_type);
drh295aedf2014-03-03 18:25:24 +00003649 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
dan1fed5da2014-02-25 21:01:25 +00003650
3651 /* No memory allocation is ever used on mem1. Prove this using
3652 ** the following assert(). If the assert() fails, it indicates a
dan3833e932014-03-01 19:44:56 +00003653 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
drh17bcb102014-09-18 21:25:33 +00003654 assert( mem1.szMalloc==0 );
dan1fed5da2014-02-25 21:01:25 +00003655
3656 /* rc==0 here means that one or both of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003657 ** all the fields up to that point were equal. Return the default_rc
dan1fed5da2014-02-25 21:01:25 +00003658 ** value. */
dan3833e932014-03-01 19:44:56 +00003659 assert( CORRUPT_DB
drh66141812014-06-30 20:25:03 +00003660 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
dan6696ba32014-06-28 19:06:49 +00003661 || pKeyInfo->db->mallocFailed
dan3833e932014-03-01 19:44:56 +00003662 );
dan1fed5da2014-02-25 21:01:25 +00003663 return pPKey2->default_rc;
3664}
drh75179de2014-09-16 14:37:35 +00003665int sqlite3VdbeRecordCompare(
3666 int nKey1, const void *pKey1, /* Left key */
3667 UnpackedRecord *pPKey2 /* Right key */
3668){
3669 return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
3670}
3671
dan1fed5da2014-02-25 21:01:25 +00003672
dan3833e932014-03-01 19:44:56 +00003673/*
3674** This function is an optimized version of sqlite3VdbeRecordCompare()
3675** that (a) the first field of pPKey2 is an integer, and (b) the
3676** size-of-header varint at the start of (pKey1/nKey1) fits in a single
3677** byte (i.e. is less than 128).
drhe2ac5062014-03-26 12:02:38 +00003678**
3679** To avoid concerns about buffer overreads, this routine is only used
3680** on schemas where the maximum valid header size is 63 bytes or less.
dan3833e932014-03-01 19:44:56 +00003681*/
dan3b9330f2014-02-27 20:44:18 +00003682static int vdbeRecordCompareInt(
3683 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003684 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003685){
dan9b8afef2014-03-03 20:48:50 +00003686 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
dan3b9330f2014-02-27 20:44:18 +00003687 int serial_type = ((const u8*)pKey1)[1];
3688 int res;
drhf926d1e2014-03-04 04:04:33 +00003689 u32 y;
3690 u64 x;
dan3b9330f2014-02-27 20:44:18 +00003691 i64 v = pPKey2->aMem[0].u.i;
3692 i64 lhs;
3693
drhe2ac5062014-03-26 12:02:38 +00003694 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
dan3833e932014-03-01 19:44:56 +00003695 switch( serial_type ){
drhf926d1e2014-03-04 04:04:33 +00003696 case 1: { /* 1-byte signed integer */
3697 lhs = ONE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003698 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003699 break;
3700 }
drhf926d1e2014-03-04 04:04:33 +00003701 case 2: { /* 2-byte signed integer */
3702 lhs = TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003703 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003704 break;
3705 }
3706 case 3: { /* 3-byte signed integer */
3707 lhs = THREE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003708 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003709 break;
3710 }
3711 case 4: { /* 4-byte signed integer */
3712 y = FOUR_BYTE_UINT(aKey);
3713 lhs = (i64)*(int*)&y;
drhb6e8fd12014-03-06 01:56:33 +00003714 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003715 break;
3716 }
3717 case 5: { /* 6-byte signed integer */
3718 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003719 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003720 break;
3721 }
3722 case 6: { /* 8-byte signed integer */
3723 x = FOUR_BYTE_UINT(aKey);
3724 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3725 lhs = *(i64*)&x;
drhb6e8fd12014-03-06 01:56:33 +00003726 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003727 break;
3728 }
dan3b9330f2014-02-27 20:44:18 +00003729 case 8:
3730 lhs = 0;
3731 break;
dan3b9330f2014-02-27 20:44:18 +00003732 case 9:
3733 lhs = 1;
3734 break;
3735
dan063d4a02014-02-28 09:48:30 +00003736 /* This case could be removed without changing the results of running
3737 ** this code. Including it causes gcc to generate a faster switch
3738 ** statement (since the range of switch targets now starts at zero and
dan597515d2014-02-28 18:39:51 +00003739 ** is contiguous) but does not cause any duplicate code to be generated
dan063d4a02014-02-28 09:48:30 +00003740 ** (as gcc is clever enough to combine the two like cases). Other
3741 ** compilers might be similar. */
3742 case 0: case 7:
drh75179de2014-09-16 14:37:35 +00003743 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan063d4a02014-02-28 09:48:30 +00003744
dan3b9330f2014-02-27 20:44:18 +00003745 default:
drh75179de2014-09-16 14:37:35 +00003746 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan3b9330f2014-02-27 20:44:18 +00003747 }
3748
3749 if( v>lhs ){
3750 res = pPKey2->r1;
3751 }else if( v<lhs ){
3752 res = pPKey2->r2;
3753 }else if( pPKey2->nField>1 ){
dan063d4a02014-02-28 09:48:30 +00003754 /* The first fields of the two keys are equal. Compare the trailing
3755 ** fields. */
drh75179de2014-09-16 14:37:35 +00003756 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003757 }else{
dan063d4a02014-02-28 09:48:30 +00003758 /* The first fields of the two keys are equal and there are no trailing
3759 ** fields. Return pPKey2->default_rc in this case. */
dan3b9330f2014-02-27 20:44:18 +00003760 res = pPKey2->default_rc;
3761 }
3762
drh79211e12014-05-02 17:33:16 +00003763 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
dan3b9330f2014-02-27 20:44:18 +00003764 return res;
3765}
3766
dan3833e932014-03-01 19:44:56 +00003767/*
3768** This function is an optimized version of sqlite3VdbeRecordCompare()
3769** that (a) the first field of pPKey2 is a string, that (b) the first field
3770** uses the collation sequence BINARY and (c) that the size-of-header varint
3771** at the start of (pKey1/nKey1) fits in a single byte.
3772*/
dan3b9330f2014-02-27 20:44:18 +00003773static int vdbeRecordCompareString(
3774 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003775 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003776){
3777 const u8 *aKey1 = (const u8*)pKey1;
3778 int serial_type;
3779 int res;
3780
3781 getVarint32(&aKey1[1], serial_type);
dan3b9330f2014-02-27 20:44:18 +00003782 if( serial_type<12 ){
3783 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
3784 }else if( !(serial_type & 0x01) ){
3785 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
3786 }else{
3787 int nCmp;
3788 int nStr;
dan3833e932014-03-01 19:44:56 +00003789 int szHdr = aKey1[0];
dan3b9330f2014-02-27 20:44:18 +00003790
3791 nStr = (serial_type-12) / 2;
drha1f7c0a2014-03-28 03:12:48 +00003792 if( (szHdr + nStr) > nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003793 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003794 return 0; /* Corruption */
3795 }
dan3b9330f2014-02-27 20:44:18 +00003796 nCmp = MIN( pPKey2->aMem[0].n, nStr );
dan3833e932014-03-01 19:44:56 +00003797 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
dan3b9330f2014-02-27 20:44:18 +00003798
3799 if( res==0 ){
3800 res = nStr - pPKey2->aMem[0].n;
3801 if( res==0 ){
3802 if( pPKey2->nField>1 ){
drh75179de2014-09-16 14:37:35 +00003803 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003804 }else{
3805 res = pPKey2->default_rc;
3806 }
3807 }else if( res>0 ){
3808 res = pPKey2->r2;
3809 }else{
3810 res = pPKey2->r1;
3811 }
3812 }else if( res>0 ){
3813 res = pPKey2->r2;
3814 }else{
3815 res = pPKey2->r1;
3816 }
3817 }
3818
drh66141812014-06-30 20:25:03 +00003819 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
dan3b9330f2014-02-27 20:44:18 +00003820 || CORRUPT_DB
dan6696ba32014-06-28 19:06:49 +00003821 || pPKey2->pKeyInfo->db->mallocFailed
dan3b9330f2014-02-27 20:44:18 +00003822 );
3823 return res;
3824}
3825
dan3833e932014-03-01 19:44:56 +00003826/*
3827** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
3828** suitable for comparing serialized records to the unpacked record passed
3829** as the only argument.
3830*/
dan1fed5da2014-02-25 21:01:25 +00003831RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
dan9b8afef2014-03-03 20:48:50 +00003832 /* varintRecordCompareInt() and varintRecordCompareString() both assume
3833 ** that the size-of-header varint that occurs at the start of each record
3834 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
3835 ** also assumes that it is safe to overread a buffer by at least the
3836 ** maximum possible legal header size plus 8 bytes. Because there is
3837 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
3838 ** buffer passed to varintRecordCompareInt() this makes it convenient to
3839 ** limit the size of the header to 64 bytes in cases where the first field
3840 ** is an integer.
3841 **
3842 ** The easiest way to enforce this limit is to consider only records with
3843 ** 13 fields or less. If the first field is an integer, the maximum legal
3844 ** header size is (12*5 + 1 + 1) bytes. */
3845 if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
dan1fed5da2014-02-25 21:01:25 +00003846 int flags = p->aMem[0].flags;
dan3b9330f2014-02-27 20:44:18 +00003847 if( p->pKeyInfo->aSortOrder[0] ){
3848 p->r1 = 1;
3849 p->r2 = -1;
3850 }else{
3851 p->r1 = -1;
3852 p->r2 = 1;
3853 }
dan1fed5da2014-02-25 21:01:25 +00003854 if( (flags & MEM_Int) ){
3855 return vdbeRecordCompareInt;
dan3b9330f2014-02-27 20:44:18 +00003856 }
drhb6e8fd12014-03-06 01:56:33 +00003857 testcase( flags & MEM_Real );
3858 testcase( flags & MEM_Null );
3859 testcase( flags & MEM_Blob );
3860 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
3861 assert( flags & MEM_Str );
dan1fed5da2014-02-25 21:01:25 +00003862 return vdbeRecordCompareString;
3863 }
3864 }
dan3b9330f2014-02-27 20:44:18 +00003865
dan3833e932014-03-01 19:44:56 +00003866 return sqlite3VdbeRecordCompare;
dan3b9330f2014-02-27 20:44:18 +00003867}
dan1fed5da2014-02-25 21:01:25 +00003868
danielk1977eb015e02004-05-18 01:31:14 +00003869/*
drh7a224de2004-06-02 01:22:02 +00003870** pCur points at an index entry created using the OP_MakeRecord opcode.
3871** Read the rowid (the last field in the record) and store it in *rowid.
3872** Return SQLITE_OK if everything works, or an error code otherwise.
drh88a003e2008-12-11 16:17:03 +00003873**
3874** pCur might be pointing to text obtained from a corrupt database file.
3875** So the content cannot be trusted. Do appropriate checks on the content.
danielk1977183f9f72004-05-13 05:20:26 +00003876*/
drhd3b74202014-09-17 16:41:15 +00003877int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
drh61fc5952007-04-01 23:49:51 +00003878 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003879 int rc;
drhd5788202004-05-28 08:21:05 +00003880 u32 szHdr; /* Size of the header */
3881 u32 typeRowid; /* Serial type of the rowid */
3882 u32 lenRowid; /* Size of the rowid */
3883 Mem m, v;
danielk1977183f9f72004-05-13 05:20:26 +00003884
drh88a003e2008-12-11 16:17:03 +00003885 /* Get the size of the index entry. Only indices entries of less
drh7b746032009-06-26 12:15:22 +00003886 ** than 2GiB are support - anything large must be database corruption.
3887 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
drhc27ae612009-07-14 18:35:44 +00003888 ** this code can safely assume that nCellKey is 32-bits
3889 */
drhea8ffdf2009-07-22 00:35:23 +00003890 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003891 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003892 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh7b746032009-06-26 12:15:22 +00003893 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
drh88a003e2008-12-11 16:17:03 +00003894
3895 /* Read in the complete content of the index entry */
drhd3b74202014-09-17 16:41:15 +00003896 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00003897 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
drhd5788202004-05-28 08:21:05 +00003898 if( rc ){
danielk1977183f9f72004-05-13 05:20:26 +00003899 return rc;
3900 }
drh88a003e2008-12-11 16:17:03 +00003901
3902 /* The index entry must begin with a header size */
shane3f8d5cf2008-04-24 19:15:09 +00003903 (void)getVarint32((u8*)m.z, szHdr);
drh7b746032009-06-26 12:15:22 +00003904 testcase( szHdr==3 );
drh88a003e2008-12-11 16:17:03 +00003905 testcase( szHdr==m.n );
drh7b746032009-06-26 12:15:22 +00003906 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
drh88a003e2008-12-11 16:17:03 +00003907 goto idx_rowid_corruption;
3908 }
3909
3910 /* The last field of the index should be an integer - the ROWID.
3911 ** Verify that the last entry really is an integer. */
shane3f8d5cf2008-04-24 19:15:09 +00003912 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
drh88a003e2008-12-11 16:17:03 +00003913 testcase( typeRowid==1 );
3914 testcase( typeRowid==2 );
3915 testcase( typeRowid==3 );
3916 testcase( typeRowid==4 );
3917 testcase( typeRowid==5 );
3918 testcase( typeRowid==6 );
3919 testcase( typeRowid==8 );
3920 testcase( typeRowid==9 );
3921 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
3922 goto idx_rowid_corruption;
3923 }
drhd5788202004-05-28 08:21:05 +00003924 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
drheeb844a2009-08-08 18:01:07 +00003925 testcase( (u32)m.n==szHdr+lenRowid );
3926 if( unlikely((u32)m.n<szHdr+lenRowid) ){
drh88a003e2008-12-11 16:17:03 +00003927 goto idx_rowid_corruption;
3928 }
3929
3930 /* Fetch the integer off the end of the index record */
drh2646da72005-12-09 20:02:05 +00003931 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
drh3c024d62007-03-30 11:23:45 +00003932 *rowid = v.u.i;
danielk1977d8123362004-06-12 09:25:12 +00003933 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00003934 return SQLITE_OK;
drh88a003e2008-12-11 16:17:03 +00003935
3936 /* Jump here if database corruption is detected after m has been
3937 ** allocated. Free the m object and return SQLITE_CORRUPT. */
3938idx_rowid_corruption:
drh17bcb102014-09-18 21:25:33 +00003939 testcase( m.szMalloc!=0 );
drh88a003e2008-12-11 16:17:03 +00003940 sqlite3VdbeMemRelease(&m);
3941 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00003942}
3943
drh7cf6e4d2004-05-19 14:56:55 +00003944/*
drh5f82e3c2009-07-06 00:44:08 +00003945** Compare the key of the index entry that cursor pC is pointing to against
3946** the key string in pUnpacked. Write into *pRes a number
drh7cf6e4d2004-05-19 14:56:55 +00003947** that is negative, zero, or positive if pC is less than, equal to,
drh5f82e3c2009-07-06 00:44:08 +00003948** or greater than pUnpacked. Return SQLITE_OK on success.
drhd3d39e92004-05-20 22:16:29 +00003949**
drh5f82e3c2009-07-06 00:44:08 +00003950** pUnpacked is either created without a rowid or is truncated so that it
drhd5788202004-05-28 08:21:05 +00003951** omits the rowid at the end. The rowid at the end of the index entry
drhec1fc802008-08-13 14:07:40 +00003952** is ignored as well. Hence, this routine only compares the prefixes
3953** of the keys prior to the final rowid, not the entire key.
drh7cf6e4d2004-05-19 14:56:55 +00003954*/
danielk1977183f9f72004-05-13 05:20:26 +00003955int sqlite3VdbeIdxKeyCompare(
drhd3b74202014-09-17 16:41:15 +00003956 sqlite3 *db, /* Database connection */
drh295aedf2014-03-03 18:25:24 +00003957 VdbeCursor *pC, /* The cursor to compare against */
drha1f7c0a2014-03-28 03:12:48 +00003958 UnpackedRecord *pUnpacked, /* Unpacked version of key */
drh295aedf2014-03-03 18:25:24 +00003959 int *res /* Write the comparison result here */
danielk1977183f9f72004-05-13 05:20:26 +00003960){
drh61fc5952007-04-01 23:49:51 +00003961 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003962 int rc;
danielk19773d1bfea2004-05-14 11:00:53 +00003963 BtCursor *pCur = pC->pCursor;
drhd5788202004-05-28 08:21:05 +00003964 Mem m;
danielk1977183f9f72004-05-13 05:20:26 +00003965
drhea8ffdf2009-07-22 00:35:23 +00003966 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003967 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003968 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh56689692014-03-03 19:29:28 +00003969 /* nCellKey will always be between 0 and 0xffffffff because of the way
drh407414c2009-07-14 14:15:27 +00003970 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
drhc27ae612009-07-14 18:35:44 +00003971 if( nCellKey<=0 || nCellKey>0x7fffffff ){
danielk1977183f9f72004-05-13 05:20:26 +00003972 *res = 0;
drh9978c972010-02-23 17:36:32 +00003973 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00003974 }
drhd3b74202014-09-17 16:41:15 +00003975 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00003976 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
drhec1fc802008-08-13 14:07:40 +00003977 if( rc ){
drhd5788202004-05-28 08:21:05 +00003978 return rc;
danielk1977183f9f72004-05-13 05:20:26 +00003979 }
drh75179de2014-09-16 14:37:35 +00003980 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
danielk1977d8123362004-06-12 09:25:12 +00003981 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00003982 return SQLITE_OK;
3983}
danielk1977b28af712004-06-21 06:50:26 +00003984
3985/*
3986** This routine sets the value to be returned by subsequent calls to
3987** sqlite3_changes() on the database handle 'db'.
3988*/
3989void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
drhb21c8cd2007-08-21 19:33:56 +00003990 assert( sqlite3_mutex_held(db->mutex) );
danielk1977b28af712004-06-21 06:50:26 +00003991 db->nChange = nChange;
3992 db->nTotalChange += nChange;
3993}
3994
3995/*
3996** Set a flag in the vdbe to update the change counter when it is finalised
3997** or reset.
3998*/
drh4794f732004-11-05 17:17:50 +00003999void sqlite3VdbeCountChanges(Vdbe *v){
4000 v->changeCntOn = 1;
danielk1977b28af712004-06-21 06:50:26 +00004001}
drhd89bd002005-01-22 03:03:54 +00004002
4003/*
4004** Mark every prepared statement associated with a database connection
4005** as expired.
4006**
4007** An expired statement means that recompilation of the statement is
4008** recommend. Statements expire when things happen that make their
4009** programs obsolete. Removing user-defined functions or collating
4010** sequences, or changing an authorization function are the types of
4011** things that make prepared statements obsolete.
4012*/
4013void sqlite3ExpirePreparedStatements(sqlite3 *db){
4014 Vdbe *p;
4015 for(p = db->pVdbe; p; p=p->pNext){
4016 p->expired = 1;
4017 }
4018}
danielk1977aee18ef2005-03-09 12:26:50 +00004019
4020/*
4021** Return the database associated with the Vdbe.
4022*/
4023sqlite3 *sqlite3VdbeDb(Vdbe *v){
4024 return v->db;
4025}
dan937d0de2009-10-15 18:35:38 +00004026
4027/*
4028** Return a pointer to an sqlite3_value structure containing the value bound
4029** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4030** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4031** constants) to the value before returning it.
4032**
4033** The returned value must be freed by the caller using sqlite3ValueFree().
4034*/
drhcf0fd4a2013-08-01 12:21:58 +00004035sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
dan937d0de2009-10-15 18:35:38 +00004036 assert( iVar>0 );
4037 if( v ){
4038 Mem *pMem = &v->aVar[iVar-1];
4039 if( 0==(pMem->flags & MEM_Null) ){
4040 sqlite3_value *pRet = sqlite3ValueNew(v->db);
4041 if( pRet ){
4042 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4043 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
dan937d0de2009-10-15 18:35:38 +00004044 }
4045 return pRet;
4046 }
4047 }
4048 return 0;
4049}
4050
4051/*
4052** Configure SQL variable iVar so that binding a new value to it signals
4053** to sqlite3_reoptimize() that re-preparing the statement may result
4054** in a better query plan.
4055*/
dan1d2ce4f2009-10-19 18:11:09 +00004056void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
dan937d0de2009-10-15 18:35:38 +00004057 assert( iVar>0 );
4058 if( iVar>32 ){
dan1d2ce4f2009-10-19 18:11:09 +00004059 v->expmask = 0xffffffff;
dan937d0de2009-10-15 18:35:38 +00004060 }else{
dan1d2ce4f2009-10-19 18:11:09 +00004061 v->expmask |= ((u32)1 << (iVar-1));
dan937d0de2009-10-15 18:35:38 +00004062 }
4063}
dan016f7812013-08-21 17:35:48 +00004064
4065#ifndef SQLITE_OMIT_VIRTUALTABLE
4066/*
4067** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4068** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4069** in memory obtained from sqlite3DbMalloc).
4070*/
4071void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4072 sqlite3 *db = p->db;
4073 sqlite3DbFree(db, p->zErrMsg);
4074 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4075 sqlite3_free(pVtab->zErrMsg);
4076 pVtab->zErrMsg = 0;
4077}
4078#endif /* SQLITE_OMIT_VIRTUALTABLE */