blob: 3a33820f3571a158a593b18e064e4b8cf726f48a [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
drh7abda852014-09-19 16:02:06 +000013** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
drh9a324642003-09-06 20:12:01 +000014*/
15#include "sqliteInt.h"
drh9a324642003-09-06 20:12:01 +000016#include "vdbeInt.h"
17
drh9a324642003-09-06 20:12:01 +000018/*
19** Create a new virtual database engine.
20*/
drh9ac79622013-12-18 15:11:47 +000021Vdbe *sqlite3VdbeCreate(Parse *pParse){
22 sqlite3 *db = pParse->db;
drh9a324642003-09-06 20:12:01 +000023 Vdbe *p;
drh17435752007-08-16 04:30:38 +000024 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
drh9a324642003-09-06 20:12:01 +000025 if( p==0 ) return 0;
26 p->db = db;
27 if( db->pVdbe ){
28 db->pVdbe->pPrev = p;
29 }
30 p->pNext = db->pVdbe;
31 p->pPrev = 0;
32 db->pVdbe = p;
33 p->magic = VDBE_MAGIC_INIT;
drh9ac79622013-12-18 15:11:47 +000034 p->pParse = pParse;
drh73d5b8f2013-12-23 19:09:07 +000035 assert( pParse->aLabel==0 );
36 assert( pParse->nLabel==0 );
37 assert( pParse->nOpAlloc==0 );
drh9a324642003-09-06 20:12:01 +000038 return p;
39}
40
41/*
drhb900aaf2006-11-09 00:24:53 +000042** Remember the SQL string for a prepared statement.
43*/
danielk19776ab3a2e2009-02-19 14:39:25 +000044void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
dan1d2ce4f2009-10-19 18:11:09 +000045 assert( isPrepareV2==1 || isPrepareV2==0 );
drhb900aaf2006-11-09 00:24:53 +000046 if( p==0 ) return;
danac455932012-11-26 19:50:41 +000047#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
danielk19776ab3a2e2009-02-19 14:39:25 +000048 if( !isPrepareV2 ) return;
49#endif
drhb900aaf2006-11-09 00:24:53 +000050 assert( p->zSql==0 );
drh17435752007-08-16 04:30:38 +000051 p->zSql = sqlite3DbStrNDup(p->db, z, n);
shanef639c402009-11-03 19:42:30 +000052 p->isPrepareV2 = (u8)isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000053}
54
55/*
56** Return the SQL associated with a prepared statement
57*/
danielk1977d0e2a852007-11-14 06:48:48 +000058const char *sqlite3_sql(sqlite3_stmt *pStmt){
danielk19776ab3a2e2009-02-19 14:39:25 +000059 Vdbe *p = (Vdbe *)pStmt;
drh87f5c5f2010-01-20 01:20:56 +000060 return (p && p->isPrepareV2) ? p->zSql : 0;
drhb900aaf2006-11-09 00:24:53 +000061}
62
63/*
drhc5155252007-01-08 21:07:17 +000064** Swap all content between two VDBE structures.
drhb900aaf2006-11-09 00:24:53 +000065*/
drhc5155252007-01-08 21:07:17 +000066void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
67 Vdbe tmp, *pTmp;
68 char *zTmp;
drhc5155252007-01-08 21:07:17 +000069 tmp = *pA;
70 *pA = *pB;
71 *pB = tmp;
72 pTmp = pA->pNext;
73 pA->pNext = pB->pNext;
74 pB->pNext = pTmp;
75 pTmp = pA->pPrev;
76 pA->pPrev = pB->pPrev;
77 pB->pPrev = pTmp;
78 zTmp = pA->zSql;
79 pA->zSql = pB->zSql;
80 pB->zSql = zTmp;
danielk19776ab3a2e2009-02-19 14:39:25 +000081 pB->isPrepareV2 = pA->isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000082}
83
drh9a324642003-09-06 20:12:01 +000084/*
dan76ccd892014-08-12 13:38:52 +000085** Resize the Vdbe.aOp array so that it is at least nOp elements larger
drh81e069e2014-08-12 14:29:20 +000086** than its current size. nOp is guaranteed to be less than or equal
87** to 1024/sizeof(Op).
danielk1977ace3eb22006-01-26 10:35:04 +000088**
danielk197700e13612008-11-17 19:18:54 +000089** If an out-of-memory error occurs while resizing the array, return
dan76ccd892014-08-12 13:38:52 +000090** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
danielk197700e13612008-11-17 19:18:54 +000091** unchanged (this is so that any opcodes already allocated can be
92** correctly deallocated along with the rest of the Vdbe).
drh76ff3a02004-09-24 22:32:30 +000093*/
dan76ccd892014-08-12 13:38:52 +000094static int growOpArray(Vdbe *v, int nOp){
drha4e5d582007-10-20 15:41:57 +000095 VdbeOp *pNew;
drh73d5b8f2013-12-23 19:09:07 +000096 Parse *p = v->pParse;
dan76ccd892014-08-12 13:38:52 +000097
drh81e069e2014-08-12 14:29:20 +000098 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
99 ** more frequent reallocs and hence provide more opportunities for
100 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
101 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
102 ** by the minimum* amount required until the size reaches 512. Normal
103 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
104 ** size of the op array or add 1KB of space, whichever is smaller. */
dan76ccd892014-08-12 13:38:52 +0000105#ifdef SQLITE_TEST_REALLOC_STRESS
106 int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
107#else
danielk197700e13612008-11-17 19:18:54 +0000108 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
dan76ccd892014-08-12 13:38:52 +0000109 UNUSED_PARAMETER(nOp);
110#endif
111
drh81e069e2014-08-12 14:29:20 +0000112 assert( nOp<=(1024/sizeof(Op)) );
dan76ccd892014-08-12 13:38:52 +0000113 assert( nNew>=(p->nOpAlloc+nOp) );
drh73d5b8f2013-12-23 19:09:07 +0000114 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
drha4e5d582007-10-20 15:41:57 +0000115 if( pNew ){
drhb45f65d2009-03-01 19:42:11 +0000116 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
drh73d5b8f2013-12-23 19:09:07 +0000117 v->aOp = pNew;
drh76ff3a02004-09-24 22:32:30 +0000118 }
danielk197700e13612008-11-17 19:18:54 +0000119 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
drh76ff3a02004-09-24 22:32:30 +0000120}
121
drh313619f2013-10-31 20:34:06 +0000122#ifdef SQLITE_DEBUG
123/* This routine is just a convenient place to set a breakpoint that will
124** fire after each opcode is inserted and displayed using
125** "PRAGMA vdbe_addoptrace=on".
126*/
127static void test_addop_breakpoint(void){
128 static int n = 0;
129 n++;
130}
131#endif
132
drh76ff3a02004-09-24 22:32:30 +0000133/*
drh9a324642003-09-06 20:12:01 +0000134** Add a new instruction to the list of instructions current in the
135** VDBE. Return the address of the new instruction.
136**
137** Parameters:
138**
139** p Pointer to the VDBE
140**
141** op The opcode for this instruction
142**
drh66a51672008-01-03 00:01:23 +0000143** p1, p2, p3 Operands
drh9a324642003-09-06 20:12:01 +0000144**
danielk19774adee202004-05-08 08:23:19 +0000145** Use the sqlite3VdbeResolveLabel() function to fix an address and
drh66a51672008-01-03 00:01:23 +0000146** the sqlite3VdbeChangeP4() function to change the value of the P4
drh9a324642003-09-06 20:12:01 +0000147** operand.
148*/
drh66a51672008-01-03 00:01:23 +0000149int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
drh9a324642003-09-06 20:12:01 +0000150 int i;
drh701a0ae2004-02-22 20:05:00 +0000151 VdbeOp *pOp;
drh9a324642003-09-06 20:12:01 +0000152
153 i = p->nOp;
drh9a324642003-09-06 20:12:01 +0000154 assert( p->magic==VDBE_MAGIC_INIT );
drh8df32842008-12-09 02:51:23 +0000155 assert( op>0 && op<0xff );
drh73d5b8f2013-12-23 19:09:07 +0000156 if( p->pParse->nOpAlloc<=i ){
dan76ccd892014-08-12 13:38:52 +0000157 if( growOpArray(p, 1) ){
drhc42ed162009-06-26 14:04:51 +0000158 return 1;
drhfd2d26b2006-03-15 22:44:36 +0000159 }
drh9a324642003-09-06 20:12:01 +0000160 }
danielk197701256832007-04-18 14:24:32 +0000161 p->nOp++;
drh701a0ae2004-02-22 20:05:00 +0000162 pOp = &p->aOp[i];
drh8df32842008-12-09 02:51:23 +0000163 pOp->opcode = (u8)op;
drh26c9b5e2008-04-11 14:56:53 +0000164 pOp->p5 = 0;
drh701a0ae2004-02-22 20:05:00 +0000165 pOp->p1 = p1;
drh701a0ae2004-02-22 20:05:00 +0000166 pOp->p2 = p2;
drh66a51672008-01-03 00:01:23 +0000167 pOp->p3 = p3;
168 pOp->p4.p = 0;
169 pOp->p4type = P4_NOTUSED;
drhc7379ce2013-10-30 02:28:23 +0000170#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000171 pOp->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000172#endif
173#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000174 if( p->db->flags & SQLITE_VdbeAddopTrace ){
drh9ac79622013-12-18 15:11:47 +0000175 int jj, kk;
176 Parse *pParse = p->pParse;
177 for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
178 struct yColCache *x = pParse->aColCache + jj;
179 if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
180 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
181 kk++;
182 }
183 if( kk ) printf("\n");
drhe0962052013-01-29 19:14:31 +0000184 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
drh313619f2013-10-31 20:34:06 +0000185 test_addop_breakpoint();
drhe0962052013-01-29 19:14:31 +0000186 }
drh9a324642003-09-06 20:12:01 +0000187#endif
drh26c9b5e2008-04-11 14:56:53 +0000188#ifdef VDBE_PROFILE
189 pOp->cycles = 0;
190 pOp->cnt = 0;
191#endif
drh688852a2014-02-17 22:40:43 +0000192#ifdef SQLITE_VDBE_COVERAGE
193 pOp->iSrcLine = 0;
194#endif
drh9a324642003-09-06 20:12:01 +0000195 return i;
196}
drh66a51672008-01-03 00:01:23 +0000197int sqlite3VdbeAddOp0(Vdbe *p, int op){
198 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
199}
200int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
201 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
202}
203int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
204 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
drh701a0ae2004-02-22 20:05:00 +0000205}
206
drh66a51672008-01-03 00:01:23 +0000207
drh701a0ae2004-02-22 20:05:00 +0000208/*
drh66a51672008-01-03 00:01:23 +0000209** Add an opcode that includes the p4 value as a pointer.
drhd4e70eb2008-01-02 00:34:36 +0000210*/
drh66a51672008-01-03 00:01:23 +0000211int sqlite3VdbeAddOp4(
drhd4e70eb2008-01-02 00:34:36 +0000212 Vdbe *p, /* Add the opcode to this VM */
213 int op, /* The new opcode */
drh66a51672008-01-03 00:01:23 +0000214 int p1, /* The P1 operand */
215 int p2, /* The P2 operand */
216 int p3, /* The P3 operand */
217 const char *zP4, /* The P4 operand */
218 int p4type /* P4 operand type */
drhd4e70eb2008-01-02 00:34:36 +0000219){
drh66a51672008-01-03 00:01:23 +0000220 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
221 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
drhd4e70eb2008-01-02 00:34:36 +0000222 return addr;
223}
224
225/*
drh5d9c9da2011-06-03 20:11:17 +0000226** Add an OP_ParseSchema opcode. This routine is broken out from
drhe4c88c02012-01-04 12:57:45 +0000227** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
228** as having been used.
drh5d9c9da2011-06-03 20:11:17 +0000229**
230** The zWhere string must have been obtained from sqlite3_malloc().
231** This routine will take ownership of the allocated memory.
232*/
233void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
234 int j;
235 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
236 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
237 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
238}
239
240/*
drh8cff69d2009-11-12 19:59:44 +0000241** Add an opcode that includes the p4 value as an integer.
242*/
243int sqlite3VdbeAddOp4Int(
244 Vdbe *p, /* Add the opcode to this VM */
245 int op, /* The new opcode */
246 int p1, /* The P1 operand */
247 int p2, /* The P2 operand */
248 int p3, /* The P3 operand */
249 int p4 /* The P4 operand as an integer */
250){
251 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
252 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
253 return addr;
254}
255
256/*
drh9a324642003-09-06 20:12:01 +0000257** Create a new symbolic label for an instruction that has yet to be
258** coded. The symbolic label is really just a negative number. The
259** label can be used as the P2 value of an operation. Later, when
260** the label is resolved to a specific address, the VDBE will scan
261** through its operation list and change all values of P2 which match
262** the label into the resolved address.
263**
264** The VDBE knows that a P2 value is a label because labels are
265** always negative and P2 values are suppose to be non-negative.
266** Hence, a negative P2 value is a label that has yet to be resolved.
danielk1977b5548a82004-06-26 13:51:33 +0000267**
268** Zero is returned if a malloc() fails.
drh9a324642003-09-06 20:12:01 +0000269*/
drh73d5b8f2013-12-23 19:09:07 +0000270int sqlite3VdbeMakeLabel(Vdbe *v){
271 Parse *p = v->pParse;
drhc35f3d52012-02-01 19:03:38 +0000272 int i = p->nLabel++;
drh73d5b8f2013-12-23 19:09:07 +0000273 assert( v->magic==VDBE_MAGIC_INIT );
drhc35f3d52012-02-01 19:03:38 +0000274 if( (i & (i-1))==0 ){
275 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
276 (i*2+1)*sizeof(p->aLabel[0]));
drh9a324642003-09-06 20:12:01 +0000277 }
drh76ff3a02004-09-24 22:32:30 +0000278 if( p->aLabel ){
279 p->aLabel[i] = -1;
drh9a324642003-09-06 20:12:01 +0000280 }
drh9a324642003-09-06 20:12:01 +0000281 return -1-i;
282}
283
284/*
285** Resolve label "x" to be the address of the next instruction to
286** be inserted. The parameter "x" must have been obtained from
danielk19774adee202004-05-08 08:23:19 +0000287** a prior call to sqlite3VdbeMakeLabel().
drh9a324642003-09-06 20:12:01 +0000288*/
drh73d5b8f2013-12-23 19:09:07 +0000289void sqlite3VdbeResolveLabel(Vdbe *v, int x){
290 Parse *p = v->pParse;
drh76ff3a02004-09-24 22:32:30 +0000291 int j = -1-x;
drh73d5b8f2013-12-23 19:09:07 +0000292 assert( v->magic==VDBE_MAGIC_INIT );
drhb2b9d3d2013-08-01 01:14:43 +0000293 assert( j<p->nLabel );
drhd2490902014-04-13 19:28:15 +0000294 if( ALWAYS(j>=0) && p->aLabel ){
drh73d5b8f2013-12-23 19:09:07 +0000295 p->aLabel[j] = v->nOp;
drh9a324642003-09-06 20:12:01 +0000296 }
drh61019c72014-01-04 16:49:02 +0000297 p->iFixedOp = v->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000298}
299
drh4611d922010-02-25 14:47:01 +0000300/*
301** Mark the VDBE as one that can only be run one time.
302*/
303void sqlite3VdbeRunOnlyOnce(Vdbe *p){
304 p->runOnlyOnce = 1;
305}
306
drhff738bc2009-09-24 00:09:58 +0000307#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
dan144926d2009-09-09 11:37:20 +0000308
309/*
310** The following type and function are used to iterate through all opcodes
311** in a Vdbe main program and each of the sub-programs (triggers) it may
312** invoke directly or indirectly. It should be used as follows:
313**
314** Op *pOp;
315** VdbeOpIter sIter;
316**
317** memset(&sIter, 0, sizeof(sIter));
318** sIter.v = v; // v is of type Vdbe*
319** while( (pOp = opIterNext(&sIter)) ){
320** // Do something with pOp
321** }
322** sqlite3DbFree(v->db, sIter.apSub);
323**
324*/
325typedef struct VdbeOpIter VdbeOpIter;
326struct VdbeOpIter {
327 Vdbe *v; /* Vdbe to iterate through the opcodes of */
328 SubProgram **apSub; /* Array of subprograms */
329 int nSub; /* Number of entries in apSub */
330 int iAddr; /* Address of next instruction to return */
331 int iSub; /* 0 = main program, 1 = first sub-program etc. */
332};
333static Op *opIterNext(VdbeOpIter *p){
334 Vdbe *v = p->v;
335 Op *pRet = 0;
336 Op *aOp;
337 int nOp;
338
339 if( p->iSub<=p->nSub ){
340
341 if( p->iSub==0 ){
342 aOp = v->aOp;
343 nOp = v->nOp;
344 }else{
345 aOp = p->apSub[p->iSub-1]->aOp;
346 nOp = p->apSub[p->iSub-1]->nOp;
347 }
348 assert( p->iAddr<nOp );
349
350 pRet = &aOp[p->iAddr];
351 p->iAddr++;
352 if( p->iAddr==nOp ){
353 p->iSub++;
354 p->iAddr = 0;
355 }
356
357 if( pRet->p4type==P4_SUBPROGRAM ){
358 int nByte = (p->nSub+1)*sizeof(SubProgram*);
359 int j;
360 for(j=0; j<p->nSub; j++){
361 if( p->apSub[j]==pRet->p4.pProgram ) break;
362 }
363 if( j==p->nSub ){
364 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
365 if( !p->apSub ){
366 pRet = 0;
367 }else{
368 p->apSub[p->nSub++] = pRet->p4.pProgram;
369 }
370 }
371 }
372 }
373
374 return pRet;
375}
376
377/*
danf3677212009-09-10 16:14:50 +0000378** Check if the program stored in the VM associated with pParse may
drhff738bc2009-09-24 00:09:58 +0000379** throw an ABORT exception (causing the statement, but not entire transaction
dan144926d2009-09-09 11:37:20 +0000380** to be rolled back). This condition is true if the main program or any
381** sub-programs contains any of the following:
382**
383** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
384** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
385** * OP_Destroy
386** * OP_VUpdate
387** * OP_VRename
dan32b09f22009-09-23 17:29:59 +0000388** * OP_FkCounter with P2==0 (immediate foreign key constraint)
dan144926d2009-09-09 11:37:20 +0000389**
danf3677212009-09-10 16:14:50 +0000390** Then check that the value of Parse.mayAbort is true if an
391** ABORT may be thrown, or false otherwise. Return true if it does
392** match, or false otherwise. This function is intended to be used as
393** part of an assert statement in the compiler. Similar to:
394**
395** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
dan144926d2009-09-09 11:37:20 +0000396*/
danf3677212009-09-10 16:14:50 +0000397int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
398 int hasAbort = 0;
dan144926d2009-09-09 11:37:20 +0000399 Op *pOp;
400 VdbeOpIter sIter;
401 memset(&sIter, 0, sizeof(sIter));
402 sIter.v = v;
403
404 while( (pOp = opIterNext(&sIter))!=0 ){
405 int opcode = pOp->opcode;
406 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
dan32b09f22009-09-23 17:29:59 +0000407#ifndef SQLITE_OMIT_FOREIGN_KEY
dan0ff297e2009-09-25 17:03:14 +0000408 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
dan32b09f22009-09-23 17:29:59 +0000409#endif
dan144926d2009-09-09 11:37:20 +0000410 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
drhd91c1a12013-02-09 13:58:25 +0000411 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
dan144926d2009-09-09 11:37:20 +0000412 ){
danf3677212009-09-10 16:14:50 +0000413 hasAbort = 1;
dan144926d2009-09-09 11:37:20 +0000414 break;
415 }
416 }
dan144926d2009-09-09 11:37:20 +0000417 sqlite3DbFree(v->db, sIter.apSub);
danf3677212009-09-10 16:14:50 +0000418
mistachkin48864df2013-03-21 21:20:32 +0000419 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
danf3677212009-09-10 16:14:50 +0000420 ** If malloc failed, then the while() loop above may not have iterated
421 ** through all opcodes and hasAbort may be set incorrectly. Return
422 ** true for this case to prevent the assert() in the callers frame
423 ** from failing. */
424 return ( v->db->mallocFailed || hasAbort==mayAbort );
dan144926d2009-09-09 11:37:20 +0000425}
drhff738bc2009-09-24 00:09:58 +0000426#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
dan144926d2009-09-09 11:37:20 +0000427
drh9a324642003-09-06 20:12:01 +0000428/*
drh9cbf3422008-01-17 16:22:13 +0000429** Loop through the program looking for P2 values that are negative
430** on jump instructions. Each such value is a label. Resolve the
431** label by setting the P2 value to its correct non-zero value.
drh76ff3a02004-09-24 22:32:30 +0000432**
433** This routine is called once after all opcodes have been inserted.
danielk1977634f2982005-03-28 08:44:07 +0000434**
drh13449892005-09-07 21:22:45 +0000435** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
danielk1977399918f2006-06-14 13:03:23 +0000436** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
danielk1977634f2982005-03-28 08:44:07 +0000437** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
drha6c2ed92009-11-14 23:22:23 +0000438**
439** The Op.opflags field is set on all opcodes.
drh76ff3a02004-09-24 22:32:30 +0000440*/
drh9cbf3422008-01-17 16:22:13 +0000441static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
drh76ff3a02004-09-24 22:32:30 +0000442 int i;
dan165921a2009-08-28 18:53:45 +0000443 int nMaxArgs = *pMaxFuncArgs;
drh76ff3a02004-09-24 22:32:30 +0000444 Op *pOp;
drh73d5b8f2013-12-23 19:09:07 +0000445 Parse *pParse = p->pParse;
446 int *aLabel = pParse->aLabel;
drhad4a4b82008-11-05 16:37:34 +0000447 p->readOnly = 1;
drh1713afb2013-06-28 01:24:57 +0000448 p->bIsReader = 0;
drh76ff3a02004-09-24 22:32:30 +0000449 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
danielk1977634f2982005-03-28 08:44:07 +0000450 u8 opcode = pOp->opcode;
451
drh8c8a8c42013-08-06 07:45:08 +0000452 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
453 ** cases from this switch! */
454 switch( opcode ){
455 case OP_Function:
456 case OP_AggStep: {
457 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
458 break;
459 }
460 case OP_Transaction: {
461 if( pOp->p2!=0 ) p->readOnly = 0;
462 /* fall thru */
463 }
464 case OP_AutoCommit:
465 case OP_Savepoint: {
466 p->bIsReader = 1;
467 break;
468 }
dand9031542013-07-05 16:54:30 +0000469#ifndef SQLITE_OMIT_WAL
drh8c8a8c42013-08-06 07:45:08 +0000470 case OP_Checkpoint:
drh9e92a472013-06-27 17:40:30 +0000471#endif
drh8c8a8c42013-08-06 07:45:08 +0000472 case OP_Vacuum:
473 case OP_JournalMode: {
474 p->readOnly = 0;
475 p->bIsReader = 1;
476 break;
477 }
danielk1977182c4ba2007-06-27 15:53:34 +0000478#ifndef SQLITE_OMIT_VIRTUALTABLE
drh8c8a8c42013-08-06 07:45:08 +0000479 case OP_VUpdate: {
480 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
481 break;
482 }
483 case OP_VFilter: {
484 int n;
485 assert( p->nOp - i >= 3 );
486 assert( pOp[-1].opcode==OP_Integer );
487 n = pOp[-1].p1;
488 if( n>nMaxArgs ) nMaxArgs = n;
489 break;
490 }
danielk1977182c4ba2007-06-27 15:53:34 +0000491#endif
drh8c8a8c42013-08-06 07:45:08 +0000492 case OP_Next:
drhf93cd942013-11-21 03:12:25 +0000493 case OP_NextIfOpen:
drh8c8a8c42013-08-06 07:45:08 +0000494 case OP_SorterNext: {
495 pOp->p4.xAdvance = sqlite3BtreeNext;
496 pOp->p4type = P4_ADVANCE;
497 break;
498 }
drhf93cd942013-11-21 03:12:25 +0000499 case OP_Prev:
500 case OP_PrevIfOpen: {
drh8c8a8c42013-08-06 07:45:08 +0000501 pOp->p4.xAdvance = sqlite3BtreePrevious;
502 pOp->p4type = P4_ADVANCE;
503 break;
504 }
danielk1977bc04f852005-03-29 08:26:13 +0000505 }
danielk1977634f2982005-03-28 08:44:07 +0000506
drh8c8a8c42013-08-06 07:45:08 +0000507 pOp->opflags = sqlite3OpcodeProperty[opcode];
drha6c2ed92009-11-14 23:22:23 +0000508 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
drh73d5b8f2013-12-23 19:09:07 +0000509 assert( -1-pOp->p2<pParse->nLabel );
drhd2981512008-01-04 19:33:49 +0000510 pOp->p2 = aLabel[-1-pOp->p2];
511 }
drh76ff3a02004-09-24 22:32:30 +0000512 }
drh73d5b8f2013-12-23 19:09:07 +0000513 sqlite3DbFree(p->db, pParse->aLabel);
514 pParse->aLabel = 0;
515 pParse->nLabel = 0;
danielk1977bc04f852005-03-29 08:26:13 +0000516 *pMaxFuncArgs = nMaxArgs;
drha7ab6d82014-07-21 15:44:39 +0000517 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
drh76ff3a02004-09-24 22:32:30 +0000518}
519
520/*
drh9a324642003-09-06 20:12:01 +0000521** Return the address of the next instruction to be inserted.
522*/
danielk19774adee202004-05-08 08:23:19 +0000523int sqlite3VdbeCurrentAddr(Vdbe *p){
drh9a324642003-09-06 20:12:01 +0000524 assert( p->magic==VDBE_MAGIC_INIT );
525 return p->nOp;
526}
527
dan65a7cd12009-09-01 12:16:01 +0000528/*
529** This function returns a pointer to the array of opcodes associated with
530** the Vdbe passed as the first argument. It is the callers responsibility
531** to arrange for the returned array to be eventually freed using the
532** vdbeFreeOpArray() function.
533**
534** Before returning, *pnOp is set to the number of entries in the returned
535** array. Also, *pnMaxArg is set to the larger of its current value and
536** the number of entries in the Vdbe.apArg[] array required to execute the
537** returned program.
538*/
dan165921a2009-08-28 18:53:45 +0000539VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
540 VdbeOp *aOp = p->aOp;
dan523a0872009-08-31 05:23:32 +0000541 assert( aOp && !p->db->mallocFailed );
dan65a7cd12009-09-01 12:16:01 +0000542
543 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
drha7ab6d82014-07-21 15:44:39 +0000544 assert( DbMaskAllZero(p->btreeMask) );
dan65a7cd12009-09-01 12:16:01 +0000545
dan165921a2009-08-28 18:53:45 +0000546 resolveP2Values(p, pnMaxArg);
547 *pnOp = p->nOp;
548 p->aOp = 0;
549 return aOp;
550}
551
drh9a324642003-09-06 20:12:01 +0000552/*
553** Add a whole list of operations to the operation stack. Return the
554** address of the first operation added.
555*/
drh688852a2014-02-17 22:40:43 +0000556int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
drh9a324642003-09-06 20:12:01 +0000557 int addr;
558 assert( p->magic==VDBE_MAGIC_INIT );
dan76ccd892014-08-12 13:38:52 +0000559 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
drh76ff3a02004-09-24 22:32:30 +0000560 return 0;
drh9a324642003-09-06 20:12:01 +0000561 }
562 addr = p->nOp;
drh7b746032009-06-26 12:15:22 +0000563 if( ALWAYS(nOp>0) ){
drh9a324642003-09-06 20:12:01 +0000564 int i;
drh905793e2004-02-21 13:31:09 +0000565 VdbeOpList const *pIn = aOp;
566 for(i=0; i<nOp; i++, pIn++){
567 int p2 = pIn->p2;
568 VdbeOp *pOut = &p->aOp[i+addr];
569 pOut->opcode = pIn->opcode;
570 pOut->p1 = pIn->p1;
drh4308e342013-11-11 16:55:52 +0000571 if( p2<0 ){
572 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
drh8558cde2008-01-05 05:20:10 +0000573 pOut->p2 = addr + ADDR(p2);
574 }else{
575 pOut->p2 = p2;
576 }
drh24003452008-01-03 01:28:59 +0000577 pOut->p3 = pIn->p3;
578 pOut->p4type = P4_NOTUSED;
579 pOut->p4.p = 0;
580 pOut->p5 = 0;
drhc7379ce2013-10-30 02:28:23 +0000581#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000582 pOut->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000583#endif
drh688852a2014-02-17 22:40:43 +0000584#ifdef SQLITE_VDBE_COVERAGE
585 pOut->iSrcLine = iLineno+i;
586#else
587 (void)iLineno;
588#endif
drhc7379ce2013-10-30 02:28:23 +0000589#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000590 if( p->db->flags & SQLITE_VdbeAddopTrace ){
danielk19774adee202004-05-08 08:23:19 +0000591 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
drh9a324642003-09-06 20:12:01 +0000592 }
593#endif
594 }
595 p->nOp += nOp;
596 }
597 return addr;
598}
599
dan6f9702e2014-11-01 20:38:06 +0000600#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
601/*
602** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
603*/
dan037b5322014-11-03 11:25:32 +0000604void sqlite3VdbeScanStatus(
dan6f9702e2014-11-01 20:38:06 +0000605 Vdbe *p, /* VM to add scanstatus() to */
606 int addrExplain, /* Address of OP_Explain (or 0) */
607 int addrLoop, /* Address of loop counter */
608 int addrVisit, /* Address of rows visited counter */
drh518140e2014-11-06 03:55:10 +0000609 LogEst nEst, /* Estimated number of output rows */
dan6f9702e2014-11-01 20:38:06 +0000610 const char *zName /* Name of table or index being scanned */
611){
dan037b5322014-11-03 11:25:32 +0000612 int nByte = (p->nScan+1) * sizeof(ScanStatus);
613 ScanStatus *aNew;
614 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
dan6f9702e2014-11-01 20:38:06 +0000615 if( aNew ){
dan037b5322014-11-03 11:25:32 +0000616 ScanStatus *pNew = &aNew[p->nScan++];
dan6f9702e2014-11-01 20:38:06 +0000617 pNew->addrExplain = addrExplain;
618 pNew->addrLoop = addrLoop;
619 pNew->addrVisit = addrVisit;
620 pNew->nEst = nEst;
621 pNew->zName = sqlite3DbStrDup(p->db, zName);
622 p->aScan = aNew;
623 }
624}
625#endif
626
627
drh9a324642003-09-06 20:12:01 +0000628/*
629** Change the value of the P1 operand for a specific instruction.
630** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000631** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000632** few minor changes to the program.
633*/
drh88caeac2011-08-24 15:12:08 +0000634void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000635 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000636 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000637 p->aOp[addr].p1 = val;
638 }
639}
640
641/*
642** Change the value of the P2 operand for a specific instruction.
643** This routine is useful for setting a jump destination.
644*/
drh88caeac2011-08-24 15:12:08 +0000645void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000646 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000647 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000648 p->aOp[addr].p2 = val;
649 }
650}
651
drhd654be82005-09-20 17:42:23 +0000652/*
danielk19771f4aa332008-01-03 09:51:55 +0000653** Change the value of the P3 operand for a specific instruction.
danielk1977207872a2008-01-03 07:54:23 +0000654*/
drh88caeac2011-08-24 15:12:08 +0000655void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000656 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000657 if( ((u32)p->nOp)>addr ){
danielk1977207872a2008-01-03 07:54:23 +0000658 p->aOp[addr].p3 = val;
659 }
660}
661
662/*
drh35573352008-01-08 23:54:25 +0000663** Change the value of the P5 operand for the most recently
664** added operation.
danielk19771f4aa332008-01-03 09:51:55 +0000665*/
drh35573352008-01-08 23:54:25 +0000666void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
drh7b746032009-06-26 12:15:22 +0000667 assert( p!=0 );
668 if( p->aOp ){
drh35573352008-01-08 23:54:25 +0000669 assert( p->nOp>0 );
670 p->aOp[p->nOp-1].p5 = val;
danielk19771f4aa332008-01-03 09:51:55 +0000671 }
672}
673
674/*
drhf8875402006-03-17 13:56:34 +0000675** Change the P2 operand of instruction addr so that it points to
drhd654be82005-09-20 17:42:23 +0000676** the address of the next instruction to be coded.
677*/
678void sqlite3VdbeJumpHere(Vdbe *p, int addr){
drh61019c72014-01-04 16:49:02 +0000679 sqlite3VdbeChangeP2(p, addr, p->nOp);
680 p->pParse->iFixedOp = p->nOp - 1;
drhd654be82005-09-20 17:42:23 +0000681}
drhb38ad992005-09-16 00:27:01 +0000682
drhb7f6f682006-07-08 17:06:43 +0000683
684/*
685** If the input FuncDef structure is ephemeral, then free it. If
686** the FuncDef is not ephermal, then do nothing.
687*/
drh633e6d52008-07-28 19:34:53 +0000688static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
drhd36e1042013-09-06 13:10:12 +0000689 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
drh633e6d52008-07-28 19:34:53 +0000690 sqlite3DbFree(db, pDef);
drhb7f6f682006-07-08 17:06:43 +0000691 }
692}
693
dand46def72010-07-24 11:28:28 +0000694static void vdbeFreeOpArray(sqlite3 *, Op *, int);
695
drhb38ad992005-09-16 00:27:01 +0000696/*
drh66a51672008-01-03 00:01:23 +0000697** Delete a P4 value if necessary.
drhb38ad992005-09-16 00:27:01 +0000698*/
drh633e6d52008-07-28 19:34:53 +0000699static void freeP4(sqlite3 *db, int p4type, void *p4){
drh0acb7e42008-06-25 00:12:41 +0000700 if( p4 ){
dand46def72010-07-24 11:28:28 +0000701 assert( db );
drh66a51672008-01-03 00:01:23 +0000702 switch( p4type ){
703 case P4_REAL:
704 case P4_INT64:
drh66a51672008-01-03 00:01:23 +0000705 case P4_DYNAMIC:
drh2ec2fb22013-11-06 19:59:23 +0000706 case P4_INTARRAY: {
drh633e6d52008-07-28 19:34:53 +0000707 sqlite3DbFree(db, p4);
drhac1733d2005-09-17 17:58:22 +0000708 break;
709 }
drh2ec2fb22013-11-06 19:59:23 +0000710 case P4_KEYINFO: {
711 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
712 break;
713 }
drhb9755982010-07-24 16:34:37 +0000714 case P4_MPRINTF: {
drh7043db92010-07-26 12:38:12 +0000715 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
drhb9755982010-07-24 16:34:37 +0000716 break;
717 }
drh66a51672008-01-03 00:01:23 +0000718 case P4_FUNCDEF: {
drh633e6d52008-07-28 19:34:53 +0000719 freeEphemeralFunction(db, (FuncDef*)p4);
drhb7f6f682006-07-08 17:06:43 +0000720 break;
721 }
drh66a51672008-01-03 00:01:23 +0000722 case P4_MEM: {
drhc176c272010-07-26 13:57:59 +0000723 if( db->pnBytesFreed==0 ){
724 sqlite3ValueFree((sqlite3_value*)p4);
725 }else{
drhf37c68e2010-07-26 14:20:06 +0000726 Mem *p = (Mem*)p4;
drh17bcb102014-09-18 21:25:33 +0000727 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
drhf37c68e2010-07-26 14:20:06 +0000728 sqlite3DbFree(db, p);
drhc176c272010-07-26 13:57:59 +0000729 }
drhac1733d2005-09-17 17:58:22 +0000730 break;
731 }
danielk1977595a5232009-07-24 17:58:53 +0000732 case P4_VTAB : {
dand46def72010-07-24 11:28:28 +0000733 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
danielk1977595a5232009-07-24 17:58:53 +0000734 break;
735 }
drhb38ad992005-09-16 00:27:01 +0000736 }
737 }
738}
739
dan65a7cd12009-09-01 12:16:01 +0000740/*
741** Free the space allocated for aOp and any p4 values allocated for the
742** opcodes contained within. If aOp is not NULL it is assumed to contain
743** nOp entries.
744*/
dan165921a2009-08-28 18:53:45 +0000745static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
746 if( aOp ){
747 Op *pOp;
748 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
749 freeP4(db, pOp->p4type, pOp->p4.p);
drhc7379ce2013-10-30 02:28:23 +0000750#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
dan165921a2009-08-28 18:53:45 +0000751 sqlite3DbFree(db, pOp->zComment);
752#endif
753 }
754 }
755 sqlite3DbFree(db, aOp);
756}
757
dan65a7cd12009-09-01 12:16:01 +0000758/*
dand19c9332010-07-26 12:05:17 +0000759** Link the SubProgram object passed as the second argument into the linked
760** list at Vdbe.pSubProgram. This list is used to delete all sub-program
761** objects when the VM is no longer required.
dan65a7cd12009-09-01 12:16:01 +0000762*/
dand19c9332010-07-26 12:05:17 +0000763void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
764 p->pNext = pVdbe->pProgram;
765 pVdbe->pProgram = p;
dan165921a2009-08-28 18:53:45 +0000766}
767
drh9a324642003-09-06 20:12:01 +0000768/*
drh48f2d3b2011-09-16 01:34:43 +0000769** Change the opcode at addr into OP_Noop
drhf8875402006-03-17 13:56:34 +0000770*/
drh48f2d3b2011-09-16 01:34:43 +0000771void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
dan76ccd892014-08-12 13:38:52 +0000772 if( addr<p->nOp ){
danielk197792d4d7a2007-05-04 12:05:56 +0000773 VdbeOp *pOp = &p->aOp[addr];
drh633e6d52008-07-28 19:34:53 +0000774 sqlite3 *db = p->db;
drh48f2d3b2011-09-16 01:34:43 +0000775 freeP4(db, pOp->p4type, pOp->p4.p);
776 memset(pOp, 0, sizeof(pOp[0]));
777 pOp->opcode = OP_Noop;
drh313619f2013-10-31 20:34:06 +0000778 if( addr==p->nOp-1 ) p->nOp--;
drhf8875402006-03-17 13:56:34 +0000779 }
780}
781
782/*
drh39c4b822014-09-29 15:42:01 +0000783** If the last opcode is "op" and it is not a jump destination,
784** then remove it. Return true if and only if an opcode was removed.
drh762c1c42014-01-02 19:35:30 +0000785*/
drh61019c72014-01-04 16:49:02 +0000786int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
787 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
788 sqlite3VdbeChangeToNoop(p, p->nOp-1);
789 return 1;
790 }else{
791 return 0;
792 }
drh762c1c42014-01-02 19:35:30 +0000793}
794
795/*
drh66a51672008-01-03 00:01:23 +0000796** Change the value of the P4 operand for a specific instruction.
drh9a324642003-09-06 20:12:01 +0000797** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000798** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000799** few minor changes to the program.
800**
drh66a51672008-01-03 00:01:23 +0000801** If n>=0 then the P4 operand is dynamic, meaning that a copy of
drh17435752007-08-16 04:30:38 +0000802** the string is made into memory obtained from sqlite3_malloc().
drh66a51672008-01-03 00:01:23 +0000803** A value of n==0 means copy bytes of zP4 up to and including the
804** first null byte. If n>0 then copy n+1 bytes of zP4.
danielk19771f55c052005-05-19 08:42:59 +0000805**
drh66a51672008-01-03 00:01:23 +0000806** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
danielk19771f55c052005-05-19 08:42:59 +0000807** to a string or structure that is guaranteed to exist for the lifetime of
808** the Vdbe. In these cases we can just copy the pointer.
drh9a324642003-09-06 20:12:01 +0000809**
drh66a51672008-01-03 00:01:23 +0000810** If addr<0 then change P4 on the most recently inserted instruction.
drh9a324642003-09-06 20:12:01 +0000811*/
drh66a51672008-01-03 00:01:23 +0000812void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
drh9a324642003-09-06 20:12:01 +0000813 Op *pOp;
drh633e6d52008-07-28 19:34:53 +0000814 sqlite3 *db;
drh91fd4d42008-01-19 20:11:25 +0000815 assert( p!=0 );
drh633e6d52008-07-28 19:34:53 +0000816 db = p->db;
drh91fd4d42008-01-19 20:11:25 +0000817 assert( p->magic==VDBE_MAGIC_INIT );
drh633e6d52008-07-28 19:34:53 +0000818 if( p->aOp==0 || db->mallocFailed ){
drh2ec2fb22013-11-06 19:59:23 +0000819 if( n!=P4_VTAB ){
drh633e6d52008-07-28 19:34:53 +0000820 freeP4(db, n, (void*)*(char**)&zP4);
danielk1977261919c2005-12-06 12:52:59 +0000821 }
danielk1977d5d56522005-03-16 12:15:20 +0000822 return;
823 }
drh7b746032009-06-26 12:15:22 +0000824 assert( p->nOp>0 );
drh91fd4d42008-01-19 20:11:25 +0000825 assert( addr<p->nOp );
826 if( addr<0 ){
drh9a324642003-09-06 20:12:01 +0000827 addr = p->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000828 }
829 pOp = &p->aOp[addr];
drh079a3072014-03-19 14:10:55 +0000830 assert( pOp->p4type==P4_NOTUSED
831 || pOp->p4type==P4_INT32
832 || pOp->p4type==P4_KEYINFO );
drh633e6d52008-07-28 19:34:53 +0000833 freeP4(db, pOp->p4type, pOp->p4.p);
drh66a51672008-01-03 00:01:23 +0000834 pOp->p4.p = 0;
drh98757152008-01-09 23:04:12 +0000835 if( n==P4_INT32 ){
mlcreech12d40822008-03-06 07:35:21 +0000836 /* Note: this cast is safe, because the origin data point was an int
837 ** that was cast to a (const char *). */
shane1fc41292008-07-08 22:28:48 +0000838 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
drh8df32842008-12-09 02:51:23 +0000839 pOp->p4type = P4_INT32;
drh98757152008-01-09 23:04:12 +0000840 }else if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +0000841 pOp->p4.p = 0;
842 pOp->p4type = P4_NOTUSED;
843 }else if( n==P4_KEYINFO ){
danielk19772dca4ac2008-01-03 11:50:29 +0000844 pOp->p4.p = (void*)zP4;
drh66a51672008-01-03 00:01:23 +0000845 pOp->p4type = P4_KEYINFO;
danielk1977595a5232009-07-24 17:58:53 +0000846 }else if( n==P4_VTAB ){
847 pOp->p4.p = (void*)zP4;
848 pOp->p4type = P4_VTAB;
849 sqlite3VtabLock((VTable *)zP4);
850 assert( ((VTable *)zP4)->db==p->db );
drh9a324642003-09-06 20:12:01 +0000851 }else if( n<0 ){
danielk19772dca4ac2008-01-03 11:50:29 +0000852 pOp->p4.p = (void*)zP4;
drh8df32842008-12-09 02:51:23 +0000853 pOp->p4type = (signed char)n;
drh9a324642003-09-06 20:12:01 +0000854 }else{
drhea678832008-12-10 19:26:22 +0000855 if( n==0 ) n = sqlite3Strlen30(zP4);
danielk19772dca4ac2008-01-03 11:50:29 +0000856 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
drh66a51672008-01-03 00:01:23 +0000857 pOp->p4type = P4_DYNAMIC;
drh9a324642003-09-06 20:12:01 +0000858 }
859}
860
drh2ec2fb22013-11-06 19:59:23 +0000861/*
862** Set the P4 on the most recently added opcode to the KeyInfo for the
863** index given.
864*/
865void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
866 Vdbe *v = pParse->pVdbe;
867 assert( v!=0 );
868 assert( pIdx!=0 );
869 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
870 P4_KEYINFO);
871}
872
drhc7379ce2013-10-30 02:28:23 +0000873#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drhad6d9462004-09-19 02:15:24 +0000874/*
mistachkind5578432012-08-25 10:01:29 +0000875** Change the comment on the most recently coded instruction. Or
drh16ee60f2008-06-20 18:13:25 +0000876** insert a No-op and add the comment to that new instruction. This
877** makes the code easier to read during debugging. None of this happens
878** in a production build.
drhad6d9462004-09-19 02:15:24 +0000879*/
drhb07028f2011-10-14 21:49:18 +0000880static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
danielk197701256832007-04-18 14:24:32 +0000881 assert( p->nOp>0 || p->aOp==0 );
drhd4e70eb2008-01-02 00:34:36 +0000882 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
danielk1977dba01372008-01-05 18:44:29 +0000883 if( p->nOp ){
drhb07028f2011-10-14 21:49:18 +0000884 assert( p->aOp );
885 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
886 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
887 }
888}
889void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
890 va_list ap;
891 if( p ){
danielk1977dba01372008-01-05 18:44:29 +0000892 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000893 vdbeVComment(p, zFormat, ap);
danielk1977dba01372008-01-05 18:44:29 +0000894 va_end(ap);
895 }
drhad6d9462004-09-19 02:15:24 +0000896}
drh16ee60f2008-06-20 18:13:25 +0000897void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
898 va_list ap;
drhb07028f2011-10-14 21:49:18 +0000899 if( p ){
900 sqlite3VdbeAddOp0(p, OP_Noop);
drh16ee60f2008-06-20 18:13:25 +0000901 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000902 vdbeVComment(p, zFormat, ap);
drh16ee60f2008-06-20 18:13:25 +0000903 va_end(ap);
904 }
905}
906#endif /* NDEBUG */
drhad6d9462004-09-19 02:15:24 +0000907
drh688852a2014-02-17 22:40:43 +0000908#ifdef SQLITE_VDBE_COVERAGE
909/*
910** Set the value if the iSrcLine field for the previously coded instruction.
911*/
912void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
913 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
914}
915#endif /* SQLITE_VDBE_COVERAGE */
916
drh9a324642003-09-06 20:12:01 +0000917/*
drh20411ea2009-05-29 19:00:12 +0000918** Return the opcode for a given address. If the address is -1, then
919** return the most recently inserted opcode.
920**
921** If a memory allocation error has occurred prior to the calling of this
922** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
drhf83dc1e2010-06-03 12:09:52 +0000923** is readable but not writable, though it is cast to a writable value.
924** The return of a dummy opcode allows the call to continue functioning
peter.d.reid60ec9142014-09-06 16:39:46 +0000925** after an OOM fault without having to check to see if the return from
drhf83dc1e2010-06-03 12:09:52 +0000926** this routine is a valid pointer. But because the dummy.opcode is 0,
927** dummy will never be written to. This is verified by code inspection and
928** by running with Valgrind.
drh9a324642003-09-06 20:12:01 +0000929*/
danielk19774adee202004-05-08 08:23:19 +0000930VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
drha0b75da2010-07-02 18:44:37 +0000931 /* C89 specifies that the constant "dummy" will be initialized to all
932 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
mistachkin0fe5f952011-09-14 18:19:08 +0000933 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
drh9a324642003-09-06 20:12:01 +0000934 assert( p->magic==VDBE_MAGIC_INIT );
drh37b89a02009-06-19 00:33:31 +0000935 if( addr<0 ){
drh37b89a02009-06-19 00:33:31 +0000936 addr = p->nOp - 1;
937 }
drh17435752007-08-16 04:30:38 +0000938 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +0000939 if( p->db->mallocFailed ){
drhf83dc1e2010-06-03 12:09:52 +0000940 return (VdbeOp*)&dummy;
drh20411ea2009-05-29 19:00:12 +0000941 }else{
942 return &p->aOp[addr];
943 }
drh9a324642003-09-06 20:12:01 +0000944}
945
drhc7379ce2013-10-30 02:28:23 +0000946#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
drh81316f82013-10-29 20:40:47 +0000947/*
drhf63552b2013-10-30 00:25:03 +0000948** Return an integer value for one of the parameters to the opcode pOp
949** determined by character c.
950*/
951static int translateP(char c, const Op *pOp){
952 if( c=='1' ) return pOp->p1;
953 if( c=='2' ) return pOp->p2;
954 if( c=='3' ) return pOp->p3;
955 if( c=='4' ) return pOp->p4.i;
956 return pOp->p5;
957}
958
drh81316f82013-10-29 20:40:47 +0000959/*
drh4eded602013-12-20 15:59:20 +0000960** Compute a string for the "comment" field of a VDBE opcode listing.
961**
962** The Synopsis: field in comments in the vdbe.c source file gets converted
963** to an extra string that is appended to the sqlite3OpcodeName(). In the
964** absence of other comments, this synopsis becomes the comment on the opcode.
965** Some translation occurs:
966**
967** "PX" -> "r[X]"
968** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
969** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
970** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
drh81316f82013-10-29 20:40:47 +0000971*/
drhf63552b2013-10-30 00:25:03 +0000972static int displayComment(
973 const Op *pOp, /* The opcode to be commented */
974 const char *zP4, /* Previously obtained value for P4 */
975 char *zTemp, /* Write result here */
976 int nTemp /* Space available in zTemp[] */
977){
drh81316f82013-10-29 20:40:47 +0000978 const char *zOpName;
979 const char *zSynopsis;
980 int nOpName;
981 int ii, jj;
982 zOpName = sqlite3OpcodeName(pOp->opcode);
983 nOpName = sqlite3Strlen30(zOpName);
984 if( zOpName[nOpName+1] ){
985 int seenCom = 0;
drhf63552b2013-10-30 00:25:03 +0000986 char c;
drh81316f82013-10-29 20:40:47 +0000987 zSynopsis = zOpName += nOpName + 1;
drhf63552b2013-10-30 00:25:03 +0000988 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
989 if( c=='P' ){
990 c = zSynopsis[++ii];
991 if( c=='4' ){
992 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
993 }else if( c=='X' ){
994 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
995 seenCom = 1;
drh81316f82013-10-29 20:40:47 +0000996 }else{
drhf63552b2013-10-30 00:25:03 +0000997 int v1 = translateP(c, pOp);
998 int v2;
999 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
1000 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1001 ii += 3;
1002 jj += sqlite3Strlen30(zTemp+jj);
1003 v2 = translateP(zSynopsis[ii], pOp);
drh4eded602013-12-20 15:59:20 +00001004 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
1005 ii += 2;
1006 v2++;
1007 }
1008 if( v2>1 ){
1009 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
1010 }
drhf63552b2013-10-30 00:25:03 +00001011 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1012 ii += 4;
1013 }
drh81316f82013-10-29 20:40:47 +00001014 }
1015 jj += sqlite3Strlen30(zTemp+jj);
1016 }else{
drhf63552b2013-10-30 00:25:03 +00001017 zTemp[jj++] = c;
drh81316f82013-10-29 20:40:47 +00001018 }
1019 }
1020 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
1021 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
1022 jj += sqlite3Strlen30(zTemp+jj);
1023 }
1024 if( jj<nTemp ) zTemp[jj] = 0;
1025 }else if( pOp->zComment ){
1026 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1027 jj = sqlite3Strlen30(zTemp);
1028 }else{
1029 zTemp[0] = 0;
1030 jj = 0;
1031 }
1032 return jj;
1033}
1034#endif /* SQLITE_DEBUG */
1035
1036
drhb7f91642004-10-31 02:22:47 +00001037#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
1038 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001039/*
drh66a51672008-01-03 00:01:23 +00001040** Compute a string that describes the P4 parameter for an opcode.
drhd3d39e92004-05-20 22:16:29 +00001041** Use zTemp for any required temporary buffer space.
1042*/
drh66a51672008-01-03 00:01:23 +00001043static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1044 char *zP4 = zTemp;
drhd3d39e92004-05-20 22:16:29 +00001045 assert( nTemp>=20 );
drh66a51672008-01-03 00:01:23 +00001046 switch( pOp->p4type ){
1047 case P4_KEYINFO: {
drhd3d39e92004-05-20 22:16:29 +00001048 int i, j;
danielk19772dca4ac2008-01-03 11:50:29 +00001049 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
drhe1a022e2012-09-17 17:16:53 +00001050 assert( pKeyInfo->aSortOrder!=0 );
drh5b843aa2013-10-30 13:46:01 +00001051 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
drhea678832008-12-10 19:26:22 +00001052 i = sqlite3Strlen30(zTemp);
drhd3d39e92004-05-20 22:16:29 +00001053 for(j=0; j<pKeyInfo->nField; j++){
1054 CollSeq *pColl = pKeyInfo->aColl[j];
drh261d8a52012-12-08 21:36:26 +00001055 const char *zColl = pColl ? pColl->zName : "nil";
1056 int n = sqlite3Strlen30(zColl);
drh464a2dd2014-12-05 14:36:15 +00001057 assert( pColl==0 || sqlite3ValidCollSeq(pColl) );
drh5b843aa2013-10-30 13:46:01 +00001058 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
1059 zColl = "B";
1060 n = 1;
1061 }
drh261d8a52012-12-08 21:36:26 +00001062 if( i+n>nTemp-6 ){
1063 memcpy(&zTemp[i],",...",4);
1064 break;
drhd3d39e92004-05-20 22:16:29 +00001065 }
drh261d8a52012-12-08 21:36:26 +00001066 zTemp[i++] = ',';
1067 if( pKeyInfo->aSortOrder[j] ){
1068 zTemp[i++] = '-';
1069 }
1070 memcpy(&zTemp[i], zColl, n+1);
1071 i += n;
drhd3d39e92004-05-20 22:16:29 +00001072 }
1073 zTemp[i++] = ')';
1074 zTemp[i] = 0;
1075 assert( i<nTemp );
drhd3d39e92004-05-20 22:16:29 +00001076 break;
1077 }
drh66a51672008-01-03 00:01:23 +00001078 case P4_COLLSEQ: {
danielk19772dca4ac2008-01-03 11:50:29 +00001079 CollSeq *pColl = pOp->p4.pColl;
drh5e6790c2013-11-12 20:18:14 +00001080 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
drhd3d39e92004-05-20 22:16:29 +00001081 break;
1082 }
drh66a51672008-01-03 00:01:23 +00001083 case P4_FUNCDEF: {
danielk19772dca4ac2008-01-03 11:50:29 +00001084 FuncDef *pDef = pOp->p4.pFunc;
drha967e882006-06-13 01:04:52 +00001085 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
drhf9b596e2004-05-26 16:54:42 +00001086 break;
1087 }
drh66a51672008-01-03 00:01:23 +00001088 case P4_INT64: {
danielk19772dca4ac2008-01-03 11:50:29 +00001089 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
drhd4e70eb2008-01-02 00:34:36 +00001090 break;
1091 }
drh66a51672008-01-03 00:01:23 +00001092 case P4_INT32: {
1093 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
drh598f1342007-10-23 15:39:45 +00001094 break;
1095 }
drh66a51672008-01-03 00:01:23 +00001096 case P4_REAL: {
danielk19772dca4ac2008-01-03 11:50:29 +00001097 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
drhd4e70eb2008-01-02 00:34:36 +00001098 break;
1099 }
drh66a51672008-01-03 00:01:23 +00001100 case P4_MEM: {
danielk19772dca4ac2008-01-03 11:50:29 +00001101 Mem *pMem = pOp->p4.pMem;
drhd4e70eb2008-01-02 00:34:36 +00001102 if( pMem->flags & MEM_Str ){
drh66a51672008-01-03 00:01:23 +00001103 zP4 = pMem->z;
drhd4e70eb2008-01-02 00:34:36 +00001104 }else if( pMem->flags & MEM_Int ){
1105 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
1106 }else if( pMem->flags & MEM_Real ){
drh74eaba42014-09-18 17:52:15 +00001107 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
drhb8475df2011-12-09 16:21:19 +00001108 }else if( pMem->flags & MEM_Null ){
1109 sqlite3_snprintf(nTemp, zTemp, "NULL");
drh56016892009-08-25 14:24:04 +00001110 }else{
1111 assert( pMem->flags & MEM_Blob );
1112 zP4 = "(blob)";
drhd4e70eb2008-01-02 00:34:36 +00001113 }
drh598f1342007-10-23 15:39:45 +00001114 break;
1115 }
drha967e882006-06-13 01:04:52 +00001116#ifndef SQLITE_OMIT_VIRTUALTABLE
drh66a51672008-01-03 00:01:23 +00001117 case P4_VTAB: {
danielk1977595a5232009-07-24 17:58:53 +00001118 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
drh19146192006-06-26 19:10:32 +00001119 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
drha967e882006-06-13 01:04:52 +00001120 break;
1121 }
1122#endif
drh0acb7e42008-06-25 00:12:41 +00001123 case P4_INTARRAY: {
1124 sqlite3_snprintf(nTemp, zTemp, "intarray");
1125 break;
1126 }
dan165921a2009-08-28 18:53:45 +00001127 case P4_SUBPROGRAM: {
1128 sqlite3_snprintf(nTemp, zTemp, "program");
1129 break;
1130 }
drh4a6f3aa2011-08-28 00:19:26 +00001131 case P4_ADVANCE: {
1132 zTemp[0] = 0;
1133 break;
1134 }
drhd3d39e92004-05-20 22:16:29 +00001135 default: {
danielk19772dca4ac2008-01-03 11:50:29 +00001136 zP4 = pOp->p4.z;
drh949f9cd2008-01-12 21:35:57 +00001137 if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +00001138 zP4 = zTemp;
drhd4e70eb2008-01-02 00:34:36 +00001139 zTemp[0] = 0;
drhd3d39e92004-05-20 22:16:29 +00001140 }
1141 }
1142 }
drh66a51672008-01-03 00:01:23 +00001143 assert( zP4!=0 );
drh66a51672008-01-03 00:01:23 +00001144 return zP4;
drhd3d39e92004-05-20 22:16:29 +00001145}
drhb7f91642004-10-31 02:22:47 +00001146#endif
drhd3d39e92004-05-20 22:16:29 +00001147
drh900b31e2007-08-28 02:27:51 +00001148/*
drhd0679ed2007-08-28 22:24:34 +00001149** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
drh3ebaee92010-05-06 21:37:22 +00001150**
drhbdaec522011-04-04 00:14:43 +00001151** The prepared statements need to know in advance the complete set of
drhe4c88c02012-01-04 12:57:45 +00001152** attached databases that will be use. A mask of these databases
1153** is maintained in p->btreeMask. The p->lockMask value is the subset of
1154** p->btreeMask of databases that will require a lock.
drh900b31e2007-08-28 02:27:51 +00001155*/
drhfb982642007-08-30 01:19:59 +00001156void sqlite3VdbeUsesBtree(Vdbe *p, int i){
drhfcd71b62011-04-05 22:08:24 +00001157 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
danielk197700e13612008-11-17 19:18:54 +00001158 assert( i<(int)sizeof(p->btreeMask)*8 );
drha7ab6d82014-07-21 15:44:39 +00001159 DbMaskSet(p->btreeMask, i);
drhdc5b0472011-04-06 22:05:53 +00001160 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
drha7ab6d82014-07-21 15:44:39 +00001161 DbMaskSet(p->lockMask, i);
drhdc5b0472011-04-06 22:05:53 +00001162 }
drh900b31e2007-08-28 02:27:51 +00001163}
1164
drhe54e0512011-04-05 17:31:56 +00001165#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001166/*
1167** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1168** this routine obtains the mutex associated with each BtShared structure
1169** that may be accessed by the VM passed as an argument. In doing so it also
1170** sets the BtShared.db member of each of the BtShared structures, ensuring
1171** that the correct busy-handler callback is invoked if required.
1172**
1173** If SQLite is not threadsafe but does support shared-cache mode, then
1174** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1175** of all of BtShared structures accessible via the database handle
1176** associated with the VM.
1177**
1178** If SQLite is not threadsafe and does not support shared-cache mode, this
1179** function is a no-op.
1180**
1181** The p->btreeMask field is a bitmask of all btrees that the prepared
1182** statement p will ever use. Let N be the number of bits in p->btreeMask
1183** corresponding to btrees that use shared cache. Then the runtime of
1184** this routine is N*N. But as N is rarely more than 1, this should not
1185** be a problem.
1186*/
1187void sqlite3VdbeEnter(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001188 int i;
drhdc5b0472011-04-06 22:05:53 +00001189 sqlite3 *db;
1190 Db *aDb;
1191 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001192 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001193 db = p->db;
1194 aDb = db->aDb;
1195 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001196 for(i=0; i<nDb; i++){
1197 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001198 sqlite3BtreeEnter(aDb[i].pBt);
1199 }
1200 }
drhbdaec522011-04-04 00:14:43 +00001201}
drhe54e0512011-04-05 17:31:56 +00001202#endif
drhbdaec522011-04-04 00:14:43 +00001203
drhe54e0512011-04-05 17:31:56 +00001204#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001205/*
1206** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1207*/
1208void sqlite3VdbeLeave(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001209 int i;
drhdc5b0472011-04-06 22:05:53 +00001210 sqlite3 *db;
1211 Db *aDb;
1212 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001213 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001214 db = p->db;
1215 aDb = db->aDb;
1216 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001217 for(i=0; i<nDb; i++){
1218 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001219 sqlite3BtreeLeave(aDb[i].pBt);
1220 }
1221 }
drhbdaec522011-04-04 00:14:43 +00001222}
drhbdaec522011-04-04 00:14:43 +00001223#endif
drhd3d39e92004-05-20 22:16:29 +00001224
danielk19778b60e0f2005-01-12 09:10:39 +00001225#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001226/*
1227** Print a single opcode. This routine is used for debugging only.
1228*/
danielk19774adee202004-05-08 08:23:19 +00001229void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
drh66a51672008-01-03 00:01:23 +00001230 char *zP4;
drhd3d39e92004-05-20 22:16:29 +00001231 char zPtr[50];
drh81316f82013-10-29 20:40:47 +00001232 char zCom[100];
drh26198bb2013-10-31 11:15:09 +00001233 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
drh9a324642003-09-06 20:12:01 +00001234 if( pOut==0 ) pOut = stdout;
drh66a51672008-01-03 00:01:23 +00001235 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
drhc7379ce2013-10-30 02:28:23 +00001236#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001237 displayComment(pOp, zP4, zCom, sizeof(zCom));
1238#else
drh2926f962014-02-17 01:13:28 +00001239 zCom[0] = 0;
drh81316f82013-10-29 20:40:47 +00001240#endif
drh4eded602013-12-20 15:59:20 +00001241 /* NB: The sqlite3OpcodeName() function is implemented by code created
1242 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1243 ** information from the vdbe.c source text */
danielk197711641c12008-01-03 08:18:30 +00001244 fprintf(pOut, zFormat1, pc,
drh1db639c2008-01-17 02:36:28 +00001245 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
drh81316f82013-10-29 20:40:47 +00001246 zCom
drh1db639c2008-01-17 02:36:28 +00001247 );
drh9a324642003-09-06 20:12:01 +00001248 fflush(pOut);
1249}
1250#endif
1251
1252/*
drh76ff3a02004-09-24 22:32:30 +00001253** Release an array of N Mem elements
1254*/
drhc890fec2008-08-01 20:10:08 +00001255static void releaseMemArray(Mem *p, int N){
danielk1977a7a8e142008-02-13 18:25:27 +00001256 if( p && N ){
drh069c23c2014-09-19 16:13:12 +00001257 Mem *pEnd = &p[N];
danielk1977a7a8e142008-02-13 18:25:27 +00001258 sqlite3 *db = p->db;
drh8df32842008-12-09 02:51:23 +00001259 u8 malloc_failed = db->mallocFailed;
dand46def72010-07-24 11:28:28 +00001260 if( db->pnBytesFreed ){
drh069c23c2014-09-19 16:13:12 +00001261 do{
drh17bcb102014-09-18 21:25:33 +00001262 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
drh069c23c2014-09-19 16:13:12 +00001263 }while( (++p)<pEnd );
drhc176c272010-07-26 13:57:59 +00001264 return;
1265 }
drh069c23c2014-09-19 16:13:12 +00001266 do{
danielk1977e972e032008-09-19 18:32:26 +00001267 assert( (&p[1])==pEnd || p[0].db==p[1].db );
drh75fd0542014-03-01 16:24:44 +00001268 assert( sqlite3VdbeCheckMemInvariants(p) );
danielk1977e972e032008-09-19 18:32:26 +00001269
1270 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1271 ** that takes advantage of the fact that the memory cell value is
1272 ** being set to NULL after releasing any dynamic resources.
1273 **
1274 ** The justification for duplicating code is that according to
1275 ** callgrind, this causes a certain test case to hit the CPU 4.7
1276 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1277 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1278 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1279 ** with no indexes using a single prepared INSERT statement, bind()
1280 ** and reset(). Inserts are grouped into a transaction.
1281 */
drhb6e8fd12014-03-06 01:56:33 +00001282 testcase( p->flags & MEM_Agg );
1283 testcase( p->flags & MEM_Dyn );
1284 testcase( p->flags & MEM_Frame );
1285 testcase( p->flags & MEM_RowSet );
dan165921a2009-08-28 18:53:45 +00001286 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
danielk1977e972e032008-09-19 18:32:26 +00001287 sqlite3VdbeMemRelease(p);
drh17bcb102014-09-18 21:25:33 +00001288 }else if( p->szMalloc ){
danielk1977e972e032008-09-19 18:32:26 +00001289 sqlite3DbFree(db, p->zMalloc);
drh17bcb102014-09-18 21:25:33 +00001290 p->szMalloc = 0;
danielk1977e972e032008-09-19 18:32:26 +00001291 }
1292
drha5750cf2014-02-07 13:20:31 +00001293 p->flags = MEM_Undefined;
drh069c23c2014-09-19 16:13:12 +00001294 }while( (++p)<pEnd );
danielk1977a7a8e142008-02-13 18:25:27 +00001295 db->mallocFailed = malloc_failed;
drh76ff3a02004-09-24 22:32:30 +00001296 }
1297}
1298
dan65a7cd12009-09-01 12:16:01 +00001299/*
1300** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1301** allocated by the OP_Program opcode in sqlite3VdbeExec().
1302*/
dan165921a2009-08-28 18:53:45 +00001303void sqlite3VdbeFrameDelete(VdbeFrame *p){
1304 int i;
1305 Mem *aMem = VdbeFrameMem(p);
1306 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1307 for(i=0; i<p->nChildCsr; i++){
1308 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1309 }
1310 releaseMemArray(aMem, p->nChildMem);
1311 sqlite3DbFree(p->v->db, p);
1312}
1313
drhb7f91642004-10-31 02:22:47 +00001314#ifndef SQLITE_OMIT_EXPLAIN
drh76ff3a02004-09-24 22:32:30 +00001315/*
drh9a324642003-09-06 20:12:01 +00001316** Give a listing of the program in the virtual machine.
1317**
danielk19774adee202004-05-08 08:23:19 +00001318** The interface is the same as sqlite3VdbeExec(). But instead of
drh9a324642003-09-06 20:12:01 +00001319** running the code, it invokes the callback once for each instruction.
1320** This feature is used to implement "EXPLAIN".
drh9cbf3422008-01-17 16:22:13 +00001321**
1322** When p->explain==1, each instruction is listed. When
1323** p->explain==2, only OP_Explain instructions are listed and these
1324** are shown in a different format. p->explain==2 is used to implement
1325** EXPLAIN QUERY PLAN.
drh5cfa5842009-12-31 20:35:08 +00001326**
1327** When p->explain==1, first the main program is listed, then each of
1328** the trigger subprograms are listed one by one.
drh9a324642003-09-06 20:12:01 +00001329*/
danielk19774adee202004-05-08 08:23:19 +00001330int sqlite3VdbeList(
drh9a324642003-09-06 20:12:01 +00001331 Vdbe *p /* The VDBE */
1332){
drh5cfa5842009-12-31 20:35:08 +00001333 int nRow; /* Stop when row count reaches this */
dan165921a2009-08-28 18:53:45 +00001334 int nSub = 0; /* Number of sub-vdbes seen so far */
1335 SubProgram **apSub = 0; /* Array of sub-vdbes */
drh5cfa5842009-12-31 20:35:08 +00001336 Mem *pSub = 0; /* Memory cell hold array of subprogs */
1337 sqlite3 *db = p->db; /* The database connection */
1338 int i; /* Loop counter */
1339 int rc = SQLITE_OK; /* Return code */
drh9734e6e2011-10-07 18:24:25 +00001340 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
drh9a324642003-09-06 20:12:01 +00001341
drh9a324642003-09-06 20:12:01 +00001342 assert( p->explain );
drh5f82e3c2009-07-06 00:44:08 +00001343 assert( p->magic==VDBE_MAGIC_RUN );
danielk19776c359f02008-11-21 16:58:03 +00001344 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
danielk197718f41892004-05-22 07:27:46 +00001345
drh9cbf3422008-01-17 16:22:13 +00001346 /* Even though this opcode does not use dynamic strings for
1347 ** the result, result columns may become dynamic if the user calls
drh4f26d6c2004-05-26 23:25:30 +00001348 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
danielk197718f41892004-05-22 07:27:46 +00001349 */
dan165921a2009-08-28 18:53:45 +00001350 releaseMemArray(pMem, 8);
drh9734e6e2011-10-07 18:24:25 +00001351 p->pResultSet = 0;
danielk197718f41892004-05-22 07:27:46 +00001352
danielk19776c359f02008-11-21 16:58:03 +00001353 if( p->rc==SQLITE_NOMEM ){
1354 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1355 ** sqlite3_column_text16() failed. */
1356 db->mallocFailed = 1;
1357 return SQLITE_ERROR;
1358 }
1359
drh5cfa5842009-12-31 20:35:08 +00001360 /* When the number of output rows reaches nRow, that means the
1361 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1362 ** nRow is the sum of the number of rows in the main program, plus
1363 ** the sum of the number of rows in all trigger subprograms encountered
1364 ** so far. The nRow value will increase as new trigger subprograms are
1365 ** encountered, but p->pc will eventually catch up to nRow.
1366 */
dan165921a2009-08-28 18:53:45 +00001367 nRow = p->nOp;
1368 if( p->explain==1 ){
drh5cfa5842009-12-31 20:35:08 +00001369 /* The first 8 memory cells are used for the result set. So we will
1370 ** commandeer the 9th cell to use as storage for an array of pointers
1371 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1372 ** cells. */
1373 assert( p->nMem>9 );
dan165921a2009-08-28 18:53:45 +00001374 pSub = &p->aMem[9];
1375 if( pSub->flags&MEM_Blob ){
drh5cfa5842009-12-31 20:35:08 +00001376 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1377 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
dan165921a2009-08-28 18:53:45 +00001378 nSub = pSub->n/sizeof(Vdbe*);
1379 apSub = (SubProgram **)pSub->z;
1380 }
1381 for(i=0; i<nSub; i++){
1382 nRow += apSub[i]->nOp;
1383 }
1384 }
1385
drhecc92422005-09-10 16:46:12 +00001386 do{
1387 i = p->pc++;
dan165921a2009-08-28 18:53:45 +00001388 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1389 if( i>=nRow ){
drh826fb5a2004-02-14 23:59:57 +00001390 p->rc = SQLITE_OK;
1391 rc = SQLITE_DONE;
drh881feaa2006-07-26 01:39:30 +00001392 }else if( db->u1.isInterrupted ){
drhc5cdca62005-01-11 16:54:14 +00001393 p->rc = SQLITE_INTERRUPT;
drh826fb5a2004-02-14 23:59:57 +00001394 rc = SQLITE_ERROR;
drhf089aa42008-07-08 19:34:06 +00001395 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
drh826fb5a2004-02-14 23:59:57 +00001396 }else{
drh81316f82013-10-29 20:40:47 +00001397 char *zP4;
dan165921a2009-08-28 18:53:45 +00001398 Op *pOp;
1399 if( i<p->nOp ){
drh5cfa5842009-12-31 20:35:08 +00001400 /* The output line number is small enough that we are still in the
1401 ** main program. */
dan165921a2009-08-28 18:53:45 +00001402 pOp = &p->aOp[i];
1403 }else{
drh5cfa5842009-12-31 20:35:08 +00001404 /* We are currently listing subprograms. Figure out which one and
1405 ** pick up the appropriate opcode. */
dan165921a2009-08-28 18:53:45 +00001406 int j;
1407 i -= p->nOp;
1408 for(j=0; i>=apSub[j]->nOp; j++){
1409 i -= apSub[j]->nOp;
1410 }
1411 pOp = &apSub[j]->aOp[i];
1412 }
danielk19770d78bae2008-01-03 07:09:48 +00001413 if( p->explain==1 ){
1414 pMem->flags = MEM_Int;
danielk19770d78bae2008-01-03 07:09:48 +00001415 pMem->u.i = i; /* Program counter */
1416 pMem++;
1417
1418 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001419 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
danielk19770d78bae2008-01-03 07:09:48 +00001420 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001421 pMem->n = sqlite3Strlen30(pMem->z);
danielk19770d78bae2008-01-03 07:09:48 +00001422 pMem->enc = SQLITE_UTF8;
1423 pMem++;
dan165921a2009-08-28 18:53:45 +00001424
drh5cfa5842009-12-31 20:35:08 +00001425 /* When an OP_Program opcode is encounter (the only opcode that has
1426 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1427 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1428 ** has not already been seen.
1429 */
dan165921a2009-08-28 18:53:45 +00001430 if( pOp->p4type==P4_SUBPROGRAM ){
1431 int nByte = (nSub+1)*sizeof(SubProgram*);
1432 int j;
1433 for(j=0; j<nSub; j++){
1434 if( apSub[j]==pOp->p4.pProgram ) break;
1435 }
dan2b9ee772012-03-31 09:59:44 +00001436 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
dan165921a2009-08-28 18:53:45 +00001437 apSub = (SubProgram **)pSub->z;
1438 apSub[nSub++] = pOp->p4.pProgram;
1439 pSub->flags |= MEM_Blob;
1440 pSub->n = nSub*sizeof(SubProgram*);
1441 }
1442 }
danielk19770d78bae2008-01-03 07:09:48 +00001443 }
drheb2e1762004-05-27 01:53:56 +00001444
1445 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001446 pMem->u.i = pOp->p1; /* P1 */
drheb2e1762004-05-27 01:53:56 +00001447 pMem++;
1448
1449 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001450 pMem->u.i = pOp->p2; /* P2 */
drheb2e1762004-05-27 01:53:56 +00001451 pMem++;
1452
dan2ce22452010-11-08 19:01:16 +00001453 pMem->flags = MEM_Int;
1454 pMem->u.i = pOp->p3; /* P3 */
dan2ce22452010-11-08 19:01:16 +00001455 pMem++;
danielk19770d78bae2008-01-03 07:09:48 +00001456
drh322f2852014-09-19 00:43:39 +00001457 if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
danielk1977357864e2009-03-25 15:43:08 +00001458 assert( p->db->mallocFailed );
1459 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001460 }
drhc91b2fd2014-03-01 18:13:23 +00001461 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001462 zP4 = displayP4(pOp, pMem->z, 32);
1463 if( zP4!=pMem->z ){
1464 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
danielk1977a7a8e142008-02-13 18:25:27 +00001465 }else{
1466 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001467 pMem->n = sqlite3Strlen30(pMem->z);
danielk1977a7a8e142008-02-13 18:25:27 +00001468 pMem->enc = SQLITE_UTF8;
1469 }
danielk19770d78bae2008-01-03 07:09:48 +00001470 pMem++;
drheb2e1762004-05-27 01:53:56 +00001471
danielk19770d78bae2008-01-03 07:09:48 +00001472 if( p->explain==1 ){
drh322f2852014-09-19 00:43:39 +00001473 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
danielk1977357864e2009-03-25 15:43:08 +00001474 assert( p->db->mallocFailed );
1475 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001476 }
drhc91b2fd2014-03-01 18:13:23 +00001477 pMem->flags = MEM_Str|MEM_Term;
drh85e5f0d2008-02-19 18:28:13 +00001478 pMem->n = 2;
1479 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
danielk19770d78bae2008-01-03 07:09:48 +00001480 pMem->enc = SQLITE_UTF8;
1481 pMem++;
1482
drhc7379ce2013-10-30 02:28:23 +00001483#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh322f2852014-09-19 00:43:39 +00001484 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
drh81316f82013-10-29 20:40:47 +00001485 assert( p->db->mallocFailed );
1486 return SQLITE_ERROR;
drh52391cb2008-02-14 23:44:13 +00001487 }
drhc91b2fd2014-03-01 18:13:23 +00001488 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001489 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
drh81316f82013-10-29 20:40:47 +00001490 pMem->enc = SQLITE_UTF8;
1491#else
1492 pMem->flags = MEM_Null; /* Comment */
drh81316f82013-10-29 20:40:47 +00001493#endif
danielk19770d78bae2008-01-03 07:09:48 +00001494 }
1495
dan2ce22452010-11-08 19:01:16 +00001496 p->nResColumn = 8 - 4*(p->explain-1);
drh9734e6e2011-10-07 18:24:25 +00001497 p->pResultSet = &p->aMem[1];
drh826fb5a2004-02-14 23:59:57 +00001498 p->rc = SQLITE_OK;
1499 rc = SQLITE_ROW;
drh9a324642003-09-06 20:12:01 +00001500 }
drh826fb5a2004-02-14 23:59:57 +00001501 return rc;
drh9a324642003-09-06 20:12:01 +00001502}
drhb7f91642004-10-31 02:22:47 +00001503#endif /* SQLITE_OMIT_EXPLAIN */
drh9a324642003-09-06 20:12:01 +00001504
drh7c4ac0c2007-04-05 11:25:58 +00001505#ifdef SQLITE_DEBUG
drh9a324642003-09-06 20:12:01 +00001506/*
drh3f7d4e42004-07-24 14:35:58 +00001507** Print the SQL that was used to generate a VDBE program.
1508*/
1509void sqlite3VdbePrintSql(Vdbe *p){
drh84e55a82013-11-13 17:58:23 +00001510 const char *z = 0;
1511 if( p->zSql ){
1512 z = p->zSql;
1513 }else if( p->nOp>=1 ){
1514 const VdbeOp *pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001515 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh84e55a82013-11-13 17:58:23 +00001516 z = pOp->p4.z;
1517 while( sqlite3Isspace(*z) ) z++;
1518 }
drh3f7d4e42004-07-24 14:35:58 +00001519 }
drh84e55a82013-11-13 17:58:23 +00001520 if( z ) printf("SQL: [%s]\n", z);
drh3f7d4e42004-07-24 14:35:58 +00001521}
drh7c4ac0c2007-04-05 11:25:58 +00001522#endif
drh3f7d4e42004-07-24 14:35:58 +00001523
drh602c2372007-03-01 00:29:13 +00001524#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1525/*
1526** Print an IOTRACE message showing SQL content.
1527*/
1528void sqlite3VdbeIOTraceSql(Vdbe *p){
1529 int nOp = p->nOp;
1530 VdbeOp *pOp;
mlcreech3a00f902008-03-04 17:45:01 +00001531 if( sqlite3IoTrace==0 ) return;
drh602c2372007-03-01 00:29:13 +00001532 if( nOp<1 ) return;
drh949f9cd2008-01-12 21:35:57 +00001533 pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001534 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh602c2372007-03-01 00:29:13 +00001535 int i, j;
drh00a18e42007-08-13 11:10:34 +00001536 char z[1000];
drh949f9cd2008-01-12 21:35:57 +00001537 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
danielk197778ca0e72009-01-20 16:53:39 +00001538 for(i=0; sqlite3Isspace(z[i]); i++){}
drh602c2372007-03-01 00:29:13 +00001539 for(j=0; z[i]; i++){
danielk197778ca0e72009-01-20 16:53:39 +00001540 if( sqlite3Isspace(z[i]) ){
drh602c2372007-03-01 00:29:13 +00001541 if( z[i-1]!=' ' ){
1542 z[j++] = ' ';
1543 }
1544 }else{
1545 z[j++] = z[i];
1546 }
1547 }
1548 z[j] = 0;
mlcreech3a00f902008-03-04 17:45:01 +00001549 sqlite3IoTrace("SQL %s\n", z);
drh602c2372007-03-01 00:29:13 +00001550 }
1551}
1552#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1553
drhb2771ce2009-02-20 01:28:59 +00001554/*
drh4800b2e2009-12-08 15:35:22 +00001555** Allocate space from a fixed size buffer and return a pointer to
1556** that space. If insufficient space is available, return NULL.
1557**
1558** The pBuf parameter is the initial value of a pointer which will
1559** receive the new memory. pBuf is normally NULL. If pBuf is not
1560** NULL, it means that memory space has already been allocated and that
1561** this routine should not allocate any new memory. When pBuf is not
1562** NULL simply return pBuf. Only allocate new memory space when pBuf
1563** is NULL.
drhb2771ce2009-02-20 01:28:59 +00001564**
1565** nByte is the number of bytes of space needed.
1566**
drh19875c82009-12-08 19:58:19 +00001567** *ppFrom points to available space and pEnd points to the end of the
1568** available space. When space is allocated, *ppFrom is advanced past
1569** the end of the allocated space.
drhb2771ce2009-02-20 01:28:59 +00001570**
1571** *pnByte is a counter of the number of bytes of space that have failed
1572** to allocate. If there is insufficient space in *ppFrom to satisfy the
danielk1977d336e222009-02-20 10:58:41 +00001573** request, then increment *pnByte by the amount of the request.
drhb2771ce2009-02-20 01:28:59 +00001574*/
drh4800b2e2009-12-08 15:35:22 +00001575static void *allocSpace(
1576 void *pBuf, /* Where return pointer will be stored */
drhb2771ce2009-02-20 01:28:59 +00001577 int nByte, /* Number of bytes to allocate */
1578 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
danielk1977d336e222009-02-20 10:58:41 +00001579 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
drhb2771ce2009-02-20 01:28:59 +00001580 int *pnByte /* If allocation cannot be made, increment *pnByte */
1581){
drhea598cb2009-04-05 12:22:08 +00001582 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
drh4800b2e2009-12-08 15:35:22 +00001583 if( pBuf ) return pBuf;
1584 nByte = ROUND8(nByte);
1585 if( &(*ppFrom)[nByte] <= pEnd ){
1586 pBuf = (void*)*ppFrom;
1587 *ppFrom += nByte;
1588 }else{
1589 *pnByte += nByte;
drhb2771ce2009-02-20 01:28:59 +00001590 }
drh4800b2e2009-12-08 15:35:22 +00001591 return pBuf;
drhb2771ce2009-02-20 01:28:59 +00001592}
drh602c2372007-03-01 00:29:13 +00001593
drh3f7d4e42004-07-24 14:35:58 +00001594/*
drh124c0b42011-06-01 18:15:55 +00001595** Rewind the VDBE back to the beginning in preparation for
1596** running it.
drh9a324642003-09-06 20:12:01 +00001597*/
drh124c0b42011-06-01 18:15:55 +00001598void sqlite3VdbeRewind(Vdbe *p){
1599#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1600 int i;
1601#endif
drh9a324642003-09-06 20:12:01 +00001602 assert( p!=0 );
drh9a324642003-09-06 20:12:01 +00001603 assert( p->magic==VDBE_MAGIC_INIT );
1604
drhc16a03b2004-09-15 13:38:10 +00001605 /* There should be at least one opcode.
drh9a324642003-09-06 20:12:01 +00001606 */
drhc16a03b2004-09-15 13:38:10 +00001607 assert( p->nOp>0 );
drh9a324642003-09-06 20:12:01 +00001608
danielk197700e13612008-11-17 19:18:54 +00001609 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
danielk1977634f2982005-03-28 08:44:07 +00001610 p->magic = VDBE_MAGIC_RUN;
1611
drh124c0b42011-06-01 18:15:55 +00001612#ifdef SQLITE_DEBUG
1613 for(i=1; i<p->nMem; i++){
1614 assert( p->aMem[i].db==p->db );
1615 }
1616#endif
1617 p->pc = -1;
1618 p->rc = SQLITE_OK;
1619 p->errorAction = OE_Abort;
1620 p->magic = VDBE_MAGIC_RUN;
1621 p->nChange = 0;
1622 p->cacheCtr = 1;
1623 p->minWriteFileFormat = 255;
1624 p->iStatement = 0;
1625 p->nFkConstraint = 0;
1626#ifdef VDBE_PROFILE
1627 for(i=0; i<p->nOp; i++){
1628 p->aOp[i].cnt = 0;
1629 p->aOp[i].cycles = 0;
1630 }
1631#endif
1632}
1633
1634/*
1635** Prepare a virtual machine for execution for the first time after
1636** creating the virtual machine. This involves things such
drh7abda852014-09-19 16:02:06 +00001637** as allocating registers and initializing the program counter.
drh124c0b42011-06-01 18:15:55 +00001638** After the VDBE has be prepped, it can be executed by one or more
1639** calls to sqlite3VdbeExec().
1640**
peter.d.reid60ec9142014-09-06 16:39:46 +00001641** This function may be called exactly once on each virtual machine.
drh124c0b42011-06-01 18:15:55 +00001642** After this routine is called the VM has been "packaged" and is ready
peter.d.reid60ec9142014-09-06 16:39:46 +00001643** to run. After this routine is called, further calls to
drh124c0b42011-06-01 18:15:55 +00001644** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1645** the Vdbe from the Parse object that helped generate it so that the
1646** the Vdbe becomes an independent entity and the Parse object can be
1647** destroyed.
1648**
1649** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1650** to its initial state after it has been run.
1651*/
1652void sqlite3VdbeMakeReady(
1653 Vdbe *p, /* The VDBE */
1654 Parse *pParse /* Parsing context */
1655){
1656 sqlite3 *db; /* The database connection */
1657 int nVar; /* Number of parameters */
1658 int nMem; /* Number of VM memory registers */
1659 int nCursor; /* Number of cursors required */
1660 int nArg; /* Number of arguments in subprograms */
dan1d8cb212011-12-09 13:24:16 +00001661 int nOnce; /* Number of OP_Once instructions */
drh124c0b42011-06-01 18:15:55 +00001662 int n; /* Loop counter */
1663 u8 *zCsr; /* Memory available for allocation */
1664 u8 *zEnd; /* First byte past allocated memory */
1665 int nByte; /* How much extra memory is needed */
1666
1667 assert( p!=0 );
1668 assert( p->nOp>0 );
1669 assert( pParse!=0 );
1670 assert( p->magic==VDBE_MAGIC_INIT );
drh73d5b8f2013-12-23 19:09:07 +00001671 assert( pParse==p->pParse );
drh124c0b42011-06-01 18:15:55 +00001672 db = p->db;
1673 assert( db->mallocFailed==0 );
1674 nVar = pParse->nVar;
1675 nMem = pParse->nMem;
1676 nCursor = pParse->nTab;
1677 nArg = pParse->nMaxArg;
dan1d8cb212011-12-09 13:24:16 +00001678 nOnce = pParse->nOnce;
drh20e226d2012-01-01 13:58:53 +00001679 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
drh124c0b42011-06-01 18:15:55 +00001680
danielk1977cd3e8f72008-03-25 09:47:35 +00001681 /* For each cursor required, also allocate a memory cell. Memory
1682 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1683 ** the vdbe program. Instead they are used to allocate space for
drhdfe88ec2008-11-03 20:55:06 +00001684 ** VdbeCursor/BtCursor structures. The blob of memory associated with
danielk1977cd3e8f72008-03-25 09:47:35 +00001685 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1686 ** stores the blob of memory associated with cursor 1, etc.
1687 **
1688 ** See also: allocateCursor().
1689 */
1690 nMem += nCursor;
1691
danielk19776ab3a2e2009-02-19 14:39:25 +00001692 /* Allocate space for memory registers, SQL variables, VDBE cursors and
drh124c0b42011-06-01 18:15:55 +00001693 ** an array to marshal SQL function arguments in.
drh9a324642003-09-06 20:12:01 +00001694 */
drh73d5b8f2013-12-23 19:09:07 +00001695 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
1696 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
drh19875c82009-12-08 19:58:19 +00001697
drh124c0b42011-06-01 18:15:55 +00001698 resolveP2Values(p, &nArg);
1699 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1700 if( pParse->explain && nMem<10 ){
1701 nMem = 10;
1702 }
1703 memset(zCsr, 0, zEnd-zCsr);
1704 zCsr += (zCsr - (u8*)0)&7;
1705 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
drhaab910c2011-06-27 00:01:22 +00001706 p->expired = 0;
drh124c0b42011-06-01 18:15:55 +00001707
1708 /* Memory for registers, parameters, cursor, etc, is allocated in two
1709 ** passes. On the first pass, we try to reuse unused space at the
1710 ** end of the opcode array. If we are unable to satisfy all memory
1711 ** requirements by reusing the opcode array tail, then the second
1712 ** pass will fill in the rest using a fresh allocation.
1713 **
1714 ** This two-pass approach that reuses as much memory as possible from
1715 ** the leftover space at the end of the opcode array can significantly
1716 ** reduce the amount of memory held by a prepared statement.
1717 */
1718 do {
1719 nByte = 0;
1720 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
1721 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
1722 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
1723 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
1724 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
1725 &zCsr, zEnd, &nByte);
drhb8475df2011-12-09 16:21:19 +00001726 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
dane2f771b2014-11-03 15:33:17 +00001727#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan43764a82014-11-01 21:00:04 +00001728 p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
dane2f771b2014-11-03 15:33:17 +00001729#endif
drh124c0b42011-06-01 18:15:55 +00001730 if( nByte ){
1731 p->pFree = sqlite3DbMallocZero(db, nByte);
drh0f7eb612006-08-08 13:51:43 +00001732 }
drh124c0b42011-06-01 18:15:55 +00001733 zCsr = p->pFree;
1734 zEnd = &zCsr[nByte];
1735 }while( nByte && !db->mallocFailed );
drhb2771ce2009-02-20 01:28:59 +00001736
drhd2a56232013-01-28 19:00:20 +00001737 p->nCursor = nCursor;
dan1d8cb212011-12-09 13:24:16 +00001738 p->nOnceFlag = nOnce;
drh124c0b42011-06-01 18:15:55 +00001739 if( p->aVar ){
1740 p->nVar = (ynVar)nVar;
1741 for(n=0; n<nVar; n++){
1742 p->aVar[n].flags = MEM_Null;
1743 p->aVar[n].db = db;
danielk197754db47e2004-05-19 10:36:43 +00001744 }
drh82a48512003-09-06 22:45:20 +00001745 }
drh9b5444a2014-12-02 13:46:53 +00001746 if( p->azVar && pParse->nzVar>0 ){
drh124c0b42011-06-01 18:15:55 +00001747 p->nzVar = pParse->nzVar;
1748 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
1749 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
danielk1977b3bce662005-01-29 08:32:43 +00001750 }
drh124c0b42011-06-01 18:15:55 +00001751 if( p->aMem ){
1752 p->aMem--; /* aMem[] goes from 1..nMem */
1753 p->nMem = nMem; /* not from 0..nMem-1 */
1754 for(n=1; n<=nMem; n++){
drha5750cf2014-02-07 13:20:31 +00001755 p->aMem[n].flags = MEM_Undefined;
drh124c0b42011-06-01 18:15:55 +00001756 p->aMem[n].db = db;
drhcf64d8b2003-12-31 17:57:10 +00001757 }
drh9a324642003-09-06 20:12:01 +00001758 }
drh124c0b42011-06-01 18:15:55 +00001759 p->explain = pParse->explain;
1760 sqlite3VdbeRewind(p);
drh9a324642003-09-06 20:12:01 +00001761}
1762
drh9a324642003-09-06 20:12:01 +00001763/*
danielk1977cd3e8f72008-03-25 09:47:35 +00001764** Close a VDBE cursor and release all the resources that cursor
1765** happens to hold.
drh9a324642003-09-06 20:12:01 +00001766*/
drhdfe88ec2008-11-03 20:55:06 +00001767void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
drh4774b132004-06-12 20:12:51 +00001768 if( pCx==0 ){
1769 return;
1770 }
dana20fde62011-07-12 14:28:05 +00001771 sqlite3VdbeSorterClose(p->db, pCx);
drh9a324642003-09-06 20:12:01 +00001772 if( pCx->pBt ){
danielk19774adee202004-05-08 08:23:19 +00001773 sqlite3BtreeClose(pCx->pBt);
drh34004ce2008-07-11 16:15:17 +00001774 /* The pCx->pCursor will be close automatically, if it exists, by
1775 ** the call above. */
1776 }else if( pCx->pCursor ){
1777 sqlite3BtreeCloseCursor(pCx->pCursor);
drh9a324642003-09-06 20:12:01 +00001778 }
drh9eff6162006-06-12 21:59:13 +00001779#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf526dca2014-10-13 17:42:05 +00001780 else if( pCx->pVtabCursor ){
drh9eff6162006-06-12 21:59:13 +00001781 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
drh5cc10232013-11-21 01:04:02 +00001782 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
danielk1977be718892006-06-23 08:05:19 +00001783 p->inVtabMethod = 1;
drh9eff6162006-06-12 21:59:13 +00001784 pModule->xClose(pVtabCursor);
danielk1977be718892006-06-23 08:05:19 +00001785 p->inVtabMethod = 0;
drh9eff6162006-06-12 21:59:13 +00001786 }
1787#endif
drh9a324642003-09-06 20:12:01 +00001788}
1789
dan65a7cd12009-09-01 12:16:01 +00001790/*
1791** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1792** is used, for example, when a trigger sub-program is halted to restore
1793** control to the main program.
1794*/
dan165921a2009-08-28 18:53:45 +00001795int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
1796 Vdbe *v = pFrame->v;
dane2f771b2014-11-03 15:33:17 +00001797#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan43764a82014-11-01 21:00:04 +00001798 v->anExec = pFrame->anExec;
dane2f771b2014-11-03 15:33:17 +00001799#endif
dan1d8cb212011-12-09 13:24:16 +00001800 v->aOnceFlag = pFrame->aOnceFlag;
1801 v->nOnceFlag = pFrame->nOnceFlag;
dan165921a2009-08-28 18:53:45 +00001802 v->aOp = pFrame->aOp;
1803 v->nOp = pFrame->nOp;
1804 v->aMem = pFrame->aMem;
1805 v->nMem = pFrame->nMem;
1806 v->apCsr = pFrame->apCsr;
1807 v->nCursor = pFrame->nCursor;
dan76d462e2009-08-30 11:42:51 +00001808 v->db->lastRowid = pFrame->lastRowid;
1809 v->nChange = pFrame->nChange;
danc3da6672014-10-28 18:24:16 +00001810 v->db->nChange = pFrame->nDbChange;
dan165921a2009-08-28 18:53:45 +00001811 return pFrame->pc;
1812}
1813
drh9a324642003-09-06 20:12:01 +00001814/*
drh5f82e3c2009-07-06 00:44:08 +00001815** Close all cursors.
dan165921a2009-08-28 18:53:45 +00001816**
1817** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1818** cell array. This is necessary as the memory cell array may contain
1819** pointers to VdbeFrame objects, which may in turn contain pointers to
1820** open cursors.
drh9a324642003-09-06 20:12:01 +00001821*/
drh5f82e3c2009-07-06 00:44:08 +00001822static void closeAllCursors(Vdbe *p){
dan165921a2009-08-28 18:53:45 +00001823 if( p->pFrame ){
drh23272752011-03-06 21:54:33 +00001824 VdbeFrame *pFrame;
dan165921a2009-08-28 18:53:45 +00001825 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
1826 sqlite3VdbeFrameRestore(pFrame);
drhf526dca2014-10-13 17:42:05 +00001827 p->pFrame = 0;
1828 p->nFrame = 0;
dan165921a2009-08-28 18:53:45 +00001829 }
drhf526dca2014-10-13 17:42:05 +00001830 assert( p->nFrame==0 );
dan165921a2009-08-28 18:53:45 +00001831
dan523a0872009-08-31 05:23:32 +00001832 if( p->apCsr ){
1833 int i;
1834 for(i=0; i<p->nCursor; i++){
1835 VdbeCursor *pC = p->apCsr[i];
1836 if( pC ){
1837 sqlite3VdbeFreeCursor(p, pC);
1838 p->apCsr[i] = 0;
1839 }
danielk1977be718892006-06-23 08:05:19 +00001840 }
drh9a324642003-09-06 20:12:01 +00001841 }
dan523a0872009-08-31 05:23:32 +00001842 if( p->aMem ){
1843 releaseMemArray(&p->aMem[1], p->nMem);
1844 }
dan27106572010-12-01 08:04:47 +00001845 while( p->pDelFrame ){
1846 VdbeFrame *pDel = p->pDelFrame;
1847 p->pDelFrame = pDel->pParent;
1848 sqlite3VdbeFrameDelete(pDel);
1849 }
dan0c547792013-07-18 17:12:08 +00001850
1851 /* Delete any auxdata allocations made by the VM */
drhf526dca2014-10-13 17:42:05 +00001852 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
dan0c547792013-07-18 17:12:08 +00001853 assert( p->pAuxData==0 );
drh9a324642003-09-06 20:12:01 +00001854}
1855
1856/*
drh7abda852014-09-19 16:02:06 +00001857** Clean up the VM after a single run.
drh9a324642003-09-06 20:12:01 +00001858*/
drhc890fec2008-08-01 20:10:08 +00001859static void Cleanup(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00001860 sqlite3 *db = p->db;
dan165921a2009-08-28 18:53:45 +00001861
1862#ifdef SQLITE_DEBUG
1863 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1864 ** Vdbe.aMem[] arrays have already been cleaned up. */
1865 int i;
drhb8475df2011-12-09 16:21:19 +00001866 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
1867 if( p->aMem ){
drha5750cf2014-02-07 13:20:31 +00001868 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
drhb8475df2011-12-09 16:21:19 +00001869 }
dan165921a2009-08-28 18:53:45 +00001870#endif
1871
drh633e6d52008-07-28 19:34:53 +00001872 sqlite3DbFree(db, p->zErrMsg);
drh9a324642003-09-06 20:12:01 +00001873 p->zErrMsg = 0;
drhd4e70eb2008-01-02 00:34:36 +00001874 p->pResultSet = 0;
drh9a324642003-09-06 20:12:01 +00001875}
1876
1877/*
danielk197722322fd2004-05-25 23:35:17 +00001878** Set the number of result columns that will be returned by this SQL
1879** statement. This is now set at compile time, rather than during
1880** execution of the vdbe program so that sqlite3_column_count() can
1881** be called on an SQL statement before sqlite3_step().
1882*/
1883void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
drh76ff3a02004-09-24 22:32:30 +00001884 Mem *pColName;
1885 int n;
drh633e6d52008-07-28 19:34:53 +00001886 sqlite3 *db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001887
drhc890fec2008-08-01 20:10:08 +00001888 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
drh633e6d52008-07-28 19:34:53 +00001889 sqlite3DbFree(db, p->aColName);
danielk1977955de522006-02-10 02:27:42 +00001890 n = nResColumn*COLNAME_N;
shane36840fd2009-06-26 16:32:13 +00001891 p->nResColumn = (u16)nResColumn;
drh633e6d52008-07-28 19:34:53 +00001892 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
drh76ff3a02004-09-24 22:32:30 +00001893 if( p->aColName==0 ) return;
1894 while( n-- > 0 ){
drh4a50aac2007-08-23 02:47:53 +00001895 pColName->flags = MEM_Null;
drh153c62c2007-08-24 03:51:33 +00001896 pColName->db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001897 pColName++;
drh76ff3a02004-09-24 22:32:30 +00001898 }
danielk197722322fd2004-05-25 23:35:17 +00001899}
1900
1901/*
danielk19773cf86062004-05-26 10:11:05 +00001902** Set the name of the idx'th column to be returned by the SQL statement.
1903** zName must be a pointer to a nul terminated string.
1904**
1905** This call must be made after a call to sqlite3VdbeSetNumCols().
1906**
danielk197710fb7492008-10-31 10:53:22 +00001907** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1908** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1909** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
danielk19773cf86062004-05-26 10:11:05 +00001910*/
danielk197710fb7492008-10-31 10:53:22 +00001911int sqlite3VdbeSetColName(
1912 Vdbe *p, /* Vdbe being configured */
1913 int idx, /* Index of column zName applies to */
1914 int var, /* One of the COLNAME_* constants */
1915 const char *zName, /* Pointer to buffer containing name */
1916 void (*xDel)(void*) /* Memory management strategy for zName */
1917){
danielk19773cf86062004-05-26 10:11:05 +00001918 int rc;
1919 Mem *pColName;
danielk1977955de522006-02-10 02:27:42 +00001920 assert( idx<p->nResColumn );
1921 assert( var<COLNAME_N );
danielk197710fb7492008-10-31 10:53:22 +00001922 if( p->db->mallocFailed ){
1923 assert( !zName || xDel!=SQLITE_DYNAMIC );
1924 return SQLITE_NOMEM;
1925 }
drh76ff3a02004-09-24 22:32:30 +00001926 assert( p->aColName!=0 );
danielk1977955de522006-02-10 02:27:42 +00001927 pColName = &(p->aColName[idx+var*p->nResColumn]);
danielk197710fb7492008-10-31 10:53:22 +00001928 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
drh0793f1b2008-11-05 17:41:19 +00001929 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
danielk19773cf86062004-05-26 10:11:05 +00001930 return rc;
1931}
1932
danielk197713adf8a2004-06-03 16:08:41 +00001933/*
1934** A read or write transaction may or may not be active on database handle
1935** db. If a transaction is active, commit it. If there is a
1936** write-transaction spanning more than one database file, this routine
1937** takes care of the master journal trickery.
1938*/
danielk19773e3a84d2008-08-01 17:37:40 +00001939static int vdbeCommit(sqlite3 *db, Vdbe *p){
danielk197713adf8a2004-06-03 16:08:41 +00001940 int i;
1941 int nTrans = 0; /* Number of databases with an active write-transaction */
1942 int rc = SQLITE_OK;
1943 int needXcommit = 0;
1944
shane36840fd2009-06-26 16:32:13 +00001945#ifdef SQLITE_OMIT_VIRTUALTABLE
1946 /* With this option, sqlite3VtabSync() is defined to be simply
1947 ** SQLITE_OK so p is not used.
1948 */
1949 UNUSED_PARAMETER(p);
1950#endif
1951
danielk19775bd270b2006-07-25 15:14:52 +00001952 /* Before doing anything else, call the xSync() callback for any
1953 ** virtual module tables written in this transaction. This has to
1954 ** be done before determining whether a master journal file is
1955 ** required, as an xSync() callback may add an attached database
1956 ** to the transaction.
1957 */
dan016f7812013-08-21 17:35:48 +00001958 rc = sqlite3VtabSync(db, p);
danielk19775bd270b2006-07-25 15:14:52 +00001959
1960 /* This loop determines (a) if the commit hook should be invoked and
1961 ** (b) how many database files have open write transactions, not
1962 ** including the temp database. (b) is important because if more than
1963 ** one database file has an open write transaction, a master journal
1964 ** file is required for an atomic commit.
1965 */
drhabfb62f2010-07-30 11:20:35 +00001966 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001967 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00001968 if( sqlite3BtreeIsInTrans(pBt) ){
danielk197713adf8a2004-06-03 16:08:41 +00001969 needXcommit = 1;
1970 if( i!=1 ) nTrans++;
dan6b9bb592012-10-05 19:43:02 +00001971 sqlite3BtreeEnter(pBt);
drhabfb62f2010-07-30 11:20:35 +00001972 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
dan6b9bb592012-10-05 19:43:02 +00001973 sqlite3BtreeLeave(pBt);
danielk197713adf8a2004-06-03 16:08:41 +00001974 }
1975 }
drhabfb62f2010-07-30 11:20:35 +00001976 if( rc!=SQLITE_OK ){
1977 return rc;
1978 }
danielk197713adf8a2004-06-03 16:08:41 +00001979
1980 /* If there are any write-transactions at all, invoke the commit hook */
1981 if( needXcommit && db->xCommitCallback ){
drh92f02c32004-09-02 14:57:08 +00001982 rc = db->xCommitCallback(db->pCommitArg);
drh92f02c32004-09-02 14:57:08 +00001983 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00001984 return SQLITE_CONSTRAINT_COMMITHOOK;
danielk197713adf8a2004-06-03 16:08:41 +00001985 }
1986 }
1987
danielk197740b38dc2004-06-26 08:38:24 +00001988 /* The simple case - no more than one database file (not counting the
1989 ** TEMP database) has a transaction active. There is no need for the
drh2ac3ee92004-06-07 16:27:46 +00001990 ** master-journal.
drhc9e06862004-06-09 20:03:08 +00001991 **
danielk197740b38dc2004-06-26 08:38:24 +00001992 ** If the return value of sqlite3BtreeGetFilename() is a zero length
danielk197717b90b52008-06-06 11:11:25 +00001993 ** string, it means the main database is :memory: or a temp file. In
1994 ** that case we do not support atomic multi-file commits, so use the
1995 ** simple case then too.
danielk197713adf8a2004-06-03 16:08:41 +00001996 */
drhea678832008-12-10 19:26:22 +00001997 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
1998 || nTrans<=1
1999 ){
danielk197704103022009-02-03 16:51:24 +00002000 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002001 Btree *pBt = db->aDb[i].pBt;
2002 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002003 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
drh2ac3ee92004-06-07 16:27:46 +00002004 }
2005 }
2006
drh80e35f42007-03-30 14:06:34 +00002007 /* Do the commit only if all databases successfully complete phase 1.
2008 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2009 ** IO error while deleting or truncating a journal file. It is unlikely,
2010 ** but could happen. In this case abandon processing and return the error.
danielk1977979f38e2007-03-27 16:19:51 +00002011 */
2012 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2013 Btree *pBt = db->aDb[i].pBt;
2014 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002015 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
danielk197713adf8a2004-06-03 16:08:41 +00002016 }
danielk1977979f38e2007-03-27 16:19:51 +00002017 }
2018 if( rc==SQLITE_OK ){
danielk1977f9e7dda2006-06-16 16:08:53 +00002019 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002020 }
2021 }
2022
2023 /* The complex case - There is a multi-file write-transaction active.
2024 ** This requires a master journal file to ensure the transaction is
peter.d.reid60ec9142014-09-06 16:39:46 +00002025 ** committed atomically.
danielk197713adf8a2004-06-03 16:08:41 +00002026 */
danielk197744ee5bf2005-05-27 09:41:12 +00002027#ifndef SQLITE_OMIT_DISKIO
danielk197713adf8a2004-06-03 16:08:41 +00002028 else{
danielk1977b4b47412007-08-17 15:53:36 +00002029 sqlite3_vfs *pVfs = db->pVfs;
drh2c8997b2005-08-27 16:36:48 +00002030 int needSync = 0;
danielk197713adf8a2004-06-03 16:08:41 +00002031 char *zMaster = 0; /* File-name for the master journal */
2032 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
danielk1977b4b47412007-08-17 15:53:36 +00002033 sqlite3_file *pMaster = 0;
danielk197762079062007-08-15 17:08:46 +00002034 i64 offset = 0;
danielk1977861f7452008-06-05 11:39:11 +00002035 int res;
drhf5808602011-12-16 00:33:04 +00002036 int retryCount = 0;
drh5c531a42011-12-16 01:21:31 +00002037 int nMainFile;
danielk197713adf8a2004-06-03 16:08:41 +00002038
2039 /* Select a master journal file name */
drh5c531a42011-12-16 01:21:31 +00002040 nMainFile = sqlite3Strlen30(zMainFile);
drh52bcde02012-01-03 14:50:45 +00002041 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
drh5c531a42011-12-16 01:21:31 +00002042 if( zMaster==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002043 do {
drhdc5ea5c2008-12-10 17:19:59 +00002044 u32 iRandom;
drh84968c02011-12-16 15:11:39 +00002045 if( retryCount ){
2046 if( retryCount>100 ){
2047 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2048 sqlite3OsDelete(pVfs, zMaster, 0);
2049 break;
2050 }else if( retryCount==1 ){
2051 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2052 }
danielk197713adf8a2004-06-03 16:08:41 +00002053 }
drh84968c02011-12-16 15:11:39 +00002054 retryCount++;
danielk197713adf8a2004-06-03 16:08:41 +00002055 sqlite3_randomness(sizeof(iRandom), &iRandom);
drh5c531a42011-12-16 01:21:31 +00002056 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
drhf5808602011-12-16 00:33:04 +00002057 (iRandom>>8)&0xffffff, iRandom&0xff);
drhf5808602011-12-16 00:33:04 +00002058 /* The antipenultimate character of the master journal name must
2059 ** be "9" to avoid name collisions when using 8+3 filenames. */
drh5c531a42011-12-16 01:21:31 +00002060 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
drh81cc5162011-05-17 20:36:21 +00002061 sqlite3FileSuffix3(zMainFile, zMaster);
danielk1977861f7452008-06-05 11:39:11 +00002062 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2063 }while( rc==SQLITE_OK && res );
2064 if( rc==SQLITE_OK ){
drh19db9352008-03-27 22:42:51 +00002065 /* Open the master journal. */
2066 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2067 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2068 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2069 );
2070 }
danielk197713adf8a2004-06-03 16:08:41 +00002071 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002072 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002073 return rc;
2074 }
2075
2076 /* Write the name of each database file in the transaction into the new
2077 ** master journal file. If an error occurs at this point close
2078 ** and delete the master journal file. All the individual journal files
2079 ** still have 'null' as the master journal pointer, so they will roll
danielk1977aca790a2005-01-13 11:07:52 +00002080 ** back independently if a failure occurs.
danielk197713adf8a2004-06-03 16:08:41 +00002081 */
danielk19771e536952007-08-16 10:09:01 +00002082 for(i=0; i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002083 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002084 if( sqlite3BtreeIsInTrans(pBt) ){
danielk19775865e3d2004-06-14 06:03:57 +00002085 char const *zFile = sqlite3BtreeGetJournalname(pBt);
drh8c96a6e2010-08-31 01:09:15 +00002086 if( zFile==0 ){
drhb290e1c2009-12-08 13:36:55 +00002087 continue; /* Ignore TEMP and :memory: databases */
2088 }
drh8c96a6e2010-08-31 01:09:15 +00002089 assert( zFile[0]!=0 );
drh2c8997b2005-08-27 16:36:48 +00002090 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
2091 needSync = 1;
2092 }
drhea678832008-12-10 19:26:22 +00002093 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2094 offset += sqlite3Strlen30(zFile)+1;
danielk197713adf8a2004-06-03 16:08:41 +00002095 if( rc!=SQLITE_OK ){
danielk1977fee2d252007-08-18 10:59:19 +00002096 sqlite3OsCloseFree(pMaster);
2097 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002098 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002099 return rc;
2100 }
2101 }
2102 }
2103
danielk19779663b8f2007-08-24 11:52:28 +00002104 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2105 ** flag is set this is not required.
2106 */
danielk1977bea2a942009-01-20 17:06:27 +00002107 if( needSync
2108 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2109 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2110 ){
danielk1977fee2d252007-08-18 10:59:19 +00002111 sqlite3OsCloseFree(pMaster);
2112 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002113 sqlite3DbFree(db, zMaster);
danielk19775865e3d2004-06-14 06:03:57 +00002114 return rc;
2115 }
drhc9e06862004-06-09 20:03:08 +00002116
danielk197713adf8a2004-06-03 16:08:41 +00002117 /* Sync all the db files involved in the transaction. The same call
2118 ** sets the master journal pointer in each individual journal. If
2119 ** an error occurs here, do not delete the master journal file.
2120 **
drh80e35f42007-03-30 14:06:34 +00002121 ** If the error occurs during the first call to
2122 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2123 ** master journal file will be orphaned. But we cannot delete it,
2124 ** in case the master journal file name was written into the journal
shanebe217792009-03-05 04:20:31 +00002125 ** file before the failure occurred.
danielk197713adf8a2004-06-03 16:08:41 +00002126 */
danielk19775bd270b2006-07-25 15:14:52 +00002127 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002128 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002129 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002130 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002131 }
2132 }
danielk1977fee2d252007-08-18 10:59:19 +00002133 sqlite3OsCloseFree(pMaster);
drhabfb62f2010-07-30 11:20:35 +00002134 assert( rc!=SQLITE_BUSY );
danielk19775bd270b2006-07-25 15:14:52 +00002135 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002136 sqlite3DbFree(db, zMaster);
danielk19775bd270b2006-07-25 15:14:52 +00002137 return rc;
2138 }
danielk197713adf8a2004-06-03 16:08:41 +00002139
danielk1977962398d2004-06-14 09:35:16 +00002140 /* Delete the master journal file. This commits the transaction. After
2141 ** doing this the directory is synced again before any individual
2142 ** transaction files are deleted.
2143 */
danielk1977fee2d252007-08-18 10:59:19 +00002144 rc = sqlite3OsDelete(pVfs, zMaster, 1);
drh633e6d52008-07-28 19:34:53 +00002145 sqlite3DbFree(db, zMaster);
drhc416ba92007-03-30 18:42:55 +00002146 zMaster = 0;
drh29a01382006-08-13 19:04:18 +00002147 if( rc ){
2148 return rc;
2149 }
danielk197713adf8a2004-06-03 16:08:41 +00002150
2151 /* All files and directories have already been synced, so the following
drh80e35f42007-03-30 14:06:34 +00002152 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2153 ** deleting or truncating journals. If something goes wrong while
2154 ** this is happening we don't really care. The integrity of the
2155 ** transaction is already guaranteed, but some stray 'cold' journals
2156 ** may be lying around. Returning an error code won't help matters.
danielk197713adf8a2004-06-03 16:08:41 +00002157 */
danielk1977979f38e2007-03-27 16:19:51 +00002158 disable_simulated_io_errors();
danielk19772d1d86f2008-06-20 14:59:51 +00002159 sqlite3BeginBenignMalloc();
danielk197713adf8a2004-06-03 16:08:41 +00002160 for(i=0; i<db->nDb; i++){
2161 Btree *pBt = db->aDb[i].pBt;
2162 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002163 sqlite3BtreeCommitPhaseTwo(pBt, 1);
danielk197713adf8a2004-06-03 16:08:41 +00002164 }
2165 }
danielk19772d1d86f2008-06-20 14:59:51 +00002166 sqlite3EndBenignMalloc();
danielk1977979f38e2007-03-27 16:19:51 +00002167 enable_simulated_io_errors();
2168
danielk1977f9e7dda2006-06-16 16:08:53 +00002169 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002170 }
danielk197744ee5bf2005-05-27 09:41:12 +00002171#endif
danielk1977026d2702004-06-14 13:14:59 +00002172
drh2ac3ee92004-06-07 16:27:46 +00002173 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00002174}
2175
danielk19771d850a72004-05-31 08:26:49 +00002176/*
drh4f7d3a52013-06-27 23:54:02 +00002177** This routine checks that the sqlite3.nVdbeActive count variable
danielk19771d850a72004-05-31 08:26:49 +00002178** matches the number of vdbe's in the list sqlite3.pVdbe that are
2179** currently active. An assertion fails if the two counts do not match.
drh92f02c32004-09-02 14:57:08 +00002180** This is an internal self-check only - it is not an essential processing
2181** step.
danielk19771d850a72004-05-31 08:26:49 +00002182**
2183** This is a no-op if NDEBUG is defined.
2184*/
2185#ifndef NDEBUG
drh9bb575f2004-09-06 17:24:11 +00002186static void checkActiveVdbeCnt(sqlite3 *db){
danielk19771d850a72004-05-31 08:26:49 +00002187 Vdbe *p;
2188 int cnt = 0;
drhad4a4b82008-11-05 16:37:34 +00002189 int nWrite = 0;
drh4f7d3a52013-06-27 23:54:02 +00002190 int nRead = 0;
danielk19771d850a72004-05-31 08:26:49 +00002191 p = db->pVdbe;
2192 while( p ){
dan857745c2014-07-19 17:57:10 +00002193 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
danielk19771d850a72004-05-31 08:26:49 +00002194 cnt++;
drhad4a4b82008-11-05 16:37:34 +00002195 if( p->readOnly==0 ) nWrite++;
drh1713afb2013-06-28 01:24:57 +00002196 if( p->bIsReader ) nRead++;
danielk19771d850a72004-05-31 08:26:49 +00002197 }
2198 p = p->pNext;
2199 }
drh4f7d3a52013-06-27 23:54:02 +00002200 assert( cnt==db->nVdbeActive );
2201 assert( nWrite==db->nVdbeWrite );
2202 assert( nRead==db->nVdbeRead );
danielk19771d850a72004-05-31 08:26:49 +00002203}
2204#else
2205#define checkActiveVdbeCnt(x)
2206#endif
2207
danielk19773cf86062004-05-26 10:11:05 +00002208/*
danielk1977bd434552009-03-18 10:33:00 +00002209** If the Vdbe passed as the first argument opened a statement-transaction,
2210** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2211** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2212** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
drhf7b54962013-05-28 12:11:54 +00002213** statement transaction is committed.
danielk1977bd434552009-03-18 10:33:00 +00002214**
2215** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2216** Otherwise SQLITE_OK.
2217*/
2218int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
danielk1977c926b6a2009-03-20 14:42:11 +00002219 sqlite3 *const db = p->db;
danielk1977bd434552009-03-18 10:33:00 +00002220 int rc = SQLITE_OK;
danielk1977ecaecf92009-07-08 08:05:35 +00002221
danielk1977e4948172009-07-17 17:25:43 +00002222 /* If p->iStatement is greater than zero, then this Vdbe opened a
2223 ** statement transaction that should be closed here. The only exception
mistachkin48864df2013-03-21 21:20:32 +00002224 ** is that an IO error may have occurred, causing an emergency rollback.
danielk1977e4948172009-07-17 17:25:43 +00002225 ** In this case (db->nStatement==0), and there is nothing to do.
2226 */
2227 if( db->nStatement && p->iStatement ){
danielk1977bd434552009-03-18 10:33:00 +00002228 int i;
2229 const int iSavepoint = p->iStatement-1;
danielk1977bd434552009-03-18 10:33:00 +00002230
2231 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2232 assert( db->nStatement>0 );
2233 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2234
2235 for(i=0; i<db->nDb; i++){
2236 int rc2 = SQLITE_OK;
2237 Btree *pBt = db->aDb[i].pBt;
2238 if( pBt ){
2239 if( eOp==SAVEPOINT_ROLLBACK ){
2240 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2241 }
2242 if( rc2==SQLITE_OK ){
2243 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2244 }
2245 if( rc==SQLITE_OK ){
2246 rc = rc2;
2247 }
2248 }
2249 }
2250 db->nStatement--;
2251 p->iStatement = 0;
dan1da40a32009-09-19 17:00:31 +00002252
dana311b802011-04-26 19:21:34 +00002253 if( rc==SQLITE_OK ){
2254 if( eOp==SAVEPOINT_ROLLBACK ){
2255 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2256 }
2257 if( rc==SQLITE_OK ){
2258 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2259 }
2260 }
2261
dan1da40a32009-09-19 17:00:31 +00002262 /* If the statement transaction is being rolled back, also restore the
2263 ** database handles deferred constraint counter to the value it had when
2264 ** the statement transaction was opened. */
2265 if( eOp==SAVEPOINT_ROLLBACK ){
2266 db->nDeferredCons = p->nStmtDefCons;
drh648e2642013-07-11 15:03:32 +00002267 db->nDeferredImmCons = p->nStmtDefImmCons;
dan1da40a32009-09-19 17:00:31 +00002268 }
danielk1977bd434552009-03-18 10:33:00 +00002269 }
2270 return rc;
2271}
2272
2273/*
dan1da40a32009-09-19 17:00:31 +00002274** This function is called when a transaction opened by the database
2275** handle associated with the VM passed as an argument is about to be
2276** committed. If there are outstanding deferred foreign key constraint
2277** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2278**
2279** If there are outstanding FK violations and this function returns
drhd91c1a12013-02-09 13:58:25 +00002280** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2281** and write an error message to it. Then return SQLITE_ERROR.
dan1da40a32009-09-19 17:00:31 +00002282*/
2283#ifndef SQLITE_OMIT_FOREIGN_KEY
dan32b09f22009-09-23 17:29:59 +00002284int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
dan1da40a32009-09-19 17:00:31 +00002285 sqlite3 *db = p->db;
drh648e2642013-07-11 15:03:32 +00002286 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2287 || (!deferred && p->nFkConstraint>0)
2288 ){
drhd91c1a12013-02-09 13:58:25 +00002289 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan32b09f22009-09-23 17:29:59 +00002290 p->errorAction = OE_Abort;
drhf9c8ce32013-11-05 13:33:55 +00002291 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
dan1da40a32009-09-19 17:00:31 +00002292 return SQLITE_ERROR;
2293 }
2294 return SQLITE_OK;
2295}
2296#endif
2297
2298/*
drh92f02c32004-09-02 14:57:08 +00002299** This routine is called the when a VDBE tries to halt. If the VDBE
2300** has made changes and is in autocommit mode, then commit those
2301** changes. If a rollback is needed, then do the rollback.
drh9a324642003-09-06 20:12:01 +00002302**
drh92f02c32004-09-02 14:57:08 +00002303** This routine is the only way to move the state of a VM from
drhff0587c2007-08-29 17:43:19 +00002304** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2305** call this on a VM that is in the SQLITE_MAGIC_HALT state.
drh92f02c32004-09-02 14:57:08 +00002306**
2307** Return an error code. If the commit could not complete because of
2308** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2309** means the close did not happen and needs to be repeated.
drh9a324642003-09-06 20:12:01 +00002310*/
drhff0587c2007-08-29 17:43:19 +00002311int sqlite3VdbeHalt(Vdbe *p){
danielk1977bd434552009-03-18 10:33:00 +00002312 int rc; /* Used to store transient return codes */
drh9bb575f2004-09-06 17:24:11 +00002313 sqlite3 *db = p->db;
danielk197707cb5602006-01-20 10:55:05 +00002314
2315 /* This function contains the logic that determines if a statement or
2316 ** transaction will be committed or rolled back as a result of the
2317 ** execution of this virtual machine.
2318 **
drh71b890a2007-10-03 15:30:52 +00002319 ** If any of the following errors occur:
danielk197707cb5602006-01-20 10:55:05 +00002320 **
drh71b890a2007-10-03 15:30:52 +00002321 ** SQLITE_NOMEM
2322 ** SQLITE_IOERR
2323 ** SQLITE_FULL
2324 ** SQLITE_INTERRUPT
danielk197707cb5602006-01-20 10:55:05 +00002325 **
drh71b890a2007-10-03 15:30:52 +00002326 ** Then the internal cache might have been left in an inconsistent
2327 ** state. We need to rollback the statement transaction, if there is
2328 ** one, or the complete transaction if there is no statement transaction.
danielk197707cb5602006-01-20 10:55:05 +00002329 */
drh9a324642003-09-06 20:12:01 +00002330
drh17435752007-08-16 04:30:38 +00002331 if( p->db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002332 p->rc = SQLITE_NOMEM;
2333 }
drh6e856bc2011-12-09 18:06:44 +00002334 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
drh5f82e3c2009-07-06 00:44:08 +00002335 closeAllCursors(p);
drh92f02c32004-09-02 14:57:08 +00002336 if( p->magic!=VDBE_MAGIC_RUN ){
drh92f02c32004-09-02 14:57:08 +00002337 return SQLITE_OK;
drh9a324642003-09-06 20:12:01 +00002338 }
danielk19771d850a72004-05-31 08:26:49 +00002339 checkActiveVdbeCnt(db);
danielk1977261919c2005-12-06 12:52:59 +00002340
danc0537fe2013-06-28 19:41:43 +00002341 /* No commit or rollback needed if the program never started or if the
2342 ** SQL statement does not read or write a database file. */
2343 if( p->pc>=0 && p->bIsReader ){
drhaac2f552006-09-23 21:44:23 +00002344 int mrc; /* Primary error code from p->rc */
danielk1977bd434552009-03-18 10:33:00 +00002345 int eStatementOp = 0;
2346 int isSpecialError; /* Set to true if a 'special' error */
drhff0587c2007-08-29 17:43:19 +00002347
2348 /* Lock all btrees used by the statement */
drhbdaec522011-04-04 00:14:43 +00002349 sqlite3VdbeEnter(p);
drhff0587c2007-08-29 17:43:19 +00002350
drh71b890a2007-10-03 15:30:52 +00002351 /* Check for one of the special errors */
drhaac2f552006-09-23 21:44:23 +00002352 mrc = p->rc & 0xff;
drh71b890a2007-10-03 15:30:52 +00002353 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
drh77658e22007-12-04 16:54:52 +00002354 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
danielk197707cb5602006-01-20 10:55:05 +00002355 if( isSpecialError ){
dan5653e4d2010-08-12 11:25:47 +00002356 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2357 ** no rollback is necessary. Otherwise, at least a savepoint
2358 ** transaction must be rolled back to restore the database to a
2359 ** consistent state.
2360 **
2361 ** Even if the statement is read-only, it is important to perform
2362 ** a statement or transaction rollback operation. If the error
mistachkin48864df2013-03-21 21:20:32 +00002363 ** occurred while writing to the journal, sub-journal or database
dan5653e4d2010-08-12 11:25:47 +00002364 ** file as part of an effort to free up cache space (see function
2365 ** pagerStress() in pager.c), the rollback is required to restore
2366 ** the pager to a consistent state.
danielk197707cb5602006-01-20 10:55:05 +00002367 */
drhad4a4b82008-11-05 16:37:34 +00002368 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
drhfa3be902009-07-07 02:44:07 +00002369 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
danielk1977bd434552009-03-18 10:33:00 +00002370 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002371 }else{
2372 /* We are forced to roll back the active transaction. Before doing
2373 ** so, abort any other statements this handle currently has active.
2374 */
drh21021a52012-02-13 17:01:51 +00002375 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002376 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002377 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002378 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002379 }
danielk1977261919c2005-12-06 12:52:59 +00002380 }
2381 }
dan32b09f22009-09-23 17:29:59 +00002382
2383 /* Check for immediate foreign key violations. */
2384 if( p->rc==SQLITE_OK ){
2385 sqlite3VdbeCheckFk(p, 0);
2386 }
danielk197707cb5602006-01-20 10:55:05 +00002387
danielk1977bd434552009-03-18 10:33:00 +00002388 /* If the auto-commit flag is set and this is the only active writer
2389 ** VM, then we do either a commit or rollback of the current transaction.
danielk197707cb5602006-01-20 10:55:05 +00002390 **
2391 ** Note: This block also runs if one of the special errors handled
drhad4a4b82008-11-05 16:37:34 +00002392 ** above has occurred.
danielk197707cb5602006-01-20 10:55:05 +00002393 */
danielk1977093e0f62008-11-13 18:00:14 +00002394 if( !sqlite3VtabInSync(db)
2395 && db->autoCommit
drh4f7d3a52013-06-27 23:54:02 +00002396 && db->nVdbeWrite==(p->readOnly==0)
danielk1977093e0f62008-11-13 18:00:14 +00002397 ){
danielk197707cb5602006-01-20 10:55:05 +00002398 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
dan19611b12011-01-24 16:00:58 +00002399 rc = sqlite3VdbeCheckFk(p, 1);
2400 if( rc!=SQLITE_OK ){
drhe9ce5852011-02-11 22:54:28 +00002401 if( NEVER(p->readOnly) ){
drhbdaec522011-04-04 00:14:43 +00002402 sqlite3VdbeLeave(p);
dan19611b12011-01-24 16:00:58 +00002403 return SQLITE_ERROR;
2404 }
drhd91c1a12013-02-09 13:58:25 +00002405 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan19611b12011-01-24 16:00:58 +00002406 }else{
2407 /* The auto-commit flag is true, the vdbe program was successful
2408 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2409 ** key constraints to hold up the transaction. This means a commit
2410 ** is required. */
2411 rc = vdbeCommit(db, p);
dan1da40a32009-09-19 17:00:31 +00002412 }
dan19611b12011-01-24 16:00:58 +00002413 if( rc==SQLITE_BUSY && p->readOnly ){
drhbdaec522011-04-04 00:14:43 +00002414 sqlite3VdbeLeave(p);
danielk197707cb5602006-01-20 10:55:05 +00002415 return SQLITE_BUSY;
2416 }else if( rc!=SQLITE_OK ){
2417 p->rc = rc;
drh0f198a72012-02-13 16:43:16 +00002418 sqlite3RollbackAll(db, SQLITE_OK);
danc3da6672014-10-28 18:24:16 +00002419 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002420 }else{
dan1da40a32009-09-19 17:00:31 +00002421 db->nDeferredCons = 0;
drh648e2642013-07-11 15:03:32 +00002422 db->nDeferredImmCons = 0;
2423 db->flags &= ~SQLITE_DeferFKs;
danielk197707cb5602006-01-20 10:55:05 +00002424 sqlite3CommitInternalChanges(db);
2425 }
2426 }else{
drh0f198a72012-02-13 16:43:16 +00002427 sqlite3RollbackAll(db, SQLITE_OK);
danc3da6672014-10-28 18:24:16 +00002428 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002429 }
danielk1977bd434552009-03-18 10:33:00 +00002430 db->nStatement = 0;
2431 }else if( eStatementOp==0 ){
danielk197707cb5602006-01-20 10:55:05 +00002432 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
danielk1977bd434552009-03-18 10:33:00 +00002433 eStatementOp = SAVEPOINT_RELEASE;
danielk197707cb5602006-01-20 10:55:05 +00002434 }else if( p->errorAction==OE_Abort ){
danielk1977bd434552009-03-18 10:33:00 +00002435 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002436 }else{
drh21021a52012-02-13 17:01:51 +00002437 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002438 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002439 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002440 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002441 }
danielk19771d850a72004-05-31 08:26:49 +00002442 }
danielk197707cb5602006-01-20 10:55:05 +00002443
danielk1977bd434552009-03-18 10:33:00 +00002444 /* If eStatementOp is non-zero, then a statement transaction needs to
2445 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2446 ** do so. If this operation returns an error, and the current statement
drh35173242010-03-08 21:40:13 +00002447 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2448 ** current statement error code.
danielk197707cb5602006-01-20 10:55:05 +00002449 */
danielk1977bd434552009-03-18 10:33:00 +00002450 if( eStatementOp ){
2451 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
dan40ad9d22010-06-03 09:17:38 +00002452 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00002453 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
dan40ad9d22010-06-03 09:17:38 +00002454 p->rc = rc;
2455 sqlite3DbFree(db, p->zErrMsg);
2456 p->zErrMsg = 0;
2457 }
drh21021a52012-02-13 17:01:51 +00002458 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
dan40ad9d22010-06-03 09:17:38 +00002459 sqlite3CloseSavepoints(db);
2460 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002461 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002462 }
danielk197777d83ba2004-05-31 10:08:14 +00002463 }
danielk197707cb5602006-01-20 10:55:05 +00002464
danielk1977bd434552009-03-18 10:33:00 +00002465 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2466 ** has been rolled back, update the database connection change-counter.
danielk197707cb5602006-01-20 10:55:05 +00002467 */
drh6be240e2009-07-14 02:33:02 +00002468 if( p->changeCntOn ){
danielk1977bd434552009-03-18 10:33:00 +00002469 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
danielk197707cb5602006-01-20 10:55:05 +00002470 sqlite3VdbeSetChanges(db, p->nChange);
2471 }else{
2472 sqlite3VdbeSetChanges(db, 0);
2473 }
2474 p->nChange = 0;
danielk1977b28af712004-06-21 06:50:26 +00002475 }
drhff0587c2007-08-29 17:43:19 +00002476
2477 /* Release the locks */
drhbdaec522011-04-04 00:14:43 +00002478 sqlite3VdbeLeave(p);
drh9a324642003-09-06 20:12:01 +00002479 }
danielk19771d850a72004-05-31 08:26:49 +00002480
danielk197765fd59f2006-06-24 11:51:33 +00002481 /* We have successfully halted and closed the VM. Record this fact. */
2482 if( p->pc>=0 ){
drh4f7d3a52013-06-27 23:54:02 +00002483 db->nVdbeActive--;
2484 if( !p->readOnly ) db->nVdbeWrite--;
drh1713afb2013-06-28 01:24:57 +00002485 if( p->bIsReader ) db->nVdbeRead--;
drh4f7d3a52013-06-27 23:54:02 +00002486 assert( db->nVdbeActive>=db->nVdbeRead );
2487 assert( db->nVdbeRead>=db->nVdbeWrite );
2488 assert( db->nVdbeWrite>=0 );
drh9a324642003-09-06 20:12:01 +00002489 }
drh92f02c32004-09-02 14:57:08 +00002490 p->magic = VDBE_MAGIC_HALT;
2491 checkActiveVdbeCnt(db);
drhff0587c2007-08-29 17:43:19 +00002492 if( p->db->mallocFailed ){
2493 p->rc = SQLITE_NOMEM;
2494 }
danielk19771d850a72004-05-31 08:26:49 +00002495
danielk1977404ca072009-03-16 13:19:36 +00002496 /* If the auto-commit flag is set to true, then any locks that were held
2497 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2498 ** to invoke any required unlock-notify callbacks.
2499 */
2500 if( db->autoCommit ){
2501 sqlite3ConnectionUnlocked(db);
2502 }
2503
drh4f7d3a52013-06-27 23:54:02 +00002504 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
dan19611b12011-01-24 16:00:58 +00002505 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
drh92f02c32004-09-02 14:57:08 +00002506}
drh4cf7c7f2007-08-28 23:28:07 +00002507
drh92f02c32004-09-02 14:57:08 +00002508
2509/*
drh3c23a882007-01-09 14:01:13 +00002510** Each VDBE holds the result of the most recent sqlite3_step() call
2511** in p->rc. This routine sets that result back to SQLITE_OK.
2512*/
2513void sqlite3VdbeResetStepResult(Vdbe *p){
2514 p->rc = SQLITE_OK;
2515}
2516
2517/*
dan029ead62011-10-27 15:19:58 +00002518** Copy the error code and error message belonging to the VDBE passed
2519** as the first argument to its database handle (so that they will be
2520** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2521**
2522** This function does not clear the VDBE error code or message, just
2523** copies them to the database handle.
2524*/
2525int sqlite3VdbeTransferError(Vdbe *p){
2526 sqlite3 *db = p->db;
2527 int rc = p->rc;
2528 if( p->zErrMsg ){
drh81bdd6d2011-10-29 01:33:24 +00002529 u8 mallocFailed = db->mallocFailed;
dan029ead62011-10-27 15:19:58 +00002530 sqlite3BeginBenignMalloc();
drha3cc0072013-12-13 16:23:55 +00002531 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
dan029ead62011-10-27 15:19:58 +00002532 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2533 sqlite3EndBenignMalloc();
drh81bdd6d2011-10-29 01:33:24 +00002534 db->mallocFailed = mallocFailed;
dan029ead62011-10-27 15:19:58 +00002535 db->errCode = rc;
2536 }else{
drh13f40da2014-08-22 18:00:11 +00002537 sqlite3Error(db, rc);
dan029ead62011-10-27 15:19:58 +00002538 }
2539 return rc;
2540}
2541
danac455932012-11-26 19:50:41 +00002542#ifdef SQLITE_ENABLE_SQLLOG
2543/*
2544** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2545** invoke it.
2546*/
2547static void vdbeInvokeSqllog(Vdbe *v){
2548 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2549 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2550 assert( v->db->init.busy==0 );
2551 if( zExpanded ){
2552 sqlite3GlobalConfig.xSqllog(
2553 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2554 );
2555 sqlite3DbFree(v->db, zExpanded);
2556 }
2557 }
2558}
2559#else
2560# define vdbeInvokeSqllog(x)
2561#endif
2562
dan029ead62011-10-27 15:19:58 +00002563/*
drh92f02c32004-09-02 14:57:08 +00002564** Clean up a VDBE after execution but do not delete the VDBE just yet.
2565** Write any error messages into *pzErrMsg. Return the result code.
2566**
2567** After this routine is run, the VDBE should be ready to be executed
2568** again.
2569**
2570** To look at it another way, this routine resets the state of the
2571** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2572** VDBE_MAGIC_INIT.
2573*/
drhc890fec2008-08-01 20:10:08 +00002574int sqlite3VdbeReset(Vdbe *p){
drh4ac285a2006-09-15 07:28:50 +00002575 sqlite3 *db;
drh4ac285a2006-09-15 07:28:50 +00002576 db = p->db;
drh92f02c32004-09-02 14:57:08 +00002577
2578 /* If the VM did not run to completion or if it encountered an
2579 ** error, then it might not have been halted properly. So halt
2580 ** it now.
2581 */
2582 sqlite3VdbeHalt(p);
2583
drhfb7e7652005-01-24 00:28:42 +00002584 /* If the VDBE has be run even partially, then transfer the error code
2585 ** and error message from the VDBE into the main database structure. But
2586 ** if the VDBE has just been set to run but has not actually executed any
2587 ** instructions yet, leave the main database error information unchanged.
drh92f02c32004-09-02 14:57:08 +00002588 */
drhfb7e7652005-01-24 00:28:42 +00002589 if( p->pc>=0 ){
danac455932012-11-26 19:50:41 +00002590 vdbeInvokeSqllog(p);
dan029ead62011-10-27 15:19:58 +00002591 sqlite3VdbeTransferError(p);
2592 sqlite3DbFree(db, p->zErrMsg);
2593 p->zErrMsg = 0;
drh4611d922010-02-25 14:47:01 +00002594 if( p->runOnlyOnce ) p->expired = 1;
danielk1977a21c6b62005-01-24 10:25:59 +00002595 }else if( p->rc && p->expired ){
2596 /* The expired flag was set on the VDBE before the first call
2597 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2598 ** called), set the database error in this case as well.
2599 */
drh13f40da2014-08-22 18:00:11 +00002600 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
drh633e6d52008-07-28 19:34:53 +00002601 sqlite3DbFree(db, p->zErrMsg);
danielk19778e556522007-11-13 10:30:24 +00002602 p->zErrMsg = 0;
drh92f02c32004-09-02 14:57:08 +00002603 }
2604
2605 /* Reclaim all memory used by the VDBE
2606 */
drhc890fec2008-08-01 20:10:08 +00002607 Cleanup(p);
drh92f02c32004-09-02 14:57:08 +00002608
2609 /* Save profiling information from this VDBE run.
2610 */
drh9a324642003-09-06 20:12:01 +00002611#ifdef VDBE_PROFILE
2612 {
2613 FILE *out = fopen("vdbe_profile.out", "a");
2614 if( out ){
2615 int i;
2616 fprintf(out, "---- ");
2617 for(i=0; i<p->nOp; i++){
2618 fprintf(out, "%02x", p->aOp[i].opcode);
2619 }
2620 fprintf(out, "\n");
drh2926f962014-02-17 01:13:28 +00002621 if( p->zSql ){
2622 char c, pc = 0;
2623 fprintf(out, "-- ");
2624 for(i=0; (c = p->zSql[i])!=0; i++){
2625 if( pc=='\n' ) fprintf(out, "-- ");
2626 putc(c, out);
2627 pc = c;
2628 }
2629 if( pc!='\n' ) fprintf(out, "\n");
2630 }
drh9a324642003-09-06 20:12:01 +00002631 for(i=0; i<p->nOp; i++){
drh15ab9412014-02-24 14:24:01 +00002632 char zHdr[100];
2633 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
drh9a324642003-09-06 20:12:01 +00002634 p->aOp[i].cnt,
2635 p->aOp[i].cycles,
2636 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2637 );
drh15ab9412014-02-24 14:24:01 +00002638 fprintf(out, "%s", zHdr);
danielk19774adee202004-05-08 08:23:19 +00002639 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
drh9a324642003-09-06 20:12:01 +00002640 }
2641 fclose(out);
2642 }
2643 }
2644#endif
drh7fa20922013-09-17 23:36:33 +00002645 p->iCurrentTime = 0;
drh9a324642003-09-06 20:12:01 +00002646 p->magic = VDBE_MAGIC_INIT;
drh4ac285a2006-09-15 07:28:50 +00002647 return p->rc & db->errMask;
drh9a324642003-09-06 20:12:01 +00002648}
drh92f02c32004-09-02 14:57:08 +00002649
drh9a324642003-09-06 20:12:01 +00002650/*
2651** Clean up and delete a VDBE after execution. Return an integer which is
2652** the result code. Write any error message text into *pzErrMsg.
2653*/
danielk19779e6db7d2004-06-21 08:18:51 +00002654int sqlite3VdbeFinalize(Vdbe *p){
danielk1977b5548a82004-06-26 13:51:33 +00002655 int rc = SQLITE_OK;
danielk1977b5548a82004-06-26 13:51:33 +00002656 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
drhc890fec2008-08-01 20:10:08 +00002657 rc = sqlite3VdbeReset(p);
drh4ac285a2006-09-15 07:28:50 +00002658 assert( (rc & p->db->errMask)==rc );
drh9a324642003-09-06 20:12:01 +00002659 }
danielk19774adee202004-05-08 08:23:19 +00002660 sqlite3VdbeDelete(p);
drh9a324642003-09-06 20:12:01 +00002661 return rc;
2662}
2663
2664/*
dan0c547792013-07-18 17:12:08 +00002665** If parameter iOp is less than zero, then invoke the destructor for
2666** all auxiliary data pointers currently cached by the VM passed as
2667** the first argument.
2668**
2669** Or, if iOp is greater than or equal to zero, then the destructor is
2670** only invoked for those auxiliary data pointers created by the user
2671** function invoked by the OP_Function opcode at instruction iOp of
2672** VM pVdbe, and only then if:
2673**
2674** * the associated function parameter is the 32nd or later (counting
2675** from left to right), or
2676**
2677** * the corresponding bit in argument mask is clear (where the first
peter.d.reid60ec9142014-09-06 16:39:46 +00002678** function parameter corresponds to bit 0 etc.).
drhf92c7ff2004-06-19 15:40:23 +00002679*/
dan0c547792013-07-18 17:12:08 +00002680void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
2681 AuxData **pp = &pVdbe->pAuxData;
2682 while( *pp ){
2683 AuxData *pAux = *pp;
2684 if( (iOp<0)
drh693e6712014-01-24 22:58:00 +00002685 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
dan0c547792013-07-18 17:12:08 +00002686 ){
drh693e6712014-01-24 22:58:00 +00002687 testcase( pAux->iArg==31 );
drhf92c7ff2004-06-19 15:40:23 +00002688 if( pAux->xDelete ){
2689 pAux->xDelete(pAux->pAux);
2690 }
dan0c547792013-07-18 17:12:08 +00002691 *pp = pAux->pNext;
2692 sqlite3DbFree(pVdbe->db, pAux);
2693 }else{
2694 pp= &pAux->pNext;
drhf92c7ff2004-06-19 15:40:23 +00002695 }
2696 }
2697}
2698
2699/*
drhcb103b92012-10-26 00:11:23 +00002700** Free all memory associated with the Vdbe passed as the second argument,
2701** except for object itself, which is preserved.
2702**
dand46def72010-07-24 11:28:28 +00002703** The difference between this function and sqlite3VdbeDelete() is that
2704** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
drhcb103b92012-10-26 00:11:23 +00002705** the database connection and frees the object itself.
dand46def72010-07-24 11:28:28 +00002706*/
drhcb103b92012-10-26 00:11:23 +00002707void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
dand19c9332010-07-26 12:05:17 +00002708 SubProgram *pSub, *pNext;
drh124c0b42011-06-01 18:15:55 +00002709 int i;
dand46def72010-07-24 11:28:28 +00002710 assert( p->db==0 || p->db==db );
2711 releaseMemArray(p->aVar, p->nVar);
2712 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
dand19c9332010-07-26 12:05:17 +00002713 for(pSub=p->pProgram; pSub; pSub=pNext){
2714 pNext = pSub->pNext;
2715 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2716 sqlite3DbFree(db, pSub);
2717 }
drh124c0b42011-06-01 18:15:55 +00002718 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
dand46def72010-07-24 11:28:28 +00002719 vdbeFreeOpArray(db, p->aOp, p->nOp);
dand46def72010-07-24 11:28:28 +00002720 sqlite3DbFree(db, p->aColName);
2721 sqlite3DbFree(db, p->zSql);
2722 sqlite3DbFree(db, p->pFree);
dan6f9702e2014-11-01 20:38:06 +00002723#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan6f9702e2014-11-01 20:38:06 +00002724 for(i=0; i<p->nScan; i++){
2725 sqlite3DbFree(db, p->aScan[i].zName);
2726 }
2727 sqlite3DbFree(db, p->aScan);
2728#endif
dand46def72010-07-24 11:28:28 +00002729}
2730
2731/*
drh9a324642003-09-06 20:12:01 +00002732** Delete an entire VDBE.
2733*/
danielk19774adee202004-05-08 08:23:19 +00002734void sqlite3VdbeDelete(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00002735 sqlite3 *db;
2736
drhfa3be902009-07-07 02:44:07 +00002737 if( NEVER(p==0) ) return;
drh633e6d52008-07-28 19:34:53 +00002738 db = p->db;
drh4245c402012-06-02 14:32:21 +00002739 assert( sqlite3_mutex_held(db->mutex) );
drhcb103b92012-10-26 00:11:23 +00002740 sqlite3VdbeClearObject(db, p);
drh9a324642003-09-06 20:12:01 +00002741 if( p->pPrev ){
2742 p->pPrev->pNext = p->pNext;
2743 }else{
drh633e6d52008-07-28 19:34:53 +00002744 assert( db->pVdbe==p );
2745 db->pVdbe = p->pNext;
drh9a324642003-09-06 20:12:01 +00002746 }
2747 if( p->pNext ){
2748 p->pNext->pPrev = p->pPrev;
2749 }
drh9a324642003-09-06 20:12:01 +00002750 p->magic = VDBE_MAGIC_DEAD;
drh87f5c5f2010-01-20 01:20:56 +00002751 p->db = 0;
drhcb103b92012-10-26 00:11:23 +00002752 sqlite3DbFree(db, p);
drh9a324642003-09-06 20:12:01 +00002753}
drha11846b2004-01-07 18:52:56 +00002754
2755/*
drh6848dad2014-08-22 23:33:03 +00002756** The cursor "p" has a pending seek operation that has not yet been
2757** carried out. Seek the cursor now. If an error occurs, return
2758** the appropriate error code.
2759*/
2760static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
2761 int res, rc;
2762#ifdef SQLITE_TEST
2763 extern int sqlite3_search_count;
2764#endif
2765 assert( p->deferredMoveto );
2766 assert( p->isTable );
2767 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
2768 if( rc ) return rc;
drh6848dad2014-08-22 23:33:03 +00002769 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
drh6848dad2014-08-22 23:33:03 +00002770#ifdef SQLITE_TEST
2771 sqlite3_search_count++;
2772#endif
2773 p->deferredMoveto = 0;
2774 p->cacheStatus = CACHE_STALE;
2775 return SQLITE_OK;
2776}
2777
2778/*
2779** Something has moved cursor "p" out of place. Maybe the row it was
2780** pointed to was deleted out from under it. Or maybe the btree was
2781** rebalanced. Whatever the cause, try to restore "p" to the place it
peter.d.reid60ec9142014-09-06 16:39:46 +00002782** is supposed to be pointing. If the row was deleted out from under the
drh6848dad2014-08-22 23:33:03 +00002783** cursor, set the cursor to point to a NULL row.
2784*/
2785static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
2786 int isDifferentRow, rc;
2787 assert( p->pCursor!=0 );
2788 assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
2789 rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
2790 p->cacheStatus = CACHE_STALE;
2791 if( isDifferentRow ) p->nullRow = 1;
2792 return rc;
2793}
2794
2795/*
drhc22284f2014-10-13 16:02:20 +00002796** Check to ensure that the cursor is valid. Restore the cursor
2797** if need be. Return any I/O error from the restore operation.
2798*/
2799int sqlite3VdbeCursorRestore(VdbeCursor *p){
2800 if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
2801 return handleMovedCursor(p);
2802 }
2803 return SQLITE_OK;
2804}
2805
2806/*
drh9a65f2c2009-06-22 19:05:40 +00002807** Make sure the cursor p is ready to read or write the row to which it
2808** was last positioned. Return an error code if an OOM fault or I/O error
2809** prevents us from positioning the cursor to its correct position.
2810**
drha11846b2004-01-07 18:52:56 +00002811** If a MoveTo operation is pending on the given cursor, then do that
drh9a65f2c2009-06-22 19:05:40 +00002812** MoveTo now. If no move is pending, check to see if the row has been
2813** deleted out from under the cursor and if it has, mark the row as
2814** a NULL row.
2815**
2816** If the cursor is already pointing to the correct row and that row has
2817** not been deleted out from under the cursor, then this routine is a no-op.
drha11846b2004-01-07 18:52:56 +00002818*/
drhdfe88ec2008-11-03 20:55:06 +00002819int sqlite3VdbeCursorMoveto(VdbeCursor *p){
drha11846b2004-01-07 18:52:56 +00002820 if( p->deferredMoveto ){
drh6848dad2014-08-22 23:33:03 +00002821 return handleDeferredMoveto(p);
2822 }
drhc22284f2014-10-13 16:02:20 +00002823 if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
drh6848dad2014-08-22 23:33:03 +00002824 return handleMovedCursor(p);
drha11846b2004-01-07 18:52:56 +00002825 }
2826 return SQLITE_OK;
2827}
danielk19774adee202004-05-08 08:23:19 +00002828
drhab9f7f12004-05-08 10:56:11 +00002829/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002830** The following functions:
danielk197790e4d952004-05-10 10:05:53 +00002831**
danielk1977cfcdaef2004-05-12 07:33:33 +00002832** sqlite3VdbeSerialType()
2833** sqlite3VdbeSerialTypeLen()
danielk197790e4d952004-05-10 10:05:53 +00002834** sqlite3VdbeSerialLen()
shane92003092008-07-31 01:43:13 +00002835** sqlite3VdbeSerialPut()
2836** sqlite3VdbeSerialGet()
danielk197790e4d952004-05-10 10:05:53 +00002837**
2838** encapsulate the code that serializes values for storage in SQLite
danielk1977cfcdaef2004-05-12 07:33:33 +00002839** data and index records. Each serialized value consists of a
2840** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2841** integer, stored as a varint.
danielk197790e4d952004-05-10 10:05:53 +00002842**
danielk1977cfcdaef2004-05-12 07:33:33 +00002843** In an SQLite index record, the serial type is stored directly before
2844** the blob of data that it corresponds to. In a table record, all serial
2845** types are stored at the start of the record, and the blobs of data at
2846** the end. Hence these functions allow the caller to handle the
mistachkin48864df2013-03-21 21:20:32 +00002847** serial-type and data blob separately.
danielk1977cfcdaef2004-05-12 07:33:33 +00002848**
2849** The following table describes the various storage classes for data:
2850**
2851** serial type bytes of data type
danielk197790e4d952004-05-10 10:05:53 +00002852** -------------- --------------- ---------------
drha19b7752004-05-30 21:14:58 +00002853** 0 0 NULL
danielk197790e4d952004-05-10 10:05:53 +00002854** 1 1 signed integer
2855** 2 2 signed integer
drha19b7752004-05-30 21:14:58 +00002856** 3 3 signed integer
2857** 4 4 signed integer
2858** 5 6 signed integer
2859** 6 8 signed integer
2860** 7 8 IEEE float
drhd946db02005-12-29 19:23:06 +00002861** 8 0 Integer constant 0
2862** 9 0 Integer constant 1
2863** 10,11 reserved for expansion
danielk197790e4d952004-05-10 10:05:53 +00002864** N>=12 and even (N-12)/2 BLOB
2865** N>=13 and odd (N-13)/2 text
2866**
drh35a59652006-01-02 18:24:40 +00002867** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2868** of SQLite will not understand those serial types.
danielk197790e4d952004-05-10 10:05:53 +00002869*/
2870
2871/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002872** Return the serial-type for the value stored in pMem.
danielk1977192ac1d2004-05-10 07:17:30 +00002873*/
drhd946db02005-12-29 19:23:06 +00002874u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
danielk1977cfcdaef2004-05-12 07:33:33 +00002875 int flags = pMem->flags;
drheac5bd72014-07-25 21:35:39 +00002876 u32 n;
danielk1977cfcdaef2004-05-12 07:33:33 +00002877
2878 if( flags&MEM_Null ){
drha19b7752004-05-30 21:14:58 +00002879 return 0;
danielk197790e4d952004-05-10 10:05:53 +00002880 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002881 if( flags&MEM_Int ){
drhfe2093d2005-01-20 22:48:47 +00002882 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
drh5284a052008-05-08 15:18:10 +00002883# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
drh3c024d62007-03-30 11:23:45 +00002884 i64 i = pMem->u.i;
drhd946db02005-12-29 19:23:06 +00002885 u64 u;
drhcfd654b2011-03-05 13:54:15 +00002886 if( i<0 ){
drh1b40e632014-11-20 02:58:10 +00002887 u = ~i;
drhcfd654b2011-03-05 13:54:15 +00002888 }else{
2889 u = i;
2890 }
drh56690b32012-09-17 15:36:31 +00002891 if( u<=127 ){
2892 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
2893 }
drh5742b632005-01-26 17:47:02 +00002894 if( u<=32767 ) return 2;
2895 if( u<=8388607 ) return 3;
2896 if( u<=2147483647 ) return 4;
2897 if( u<=MAX_6BYTE ) return 5;
drha19b7752004-05-30 21:14:58 +00002898 return 6;
danielk197790e4d952004-05-10 10:05:53 +00002899 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002900 if( flags&MEM_Real ){
drha19b7752004-05-30 21:14:58 +00002901 return 7;
danielk197790e4d952004-05-10 10:05:53 +00002902 }
danielk1977e4359752008-11-03 09:39:45 +00002903 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
drheac5bd72014-07-25 21:35:39 +00002904 assert( pMem->n>=0 );
2905 n = (u32)pMem->n;
drhfdf972a2007-05-02 13:30:27 +00002906 if( flags & MEM_Zero ){
drh8df32842008-12-09 02:51:23 +00002907 n += pMem->u.nZero;
danielk197790e4d952004-05-10 10:05:53 +00002908 }
drhfdf972a2007-05-02 13:30:27 +00002909 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
danielk1977192ac1d2004-05-10 07:17:30 +00002910}
2911
2912/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002913** Return the length of the data corresponding to the supplied serial-type.
danielk1977192ac1d2004-05-10 07:17:30 +00002914*/
drh35cd6432009-06-05 14:17:21 +00002915u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
drha19b7752004-05-30 21:14:58 +00002916 if( serial_type>=12 ){
drh51846b52004-05-28 16:00:21 +00002917 return (serial_type-12)/2;
2918 }else{
drh57196282004-10-06 15:41:16 +00002919 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
drh51846b52004-05-28 16:00:21 +00002920 return aSize[serial_type];
2921 }
danielk1977192ac1d2004-05-10 07:17:30 +00002922}
2923
2924/*
drh110daac2007-05-04 11:59:31 +00002925** If we are on an architecture with mixed-endian floating
drh7a4f5022007-05-23 07:20:08 +00002926** points (ex: ARM7) then swap the lower 4 bytes with the
drh110daac2007-05-04 11:59:31 +00002927** upper 4 bytes. Return the result.
2928**
drh7a4f5022007-05-23 07:20:08 +00002929** For most architectures, this is a no-op.
2930**
2931** (later): It is reported to me that the mixed-endian problem
2932** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2933** that early versions of GCC stored the two words of a 64-bit
2934** float in the wrong order. And that error has been propagated
2935** ever since. The blame is not necessarily with GCC, though.
2936** GCC might have just copying the problem from a prior compiler.
2937** I am also told that newer versions of GCC that follow a different
2938** ABI get the byte order right.
2939**
2940** Developers using SQLite on an ARM7 should compile and run their
2941** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2942** enabled, some asserts below will ensure that the byte order of
2943** floating point values is correct.
drh60d09a72007-08-30 15:05:08 +00002944**
2945** (2007-08-30) Frank van Vugt has studied this problem closely
2946** and has send his findings to the SQLite developers. Frank
2947** writes that some Linux kernels offer floating point hardware
2948** emulation that uses only 32-bit mantissas instead of a full
2949** 48-bits as required by the IEEE standard. (This is the
2950** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2951** byte swapping becomes very complicated. To avoid problems,
2952** the necessary byte swapping is carried out using a 64-bit integer
2953** rather than a 64-bit float. Frank assures us that the code here
2954** works for him. We, the developers, have no way to independently
2955** verify this, but Frank seems to know what he is talking about
2956** so we trust him.
drh110daac2007-05-04 11:59:31 +00002957*/
2958#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
drh60d09a72007-08-30 15:05:08 +00002959static u64 floatSwap(u64 in){
drh110daac2007-05-04 11:59:31 +00002960 union {
drh60d09a72007-08-30 15:05:08 +00002961 u64 r;
drh110daac2007-05-04 11:59:31 +00002962 u32 i[2];
2963 } u;
2964 u32 t;
2965
2966 u.r = in;
2967 t = u.i[0];
2968 u.i[0] = u.i[1];
2969 u.i[1] = t;
2970 return u.r;
2971}
2972# define swapMixedEndianFloat(X) X = floatSwap(X)
2973#else
2974# define swapMixedEndianFloat(X)
2975#endif
2976
2977/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002978** Write the serialized data blob for the value stored in pMem into
2979** buf. It is assumed that the caller has allocated sufficient space.
2980** Return the number of bytes written.
drhfdf972a2007-05-02 13:30:27 +00002981**
drh038b7bc2013-12-09 23:17:22 +00002982** nBuf is the amount of space left in buf[]. The caller is responsible
2983** for allocating enough space to buf[] to hold the entire field, exclusive
2984** of the pMem->u.nZero bytes for a MEM_Zero value.
drhfdf972a2007-05-02 13:30:27 +00002985**
2986** Return the number of bytes actually written into buf[]. The number
2987** of bytes in the zero-filled tail is included in the return value only
2988** if those bytes were zeroed in buf[].
danielk1977cfcdaef2004-05-12 07:33:33 +00002989*/
drha9ab4812013-12-11 11:00:44 +00002990u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
drh35cd6432009-06-05 14:17:21 +00002991 u32 len;
danielk1977183f9f72004-05-13 05:20:26 +00002992
drh1483e142004-05-21 21:12:42 +00002993 /* Integer and Real */
drhd946db02005-12-29 19:23:06 +00002994 if( serial_type<=7 && serial_type>0 ){
drh1483e142004-05-21 21:12:42 +00002995 u64 v;
drh35cd6432009-06-05 14:17:21 +00002996 u32 i;
drha19b7752004-05-30 21:14:58 +00002997 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00002998 assert( sizeof(v)==sizeof(pMem->u.r) );
2999 memcpy(&v, &pMem->u.r, sizeof(v));
drh60d09a72007-08-30 15:05:08 +00003000 swapMixedEndianFloat(v);
drh1483e142004-05-21 21:12:42 +00003001 }else{
drh3c024d62007-03-30 11:23:45 +00003002 v = pMem->u.i;
danielk1977cfcdaef2004-05-12 07:33:33 +00003003 }
drh1483e142004-05-21 21:12:42 +00003004 len = i = sqlite3VdbeSerialTypeLen(serial_type);
drh3f5b1992014-08-22 13:22:32 +00003005 assert( i>0 );
3006 do{
3007 buf[--i] = (u8)(v&0xFF);
drh1483e142004-05-21 21:12:42 +00003008 v >>= 8;
drh3f5b1992014-08-22 13:22:32 +00003009 }while( i );
drh1483e142004-05-21 21:12:42 +00003010 return len;
danielk1977cfcdaef2004-05-12 07:33:33 +00003011 }
drhd946db02005-12-29 19:23:06 +00003012
danielk1977cfcdaef2004-05-12 07:33:33 +00003013 /* String or blob */
drhd946db02005-12-29 19:23:06 +00003014 if( serial_type>=12 ){
drh8df32842008-12-09 02:51:23 +00003015 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
shane75ac1de2009-06-09 18:58:52 +00003016 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
drhfdf972a2007-05-02 13:30:27 +00003017 len = pMem->n;
drhd946db02005-12-29 19:23:06 +00003018 memcpy(buf, pMem->z, len);
3019 return len;
3020 }
3021
3022 /* NULL or constants 0 or 1 */
3023 return 0;
danielk1977cfcdaef2004-05-12 07:33:33 +00003024}
3025
drhf926d1e2014-03-04 04:04:33 +00003026/* Input "x" is a sequence of unsigned characters that represent a
3027** big-endian integer. Return the equivalent native integer
3028*/
3029#define ONE_BYTE_INT(x) ((i8)(x)[0])
3030#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
3031#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3032#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drh8932bec2014-08-22 14:56:13 +00003033#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drhf926d1e2014-03-04 04:04:33 +00003034
danielk1977cfcdaef2004-05-12 07:33:33 +00003035/*
3036** Deserialize the data blob pointed to by buf as serial type serial_type
3037** and store the result in pMem. Return the number of bytes read.
drh14a924a2014-08-22 14:34:05 +00003038**
3039** This function is implemented as two separate routines for performance.
3040** The few cases that require local variables are broken out into a separate
3041** routine so that in most cases the overhead of moving the stack pointer
3042** is avoided.
danielk1977cfcdaef2004-05-12 07:33:33 +00003043*/
drh14a924a2014-08-22 14:34:05 +00003044static u32 SQLITE_NOINLINE serialGet(
danielk197793d46752004-05-23 13:30:58 +00003045 const unsigned char *buf, /* Buffer to deserialize from */
drh25aa1b42004-05-28 01:39:01 +00003046 u32 serial_type, /* Serial type to deserialize */
3047 Mem *pMem /* Memory cell to write value into */
danielk1977b1bc9532004-05-22 03:05:33 +00003048){
drh8932bec2014-08-22 14:56:13 +00003049 u64 x = FOUR_BYTE_UINT(buf);
3050 u32 y = FOUR_BYTE_UINT(buf+4);
3051 x = (x<<32) + y;
drh14a924a2014-08-22 14:34:05 +00003052 if( serial_type==6 ){
drh654858d2014-11-20 02:18:14 +00003053 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3054 ** twos-complement integer. */
drh14a924a2014-08-22 14:34:05 +00003055 pMem->u.i = *(i64*)&x;
3056 pMem->flags = MEM_Int;
3057 testcase( pMem->u.i<0 );
3058 }else{
drh654858d2014-11-20 02:18:14 +00003059 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3060 ** floating point number. */
drh14a924a2014-08-22 14:34:05 +00003061#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3062 /* Verify that integers and floating point values use the same
3063 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3064 ** defined that 64-bit floating point values really are mixed
3065 ** endian.
3066 */
3067 static const u64 t1 = ((u64)0x3ff00000)<<32;
3068 static const double r1 = 1.0;
3069 u64 t2 = t1;
3070 swapMixedEndianFloat(t2);
3071 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3072#endif
drh74eaba42014-09-18 17:52:15 +00003073 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
drh14a924a2014-08-22 14:34:05 +00003074 swapMixedEndianFloat(x);
drh74eaba42014-09-18 17:52:15 +00003075 memcpy(&pMem->u.r, &x, sizeof(x));
3076 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
drh14a924a2014-08-22 14:34:05 +00003077 }
3078 return 8;
3079}
danielk1977b1bc9532004-05-22 03:05:33 +00003080u32 sqlite3VdbeSerialGet(
3081 const unsigned char *buf, /* Buffer to deserialize from */
3082 u32 serial_type, /* Serial type to deserialize */
3083 Mem *pMem /* Memory cell to write value into */
3084){
drh3c685822005-05-21 18:32:18 +00003085 switch( serial_type ){
drh3c685822005-05-21 18:32:18 +00003086 case 10: /* Reserved for future use */
3087 case 11: /* Reserved for future use */
drh654858d2014-11-20 02:18:14 +00003088 case 0: { /* Null */
3089 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
drh3c685822005-05-21 18:32:18 +00003090 pMem->flags = MEM_Null;
3091 break;
3092 }
drh654858d2014-11-20 02:18:14 +00003093 case 1: {
3094 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3095 ** integer. */
drhf926d1e2014-03-04 04:04:33 +00003096 pMem->u.i = ONE_BYTE_INT(buf);
drh1483e142004-05-21 21:12:42 +00003097 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003098 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003099 return 1;
drh1483e142004-05-21 21:12:42 +00003100 }
drh3c685822005-05-21 18:32:18 +00003101 case 2: { /* 2-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003102 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3103 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003104 pMem->u.i = TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003105 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003106 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003107 return 2;
3108 }
3109 case 3: { /* 3-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003110 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3111 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003112 pMem->u.i = THREE_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003113 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003114 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003115 return 3;
3116 }
3117 case 4: { /* 4-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003118 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3119 ** twos-complement integer. */
drh8932bec2014-08-22 14:56:13 +00003120 pMem->u.i = FOUR_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003121 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003122 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003123 return 4;
3124 }
3125 case 5: { /* 6-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003126 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3127 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003128 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003129 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003130 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003131 return 6;
3132 }
drh91124b32005-08-18 18:15:05 +00003133 case 6: /* 8-byte signed integer */
drh3c685822005-05-21 18:32:18 +00003134 case 7: { /* IEEE floating point */
drh8932bec2014-08-22 14:56:13 +00003135 /* These use local variables, so do them in a separate routine
3136 ** to avoid having to move the frame pointer in the common case */
drh14a924a2014-08-22 14:34:05 +00003137 return serialGet(buf,serial_type,pMem);
drh3c685822005-05-21 18:32:18 +00003138 }
drhd946db02005-12-29 19:23:06 +00003139 case 8: /* Integer 0 */
3140 case 9: { /* Integer 1 */
drh654858d2014-11-20 02:18:14 +00003141 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3142 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
drh3c024d62007-03-30 11:23:45 +00003143 pMem->u.i = serial_type-8;
drhd946db02005-12-29 19:23:06 +00003144 pMem->flags = MEM_Int;
3145 return 0;
3146 }
drh3c685822005-05-21 18:32:18 +00003147 default: {
drh654858d2014-11-20 02:18:14 +00003148 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3149 ** length.
3150 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3151 ** (N-13)/2 bytes in length. */
drhc138daf2013-11-19 13:55:34 +00003152 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
drh3c685822005-05-21 18:32:18 +00003153 pMem->z = (char *)buf;
drh14a924a2014-08-22 14:34:05 +00003154 pMem->n = (serial_type-12)/2;
drhc138daf2013-11-19 13:55:34 +00003155 pMem->flags = aFlag[serial_type&1];
drh14a924a2014-08-22 14:34:05 +00003156 return pMem->n;
drh696b32f2004-05-30 01:51:52 +00003157 }
danielk1977cfcdaef2004-05-12 07:33:33 +00003158 }
drh3c685822005-05-21 18:32:18 +00003159 return 0;
danielk1977192ac1d2004-05-10 07:17:30 +00003160}
drh1e968a02008-03-25 00:22:21 +00003161/*
dan03e9cfc2011-09-05 14:20:27 +00003162** This routine is used to allocate sufficient space for an UnpackedRecord
3163** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3164** the first argument is a pointer to KeyInfo structure pKeyInfo.
drh1e968a02008-03-25 00:22:21 +00003165**
dan03e9cfc2011-09-05 14:20:27 +00003166** The space is either allocated using sqlite3DbMallocRaw() or from within
3167** the unaligned buffer passed via the second and third arguments (presumably
3168** stack space). If the former, then *ppFree is set to a pointer that should
3169** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3170** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3171** before returning.
drh1e968a02008-03-25 00:22:21 +00003172**
dan03e9cfc2011-09-05 14:20:27 +00003173** If an OOM error occurs, NULL is returned.
3174*/
3175UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3176 KeyInfo *pKeyInfo, /* Description of the record */
3177 char *pSpace, /* Unaligned space available */
3178 int szSpace, /* Size of pSpace[] in bytes */
3179 char **ppFree /* OUT: Caller should free this pointer */
drh1e968a02008-03-25 00:22:21 +00003180){
dan03e9cfc2011-09-05 14:20:27 +00003181 UnpackedRecord *p; /* Unpacked record to return */
3182 int nOff; /* Increment pSpace by nOff to align it */
3183 int nByte; /* Number of bytes required for *p */
3184
3185 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
shane80167bf2009-04-10 15:42:36 +00003186 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
3187 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
3188 */
3189 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
drh8c5d1522009-04-10 00:56:28 +00003190 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
dan42acb3e2011-09-05 20:16:38 +00003191 if( nByte>szSpace+nOff ){
dan03e9cfc2011-09-05 14:20:27 +00003192 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3193 *ppFree = (char *)p;
dan42acb3e2011-09-05 20:16:38 +00003194 if( !p ) return 0;
drh1e968a02008-03-25 00:22:21 +00003195 }else{
dan42acb3e2011-09-05 20:16:38 +00003196 p = (UnpackedRecord*)&pSpace[nOff];
dan03e9cfc2011-09-05 14:20:27 +00003197 *ppFree = 0;
drh1e968a02008-03-25 00:22:21 +00003198 }
dan42acb3e2011-09-05 20:16:38 +00003199
3200 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
drhe1a022e2012-09-17 17:16:53 +00003201 assert( pKeyInfo->aSortOrder!=0 );
drh1e968a02008-03-25 00:22:21 +00003202 p->pKeyInfo = pKeyInfo;
3203 p->nField = pKeyInfo->nField + 1;
dan03e9cfc2011-09-05 14:20:27 +00003204 return p;
3205}
3206
3207/*
3208** Given the nKey-byte encoding of a record in pKey[], populate the
3209** UnpackedRecord structure indicated by the fourth argument with the
3210** contents of the decoded record.
3211*/
3212void sqlite3VdbeRecordUnpack(
3213 KeyInfo *pKeyInfo, /* Information about the record format */
3214 int nKey, /* Size of the binary record */
3215 const void *pKey, /* The binary record */
3216 UnpackedRecord *p /* Populate this structure before returning. */
3217){
3218 const unsigned char *aKey = (const unsigned char *)pKey;
3219 int d;
3220 u32 idx; /* Offset in aKey[] to read from */
3221 u16 u; /* Unsigned loop counter */
3222 u32 szHdr;
dan42acb3e2011-09-05 20:16:38 +00003223 Mem *pMem = p->aMem;
dan03e9cfc2011-09-05 14:20:27 +00003224
dan1fed5da2014-02-25 21:01:25 +00003225 p->default_rc = 0;
drh8c5d1522009-04-10 00:56:28 +00003226 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
shane3f8d5cf2008-04-24 19:15:09 +00003227 idx = getVarint32(aKey, szHdr);
drh1e968a02008-03-25 00:22:21 +00003228 d = szHdr;
shane0b8d2762008-07-22 05:18:00 +00003229 u = 0;
drh7f4b19f2014-09-16 13:30:05 +00003230 while( idx<szHdr && d<=nKey ){
drh1e968a02008-03-25 00:22:21 +00003231 u32 serial_type;
3232
danielk197700e13612008-11-17 19:18:54 +00003233 idx += getVarint32(&aKey[idx], serial_type);
drh1e968a02008-03-25 00:22:21 +00003234 pMem->enc = pKeyInfo->enc;
3235 pMem->db = pKeyInfo->db;
drhc3f1d5f2011-05-30 23:42:16 +00003236 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
drh17bcb102014-09-18 21:25:33 +00003237 pMem->szMalloc = 0;
drh1e968a02008-03-25 00:22:21 +00003238 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
drhe14006d2008-03-25 17:23:32 +00003239 pMem++;
drh7f4b19f2014-09-16 13:30:05 +00003240 if( (++u)>=p->nField ) break;
drh1e968a02008-03-25 00:22:21 +00003241 }
drh7d10d5a2008-08-20 16:35:10 +00003242 assert( u<=pKeyInfo->nField + 1 );
shane0b8d2762008-07-22 05:18:00 +00003243 p->nField = u;
drh1e968a02008-03-25 00:22:21 +00003244}
3245
dan3833e932014-03-01 19:44:56 +00003246#if SQLITE_DEBUG
dan3b9330f2014-02-27 20:44:18 +00003247/*
dan3833e932014-03-01 19:44:56 +00003248** This function compares two index or table record keys in the same way
3249** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3250** this function deserializes and compares values using the
3251** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3252** in assert() statements to ensure that the optimized code in
3253** sqlite3VdbeRecordCompare() returns results with these two primitives.
drh79211e12014-05-02 17:33:16 +00003254**
3255** Return true if the result of comparison is equivalent to desiredResult.
3256** Return false if there is a disagreement.
dan3b9330f2014-02-27 20:44:18 +00003257*/
dan3833e932014-03-01 19:44:56 +00003258static int vdbeRecordCompareDebug(
dan1fed5da2014-02-25 21:01:25 +00003259 int nKey1, const void *pKey1, /* Left key */
drh79211e12014-05-02 17:33:16 +00003260 const UnpackedRecord *pPKey2, /* Right key */
3261 int desiredResult /* Correct answer */
dan1fed5da2014-02-25 21:01:25 +00003262){
dan3b9330f2014-02-27 20:44:18 +00003263 u32 d1; /* Offset into aKey[] of next data element */
3264 u32 idx1; /* Offset into aKey[] of next header element */
3265 u32 szHdr1; /* Number of bytes in header */
3266 int i = 0;
3267 int rc = 0;
3268 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3269 KeyInfo *pKeyInfo;
3270 Mem mem1;
dan1fed5da2014-02-25 21:01:25 +00003271
dan3b9330f2014-02-27 20:44:18 +00003272 pKeyInfo = pPKey2->pKeyInfo;
drh84de6902014-05-02 18:46:52 +00003273 if( pKeyInfo->db==0 ) return 1;
dan3b9330f2014-02-27 20:44:18 +00003274 mem1.enc = pKeyInfo->enc;
3275 mem1.db = pKeyInfo->db;
3276 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
drh17bcb102014-09-18 21:25:33 +00003277 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003278
dan3b9330f2014-02-27 20:44:18 +00003279 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3280 ** We could initialize it, as shown here, to silence those complaints.
3281 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3282 ** the unnecessary initialization has a measurable negative performance
3283 ** impact, since this routine is a very high runner. And so, we choose
3284 ** to ignore the compiler warnings and leave this variable uninitialized.
3285 */
3286 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3287
3288 idx1 = getVarint32(aKey1, szHdr1);
3289 d1 = szHdr1;
3290 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3291 assert( pKeyInfo->aSortOrder!=0 );
3292 assert( pKeyInfo->nField>0 );
3293 assert( idx1<=szHdr1 || CORRUPT_DB );
3294 do{
3295 u32 serial_type1;
dan1fed5da2014-02-25 21:01:25 +00003296
dan3b9330f2014-02-27 20:44:18 +00003297 /* Read the serial types for the next element in each key. */
3298 idx1 += getVarint32( aKey1+idx1, serial_type1 );
dan1fed5da2014-02-25 21:01:25 +00003299
dan3b9330f2014-02-27 20:44:18 +00003300 /* Verify that there is enough key space remaining to avoid
3301 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3302 ** always be greater than or equal to the amount of required key space.
3303 ** Use that approximation to avoid the more expensive call to
3304 ** sqlite3VdbeSerialTypeLen() in the common case.
3305 */
3306 if( d1+serial_type1+2>(u32)nKey1
3307 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3308 ){
3309 break;
dan1fed5da2014-02-25 21:01:25 +00003310 }
dan1fed5da2014-02-25 21:01:25 +00003311
dan3b9330f2014-02-27 20:44:18 +00003312 /* Extract the values to be compared.
3313 */
3314 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
dan1fed5da2014-02-25 21:01:25 +00003315
dan3b9330f2014-02-27 20:44:18 +00003316 /* Do the comparison
3317 */
3318 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3319 if( rc!=0 ){
drh17bcb102014-09-18 21:25:33 +00003320 assert( mem1.szMalloc==0 ); /* See comment below */
dan3b9330f2014-02-27 20:44:18 +00003321 if( pKeyInfo->aSortOrder[i] ){
3322 rc = -rc; /* Invert the result for DESC sort order. */
dan1fed5da2014-02-25 21:01:25 +00003323 }
drh79211e12014-05-02 17:33:16 +00003324 goto debugCompareEnd;
dan1fed5da2014-02-25 21:01:25 +00003325 }
dan3b9330f2014-02-27 20:44:18 +00003326 i++;
3327 }while( idx1<szHdr1 && i<pPKey2->nField );
dan1fed5da2014-02-25 21:01:25 +00003328
dan3b9330f2014-02-27 20:44:18 +00003329 /* No memory allocation is ever used on mem1. Prove this using
3330 ** the following assert(). If the assert() fails, it indicates a
3331 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3332 */
drh17bcb102014-09-18 21:25:33 +00003333 assert( mem1.szMalloc==0 );
dan3b9330f2014-02-27 20:44:18 +00003334
3335 /* rc==0 here means that one of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003336 ** all the fields up to that point were equal. Return the default_rc
dan3b9330f2014-02-27 20:44:18 +00003337 ** value. */
drh79211e12014-05-02 17:33:16 +00003338 rc = pPKey2->default_rc;
3339
3340debugCompareEnd:
3341 if( desiredResult==0 && rc==0 ) return 1;
3342 if( desiredResult<0 && rc<0 ) return 1;
3343 if( desiredResult>0 && rc>0 ) return 1;
3344 if( CORRUPT_DB ) return 1;
3345 if( pKeyInfo->db->mallocFailed ) return 1;
3346 return 0;
dan1fed5da2014-02-25 21:01:25 +00003347}
dan3833e932014-03-01 19:44:56 +00003348#endif
dan1fed5da2014-02-25 21:01:25 +00003349
dan3833e932014-03-01 19:44:56 +00003350/*
3351** Both *pMem1 and *pMem2 contain string values. Compare the two values
3352** using the collation sequence pColl. As usual, return a negative , zero
3353** or positive value if *pMem1 is less than, equal to or greater than
3354** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3355*/
dan1fed5da2014-02-25 21:01:25 +00003356static int vdbeCompareMemString(
dan3833e932014-03-01 19:44:56 +00003357 const Mem *pMem1,
3358 const Mem *pMem2,
dan38fdead2014-04-01 10:19:02 +00003359 const CollSeq *pColl,
3360 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
dan1fed5da2014-02-25 21:01:25 +00003361){
drh464a2dd2014-12-05 14:36:15 +00003362 assert( sqlite3ValidCollSeq(pColl) );
dan1fed5da2014-02-25 21:01:25 +00003363 if( pMem1->enc==pColl->enc ){
3364 /* The strings are already in the correct encoding. Call the
3365 ** comparison function directly */
3366 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3367 }else{
3368 int rc;
3369 const void *v1, *v2;
3370 int n1, n2;
3371 Mem c1;
3372 Mem c2;
drh17bcb102014-09-18 21:25:33 +00003373 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3374 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
dan1fed5da2014-02-25 21:01:25 +00003375 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3376 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3377 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3378 n1 = v1==0 ? 0 : c1.n;
3379 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3380 n2 = v2==0 ? 0 : c2.n;
3381 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
3382 sqlite3VdbeMemRelease(&c1);
3383 sqlite3VdbeMemRelease(&c2);
dan38fdead2014-04-01 10:19:02 +00003384 if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
dan1fed5da2014-02-25 21:01:25 +00003385 return rc;
3386 }
3387}
3388
3389/*
drh982ff722014-09-16 03:24:43 +00003390** Compare two blobs. Return negative, zero, or positive if the first
3391** is less than, equal to, or greater than the second, respectively.
3392** If one blob is a prefix of the other, then the shorter is the lessor.
3393*/
3394static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3395 int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
3396 if( c ) return c;
3397 return pB1->n - pB2->n;
3398}
3399
3400
3401/*
dan1fed5da2014-02-25 21:01:25 +00003402** Compare the values contained by the two memory cells, returning
3403** negative, zero or positive if pMem1 is less than, equal to, or greater
3404** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3405** and reals) sorted numerically, followed by text ordered by the collating
3406** sequence pColl and finally blob's ordered by memcmp().
3407**
3408** Two NULL values are considered equal by this function.
3409*/
3410int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
dan1fed5da2014-02-25 21:01:25 +00003411 int f1, f2;
3412 int combined_flags;
3413
3414 f1 = pMem1->flags;
3415 f2 = pMem2->flags;
3416 combined_flags = f1|f2;
3417 assert( (combined_flags & MEM_RowSet)==0 );
3418
3419 /* If one value is NULL, it is less than the other. If both values
3420 ** are NULL, return 0.
3421 */
3422 if( combined_flags&MEM_Null ){
3423 return (f2&MEM_Null) - (f1&MEM_Null);
3424 }
3425
3426 /* If one value is a number and the other is not, the number is less.
3427 ** If both are numbers, compare as reals if one is a real, or as integers
3428 ** if both values are integers.
3429 */
3430 if( combined_flags&(MEM_Int|MEM_Real) ){
3431 double r1, r2;
3432 if( (f1 & f2 & MEM_Int)!=0 ){
3433 if( pMem1->u.i < pMem2->u.i ) return -1;
3434 if( pMem1->u.i > pMem2->u.i ) return 1;
3435 return 0;
3436 }
3437 if( (f1&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003438 r1 = pMem1->u.r;
dan1fed5da2014-02-25 21:01:25 +00003439 }else if( (f1&MEM_Int)!=0 ){
3440 r1 = (double)pMem1->u.i;
3441 }else{
3442 return 1;
3443 }
3444 if( (f2&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003445 r2 = pMem2->u.r;
dan1fed5da2014-02-25 21:01:25 +00003446 }else if( (f2&MEM_Int)!=0 ){
3447 r2 = (double)pMem2->u.i;
3448 }else{
3449 return -1;
3450 }
3451 if( r1<r2 ) return -1;
3452 if( r1>r2 ) return 1;
3453 return 0;
3454 }
3455
3456 /* If one value is a string and the other is a blob, the string is less.
3457 ** If both are strings, compare using the collating functions.
3458 */
3459 if( combined_flags&MEM_Str ){
3460 if( (f1 & MEM_Str)==0 ){
3461 return 1;
3462 }
3463 if( (f2 & MEM_Str)==0 ){
3464 return -1;
3465 }
3466
3467 assert( pMem1->enc==pMem2->enc );
3468 assert( pMem1->enc==SQLITE_UTF8 ||
3469 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3470
3471 /* The collation sequence must be defined at this point, even if
3472 ** the user deletes the collation sequence after the vdbe program is
3473 ** compiled (this was not always the case).
3474 */
3475 assert( !pColl || pColl->xCmp );
3476
3477 if( pColl ){
drh464a2dd2014-12-05 14:36:15 +00003478 assert( sqlite3ValidCollSeq(pColl) );
dan38fdead2014-04-01 10:19:02 +00003479 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
dan1fed5da2014-02-25 21:01:25 +00003480 }
3481 /* If a NULL pointer was passed as the collate function, fall through
3482 ** to the blob case and use memcmp(). */
3483 }
3484
3485 /* Both values must be blobs. Compare using memcmp(). */
drh982ff722014-09-16 03:24:43 +00003486 return sqlite3BlobCompare(pMem1, pMem2);
dan1fed5da2014-02-25 21:01:25 +00003487}
3488
3489
dan3833e932014-03-01 19:44:56 +00003490/*
3491** The first argument passed to this function is a serial-type that
3492** corresponds to an integer - all values between 1 and 9 inclusive
3493** except 7. The second points to a buffer containing an integer value
3494** serialized according to serial_type. This function deserializes
3495** and returns the value.
3496*/
dan3b9330f2014-02-27 20:44:18 +00003497static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
drhf926d1e2014-03-04 04:04:33 +00003498 u32 y;
dan3833e932014-03-01 19:44:56 +00003499 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
dan3b9330f2014-02-27 20:44:18 +00003500 switch( serial_type ){
dan3833e932014-03-01 19:44:56 +00003501 case 0:
dan3b9330f2014-02-27 20:44:18 +00003502 case 1:
drhb6e8fd12014-03-06 01:56:33 +00003503 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003504 return ONE_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003505 case 2:
drhb6e8fd12014-03-06 01:56:33 +00003506 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003507 return TWO_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003508 case 3:
drhb6e8fd12014-03-06 01:56:33 +00003509 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003510 return THREE_BYTE_INT(aKey);
3511 case 4: {
drhb6e8fd12014-03-06 01:56:33 +00003512 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003513 y = FOUR_BYTE_UINT(aKey);
3514 return (i64)*(int*)&y;
3515 }
dan3b9330f2014-02-27 20:44:18 +00003516 case 5: {
drhb6e8fd12014-03-06 01:56:33 +00003517 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003518 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhaf5b2af2013-08-05 15:32:09 +00003519 }
dan3b9330f2014-02-27 20:44:18 +00003520 case 6: {
drhf926d1e2014-03-04 04:04:33 +00003521 u64 x = FOUR_BYTE_UINT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003522 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003523 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3524 return (i64)*(i64*)&x;
drh1e968a02008-03-25 00:22:21 +00003525 }
dan3b9330f2014-02-27 20:44:18 +00003526 }
drh407414c2009-07-14 14:15:27 +00003527
dan3b9330f2014-02-27 20:44:18 +00003528 return (serial_type - 8);
drh1e968a02008-03-25 00:22:21 +00003529}
danielk1977eb015e02004-05-18 01:31:14 +00003530
dan3833e932014-03-01 19:44:56 +00003531/*
3532** This function compares the two table rows or index records
3533** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
3534** or positive integer if key1 is less than, equal to or
3535** greater than key2. The {nKey1, pKey1} key must be a blob
peter.d.reid60ec9142014-09-06 16:39:46 +00003536** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
dan3833e932014-03-01 19:44:56 +00003537** key must be a parsed key such as obtained from
3538** sqlite3VdbeParseRecord.
3539**
3540** If argument bSkip is non-zero, it is assumed that the caller has already
3541** determined that the first fields of the keys are equal.
3542**
3543** Key1 and Key2 do not have to contain the same number of fields. If all
3544** fields that appear in both keys are equal, then pPKey2->default_rc is
3545** returned.
drha1f7c0a2014-03-28 03:12:48 +00003546**
dan38fdead2014-04-01 10:19:02 +00003547** If database corruption is discovered, set pPKey2->errCode to
3548** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3549** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3550** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
dan3833e932014-03-01 19:44:56 +00003551*/
drh75179de2014-09-16 14:37:35 +00003552static int vdbeRecordCompareWithSkip(
dan3833e932014-03-01 19:44:56 +00003553 int nKey1, const void *pKey1, /* Left key */
drha1f7c0a2014-03-28 03:12:48 +00003554 UnpackedRecord *pPKey2, /* Right key */
dan3833e932014-03-01 19:44:56 +00003555 int bSkip /* If true, skip the first field */
dan1fed5da2014-02-25 21:01:25 +00003556){
dan3833e932014-03-01 19:44:56 +00003557 u32 d1; /* Offset into aKey[] of next data element */
3558 int i; /* Index of next field to compare */
mistachkinffe6bc22014-03-04 11:16:20 +00003559 u32 szHdr1; /* Size of record header in bytes */
dan3833e932014-03-01 19:44:56 +00003560 u32 idx1; /* Offset of first type in header */
3561 int rc = 0; /* Return value */
3562 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
dan1fed5da2014-02-25 21:01:25 +00003563 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3564 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3565 Mem mem1;
3566
dan3833e932014-03-01 19:44:56 +00003567 /* If bSkip is true, then the caller has already determined that the first
3568 ** two elements in the keys are equal. Fix the various stack variables so
dan3b9330f2014-02-27 20:44:18 +00003569 ** that this routine begins comparing at the second field. */
dan3833e932014-03-01 19:44:56 +00003570 if( bSkip ){
dan3b9330f2014-02-27 20:44:18 +00003571 u32 s1;
dan3b9330f2014-02-27 20:44:18 +00003572 idx1 = 1 + getVarint32(&aKey1[1], s1);
dan3833e932014-03-01 19:44:56 +00003573 szHdr1 = aKey1[0];
3574 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
dan3b9330f2014-02-27 20:44:18 +00003575 i = 1;
3576 pRhs++;
dan3833e932014-03-01 19:44:56 +00003577 }else{
3578 idx1 = getVarint32(aKey1, szHdr1);
3579 d1 = szHdr1;
drha1f7c0a2014-03-28 03:12:48 +00003580 if( d1>(unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003581 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003582 return 0; /* Corruption */
3583 }
dan3833e932014-03-01 19:44:56 +00003584 i = 0;
dan3b9330f2014-02-27 20:44:18 +00003585 }
3586
drh17bcb102014-09-18 21:25:33 +00003587 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003588 assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
3589 || CORRUPT_DB );
3590 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
3591 assert( pPKey2->pKeyInfo->nField>0 );
3592 assert( idx1<=szHdr1 || CORRUPT_DB );
3593 do{
dan1fed5da2014-02-25 21:01:25 +00003594 u32 serial_type;
3595
3596 /* RHS is an integer */
3597 if( pRhs->flags & MEM_Int ){
3598 serial_type = aKey1[idx1];
drhb6e8fd12014-03-06 01:56:33 +00003599 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003600 if( serial_type>=12 ){
3601 rc = +1;
3602 }else if( serial_type==0 ){
3603 rc = -1;
dan3b9330f2014-02-27 20:44:18 +00003604 }else if( serial_type==7 ){
3605 double rhs = (double)pRhs->u.i;
dan1fed5da2014-02-25 21:01:25 +00003606 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
drh74eaba42014-09-18 17:52:15 +00003607 if( mem1.u.r<rhs ){
dan3b9330f2014-02-27 20:44:18 +00003608 rc = -1;
drh74eaba42014-09-18 17:52:15 +00003609 }else if( mem1.u.r>rhs ){
dan3b9330f2014-02-27 20:44:18 +00003610 rc = +1;
3611 }
3612 }else{
3613 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
3614 i64 rhs = pRhs->u.i;
3615 if( lhs<rhs ){
3616 rc = -1;
3617 }else if( lhs>rhs ){
3618 rc = +1;
dan1fed5da2014-02-25 21:01:25 +00003619 }
3620 }
3621 }
3622
3623 /* RHS is real */
3624 else if( pRhs->flags & MEM_Real ){
3625 serial_type = aKey1[idx1];
3626 if( serial_type>=12 ){
3627 rc = +1;
3628 }else if( serial_type==0 ){
3629 rc = -1;
3630 }else{
drh74eaba42014-09-18 17:52:15 +00003631 double rhs = pRhs->u.r;
dan1fed5da2014-02-25 21:01:25 +00003632 double lhs;
3633 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
3634 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00003635 lhs = mem1.u.r;
dan1fed5da2014-02-25 21:01:25 +00003636 }else{
drh295aedf2014-03-03 18:25:24 +00003637 lhs = (double)mem1.u.i;
dan1fed5da2014-02-25 21:01:25 +00003638 }
3639 if( lhs<rhs ){
3640 rc = -1;
3641 }else if( lhs>rhs ){
3642 rc = +1;
3643 }
3644 }
3645 }
3646
3647 /* RHS is a string */
3648 else if( pRhs->flags & MEM_Str ){
3649 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003650 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003651 if( serial_type<12 ){
3652 rc = -1;
3653 }else if( !(serial_type & 0x01) ){
3654 rc = +1;
3655 }else{
3656 mem1.n = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003657 testcase( (d1+mem1.n)==(unsigned)nKey1 );
3658 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003659 if( (d1+mem1.n) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003660 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003661 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003662 }else if( pKeyInfo->aColl[i] ){
3663 mem1.enc = pKeyInfo->enc;
3664 mem1.db = pKeyInfo->db;
3665 mem1.flags = MEM_Str;
drhfcb44a82014-03-03 15:13:27 +00003666 mem1.z = (char*)&aKey1[d1];
dan38fdead2014-04-01 10:19:02 +00003667 rc = vdbeCompareMemString(
3668 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
3669 );
dan1fed5da2014-02-25 21:01:25 +00003670 }else{
3671 int nCmp = MIN(mem1.n, pRhs->n);
3672 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3673 if( rc==0 ) rc = mem1.n - pRhs->n;
3674 }
3675 }
3676 }
3677
3678 /* RHS is a blob */
3679 else if( pRhs->flags & MEM_Blob ){
3680 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003681 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003682 if( serial_type<12 || (serial_type & 0x01) ){
3683 rc = -1;
3684 }else{
3685 int nStr = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003686 testcase( (d1+nStr)==(unsigned)nKey1 );
3687 testcase( (d1+nStr+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003688 if( (d1+nStr) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003689 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003690 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003691 }else{
3692 int nCmp = MIN(nStr, pRhs->n);
3693 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3694 if( rc==0 ) rc = nStr - pRhs->n;
3695 }
3696 }
3697 }
3698
3699 /* RHS is null */
3700 else{
3701 serial_type = aKey1[idx1];
3702 rc = (serial_type!=0);
3703 }
3704
3705 if( rc!=0 ){
dan1fed5da2014-02-25 21:01:25 +00003706 if( pKeyInfo->aSortOrder[i] ){
3707 rc = -rc;
dan1fed5da2014-02-25 21:01:25 +00003708 }
drh79211e12014-05-02 17:33:16 +00003709 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
drh17bcb102014-09-18 21:25:33 +00003710 assert( mem1.szMalloc==0 ); /* See comment below */
dan1fed5da2014-02-25 21:01:25 +00003711 return rc;
3712 }
3713
3714 i++;
dan3b9330f2014-02-27 20:44:18 +00003715 pRhs++;
dan1fed5da2014-02-25 21:01:25 +00003716 d1 += sqlite3VdbeSerialTypeLen(serial_type);
3717 idx1 += sqlite3VarintLen(serial_type);
drh295aedf2014-03-03 18:25:24 +00003718 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
dan1fed5da2014-02-25 21:01:25 +00003719
3720 /* No memory allocation is ever used on mem1. Prove this using
3721 ** the following assert(). If the assert() fails, it indicates a
dan3833e932014-03-01 19:44:56 +00003722 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
drh17bcb102014-09-18 21:25:33 +00003723 assert( mem1.szMalloc==0 );
dan1fed5da2014-02-25 21:01:25 +00003724
3725 /* rc==0 here means that one or both of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003726 ** all the fields up to that point were equal. Return the default_rc
dan1fed5da2014-02-25 21:01:25 +00003727 ** value. */
dan3833e932014-03-01 19:44:56 +00003728 assert( CORRUPT_DB
drh66141812014-06-30 20:25:03 +00003729 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
dan6696ba32014-06-28 19:06:49 +00003730 || pKeyInfo->db->mallocFailed
dan3833e932014-03-01 19:44:56 +00003731 );
dan1fed5da2014-02-25 21:01:25 +00003732 return pPKey2->default_rc;
3733}
drh75179de2014-09-16 14:37:35 +00003734int sqlite3VdbeRecordCompare(
3735 int nKey1, const void *pKey1, /* Left key */
3736 UnpackedRecord *pPKey2 /* Right key */
3737){
3738 return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
3739}
3740
dan1fed5da2014-02-25 21:01:25 +00003741
dan3833e932014-03-01 19:44:56 +00003742/*
3743** This function is an optimized version of sqlite3VdbeRecordCompare()
3744** that (a) the first field of pPKey2 is an integer, and (b) the
3745** size-of-header varint at the start of (pKey1/nKey1) fits in a single
3746** byte (i.e. is less than 128).
drhe2ac5062014-03-26 12:02:38 +00003747**
3748** To avoid concerns about buffer overreads, this routine is only used
3749** on schemas where the maximum valid header size is 63 bytes or less.
dan3833e932014-03-01 19:44:56 +00003750*/
dan3b9330f2014-02-27 20:44:18 +00003751static int vdbeRecordCompareInt(
3752 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003753 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003754){
dan9b8afef2014-03-03 20:48:50 +00003755 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
dan3b9330f2014-02-27 20:44:18 +00003756 int serial_type = ((const u8*)pKey1)[1];
3757 int res;
drhf926d1e2014-03-04 04:04:33 +00003758 u32 y;
3759 u64 x;
dan3b9330f2014-02-27 20:44:18 +00003760 i64 v = pPKey2->aMem[0].u.i;
3761 i64 lhs;
3762
drhe2ac5062014-03-26 12:02:38 +00003763 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
dan3833e932014-03-01 19:44:56 +00003764 switch( serial_type ){
drhf926d1e2014-03-04 04:04:33 +00003765 case 1: { /* 1-byte signed integer */
3766 lhs = ONE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003767 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003768 break;
3769 }
drhf926d1e2014-03-04 04:04:33 +00003770 case 2: { /* 2-byte signed integer */
3771 lhs = TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003772 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003773 break;
3774 }
3775 case 3: { /* 3-byte signed integer */
3776 lhs = THREE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003777 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003778 break;
3779 }
3780 case 4: { /* 4-byte signed integer */
3781 y = FOUR_BYTE_UINT(aKey);
3782 lhs = (i64)*(int*)&y;
drhb6e8fd12014-03-06 01:56:33 +00003783 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003784 break;
3785 }
3786 case 5: { /* 6-byte signed integer */
3787 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003788 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003789 break;
3790 }
3791 case 6: { /* 8-byte signed integer */
3792 x = FOUR_BYTE_UINT(aKey);
3793 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3794 lhs = *(i64*)&x;
drhb6e8fd12014-03-06 01:56:33 +00003795 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003796 break;
3797 }
dan3b9330f2014-02-27 20:44:18 +00003798 case 8:
3799 lhs = 0;
3800 break;
dan3b9330f2014-02-27 20:44:18 +00003801 case 9:
3802 lhs = 1;
3803 break;
3804
dan063d4a02014-02-28 09:48:30 +00003805 /* This case could be removed without changing the results of running
3806 ** this code. Including it causes gcc to generate a faster switch
3807 ** statement (since the range of switch targets now starts at zero and
dan597515d2014-02-28 18:39:51 +00003808 ** is contiguous) but does not cause any duplicate code to be generated
dan063d4a02014-02-28 09:48:30 +00003809 ** (as gcc is clever enough to combine the two like cases). Other
3810 ** compilers might be similar. */
3811 case 0: case 7:
drh75179de2014-09-16 14:37:35 +00003812 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan063d4a02014-02-28 09:48:30 +00003813
dan3b9330f2014-02-27 20:44:18 +00003814 default:
drh75179de2014-09-16 14:37:35 +00003815 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan3b9330f2014-02-27 20:44:18 +00003816 }
3817
3818 if( v>lhs ){
3819 res = pPKey2->r1;
3820 }else if( v<lhs ){
3821 res = pPKey2->r2;
3822 }else if( pPKey2->nField>1 ){
dan063d4a02014-02-28 09:48:30 +00003823 /* The first fields of the two keys are equal. Compare the trailing
3824 ** fields. */
drh75179de2014-09-16 14:37:35 +00003825 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003826 }else{
dan063d4a02014-02-28 09:48:30 +00003827 /* The first fields of the two keys are equal and there are no trailing
3828 ** fields. Return pPKey2->default_rc in this case. */
dan3b9330f2014-02-27 20:44:18 +00003829 res = pPKey2->default_rc;
3830 }
3831
drh79211e12014-05-02 17:33:16 +00003832 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
dan3b9330f2014-02-27 20:44:18 +00003833 return res;
3834}
3835
dan3833e932014-03-01 19:44:56 +00003836/*
3837** This function is an optimized version of sqlite3VdbeRecordCompare()
3838** that (a) the first field of pPKey2 is a string, that (b) the first field
3839** uses the collation sequence BINARY and (c) that the size-of-header varint
3840** at the start of (pKey1/nKey1) fits in a single byte.
3841*/
dan3b9330f2014-02-27 20:44:18 +00003842static int vdbeRecordCompareString(
3843 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003844 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003845){
3846 const u8 *aKey1 = (const u8*)pKey1;
3847 int serial_type;
3848 int res;
3849
3850 getVarint32(&aKey1[1], serial_type);
dan3b9330f2014-02-27 20:44:18 +00003851 if( serial_type<12 ){
3852 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
3853 }else if( !(serial_type & 0x01) ){
3854 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
3855 }else{
3856 int nCmp;
3857 int nStr;
dan3833e932014-03-01 19:44:56 +00003858 int szHdr = aKey1[0];
dan3b9330f2014-02-27 20:44:18 +00003859
3860 nStr = (serial_type-12) / 2;
drha1f7c0a2014-03-28 03:12:48 +00003861 if( (szHdr + nStr) > nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003862 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003863 return 0; /* Corruption */
3864 }
dan3b9330f2014-02-27 20:44:18 +00003865 nCmp = MIN( pPKey2->aMem[0].n, nStr );
dan3833e932014-03-01 19:44:56 +00003866 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
dan3b9330f2014-02-27 20:44:18 +00003867
3868 if( res==0 ){
3869 res = nStr - pPKey2->aMem[0].n;
3870 if( res==0 ){
3871 if( pPKey2->nField>1 ){
drh75179de2014-09-16 14:37:35 +00003872 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003873 }else{
3874 res = pPKey2->default_rc;
3875 }
3876 }else if( res>0 ){
3877 res = pPKey2->r2;
3878 }else{
3879 res = pPKey2->r1;
3880 }
3881 }else if( res>0 ){
3882 res = pPKey2->r2;
3883 }else{
3884 res = pPKey2->r1;
3885 }
3886 }
3887
drh66141812014-06-30 20:25:03 +00003888 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
dan3b9330f2014-02-27 20:44:18 +00003889 || CORRUPT_DB
dan6696ba32014-06-28 19:06:49 +00003890 || pPKey2->pKeyInfo->db->mallocFailed
dan3b9330f2014-02-27 20:44:18 +00003891 );
3892 return res;
3893}
3894
dan3833e932014-03-01 19:44:56 +00003895/*
3896** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
3897** suitable for comparing serialized records to the unpacked record passed
3898** as the only argument.
3899*/
dan1fed5da2014-02-25 21:01:25 +00003900RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
dan9b8afef2014-03-03 20:48:50 +00003901 /* varintRecordCompareInt() and varintRecordCompareString() both assume
3902 ** that the size-of-header varint that occurs at the start of each record
3903 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
3904 ** also assumes that it is safe to overread a buffer by at least the
3905 ** maximum possible legal header size plus 8 bytes. Because there is
3906 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
3907 ** buffer passed to varintRecordCompareInt() this makes it convenient to
3908 ** limit the size of the header to 64 bytes in cases where the first field
3909 ** is an integer.
3910 **
3911 ** The easiest way to enforce this limit is to consider only records with
3912 ** 13 fields or less. If the first field is an integer, the maximum legal
3913 ** header size is (12*5 + 1 + 1) bytes. */
3914 if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
dan1fed5da2014-02-25 21:01:25 +00003915 int flags = p->aMem[0].flags;
dan3b9330f2014-02-27 20:44:18 +00003916 if( p->pKeyInfo->aSortOrder[0] ){
3917 p->r1 = 1;
3918 p->r2 = -1;
3919 }else{
3920 p->r1 = -1;
3921 p->r2 = 1;
3922 }
dan1fed5da2014-02-25 21:01:25 +00003923 if( (flags & MEM_Int) ){
3924 return vdbeRecordCompareInt;
dan3b9330f2014-02-27 20:44:18 +00003925 }
drhb6e8fd12014-03-06 01:56:33 +00003926 testcase( flags & MEM_Real );
3927 testcase( flags & MEM_Null );
3928 testcase( flags & MEM_Blob );
3929 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
3930 assert( flags & MEM_Str );
dan1fed5da2014-02-25 21:01:25 +00003931 return vdbeRecordCompareString;
3932 }
3933 }
dan3b9330f2014-02-27 20:44:18 +00003934
dan3833e932014-03-01 19:44:56 +00003935 return sqlite3VdbeRecordCompare;
dan3b9330f2014-02-27 20:44:18 +00003936}
dan1fed5da2014-02-25 21:01:25 +00003937
danielk1977eb015e02004-05-18 01:31:14 +00003938/*
drh7a224de2004-06-02 01:22:02 +00003939** pCur points at an index entry created using the OP_MakeRecord opcode.
3940** Read the rowid (the last field in the record) and store it in *rowid.
3941** Return SQLITE_OK if everything works, or an error code otherwise.
drh88a003e2008-12-11 16:17:03 +00003942**
3943** pCur might be pointing to text obtained from a corrupt database file.
3944** So the content cannot be trusted. Do appropriate checks on the content.
danielk1977183f9f72004-05-13 05:20:26 +00003945*/
drhd3b74202014-09-17 16:41:15 +00003946int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
drh61fc5952007-04-01 23:49:51 +00003947 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003948 int rc;
drhd5788202004-05-28 08:21:05 +00003949 u32 szHdr; /* Size of the header */
3950 u32 typeRowid; /* Serial type of the rowid */
3951 u32 lenRowid; /* Size of the rowid */
3952 Mem m, v;
danielk1977183f9f72004-05-13 05:20:26 +00003953
drh88a003e2008-12-11 16:17:03 +00003954 /* Get the size of the index entry. Only indices entries of less
drh7b746032009-06-26 12:15:22 +00003955 ** than 2GiB are support - anything large must be database corruption.
3956 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
drhc27ae612009-07-14 18:35:44 +00003957 ** this code can safely assume that nCellKey is 32-bits
3958 */
drhea8ffdf2009-07-22 00:35:23 +00003959 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003960 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003961 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh7b746032009-06-26 12:15:22 +00003962 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
drh88a003e2008-12-11 16:17:03 +00003963
3964 /* Read in the complete content of the index entry */
drhd3b74202014-09-17 16:41:15 +00003965 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00003966 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
drhd5788202004-05-28 08:21:05 +00003967 if( rc ){
danielk1977183f9f72004-05-13 05:20:26 +00003968 return rc;
3969 }
drh88a003e2008-12-11 16:17:03 +00003970
3971 /* The index entry must begin with a header size */
shane3f8d5cf2008-04-24 19:15:09 +00003972 (void)getVarint32((u8*)m.z, szHdr);
drh7b746032009-06-26 12:15:22 +00003973 testcase( szHdr==3 );
drh88a003e2008-12-11 16:17:03 +00003974 testcase( szHdr==m.n );
drh7b746032009-06-26 12:15:22 +00003975 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
drh88a003e2008-12-11 16:17:03 +00003976 goto idx_rowid_corruption;
3977 }
3978
3979 /* The last field of the index should be an integer - the ROWID.
3980 ** Verify that the last entry really is an integer. */
shane3f8d5cf2008-04-24 19:15:09 +00003981 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
drh88a003e2008-12-11 16:17:03 +00003982 testcase( typeRowid==1 );
3983 testcase( typeRowid==2 );
3984 testcase( typeRowid==3 );
3985 testcase( typeRowid==4 );
3986 testcase( typeRowid==5 );
3987 testcase( typeRowid==6 );
3988 testcase( typeRowid==8 );
3989 testcase( typeRowid==9 );
3990 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
3991 goto idx_rowid_corruption;
3992 }
drhd5788202004-05-28 08:21:05 +00003993 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
drheeb844a2009-08-08 18:01:07 +00003994 testcase( (u32)m.n==szHdr+lenRowid );
3995 if( unlikely((u32)m.n<szHdr+lenRowid) ){
drh88a003e2008-12-11 16:17:03 +00003996 goto idx_rowid_corruption;
3997 }
3998
3999 /* Fetch the integer off the end of the index record */
drh2646da72005-12-09 20:02:05 +00004000 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
drh3c024d62007-03-30 11:23:45 +00004001 *rowid = v.u.i;
danielk1977d8123362004-06-12 09:25:12 +00004002 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00004003 return SQLITE_OK;
drh88a003e2008-12-11 16:17:03 +00004004
4005 /* Jump here if database corruption is detected after m has been
4006 ** allocated. Free the m object and return SQLITE_CORRUPT. */
4007idx_rowid_corruption:
drh17bcb102014-09-18 21:25:33 +00004008 testcase( m.szMalloc!=0 );
drh88a003e2008-12-11 16:17:03 +00004009 sqlite3VdbeMemRelease(&m);
4010 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00004011}
4012
drh7cf6e4d2004-05-19 14:56:55 +00004013/*
drh5f82e3c2009-07-06 00:44:08 +00004014** Compare the key of the index entry that cursor pC is pointing to against
4015** the key string in pUnpacked. Write into *pRes a number
drh7cf6e4d2004-05-19 14:56:55 +00004016** that is negative, zero, or positive if pC is less than, equal to,
drh5f82e3c2009-07-06 00:44:08 +00004017** or greater than pUnpacked. Return SQLITE_OK on success.
drhd3d39e92004-05-20 22:16:29 +00004018**
drh5f82e3c2009-07-06 00:44:08 +00004019** pUnpacked is either created without a rowid or is truncated so that it
drhd5788202004-05-28 08:21:05 +00004020** omits the rowid at the end. The rowid at the end of the index entry
drhec1fc802008-08-13 14:07:40 +00004021** is ignored as well. Hence, this routine only compares the prefixes
4022** of the keys prior to the final rowid, not the entire key.
drh7cf6e4d2004-05-19 14:56:55 +00004023*/
danielk1977183f9f72004-05-13 05:20:26 +00004024int sqlite3VdbeIdxKeyCompare(
drhd3b74202014-09-17 16:41:15 +00004025 sqlite3 *db, /* Database connection */
drh295aedf2014-03-03 18:25:24 +00004026 VdbeCursor *pC, /* The cursor to compare against */
drha1f7c0a2014-03-28 03:12:48 +00004027 UnpackedRecord *pUnpacked, /* Unpacked version of key */
drh295aedf2014-03-03 18:25:24 +00004028 int *res /* Write the comparison result here */
danielk1977183f9f72004-05-13 05:20:26 +00004029){
drh61fc5952007-04-01 23:49:51 +00004030 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00004031 int rc;
danielk19773d1bfea2004-05-14 11:00:53 +00004032 BtCursor *pCur = pC->pCursor;
drhd5788202004-05-28 08:21:05 +00004033 Mem m;
danielk1977183f9f72004-05-13 05:20:26 +00004034
drhea8ffdf2009-07-22 00:35:23 +00004035 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00004036 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00004037 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh56689692014-03-03 19:29:28 +00004038 /* nCellKey will always be between 0 and 0xffffffff because of the way
drh407414c2009-07-14 14:15:27 +00004039 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
drhc27ae612009-07-14 18:35:44 +00004040 if( nCellKey<=0 || nCellKey>0x7fffffff ){
danielk1977183f9f72004-05-13 05:20:26 +00004041 *res = 0;
drh9978c972010-02-23 17:36:32 +00004042 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00004043 }
drhd3b74202014-09-17 16:41:15 +00004044 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00004045 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
drhec1fc802008-08-13 14:07:40 +00004046 if( rc ){
drhd5788202004-05-28 08:21:05 +00004047 return rc;
danielk1977183f9f72004-05-13 05:20:26 +00004048 }
drh75179de2014-09-16 14:37:35 +00004049 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
danielk1977d8123362004-06-12 09:25:12 +00004050 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00004051 return SQLITE_OK;
4052}
danielk1977b28af712004-06-21 06:50:26 +00004053
4054/*
4055** This routine sets the value to be returned by subsequent calls to
4056** sqlite3_changes() on the database handle 'db'.
4057*/
4058void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
drhb21c8cd2007-08-21 19:33:56 +00004059 assert( sqlite3_mutex_held(db->mutex) );
danielk1977b28af712004-06-21 06:50:26 +00004060 db->nChange = nChange;
4061 db->nTotalChange += nChange;
4062}
4063
4064/*
4065** Set a flag in the vdbe to update the change counter when it is finalised
4066** or reset.
4067*/
drh4794f732004-11-05 17:17:50 +00004068void sqlite3VdbeCountChanges(Vdbe *v){
4069 v->changeCntOn = 1;
danielk1977b28af712004-06-21 06:50:26 +00004070}
drhd89bd002005-01-22 03:03:54 +00004071
4072/*
4073** Mark every prepared statement associated with a database connection
4074** as expired.
4075**
4076** An expired statement means that recompilation of the statement is
4077** recommend. Statements expire when things happen that make their
4078** programs obsolete. Removing user-defined functions or collating
4079** sequences, or changing an authorization function are the types of
4080** things that make prepared statements obsolete.
4081*/
4082void sqlite3ExpirePreparedStatements(sqlite3 *db){
4083 Vdbe *p;
4084 for(p = db->pVdbe; p; p=p->pNext){
4085 p->expired = 1;
4086 }
4087}
danielk1977aee18ef2005-03-09 12:26:50 +00004088
4089/*
4090** Return the database associated with the Vdbe.
4091*/
4092sqlite3 *sqlite3VdbeDb(Vdbe *v){
4093 return v->db;
4094}
dan937d0de2009-10-15 18:35:38 +00004095
4096/*
4097** Return a pointer to an sqlite3_value structure containing the value bound
4098** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4099** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4100** constants) to the value before returning it.
4101**
4102** The returned value must be freed by the caller using sqlite3ValueFree().
4103*/
drhcf0fd4a2013-08-01 12:21:58 +00004104sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
dan937d0de2009-10-15 18:35:38 +00004105 assert( iVar>0 );
4106 if( v ){
4107 Mem *pMem = &v->aVar[iVar-1];
4108 if( 0==(pMem->flags & MEM_Null) ){
4109 sqlite3_value *pRet = sqlite3ValueNew(v->db);
4110 if( pRet ){
4111 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4112 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
dan937d0de2009-10-15 18:35:38 +00004113 }
4114 return pRet;
4115 }
4116 }
4117 return 0;
4118}
4119
4120/*
4121** Configure SQL variable iVar so that binding a new value to it signals
4122** to sqlite3_reoptimize() that re-preparing the statement may result
4123** in a better query plan.
4124*/
dan1d2ce4f2009-10-19 18:11:09 +00004125void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
dan937d0de2009-10-15 18:35:38 +00004126 assert( iVar>0 );
4127 if( iVar>32 ){
dan1d2ce4f2009-10-19 18:11:09 +00004128 v->expmask = 0xffffffff;
dan937d0de2009-10-15 18:35:38 +00004129 }else{
dan1d2ce4f2009-10-19 18:11:09 +00004130 v->expmask |= ((u32)1 << (iVar-1));
dan937d0de2009-10-15 18:35:38 +00004131 }
4132}
dan016f7812013-08-21 17:35:48 +00004133
4134#ifndef SQLITE_OMIT_VIRTUALTABLE
4135/*
4136** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4137** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4138** in memory obtained from sqlite3DbMalloc).
4139*/
4140void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4141 sqlite3 *db = p->db;
4142 sqlite3DbFree(db, p->zErrMsg);
4143 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4144 sqlite3_free(pVtab->zErrMsg);
4145 pVtab->zErrMsg = 0;
4146}
4147#endif /* SQLITE_OMIT_VIRTUALTABLE */