blob: bd00786ebc253637a32f17cfa5a31db3787ac928 [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;
dan04668832014-12-16 20:13:30 +0000399 int hasFkCounter = 0;
dan144926d2009-09-09 11:37:20 +0000400 Op *pOp;
401 VdbeOpIter sIter;
402 memset(&sIter, 0, sizeof(sIter));
403 sIter.v = v;
404
405 while( (pOp = opIterNext(&sIter))!=0 ){
406 int opcode = pOp->opcode;
407 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
408 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
drhd91c1a12013-02-09 13:58:25 +0000409 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
dan144926d2009-09-09 11:37:20 +0000410 ){
danf3677212009-09-10 16:14:50 +0000411 hasAbort = 1;
dan144926d2009-09-09 11:37:20 +0000412 break;
413 }
dan04668832014-12-16 20:13:30 +0000414#ifndef SQLITE_OMIT_FOREIGN_KEY
415 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
416 hasFkCounter = 1;
417 }
418#endif
dan144926d2009-09-09 11:37:20 +0000419 }
dan144926d2009-09-09 11:37:20 +0000420 sqlite3DbFree(v->db, sIter.apSub);
danf3677212009-09-10 16:14:50 +0000421
mistachkin48864df2013-03-21 21:20:32 +0000422 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
danf3677212009-09-10 16:14:50 +0000423 ** If malloc failed, then the while() loop above may not have iterated
424 ** through all opcodes and hasAbort may be set incorrectly. Return
425 ** true for this case to prevent the assert() in the callers frame
426 ** from failing. */
dan04668832014-12-16 20:13:30 +0000427 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter );
dan144926d2009-09-09 11:37:20 +0000428}
drhff738bc2009-09-24 00:09:58 +0000429#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
dan144926d2009-09-09 11:37:20 +0000430
drh9a324642003-09-06 20:12:01 +0000431/*
drh9cbf3422008-01-17 16:22:13 +0000432** Loop through the program looking for P2 values that are negative
433** on jump instructions. Each such value is a label. Resolve the
434** label by setting the P2 value to its correct non-zero value.
drh76ff3a02004-09-24 22:32:30 +0000435**
436** This routine is called once after all opcodes have been inserted.
danielk1977634f2982005-03-28 08:44:07 +0000437**
drh13449892005-09-07 21:22:45 +0000438** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
danielk1977399918f2006-06-14 13:03:23 +0000439** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
danielk1977634f2982005-03-28 08:44:07 +0000440** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
drha6c2ed92009-11-14 23:22:23 +0000441**
442** The Op.opflags field is set on all opcodes.
drh76ff3a02004-09-24 22:32:30 +0000443*/
drh9cbf3422008-01-17 16:22:13 +0000444static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
drh76ff3a02004-09-24 22:32:30 +0000445 int i;
dan165921a2009-08-28 18:53:45 +0000446 int nMaxArgs = *pMaxFuncArgs;
drh76ff3a02004-09-24 22:32:30 +0000447 Op *pOp;
drh73d5b8f2013-12-23 19:09:07 +0000448 Parse *pParse = p->pParse;
449 int *aLabel = pParse->aLabel;
drhad4a4b82008-11-05 16:37:34 +0000450 p->readOnly = 1;
drh1713afb2013-06-28 01:24:57 +0000451 p->bIsReader = 0;
drh76ff3a02004-09-24 22:32:30 +0000452 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
danielk1977634f2982005-03-28 08:44:07 +0000453 u8 opcode = pOp->opcode;
454
drh8c8a8c42013-08-06 07:45:08 +0000455 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
456 ** cases from this switch! */
457 switch( opcode ){
458 case OP_Function:
459 case OP_AggStep: {
460 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
461 break;
462 }
463 case OP_Transaction: {
464 if( pOp->p2!=0 ) p->readOnly = 0;
465 /* fall thru */
466 }
467 case OP_AutoCommit:
468 case OP_Savepoint: {
469 p->bIsReader = 1;
470 break;
471 }
dand9031542013-07-05 16:54:30 +0000472#ifndef SQLITE_OMIT_WAL
drh8c8a8c42013-08-06 07:45:08 +0000473 case OP_Checkpoint:
drh9e92a472013-06-27 17:40:30 +0000474#endif
drh8c8a8c42013-08-06 07:45:08 +0000475 case OP_Vacuum:
476 case OP_JournalMode: {
477 p->readOnly = 0;
478 p->bIsReader = 1;
479 break;
480 }
danielk1977182c4ba2007-06-27 15:53:34 +0000481#ifndef SQLITE_OMIT_VIRTUALTABLE
drh8c8a8c42013-08-06 07:45:08 +0000482 case OP_VUpdate: {
483 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
484 break;
485 }
486 case OP_VFilter: {
487 int n;
488 assert( p->nOp - i >= 3 );
489 assert( pOp[-1].opcode==OP_Integer );
490 n = pOp[-1].p1;
491 if( n>nMaxArgs ) nMaxArgs = n;
492 break;
493 }
danielk1977182c4ba2007-06-27 15:53:34 +0000494#endif
drh8c8a8c42013-08-06 07:45:08 +0000495 case OP_Next:
drhf93cd942013-11-21 03:12:25 +0000496 case OP_NextIfOpen:
drh8c8a8c42013-08-06 07:45:08 +0000497 case OP_SorterNext: {
498 pOp->p4.xAdvance = sqlite3BtreeNext;
499 pOp->p4type = P4_ADVANCE;
500 break;
501 }
drhf93cd942013-11-21 03:12:25 +0000502 case OP_Prev:
503 case OP_PrevIfOpen: {
drh8c8a8c42013-08-06 07:45:08 +0000504 pOp->p4.xAdvance = sqlite3BtreePrevious;
505 pOp->p4type = P4_ADVANCE;
506 break;
507 }
danielk1977bc04f852005-03-29 08:26:13 +0000508 }
danielk1977634f2982005-03-28 08:44:07 +0000509
drh8c8a8c42013-08-06 07:45:08 +0000510 pOp->opflags = sqlite3OpcodeProperty[opcode];
drha6c2ed92009-11-14 23:22:23 +0000511 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
drh73d5b8f2013-12-23 19:09:07 +0000512 assert( -1-pOp->p2<pParse->nLabel );
drhd2981512008-01-04 19:33:49 +0000513 pOp->p2 = aLabel[-1-pOp->p2];
514 }
drh76ff3a02004-09-24 22:32:30 +0000515 }
drh73d5b8f2013-12-23 19:09:07 +0000516 sqlite3DbFree(p->db, pParse->aLabel);
517 pParse->aLabel = 0;
518 pParse->nLabel = 0;
danielk1977bc04f852005-03-29 08:26:13 +0000519 *pMaxFuncArgs = nMaxArgs;
drha7ab6d82014-07-21 15:44:39 +0000520 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
drh76ff3a02004-09-24 22:32:30 +0000521}
522
523/*
drh9a324642003-09-06 20:12:01 +0000524** Return the address of the next instruction to be inserted.
525*/
danielk19774adee202004-05-08 08:23:19 +0000526int sqlite3VdbeCurrentAddr(Vdbe *p){
drh9a324642003-09-06 20:12:01 +0000527 assert( p->magic==VDBE_MAGIC_INIT );
528 return p->nOp;
529}
530
dan65a7cd12009-09-01 12:16:01 +0000531/*
532** This function returns a pointer to the array of opcodes associated with
533** the Vdbe passed as the first argument. It is the callers responsibility
534** to arrange for the returned array to be eventually freed using the
535** vdbeFreeOpArray() function.
536**
537** Before returning, *pnOp is set to the number of entries in the returned
538** array. Also, *pnMaxArg is set to the larger of its current value and
539** the number of entries in the Vdbe.apArg[] array required to execute the
540** returned program.
541*/
dan165921a2009-08-28 18:53:45 +0000542VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
543 VdbeOp *aOp = p->aOp;
dan523a0872009-08-31 05:23:32 +0000544 assert( aOp && !p->db->mallocFailed );
dan65a7cd12009-09-01 12:16:01 +0000545
546 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
drha7ab6d82014-07-21 15:44:39 +0000547 assert( DbMaskAllZero(p->btreeMask) );
dan65a7cd12009-09-01 12:16:01 +0000548
dan165921a2009-08-28 18:53:45 +0000549 resolveP2Values(p, pnMaxArg);
550 *pnOp = p->nOp;
551 p->aOp = 0;
552 return aOp;
553}
554
drh9a324642003-09-06 20:12:01 +0000555/*
556** Add a whole list of operations to the operation stack. Return the
557** address of the first operation added.
558*/
drh688852a2014-02-17 22:40:43 +0000559int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
drh9a324642003-09-06 20:12:01 +0000560 int addr;
561 assert( p->magic==VDBE_MAGIC_INIT );
dan76ccd892014-08-12 13:38:52 +0000562 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
drh76ff3a02004-09-24 22:32:30 +0000563 return 0;
drh9a324642003-09-06 20:12:01 +0000564 }
565 addr = p->nOp;
drh7b746032009-06-26 12:15:22 +0000566 if( ALWAYS(nOp>0) ){
drh9a324642003-09-06 20:12:01 +0000567 int i;
drh905793e2004-02-21 13:31:09 +0000568 VdbeOpList const *pIn = aOp;
569 for(i=0; i<nOp; i++, pIn++){
570 int p2 = pIn->p2;
571 VdbeOp *pOut = &p->aOp[i+addr];
572 pOut->opcode = pIn->opcode;
573 pOut->p1 = pIn->p1;
drh4308e342013-11-11 16:55:52 +0000574 if( p2<0 ){
575 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
drh8558cde2008-01-05 05:20:10 +0000576 pOut->p2 = addr + ADDR(p2);
577 }else{
578 pOut->p2 = p2;
579 }
drh24003452008-01-03 01:28:59 +0000580 pOut->p3 = pIn->p3;
581 pOut->p4type = P4_NOTUSED;
582 pOut->p4.p = 0;
583 pOut->p5 = 0;
drhc7379ce2013-10-30 02:28:23 +0000584#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000585 pOut->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000586#endif
drh688852a2014-02-17 22:40:43 +0000587#ifdef SQLITE_VDBE_COVERAGE
588 pOut->iSrcLine = iLineno+i;
589#else
590 (void)iLineno;
591#endif
drhc7379ce2013-10-30 02:28:23 +0000592#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000593 if( p->db->flags & SQLITE_VdbeAddopTrace ){
danielk19774adee202004-05-08 08:23:19 +0000594 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
drh9a324642003-09-06 20:12:01 +0000595 }
596#endif
597 }
598 p->nOp += nOp;
599 }
600 return addr;
601}
602
dan6f9702e2014-11-01 20:38:06 +0000603#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
604/*
605** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
606*/
dan037b5322014-11-03 11:25:32 +0000607void sqlite3VdbeScanStatus(
dan6f9702e2014-11-01 20:38:06 +0000608 Vdbe *p, /* VM to add scanstatus() to */
609 int addrExplain, /* Address of OP_Explain (or 0) */
610 int addrLoop, /* Address of loop counter */
611 int addrVisit, /* Address of rows visited counter */
drh518140e2014-11-06 03:55:10 +0000612 LogEst nEst, /* Estimated number of output rows */
dan6f9702e2014-11-01 20:38:06 +0000613 const char *zName /* Name of table or index being scanned */
614){
dan037b5322014-11-03 11:25:32 +0000615 int nByte = (p->nScan+1) * sizeof(ScanStatus);
616 ScanStatus *aNew;
617 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
dan6f9702e2014-11-01 20:38:06 +0000618 if( aNew ){
dan037b5322014-11-03 11:25:32 +0000619 ScanStatus *pNew = &aNew[p->nScan++];
dan6f9702e2014-11-01 20:38:06 +0000620 pNew->addrExplain = addrExplain;
621 pNew->addrLoop = addrLoop;
622 pNew->addrVisit = addrVisit;
623 pNew->nEst = nEst;
624 pNew->zName = sqlite3DbStrDup(p->db, zName);
625 p->aScan = aNew;
626 }
627}
628#endif
629
630
drh9a324642003-09-06 20:12:01 +0000631/*
632** Change the value of the P1 operand for a specific instruction.
633** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000634** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000635** few minor changes to the program.
636*/
drh88caeac2011-08-24 15:12:08 +0000637void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000638 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000639 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000640 p->aOp[addr].p1 = val;
641 }
642}
643
644/*
645** Change the value of the P2 operand for a specific instruction.
646** This routine is useful for setting a jump destination.
647*/
drh88caeac2011-08-24 15:12:08 +0000648void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000649 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000650 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000651 p->aOp[addr].p2 = val;
652 }
653}
654
drhd654be82005-09-20 17:42:23 +0000655/*
danielk19771f4aa332008-01-03 09:51:55 +0000656** Change the value of the P3 operand for a specific instruction.
danielk1977207872a2008-01-03 07:54:23 +0000657*/
drh88caeac2011-08-24 15:12:08 +0000658void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000659 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000660 if( ((u32)p->nOp)>addr ){
danielk1977207872a2008-01-03 07:54:23 +0000661 p->aOp[addr].p3 = val;
662 }
663}
664
665/*
drh35573352008-01-08 23:54:25 +0000666** Change the value of the P5 operand for the most recently
667** added operation.
danielk19771f4aa332008-01-03 09:51:55 +0000668*/
drh35573352008-01-08 23:54:25 +0000669void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
drh7b746032009-06-26 12:15:22 +0000670 assert( p!=0 );
671 if( p->aOp ){
drh35573352008-01-08 23:54:25 +0000672 assert( p->nOp>0 );
673 p->aOp[p->nOp-1].p5 = val;
danielk19771f4aa332008-01-03 09:51:55 +0000674 }
675}
676
677/*
drhf8875402006-03-17 13:56:34 +0000678** Change the P2 operand of instruction addr so that it points to
drhd654be82005-09-20 17:42:23 +0000679** the address of the next instruction to be coded.
680*/
681void sqlite3VdbeJumpHere(Vdbe *p, int addr){
drh61019c72014-01-04 16:49:02 +0000682 sqlite3VdbeChangeP2(p, addr, p->nOp);
683 p->pParse->iFixedOp = p->nOp - 1;
drhd654be82005-09-20 17:42:23 +0000684}
drhb38ad992005-09-16 00:27:01 +0000685
drhb7f6f682006-07-08 17:06:43 +0000686
687/*
688** If the input FuncDef structure is ephemeral, then free it. If
689** the FuncDef is not ephermal, then do nothing.
690*/
drh633e6d52008-07-28 19:34:53 +0000691static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
drhd36e1042013-09-06 13:10:12 +0000692 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
drh633e6d52008-07-28 19:34:53 +0000693 sqlite3DbFree(db, pDef);
drhb7f6f682006-07-08 17:06:43 +0000694 }
695}
696
dand46def72010-07-24 11:28:28 +0000697static void vdbeFreeOpArray(sqlite3 *, Op *, int);
698
drhb38ad992005-09-16 00:27:01 +0000699/*
drh66a51672008-01-03 00:01:23 +0000700** Delete a P4 value if necessary.
drhb38ad992005-09-16 00:27:01 +0000701*/
drh633e6d52008-07-28 19:34:53 +0000702static void freeP4(sqlite3 *db, int p4type, void *p4){
drh0acb7e42008-06-25 00:12:41 +0000703 if( p4 ){
dand46def72010-07-24 11:28:28 +0000704 assert( db );
drh66a51672008-01-03 00:01:23 +0000705 switch( p4type ){
706 case P4_REAL:
707 case P4_INT64:
drh66a51672008-01-03 00:01:23 +0000708 case P4_DYNAMIC:
drh2ec2fb22013-11-06 19:59:23 +0000709 case P4_INTARRAY: {
drh633e6d52008-07-28 19:34:53 +0000710 sqlite3DbFree(db, p4);
drhac1733d2005-09-17 17:58:22 +0000711 break;
712 }
drh2ec2fb22013-11-06 19:59:23 +0000713 case P4_KEYINFO: {
714 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
715 break;
716 }
drhb9755982010-07-24 16:34:37 +0000717 case P4_MPRINTF: {
drh7043db92010-07-26 12:38:12 +0000718 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
drhb9755982010-07-24 16:34:37 +0000719 break;
720 }
drh66a51672008-01-03 00:01:23 +0000721 case P4_FUNCDEF: {
drh633e6d52008-07-28 19:34:53 +0000722 freeEphemeralFunction(db, (FuncDef*)p4);
drhb7f6f682006-07-08 17:06:43 +0000723 break;
724 }
drh66a51672008-01-03 00:01:23 +0000725 case P4_MEM: {
drhc176c272010-07-26 13:57:59 +0000726 if( db->pnBytesFreed==0 ){
727 sqlite3ValueFree((sqlite3_value*)p4);
728 }else{
drhf37c68e2010-07-26 14:20:06 +0000729 Mem *p = (Mem*)p4;
drh17bcb102014-09-18 21:25:33 +0000730 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
drhf37c68e2010-07-26 14:20:06 +0000731 sqlite3DbFree(db, p);
drhc176c272010-07-26 13:57:59 +0000732 }
drhac1733d2005-09-17 17:58:22 +0000733 break;
734 }
danielk1977595a5232009-07-24 17:58:53 +0000735 case P4_VTAB : {
dand46def72010-07-24 11:28:28 +0000736 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
danielk1977595a5232009-07-24 17:58:53 +0000737 break;
738 }
drhb38ad992005-09-16 00:27:01 +0000739 }
740 }
741}
742
dan65a7cd12009-09-01 12:16:01 +0000743/*
744** Free the space allocated for aOp and any p4 values allocated for the
745** opcodes contained within. If aOp is not NULL it is assumed to contain
746** nOp entries.
747*/
dan165921a2009-08-28 18:53:45 +0000748static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
749 if( aOp ){
750 Op *pOp;
751 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
752 freeP4(db, pOp->p4type, pOp->p4.p);
drhc7379ce2013-10-30 02:28:23 +0000753#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
dan165921a2009-08-28 18:53:45 +0000754 sqlite3DbFree(db, pOp->zComment);
755#endif
756 }
757 }
758 sqlite3DbFree(db, aOp);
759}
760
dan65a7cd12009-09-01 12:16:01 +0000761/*
dand19c9332010-07-26 12:05:17 +0000762** Link the SubProgram object passed as the second argument into the linked
763** list at Vdbe.pSubProgram. This list is used to delete all sub-program
764** objects when the VM is no longer required.
dan65a7cd12009-09-01 12:16:01 +0000765*/
dand19c9332010-07-26 12:05:17 +0000766void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
767 p->pNext = pVdbe->pProgram;
768 pVdbe->pProgram = p;
dan165921a2009-08-28 18:53:45 +0000769}
770
drh9a324642003-09-06 20:12:01 +0000771/*
drh48f2d3b2011-09-16 01:34:43 +0000772** Change the opcode at addr into OP_Noop
drhf8875402006-03-17 13:56:34 +0000773*/
drh48f2d3b2011-09-16 01:34:43 +0000774void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
dan76ccd892014-08-12 13:38:52 +0000775 if( addr<p->nOp ){
danielk197792d4d7a2007-05-04 12:05:56 +0000776 VdbeOp *pOp = &p->aOp[addr];
drh633e6d52008-07-28 19:34:53 +0000777 sqlite3 *db = p->db;
drh48f2d3b2011-09-16 01:34:43 +0000778 freeP4(db, pOp->p4type, pOp->p4.p);
779 memset(pOp, 0, sizeof(pOp[0]));
780 pOp->opcode = OP_Noop;
drh313619f2013-10-31 20:34:06 +0000781 if( addr==p->nOp-1 ) p->nOp--;
drhf8875402006-03-17 13:56:34 +0000782 }
783}
784
785/*
drh39c4b822014-09-29 15:42:01 +0000786** If the last opcode is "op" and it is not a jump destination,
787** then remove it. Return true if and only if an opcode was removed.
drh762c1c42014-01-02 19:35:30 +0000788*/
drh61019c72014-01-04 16:49:02 +0000789int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
790 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
791 sqlite3VdbeChangeToNoop(p, p->nOp-1);
792 return 1;
793 }else{
794 return 0;
795 }
drh762c1c42014-01-02 19:35:30 +0000796}
797
798/*
drh66a51672008-01-03 00:01:23 +0000799** Change the value of the P4 operand for a specific instruction.
drh9a324642003-09-06 20:12:01 +0000800** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000801** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000802** few minor changes to the program.
803**
drh66a51672008-01-03 00:01:23 +0000804** If n>=0 then the P4 operand is dynamic, meaning that a copy of
drh17435752007-08-16 04:30:38 +0000805** the string is made into memory obtained from sqlite3_malloc().
drh66a51672008-01-03 00:01:23 +0000806** A value of n==0 means copy bytes of zP4 up to and including the
807** first null byte. If n>0 then copy n+1 bytes of zP4.
danielk19771f55c052005-05-19 08:42:59 +0000808**
drh66a51672008-01-03 00:01:23 +0000809** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
danielk19771f55c052005-05-19 08:42:59 +0000810** to a string or structure that is guaranteed to exist for the lifetime of
811** the Vdbe. In these cases we can just copy the pointer.
drh9a324642003-09-06 20:12:01 +0000812**
drh66a51672008-01-03 00:01:23 +0000813** If addr<0 then change P4 on the most recently inserted instruction.
drh9a324642003-09-06 20:12:01 +0000814*/
drh66a51672008-01-03 00:01:23 +0000815void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
drh9a324642003-09-06 20:12:01 +0000816 Op *pOp;
drh633e6d52008-07-28 19:34:53 +0000817 sqlite3 *db;
drh91fd4d42008-01-19 20:11:25 +0000818 assert( p!=0 );
drh633e6d52008-07-28 19:34:53 +0000819 db = p->db;
drh91fd4d42008-01-19 20:11:25 +0000820 assert( p->magic==VDBE_MAGIC_INIT );
drh633e6d52008-07-28 19:34:53 +0000821 if( p->aOp==0 || db->mallocFailed ){
drh2ec2fb22013-11-06 19:59:23 +0000822 if( n!=P4_VTAB ){
drh633e6d52008-07-28 19:34:53 +0000823 freeP4(db, n, (void*)*(char**)&zP4);
danielk1977261919c2005-12-06 12:52:59 +0000824 }
danielk1977d5d56522005-03-16 12:15:20 +0000825 return;
826 }
drh7b746032009-06-26 12:15:22 +0000827 assert( p->nOp>0 );
drh91fd4d42008-01-19 20:11:25 +0000828 assert( addr<p->nOp );
829 if( addr<0 ){
drh9a324642003-09-06 20:12:01 +0000830 addr = p->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000831 }
832 pOp = &p->aOp[addr];
drh079a3072014-03-19 14:10:55 +0000833 assert( pOp->p4type==P4_NOTUSED
834 || pOp->p4type==P4_INT32
835 || pOp->p4type==P4_KEYINFO );
drh633e6d52008-07-28 19:34:53 +0000836 freeP4(db, pOp->p4type, pOp->p4.p);
drh66a51672008-01-03 00:01:23 +0000837 pOp->p4.p = 0;
drh98757152008-01-09 23:04:12 +0000838 if( n==P4_INT32 ){
mlcreech12d40822008-03-06 07:35:21 +0000839 /* Note: this cast is safe, because the origin data point was an int
840 ** that was cast to a (const char *). */
shane1fc41292008-07-08 22:28:48 +0000841 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
drh8df32842008-12-09 02:51:23 +0000842 pOp->p4type = P4_INT32;
drh98757152008-01-09 23:04:12 +0000843 }else if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +0000844 pOp->p4.p = 0;
845 pOp->p4type = P4_NOTUSED;
846 }else if( n==P4_KEYINFO ){
danielk19772dca4ac2008-01-03 11:50:29 +0000847 pOp->p4.p = (void*)zP4;
drh66a51672008-01-03 00:01:23 +0000848 pOp->p4type = P4_KEYINFO;
danielk1977595a5232009-07-24 17:58:53 +0000849 }else if( n==P4_VTAB ){
850 pOp->p4.p = (void*)zP4;
851 pOp->p4type = P4_VTAB;
852 sqlite3VtabLock((VTable *)zP4);
853 assert( ((VTable *)zP4)->db==p->db );
drh9a324642003-09-06 20:12:01 +0000854 }else if( n<0 ){
danielk19772dca4ac2008-01-03 11:50:29 +0000855 pOp->p4.p = (void*)zP4;
drh8df32842008-12-09 02:51:23 +0000856 pOp->p4type = (signed char)n;
drh9a324642003-09-06 20:12:01 +0000857 }else{
drhea678832008-12-10 19:26:22 +0000858 if( n==0 ) n = sqlite3Strlen30(zP4);
danielk19772dca4ac2008-01-03 11:50:29 +0000859 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
drh66a51672008-01-03 00:01:23 +0000860 pOp->p4type = P4_DYNAMIC;
drh9a324642003-09-06 20:12:01 +0000861 }
862}
863
drh2ec2fb22013-11-06 19:59:23 +0000864/*
865** Set the P4 on the most recently added opcode to the KeyInfo for the
866** index given.
867*/
868void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
869 Vdbe *v = pParse->pVdbe;
870 assert( v!=0 );
871 assert( pIdx!=0 );
872 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
873 P4_KEYINFO);
874}
875
drhc7379ce2013-10-30 02:28:23 +0000876#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drhad6d9462004-09-19 02:15:24 +0000877/*
mistachkind5578432012-08-25 10:01:29 +0000878** Change the comment on the most recently coded instruction. Or
drh16ee60f2008-06-20 18:13:25 +0000879** insert a No-op and add the comment to that new instruction. This
880** makes the code easier to read during debugging. None of this happens
881** in a production build.
drhad6d9462004-09-19 02:15:24 +0000882*/
drhb07028f2011-10-14 21:49:18 +0000883static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
danielk197701256832007-04-18 14:24:32 +0000884 assert( p->nOp>0 || p->aOp==0 );
drhd4e70eb2008-01-02 00:34:36 +0000885 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
danielk1977dba01372008-01-05 18:44:29 +0000886 if( p->nOp ){
drhb07028f2011-10-14 21:49:18 +0000887 assert( p->aOp );
888 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
889 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
890 }
891}
892void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
893 va_list ap;
894 if( p ){
danielk1977dba01372008-01-05 18:44:29 +0000895 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000896 vdbeVComment(p, zFormat, ap);
danielk1977dba01372008-01-05 18:44:29 +0000897 va_end(ap);
898 }
drhad6d9462004-09-19 02:15:24 +0000899}
drh16ee60f2008-06-20 18:13:25 +0000900void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
901 va_list ap;
drhb07028f2011-10-14 21:49:18 +0000902 if( p ){
903 sqlite3VdbeAddOp0(p, OP_Noop);
drh16ee60f2008-06-20 18:13:25 +0000904 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000905 vdbeVComment(p, zFormat, ap);
drh16ee60f2008-06-20 18:13:25 +0000906 va_end(ap);
907 }
908}
909#endif /* NDEBUG */
drhad6d9462004-09-19 02:15:24 +0000910
drh688852a2014-02-17 22:40:43 +0000911#ifdef SQLITE_VDBE_COVERAGE
912/*
913** Set the value if the iSrcLine field for the previously coded instruction.
914*/
915void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
916 sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
917}
918#endif /* SQLITE_VDBE_COVERAGE */
919
drh9a324642003-09-06 20:12:01 +0000920/*
drh20411ea2009-05-29 19:00:12 +0000921** Return the opcode for a given address. If the address is -1, then
922** return the most recently inserted opcode.
923**
924** If a memory allocation error has occurred prior to the calling of this
925** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
drhf83dc1e2010-06-03 12:09:52 +0000926** is readable but not writable, though it is cast to a writable value.
927** The return of a dummy opcode allows the call to continue functioning
peter.d.reid60ec9142014-09-06 16:39:46 +0000928** after an OOM fault without having to check to see if the return from
drhf83dc1e2010-06-03 12:09:52 +0000929** this routine is a valid pointer. But because the dummy.opcode is 0,
930** dummy will never be written to. This is verified by code inspection and
931** by running with Valgrind.
drh9a324642003-09-06 20:12:01 +0000932*/
danielk19774adee202004-05-08 08:23:19 +0000933VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
drha0b75da2010-07-02 18:44:37 +0000934 /* C89 specifies that the constant "dummy" will be initialized to all
935 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
mistachkin0fe5f952011-09-14 18:19:08 +0000936 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
drh9a324642003-09-06 20:12:01 +0000937 assert( p->magic==VDBE_MAGIC_INIT );
drh37b89a02009-06-19 00:33:31 +0000938 if( addr<0 ){
drh37b89a02009-06-19 00:33:31 +0000939 addr = p->nOp - 1;
940 }
drh17435752007-08-16 04:30:38 +0000941 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +0000942 if( p->db->mallocFailed ){
drhf83dc1e2010-06-03 12:09:52 +0000943 return (VdbeOp*)&dummy;
drh20411ea2009-05-29 19:00:12 +0000944 }else{
945 return &p->aOp[addr];
946 }
drh9a324642003-09-06 20:12:01 +0000947}
948
drhc7379ce2013-10-30 02:28:23 +0000949#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
drh81316f82013-10-29 20:40:47 +0000950/*
drhf63552b2013-10-30 00:25:03 +0000951** Return an integer value for one of the parameters to the opcode pOp
952** determined by character c.
953*/
954static int translateP(char c, const Op *pOp){
955 if( c=='1' ) return pOp->p1;
956 if( c=='2' ) return pOp->p2;
957 if( c=='3' ) return pOp->p3;
958 if( c=='4' ) return pOp->p4.i;
959 return pOp->p5;
960}
961
drh81316f82013-10-29 20:40:47 +0000962/*
drh4eded602013-12-20 15:59:20 +0000963** Compute a string for the "comment" field of a VDBE opcode listing.
964**
965** The Synopsis: field in comments in the vdbe.c source file gets converted
966** to an extra string that is appended to the sqlite3OpcodeName(). In the
967** absence of other comments, this synopsis becomes the comment on the opcode.
968** Some translation occurs:
969**
970** "PX" -> "r[X]"
971** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
972** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
973** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
drh81316f82013-10-29 20:40:47 +0000974*/
drhf63552b2013-10-30 00:25:03 +0000975static int displayComment(
976 const Op *pOp, /* The opcode to be commented */
977 const char *zP4, /* Previously obtained value for P4 */
978 char *zTemp, /* Write result here */
979 int nTemp /* Space available in zTemp[] */
980){
drh81316f82013-10-29 20:40:47 +0000981 const char *zOpName;
982 const char *zSynopsis;
983 int nOpName;
984 int ii, jj;
985 zOpName = sqlite3OpcodeName(pOp->opcode);
986 nOpName = sqlite3Strlen30(zOpName);
987 if( zOpName[nOpName+1] ){
988 int seenCom = 0;
drhf63552b2013-10-30 00:25:03 +0000989 char c;
drh81316f82013-10-29 20:40:47 +0000990 zSynopsis = zOpName += nOpName + 1;
drhf63552b2013-10-30 00:25:03 +0000991 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
992 if( c=='P' ){
993 c = zSynopsis[++ii];
994 if( c=='4' ){
995 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
996 }else if( c=='X' ){
997 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
998 seenCom = 1;
drh81316f82013-10-29 20:40:47 +0000999 }else{
drhf63552b2013-10-30 00:25:03 +00001000 int v1 = translateP(c, pOp);
1001 int v2;
1002 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
1003 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1004 ii += 3;
1005 jj += sqlite3Strlen30(zTemp+jj);
1006 v2 = translateP(zSynopsis[ii], pOp);
drh4eded602013-12-20 15:59:20 +00001007 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
1008 ii += 2;
1009 v2++;
1010 }
1011 if( v2>1 ){
1012 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
1013 }
drhf63552b2013-10-30 00:25:03 +00001014 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1015 ii += 4;
1016 }
drh81316f82013-10-29 20:40:47 +00001017 }
1018 jj += sqlite3Strlen30(zTemp+jj);
1019 }else{
drhf63552b2013-10-30 00:25:03 +00001020 zTemp[jj++] = c;
drh81316f82013-10-29 20:40:47 +00001021 }
1022 }
1023 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
1024 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
1025 jj += sqlite3Strlen30(zTemp+jj);
1026 }
1027 if( jj<nTemp ) zTemp[jj] = 0;
1028 }else if( pOp->zComment ){
1029 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
1030 jj = sqlite3Strlen30(zTemp);
1031 }else{
1032 zTemp[0] = 0;
1033 jj = 0;
1034 }
1035 return jj;
1036}
1037#endif /* SQLITE_DEBUG */
1038
1039
drhb7f91642004-10-31 02:22:47 +00001040#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
1041 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001042/*
drh66a51672008-01-03 00:01:23 +00001043** Compute a string that describes the P4 parameter for an opcode.
drhd3d39e92004-05-20 22:16:29 +00001044** Use zTemp for any required temporary buffer space.
1045*/
drh66a51672008-01-03 00:01:23 +00001046static char *displayP4(Op *pOp, char *zTemp, int nTemp){
1047 char *zP4 = zTemp;
drhd3d39e92004-05-20 22:16:29 +00001048 assert( nTemp>=20 );
drh66a51672008-01-03 00:01:23 +00001049 switch( pOp->p4type ){
1050 case P4_KEYINFO: {
drhd3d39e92004-05-20 22:16:29 +00001051 int i, j;
danielk19772dca4ac2008-01-03 11:50:29 +00001052 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
drhe1a022e2012-09-17 17:16:53 +00001053 assert( pKeyInfo->aSortOrder!=0 );
drh5b843aa2013-10-30 13:46:01 +00001054 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
drhea678832008-12-10 19:26:22 +00001055 i = sqlite3Strlen30(zTemp);
drhd3d39e92004-05-20 22:16:29 +00001056 for(j=0; j<pKeyInfo->nField; j++){
1057 CollSeq *pColl = pKeyInfo->aColl[j];
drh261d8a52012-12-08 21:36:26 +00001058 const char *zColl = pColl ? pColl->zName : "nil";
1059 int n = sqlite3Strlen30(zColl);
drh5b843aa2013-10-30 13:46:01 +00001060 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
1061 zColl = "B";
1062 n = 1;
1063 }
drh261d8a52012-12-08 21:36:26 +00001064 if( i+n>nTemp-6 ){
1065 memcpy(&zTemp[i],",...",4);
1066 break;
drhd3d39e92004-05-20 22:16:29 +00001067 }
drh261d8a52012-12-08 21:36:26 +00001068 zTemp[i++] = ',';
1069 if( pKeyInfo->aSortOrder[j] ){
1070 zTemp[i++] = '-';
1071 }
1072 memcpy(&zTemp[i], zColl, n+1);
1073 i += n;
drhd3d39e92004-05-20 22:16:29 +00001074 }
1075 zTemp[i++] = ')';
1076 zTemp[i] = 0;
1077 assert( i<nTemp );
drhd3d39e92004-05-20 22:16:29 +00001078 break;
1079 }
drh66a51672008-01-03 00:01:23 +00001080 case P4_COLLSEQ: {
danielk19772dca4ac2008-01-03 11:50:29 +00001081 CollSeq *pColl = pOp->p4.pColl;
drh5e6790c2013-11-12 20:18:14 +00001082 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
drhd3d39e92004-05-20 22:16:29 +00001083 break;
1084 }
drh66a51672008-01-03 00:01:23 +00001085 case P4_FUNCDEF: {
danielk19772dca4ac2008-01-03 11:50:29 +00001086 FuncDef *pDef = pOp->p4.pFunc;
drha967e882006-06-13 01:04:52 +00001087 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
drhf9b596e2004-05-26 16:54:42 +00001088 break;
1089 }
drh66a51672008-01-03 00:01:23 +00001090 case P4_INT64: {
danielk19772dca4ac2008-01-03 11:50:29 +00001091 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
drhd4e70eb2008-01-02 00:34:36 +00001092 break;
1093 }
drh66a51672008-01-03 00:01:23 +00001094 case P4_INT32: {
1095 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
drh598f1342007-10-23 15:39:45 +00001096 break;
1097 }
drh66a51672008-01-03 00:01:23 +00001098 case P4_REAL: {
danielk19772dca4ac2008-01-03 11:50:29 +00001099 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
drhd4e70eb2008-01-02 00:34:36 +00001100 break;
1101 }
drh66a51672008-01-03 00:01:23 +00001102 case P4_MEM: {
danielk19772dca4ac2008-01-03 11:50:29 +00001103 Mem *pMem = pOp->p4.pMem;
drhd4e70eb2008-01-02 00:34:36 +00001104 if( pMem->flags & MEM_Str ){
drh66a51672008-01-03 00:01:23 +00001105 zP4 = pMem->z;
drhd4e70eb2008-01-02 00:34:36 +00001106 }else if( pMem->flags & MEM_Int ){
1107 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
1108 }else if( pMem->flags & MEM_Real ){
drh74eaba42014-09-18 17:52:15 +00001109 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
drhb8475df2011-12-09 16:21:19 +00001110 }else if( pMem->flags & MEM_Null ){
1111 sqlite3_snprintf(nTemp, zTemp, "NULL");
drh56016892009-08-25 14:24:04 +00001112 }else{
1113 assert( pMem->flags & MEM_Blob );
1114 zP4 = "(blob)";
drhd4e70eb2008-01-02 00:34:36 +00001115 }
drh598f1342007-10-23 15:39:45 +00001116 break;
1117 }
drha967e882006-06-13 01:04:52 +00001118#ifndef SQLITE_OMIT_VIRTUALTABLE
drh66a51672008-01-03 00:01:23 +00001119 case P4_VTAB: {
danielk1977595a5232009-07-24 17:58:53 +00001120 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
drh19146192006-06-26 19:10:32 +00001121 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
drha967e882006-06-13 01:04:52 +00001122 break;
1123 }
1124#endif
drh0acb7e42008-06-25 00:12:41 +00001125 case P4_INTARRAY: {
1126 sqlite3_snprintf(nTemp, zTemp, "intarray");
1127 break;
1128 }
dan165921a2009-08-28 18:53:45 +00001129 case P4_SUBPROGRAM: {
1130 sqlite3_snprintf(nTemp, zTemp, "program");
1131 break;
1132 }
drh4a6f3aa2011-08-28 00:19:26 +00001133 case P4_ADVANCE: {
1134 zTemp[0] = 0;
1135 break;
1136 }
drhd3d39e92004-05-20 22:16:29 +00001137 default: {
danielk19772dca4ac2008-01-03 11:50:29 +00001138 zP4 = pOp->p4.z;
drh949f9cd2008-01-12 21:35:57 +00001139 if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +00001140 zP4 = zTemp;
drhd4e70eb2008-01-02 00:34:36 +00001141 zTemp[0] = 0;
drhd3d39e92004-05-20 22:16:29 +00001142 }
1143 }
1144 }
drh66a51672008-01-03 00:01:23 +00001145 assert( zP4!=0 );
drh66a51672008-01-03 00:01:23 +00001146 return zP4;
drhd3d39e92004-05-20 22:16:29 +00001147}
drhb7f91642004-10-31 02:22:47 +00001148#endif
drhd3d39e92004-05-20 22:16:29 +00001149
drh900b31e2007-08-28 02:27:51 +00001150/*
drhd0679ed2007-08-28 22:24:34 +00001151** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
drh3ebaee92010-05-06 21:37:22 +00001152**
drhbdaec522011-04-04 00:14:43 +00001153** The prepared statements need to know in advance the complete set of
drhe4c88c02012-01-04 12:57:45 +00001154** attached databases that will be use. A mask of these databases
1155** is maintained in p->btreeMask. The p->lockMask value is the subset of
1156** p->btreeMask of databases that will require a lock.
drh900b31e2007-08-28 02:27:51 +00001157*/
drhfb982642007-08-30 01:19:59 +00001158void sqlite3VdbeUsesBtree(Vdbe *p, int i){
drhfcd71b62011-04-05 22:08:24 +00001159 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
danielk197700e13612008-11-17 19:18:54 +00001160 assert( i<(int)sizeof(p->btreeMask)*8 );
drha7ab6d82014-07-21 15:44:39 +00001161 DbMaskSet(p->btreeMask, i);
drhdc5b0472011-04-06 22:05:53 +00001162 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
drha7ab6d82014-07-21 15:44:39 +00001163 DbMaskSet(p->lockMask, i);
drhdc5b0472011-04-06 22:05:53 +00001164 }
drh900b31e2007-08-28 02:27:51 +00001165}
1166
drhe54e0512011-04-05 17:31:56 +00001167#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001168/*
1169** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1170** this routine obtains the mutex associated with each BtShared structure
1171** that may be accessed by the VM passed as an argument. In doing so it also
1172** sets the BtShared.db member of each of the BtShared structures, ensuring
1173** that the correct busy-handler callback is invoked if required.
1174**
1175** If SQLite is not threadsafe but does support shared-cache mode, then
1176** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1177** of all of BtShared structures accessible via the database handle
1178** associated with the VM.
1179**
1180** If SQLite is not threadsafe and does not support shared-cache mode, this
1181** function is a no-op.
1182**
1183** The p->btreeMask field is a bitmask of all btrees that the prepared
1184** statement p will ever use. Let N be the number of bits in p->btreeMask
1185** corresponding to btrees that use shared cache. Then the runtime of
1186** this routine is N*N. But as N is rarely more than 1, this should not
1187** be a problem.
1188*/
1189void sqlite3VdbeEnter(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001190 int i;
drhdc5b0472011-04-06 22:05:53 +00001191 sqlite3 *db;
1192 Db *aDb;
1193 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001194 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001195 db = p->db;
1196 aDb = db->aDb;
1197 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001198 for(i=0; i<nDb; i++){
1199 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001200 sqlite3BtreeEnter(aDb[i].pBt);
1201 }
1202 }
drhbdaec522011-04-04 00:14:43 +00001203}
drhe54e0512011-04-05 17:31:56 +00001204#endif
drhbdaec522011-04-04 00:14:43 +00001205
drhe54e0512011-04-05 17:31:56 +00001206#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001207/*
1208** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1209*/
1210void sqlite3VdbeLeave(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001211 int i;
drhdc5b0472011-04-06 22:05:53 +00001212 sqlite3 *db;
1213 Db *aDb;
1214 int nDb;
drha7ab6d82014-07-21 15:44:39 +00001215 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
drhdc5b0472011-04-06 22:05:53 +00001216 db = p->db;
1217 aDb = db->aDb;
1218 nDb = db->nDb;
drha7ab6d82014-07-21 15:44:39 +00001219 for(i=0; i<nDb; i++){
1220 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001221 sqlite3BtreeLeave(aDb[i].pBt);
1222 }
1223 }
drhbdaec522011-04-04 00:14:43 +00001224}
drhbdaec522011-04-04 00:14:43 +00001225#endif
drhd3d39e92004-05-20 22:16:29 +00001226
danielk19778b60e0f2005-01-12 09:10:39 +00001227#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001228/*
1229** Print a single opcode. This routine is used for debugging only.
1230*/
danielk19774adee202004-05-08 08:23:19 +00001231void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
drh66a51672008-01-03 00:01:23 +00001232 char *zP4;
drhd3d39e92004-05-20 22:16:29 +00001233 char zPtr[50];
drh81316f82013-10-29 20:40:47 +00001234 char zCom[100];
drh26198bb2013-10-31 11:15:09 +00001235 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
drh9a324642003-09-06 20:12:01 +00001236 if( pOut==0 ) pOut = stdout;
drh66a51672008-01-03 00:01:23 +00001237 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
drhc7379ce2013-10-30 02:28:23 +00001238#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001239 displayComment(pOp, zP4, zCom, sizeof(zCom));
1240#else
drh2926f962014-02-17 01:13:28 +00001241 zCom[0] = 0;
drh81316f82013-10-29 20:40:47 +00001242#endif
drh4eded602013-12-20 15:59:20 +00001243 /* NB: The sqlite3OpcodeName() function is implemented by code created
1244 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
1245 ** information from the vdbe.c source text */
danielk197711641c12008-01-03 08:18:30 +00001246 fprintf(pOut, zFormat1, pc,
drh1db639c2008-01-17 02:36:28 +00001247 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
drh81316f82013-10-29 20:40:47 +00001248 zCom
drh1db639c2008-01-17 02:36:28 +00001249 );
drh9a324642003-09-06 20:12:01 +00001250 fflush(pOut);
1251}
1252#endif
1253
1254/*
drh76ff3a02004-09-24 22:32:30 +00001255** Release an array of N Mem elements
1256*/
drhc890fec2008-08-01 20:10:08 +00001257static void releaseMemArray(Mem *p, int N){
danielk1977a7a8e142008-02-13 18:25:27 +00001258 if( p && N ){
drh069c23c2014-09-19 16:13:12 +00001259 Mem *pEnd = &p[N];
danielk1977a7a8e142008-02-13 18:25:27 +00001260 sqlite3 *db = p->db;
drh8df32842008-12-09 02:51:23 +00001261 u8 malloc_failed = db->mallocFailed;
dand46def72010-07-24 11:28:28 +00001262 if( db->pnBytesFreed ){
drh069c23c2014-09-19 16:13:12 +00001263 do{
drh17bcb102014-09-18 21:25:33 +00001264 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
drh069c23c2014-09-19 16:13:12 +00001265 }while( (++p)<pEnd );
drhc176c272010-07-26 13:57:59 +00001266 return;
1267 }
drh069c23c2014-09-19 16:13:12 +00001268 do{
danielk1977e972e032008-09-19 18:32:26 +00001269 assert( (&p[1])==pEnd || p[0].db==p[1].db );
drh75fd0542014-03-01 16:24:44 +00001270 assert( sqlite3VdbeCheckMemInvariants(p) );
danielk1977e972e032008-09-19 18:32:26 +00001271
1272 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1273 ** that takes advantage of the fact that the memory cell value is
1274 ** being set to NULL after releasing any dynamic resources.
1275 **
1276 ** The justification for duplicating code is that according to
1277 ** callgrind, this causes a certain test case to hit the CPU 4.7
1278 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1279 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1280 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1281 ** with no indexes using a single prepared INSERT statement, bind()
1282 ** and reset(). Inserts are grouped into a transaction.
1283 */
drhb6e8fd12014-03-06 01:56:33 +00001284 testcase( p->flags & MEM_Agg );
1285 testcase( p->flags & MEM_Dyn );
1286 testcase( p->flags & MEM_Frame );
1287 testcase( p->flags & MEM_RowSet );
dan165921a2009-08-28 18:53:45 +00001288 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
danielk1977e972e032008-09-19 18:32:26 +00001289 sqlite3VdbeMemRelease(p);
drh17bcb102014-09-18 21:25:33 +00001290 }else if( p->szMalloc ){
danielk1977e972e032008-09-19 18:32:26 +00001291 sqlite3DbFree(db, p->zMalloc);
drh17bcb102014-09-18 21:25:33 +00001292 p->szMalloc = 0;
danielk1977e972e032008-09-19 18:32:26 +00001293 }
1294
drha5750cf2014-02-07 13:20:31 +00001295 p->flags = MEM_Undefined;
drh069c23c2014-09-19 16:13:12 +00001296 }while( (++p)<pEnd );
danielk1977a7a8e142008-02-13 18:25:27 +00001297 db->mallocFailed = malloc_failed;
drh76ff3a02004-09-24 22:32:30 +00001298 }
1299}
1300
dan65a7cd12009-09-01 12:16:01 +00001301/*
1302** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1303** allocated by the OP_Program opcode in sqlite3VdbeExec().
1304*/
dan165921a2009-08-28 18:53:45 +00001305void sqlite3VdbeFrameDelete(VdbeFrame *p){
1306 int i;
1307 Mem *aMem = VdbeFrameMem(p);
1308 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1309 for(i=0; i<p->nChildCsr; i++){
1310 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1311 }
1312 releaseMemArray(aMem, p->nChildMem);
1313 sqlite3DbFree(p->v->db, p);
1314}
1315
drhb7f91642004-10-31 02:22:47 +00001316#ifndef SQLITE_OMIT_EXPLAIN
drh76ff3a02004-09-24 22:32:30 +00001317/*
drh9a324642003-09-06 20:12:01 +00001318** Give a listing of the program in the virtual machine.
1319**
danielk19774adee202004-05-08 08:23:19 +00001320** The interface is the same as sqlite3VdbeExec(). But instead of
drh9a324642003-09-06 20:12:01 +00001321** running the code, it invokes the callback once for each instruction.
1322** This feature is used to implement "EXPLAIN".
drh9cbf3422008-01-17 16:22:13 +00001323**
1324** When p->explain==1, each instruction is listed. When
1325** p->explain==2, only OP_Explain instructions are listed and these
1326** are shown in a different format. p->explain==2 is used to implement
1327** EXPLAIN QUERY PLAN.
drh5cfa5842009-12-31 20:35:08 +00001328**
1329** When p->explain==1, first the main program is listed, then each of
1330** the trigger subprograms are listed one by one.
drh9a324642003-09-06 20:12:01 +00001331*/
danielk19774adee202004-05-08 08:23:19 +00001332int sqlite3VdbeList(
drh9a324642003-09-06 20:12:01 +00001333 Vdbe *p /* The VDBE */
1334){
drh5cfa5842009-12-31 20:35:08 +00001335 int nRow; /* Stop when row count reaches this */
dan165921a2009-08-28 18:53:45 +00001336 int nSub = 0; /* Number of sub-vdbes seen so far */
1337 SubProgram **apSub = 0; /* Array of sub-vdbes */
drh5cfa5842009-12-31 20:35:08 +00001338 Mem *pSub = 0; /* Memory cell hold array of subprogs */
1339 sqlite3 *db = p->db; /* The database connection */
1340 int i; /* Loop counter */
1341 int rc = SQLITE_OK; /* Return code */
drh9734e6e2011-10-07 18:24:25 +00001342 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
drh9a324642003-09-06 20:12:01 +00001343
drh9a324642003-09-06 20:12:01 +00001344 assert( p->explain );
drh5f82e3c2009-07-06 00:44:08 +00001345 assert( p->magic==VDBE_MAGIC_RUN );
danielk19776c359f02008-11-21 16:58:03 +00001346 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
danielk197718f41892004-05-22 07:27:46 +00001347
drh9cbf3422008-01-17 16:22:13 +00001348 /* Even though this opcode does not use dynamic strings for
1349 ** the result, result columns may become dynamic if the user calls
drh4f26d6c2004-05-26 23:25:30 +00001350 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
danielk197718f41892004-05-22 07:27:46 +00001351 */
dan165921a2009-08-28 18:53:45 +00001352 releaseMemArray(pMem, 8);
drh9734e6e2011-10-07 18:24:25 +00001353 p->pResultSet = 0;
danielk197718f41892004-05-22 07:27:46 +00001354
danielk19776c359f02008-11-21 16:58:03 +00001355 if( p->rc==SQLITE_NOMEM ){
1356 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1357 ** sqlite3_column_text16() failed. */
1358 db->mallocFailed = 1;
1359 return SQLITE_ERROR;
1360 }
1361
drh5cfa5842009-12-31 20:35:08 +00001362 /* When the number of output rows reaches nRow, that means the
1363 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1364 ** nRow is the sum of the number of rows in the main program, plus
1365 ** the sum of the number of rows in all trigger subprograms encountered
1366 ** so far. The nRow value will increase as new trigger subprograms are
1367 ** encountered, but p->pc will eventually catch up to nRow.
1368 */
dan165921a2009-08-28 18:53:45 +00001369 nRow = p->nOp;
1370 if( p->explain==1 ){
drh5cfa5842009-12-31 20:35:08 +00001371 /* The first 8 memory cells are used for the result set. So we will
1372 ** commandeer the 9th cell to use as storage for an array of pointers
1373 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1374 ** cells. */
1375 assert( p->nMem>9 );
dan165921a2009-08-28 18:53:45 +00001376 pSub = &p->aMem[9];
1377 if( pSub->flags&MEM_Blob ){
drh5cfa5842009-12-31 20:35:08 +00001378 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1379 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
dan165921a2009-08-28 18:53:45 +00001380 nSub = pSub->n/sizeof(Vdbe*);
1381 apSub = (SubProgram **)pSub->z;
1382 }
1383 for(i=0; i<nSub; i++){
1384 nRow += apSub[i]->nOp;
1385 }
1386 }
1387
drhecc92422005-09-10 16:46:12 +00001388 do{
1389 i = p->pc++;
dan165921a2009-08-28 18:53:45 +00001390 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1391 if( i>=nRow ){
drh826fb5a2004-02-14 23:59:57 +00001392 p->rc = SQLITE_OK;
1393 rc = SQLITE_DONE;
drh881feaa2006-07-26 01:39:30 +00001394 }else if( db->u1.isInterrupted ){
drhc5cdca62005-01-11 16:54:14 +00001395 p->rc = SQLITE_INTERRUPT;
drh826fb5a2004-02-14 23:59:57 +00001396 rc = SQLITE_ERROR;
drhf089aa42008-07-08 19:34:06 +00001397 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
drh826fb5a2004-02-14 23:59:57 +00001398 }else{
drh81316f82013-10-29 20:40:47 +00001399 char *zP4;
dan165921a2009-08-28 18:53:45 +00001400 Op *pOp;
1401 if( i<p->nOp ){
drh5cfa5842009-12-31 20:35:08 +00001402 /* The output line number is small enough that we are still in the
1403 ** main program. */
dan165921a2009-08-28 18:53:45 +00001404 pOp = &p->aOp[i];
1405 }else{
drh5cfa5842009-12-31 20:35:08 +00001406 /* We are currently listing subprograms. Figure out which one and
1407 ** pick up the appropriate opcode. */
dan165921a2009-08-28 18:53:45 +00001408 int j;
1409 i -= p->nOp;
1410 for(j=0; i>=apSub[j]->nOp; j++){
1411 i -= apSub[j]->nOp;
1412 }
1413 pOp = &apSub[j]->aOp[i];
1414 }
danielk19770d78bae2008-01-03 07:09:48 +00001415 if( p->explain==1 ){
1416 pMem->flags = MEM_Int;
danielk19770d78bae2008-01-03 07:09:48 +00001417 pMem->u.i = i; /* Program counter */
1418 pMem++;
1419
1420 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001421 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
danielk19770d78bae2008-01-03 07:09:48 +00001422 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001423 pMem->n = sqlite3Strlen30(pMem->z);
danielk19770d78bae2008-01-03 07:09:48 +00001424 pMem->enc = SQLITE_UTF8;
1425 pMem++;
dan165921a2009-08-28 18:53:45 +00001426
drh5cfa5842009-12-31 20:35:08 +00001427 /* When an OP_Program opcode is encounter (the only opcode that has
1428 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1429 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1430 ** has not already been seen.
1431 */
dan165921a2009-08-28 18:53:45 +00001432 if( pOp->p4type==P4_SUBPROGRAM ){
1433 int nByte = (nSub+1)*sizeof(SubProgram*);
1434 int j;
1435 for(j=0; j<nSub; j++){
1436 if( apSub[j]==pOp->p4.pProgram ) break;
1437 }
dan2b9ee772012-03-31 09:59:44 +00001438 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
dan165921a2009-08-28 18:53:45 +00001439 apSub = (SubProgram **)pSub->z;
1440 apSub[nSub++] = pOp->p4.pProgram;
1441 pSub->flags |= MEM_Blob;
1442 pSub->n = nSub*sizeof(SubProgram*);
1443 }
1444 }
danielk19770d78bae2008-01-03 07:09:48 +00001445 }
drheb2e1762004-05-27 01:53:56 +00001446
1447 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001448 pMem->u.i = pOp->p1; /* P1 */
drheb2e1762004-05-27 01:53:56 +00001449 pMem++;
1450
1451 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001452 pMem->u.i = pOp->p2; /* P2 */
drheb2e1762004-05-27 01:53:56 +00001453 pMem++;
1454
dan2ce22452010-11-08 19:01:16 +00001455 pMem->flags = MEM_Int;
1456 pMem->u.i = pOp->p3; /* P3 */
dan2ce22452010-11-08 19:01:16 +00001457 pMem++;
danielk19770d78bae2008-01-03 07:09:48 +00001458
drh322f2852014-09-19 00:43:39 +00001459 if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
danielk1977357864e2009-03-25 15:43:08 +00001460 assert( p->db->mallocFailed );
1461 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001462 }
drhc91b2fd2014-03-01 18:13:23 +00001463 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001464 zP4 = displayP4(pOp, pMem->z, 32);
1465 if( zP4!=pMem->z ){
1466 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
danielk1977a7a8e142008-02-13 18:25:27 +00001467 }else{
1468 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001469 pMem->n = sqlite3Strlen30(pMem->z);
danielk1977a7a8e142008-02-13 18:25:27 +00001470 pMem->enc = SQLITE_UTF8;
1471 }
danielk19770d78bae2008-01-03 07:09:48 +00001472 pMem++;
drheb2e1762004-05-27 01:53:56 +00001473
danielk19770d78bae2008-01-03 07:09:48 +00001474 if( p->explain==1 ){
drh322f2852014-09-19 00:43:39 +00001475 if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
danielk1977357864e2009-03-25 15:43:08 +00001476 assert( p->db->mallocFailed );
1477 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001478 }
drhc91b2fd2014-03-01 18:13:23 +00001479 pMem->flags = MEM_Str|MEM_Term;
drh85e5f0d2008-02-19 18:28:13 +00001480 pMem->n = 2;
1481 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
danielk19770d78bae2008-01-03 07:09:48 +00001482 pMem->enc = SQLITE_UTF8;
1483 pMem++;
1484
drhc7379ce2013-10-30 02:28:23 +00001485#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh322f2852014-09-19 00:43:39 +00001486 if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
drh81316f82013-10-29 20:40:47 +00001487 assert( p->db->mallocFailed );
1488 return SQLITE_ERROR;
drh52391cb2008-02-14 23:44:13 +00001489 }
drhc91b2fd2014-03-01 18:13:23 +00001490 pMem->flags = MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001491 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
drh81316f82013-10-29 20:40:47 +00001492 pMem->enc = SQLITE_UTF8;
1493#else
1494 pMem->flags = MEM_Null; /* Comment */
drh81316f82013-10-29 20:40:47 +00001495#endif
danielk19770d78bae2008-01-03 07:09:48 +00001496 }
1497
dan2ce22452010-11-08 19:01:16 +00001498 p->nResColumn = 8 - 4*(p->explain-1);
drh9734e6e2011-10-07 18:24:25 +00001499 p->pResultSet = &p->aMem[1];
drh826fb5a2004-02-14 23:59:57 +00001500 p->rc = SQLITE_OK;
1501 rc = SQLITE_ROW;
drh9a324642003-09-06 20:12:01 +00001502 }
drh826fb5a2004-02-14 23:59:57 +00001503 return rc;
drh9a324642003-09-06 20:12:01 +00001504}
drhb7f91642004-10-31 02:22:47 +00001505#endif /* SQLITE_OMIT_EXPLAIN */
drh9a324642003-09-06 20:12:01 +00001506
drh7c4ac0c2007-04-05 11:25:58 +00001507#ifdef SQLITE_DEBUG
drh9a324642003-09-06 20:12:01 +00001508/*
drh3f7d4e42004-07-24 14:35:58 +00001509** Print the SQL that was used to generate a VDBE program.
1510*/
1511void sqlite3VdbePrintSql(Vdbe *p){
drh84e55a82013-11-13 17:58:23 +00001512 const char *z = 0;
1513 if( p->zSql ){
1514 z = p->zSql;
1515 }else if( p->nOp>=1 ){
1516 const VdbeOp *pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001517 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh84e55a82013-11-13 17:58:23 +00001518 z = pOp->p4.z;
1519 while( sqlite3Isspace(*z) ) z++;
1520 }
drh3f7d4e42004-07-24 14:35:58 +00001521 }
drh84e55a82013-11-13 17:58:23 +00001522 if( z ) printf("SQL: [%s]\n", z);
drh3f7d4e42004-07-24 14:35:58 +00001523}
drh7c4ac0c2007-04-05 11:25:58 +00001524#endif
drh3f7d4e42004-07-24 14:35:58 +00001525
drh602c2372007-03-01 00:29:13 +00001526#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1527/*
1528** Print an IOTRACE message showing SQL content.
1529*/
1530void sqlite3VdbeIOTraceSql(Vdbe *p){
1531 int nOp = p->nOp;
1532 VdbeOp *pOp;
mlcreech3a00f902008-03-04 17:45:01 +00001533 if( sqlite3IoTrace==0 ) return;
drh602c2372007-03-01 00:29:13 +00001534 if( nOp<1 ) return;
drh949f9cd2008-01-12 21:35:57 +00001535 pOp = &p->aOp[0];
drhaceb31b2014-02-08 01:40:27 +00001536 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
drh602c2372007-03-01 00:29:13 +00001537 int i, j;
drh00a18e42007-08-13 11:10:34 +00001538 char z[1000];
drh949f9cd2008-01-12 21:35:57 +00001539 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
danielk197778ca0e72009-01-20 16:53:39 +00001540 for(i=0; sqlite3Isspace(z[i]); i++){}
drh602c2372007-03-01 00:29:13 +00001541 for(j=0; z[i]; i++){
danielk197778ca0e72009-01-20 16:53:39 +00001542 if( sqlite3Isspace(z[i]) ){
drh602c2372007-03-01 00:29:13 +00001543 if( z[i-1]!=' ' ){
1544 z[j++] = ' ';
1545 }
1546 }else{
1547 z[j++] = z[i];
1548 }
1549 }
1550 z[j] = 0;
mlcreech3a00f902008-03-04 17:45:01 +00001551 sqlite3IoTrace("SQL %s\n", z);
drh602c2372007-03-01 00:29:13 +00001552 }
1553}
1554#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1555
drhb2771ce2009-02-20 01:28:59 +00001556/*
drh4800b2e2009-12-08 15:35:22 +00001557** Allocate space from a fixed size buffer and return a pointer to
1558** that space. If insufficient space is available, return NULL.
1559**
1560** The pBuf parameter is the initial value of a pointer which will
1561** receive the new memory. pBuf is normally NULL. If pBuf is not
1562** NULL, it means that memory space has already been allocated and that
1563** this routine should not allocate any new memory. When pBuf is not
1564** NULL simply return pBuf. Only allocate new memory space when pBuf
1565** is NULL.
drhb2771ce2009-02-20 01:28:59 +00001566**
1567** nByte is the number of bytes of space needed.
1568**
drh19875c82009-12-08 19:58:19 +00001569** *ppFrom points to available space and pEnd points to the end of the
1570** available space. When space is allocated, *ppFrom is advanced past
1571** the end of the allocated space.
drhb2771ce2009-02-20 01:28:59 +00001572**
1573** *pnByte is a counter of the number of bytes of space that have failed
1574** to allocate. If there is insufficient space in *ppFrom to satisfy the
danielk1977d336e222009-02-20 10:58:41 +00001575** request, then increment *pnByte by the amount of the request.
drhb2771ce2009-02-20 01:28:59 +00001576*/
drh4800b2e2009-12-08 15:35:22 +00001577static void *allocSpace(
1578 void *pBuf, /* Where return pointer will be stored */
drhb2771ce2009-02-20 01:28:59 +00001579 int nByte, /* Number of bytes to allocate */
1580 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
danielk1977d336e222009-02-20 10:58:41 +00001581 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
drhb2771ce2009-02-20 01:28:59 +00001582 int *pnByte /* If allocation cannot be made, increment *pnByte */
1583){
drhea598cb2009-04-05 12:22:08 +00001584 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
drh4800b2e2009-12-08 15:35:22 +00001585 if( pBuf ) return pBuf;
1586 nByte = ROUND8(nByte);
1587 if( &(*ppFrom)[nByte] <= pEnd ){
1588 pBuf = (void*)*ppFrom;
1589 *ppFrom += nByte;
1590 }else{
1591 *pnByte += nByte;
drhb2771ce2009-02-20 01:28:59 +00001592 }
drh4800b2e2009-12-08 15:35:22 +00001593 return pBuf;
drhb2771ce2009-02-20 01:28:59 +00001594}
drh602c2372007-03-01 00:29:13 +00001595
drh3f7d4e42004-07-24 14:35:58 +00001596/*
drh124c0b42011-06-01 18:15:55 +00001597** Rewind the VDBE back to the beginning in preparation for
1598** running it.
drh9a324642003-09-06 20:12:01 +00001599*/
drh124c0b42011-06-01 18:15:55 +00001600void sqlite3VdbeRewind(Vdbe *p){
1601#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1602 int i;
1603#endif
drh9a324642003-09-06 20:12:01 +00001604 assert( p!=0 );
drh9a324642003-09-06 20:12:01 +00001605 assert( p->magic==VDBE_MAGIC_INIT );
1606
drhc16a03b2004-09-15 13:38:10 +00001607 /* There should be at least one opcode.
drh9a324642003-09-06 20:12:01 +00001608 */
drhc16a03b2004-09-15 13:38:10 +00001609 assert( p->nOp>0 );
drh9a324642003-09-06 20:12:01 +00001610
danielk197700e13612008-11-17 19:18:54 +00001611 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
danielk1977634f2982005-03-28 08:44:07 +00001612 p->magic = VDBE_MAGIC_RUN;
1613
drh124c0b42011-06-01 18:15:55 +00001614#ifdef SQLITE_DEBUG
1615 for(i=1; i<p->nMem; i++){
1616 assert( p->aMem[i].db==p->db );
1617 }
1618#endif
1619 p->pc = -1;
1620 p->rc = SQLITE_OK;
1621 p->errorAction = OE_Abort;
1622 p->magic = VDBE_MAGIC_RUN;
1623 p->nChange = 0;
1624 p->cacheCtr = 1;
1625 p->minWriteFileFormat = 255;
1626 p->iStatement = 0;
1627 p->nFkConstraint = 0;
1628#ifdef VDBE_PROFILE
1629 for(i=0; i<p->nOp; i++){
1630 p->aOp[i].cnt = 0;
1631 p->aOp[i].cycles = 0;
1632 }
1633#endif
1634}
1635
1636/*
1637** Prepare a virtual machine for execution for the first time after
1638** creating the virtual machine. This involves things such
drh7abda852014-09-19 16:02:06 +00001639** as allocating registers and initializing the program counter.
drh124c0b42011-06-01 18:15:55 +00001640** After the VDBE has be prepped, it can be executed by one or more
1641** calls to sqlite3VdbeExec().
1642**
peter.d.reid60ec9142014-09-06 16:39:46 +00001643** This function may be called exactly once on each virtual machine.
drh124c0b42011-06-01 18:15:55 +00001644** After this routine is called the VM has been "packaged" and is ready
peter.d.reid60ec9142014-09-06 16:39:46 +00001645** to run. After this routine is called, further calls to
drh124c0b42011-06-01 18:15:55 +00001646** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1647** the Vdbe from the Parse object that helped generate it so that the
1648** the Vdbe becomes an independent entity and the Parse object can be
1649** destroyed.
1650**
1651** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1652** to its initial state after it has been run.
1653*/
1654void sqlite3VdbeMakeReady(
1655 Vdbe *p, /* The VDBE */
1656 Parse *pParse /* Parsing context */
1657){
1658 sqlite3 *db; /* The database connection */
1659 int nVar; /* Number of parameters */
1660 int nMem; /* Number of VM memory registers */
1661 int nCursor; /* Number of cursors required */
1662 int nArg; /* Number of arguments in subprograms */
dan1d8cb212011-12-09 13:24:16 +00001663 int nOnce; /* Number of OP_Once instructions */
drh124c0b42011-06-01 18:15:55 +00001664 int n; /* Loop counter */
1665 u8 *zCsr; /* Memory available for allocation */
1666 u8 *zEnd; /* First byte past allocated memory */
1667 int nByte; /* How much extra memory is needed */
1668
1669 assert( p!=0 );
1670 assert( p->nOp>0 );
1671 assert( pParse!=0 );
1672 assert( p->magic==VDBE_MAGIC_INIT );
drh73d5b8f2013-12-23 19:09:07 +00001673 assert( pParse==p->pParse );
drh124c0b42011-06-01 18:15:55 +00001674 db = p->db;
1675 assert( db->mallocFailed==0 );
1676 nVar = pParse->nVar;
1677 nMem = pParse->nMem;
1678 nCursor = pParse->nTab;
1679 nArg = pParse->nMaxArg;
dan1d8cb212011-12-09 13:24:16 +00001680 nOnce = pParse->nOnce;
drh20e226d2012-01-01 13:58:53 +00001681 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
drh124c0b42011-06-01 18:15:55 +00001682
danielk1977cd3e8f72008-03-25 09:47:35 +00001683 /* For each cursor required, also allocate a memory cell. Memory
1684 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1685 ** the vdbe program. Instead they are used to allocate space for
drhdfe88ec2008-11-03 20:55:06 +00001686 ** VdbeCursor/BtCursor structures. The blob of memory associated with
danielk1977cd3e8f72008-03-25 09:47:35 +00001687 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1688 ** stores the blob of memory associated with cursor 1, etc.
1689 **
1690 ** See also: allocateCursor().
1691 */
1692 nMem += nCursor;
1693
danielk19776ab3a2e2009-02-19 14:39:25 +00001694 /* Allocate space for memory registers, SQL variables, VDBE cursors and
drh124c0b42011-06-01 18:15:55 +00001695 ** an array to marshal SQL function arguments in.
drh9a324642003-09-06 20:12:01 +00001696 */
drh73d5b8f2013-12-23 19:09:07 +00001697 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
1698 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
drh19875c82009-12-08 19:58:19 +00001699
drh124c0b42011-06-01 18:15:55 +00001700 resolveP2Values(p, &nArg);
1701 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1702 if( pParse->explain && nMem<10 ){
1703 nMem = 10;
1704 }
1705 memset(zCsr, 0, zEnd-zCsr);
1706 zCsr += (zCsr - (u8*)0)&7;
1707 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
drhaab910c2011-06-27 00:01:22 +00001708 p->expired = 0;
drh124c0b42011-06-01 18:15:55 +00001709
1710 /* Memory for registers, parameters, cursor, etc, is allocated in two
1711 ** passes. On the first pass, we try to reuse unused space at the
1712 ** end of the opcode array. If we are unable to satisfy all memory
1713 ** requirements by reusing the opcode array tail, then the second
1714 ** pass will fill in the rest using a fresh allocation.
1715 **
1716 ** This two-pass approach that reuses as much memory as possible from
1717 ** the leftover space at the end of the opcode array can significantly
1718 ** reduce the amount of memory held by a prepared statement.
1719 */
1720 do {
1721 nByte = 0;
1722 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
1723 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
1724 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
1725 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
1726 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
1727 &zCsr, zEnd, &nByte);
drhb8475df2011-12-09 16:21:19 +00001728 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
dane2f771b2014-11-03 15:33:17 +00001729#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan43764a82014-11-01 21:00:04 +00001730 p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
dane2f771b2014-11-03 15:33:17 +00001731#endif
drh124c0b42011-06-01 18:15:55 +00001732 if( nByte ){
1733 p->pFree = sqlite3DbMallocZero(db, nByte);
drh0f7eb612006-08-08 13:51:43 +00001734 }
drh124c0b42011-06-01 18:15:55 +00001735 zCsr = p->pFree;
1736 zEnd = &zCsr[nByte];
1737 }while( nByte && !db->mallocFailed );
drhb2771ce2009-02-20 01:28:59 +00001738
drhd2a56232013-01-28 19:00:20 +00001739 p->nCursor = nCursor;
dan1d8cb212011-12-09 13:24:16 +00001740 p->nOnceFlag = nOnce;
drh124c0b42011-06-01 18:15:55 +00001741 if( p->aVar ){
1742 p->nVar = (ynVar)nVar;
1743 for(n=0; n<nVar; n++){
1744 p->aVar[n].flags = MEM_Null;
1745 p->aVar[n].db = db;
danielk197754db47e2004-05-19 10:36:43 +00001746 }
drh82a48512003-09-06 22:45:20 +00001747 }
drh9b5444a2014-12-02 13:46:53 +00001748 if( p->azVar && pParse->nzVar>0 ){
drh124c0b42011-06-01 18:15:55 +00001749 p->nzVar = pParse->nzVar;
1750 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
1751 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
danielk1977b3bce662005-01-29 08:32:43 +00001752 }
drh124c0b42011-06-01 18:15:55 +00001753 if( p->aMem ){
1754 p->aMem--; /* aMem[] goes from 1..nMem */
1755 p->nMem = nMem; /* not from 0..nMem-1 */
1756 for(n=1; n<=nMem; n++){
drha5750cf2014-02-07 13:20:31 +00001757 p->aMem[n].flags = MEM_Undefined;
drh124c0b42011-06-01 18:15:55 +00001758 p->aMem[n].db = db;
drhcf64d8b2003-12-31 17:57:10 +00001759 }
drh9a324642003-09-06 20:12:01 +00001760 }
drh124c0b42011-06-01 18:15:55 +00001761 p->explain = pParse->explain;
1762 sqlite3VdbeRewind(p);
drh9a324642003-09-06 20:12:01 +00001763}
1764
drh9a324642003-09-06 20:12:01 +00001765/*
danielk1977cd3e8f72008-03-25 09:47:35 +00001766** Close a VDBE cursor and release all the resources that cursor
1767** happens to hold.
drh9a324642003-09-06 20:12:01 +00001768*/
drhdfe88ec2008-11-03 20:55:06 +00001769void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
drh4774b132004-06-12 20:12:51 +00001770 if( pCx==0 ){
1771 return;
1772 }
dana20fde62011-07-12 14:28:05 +00001773 sqlite3VdbeSorterClose(p->db, pCx);
drh9a324642003-09-06 20:12:01 +00001774 if( pCx->pBt ){
danielk19774adee202004-05-08 08:23:19 +00001775 sqlite3BtreeClose(pCx->pBt);
drh34004ce2008-07-11 16:15:17 +00001776 /* The pCx->pCursor will be close automatically, if it exists, by
1777 ** the call above. */
1778 }else if( pCx->pCursor ){
1779 sqlite3BtreeCloseCursor(pCx->pCursor);
drh9a324642003-09-06 20:12:01 +00001780 }
drh9eff6162006-06-12 21:59:13 +00001781#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf526dca2014-10-13 17:42:05 +00001782 else if( pCx->pVtabCursor ){
drh9eff6162006-06-12 21:59:13 +00001783 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
drh5cc10232013-11-21 01:04:02 +00001784 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
drha68d6282015-03-24 13:32:53 +00001785 assert( pVtabCursor->pVtab->nRef>0 );
1786 pVtabCursor->pVtab->nRef--;
drh9eff6162006-06-12 21:59:13 +00001787 pModule->xClose(pVtabCursor);
1788 }
1789#endif
drh9a324642003-09-06 20:12:01 +00001790}
1791
dan65a7cd12009-09-01 12:16:01 +00001792/*
1793** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1794** is used, for example, when a trigger sub-program is halted to restore
1795** control to the main program.
1796*/
dan165921a2009-08-28 18:53:45 +00001797int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
1798 Vdbe *v = pFrame->v;
dane2f771b2014-11-03 15:33:17 +00001799#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan43764a82014-11-01 21:00:04 +00001800 v->anExec = pFrame->anExec;
dane2f771b2014-11-03 15:33:17 +00001801#endif
dan1d8cb212011-12-09 13:24:16 +00001802 v->aOnceFlag = pFrame->aOnceFlag;
1803 v->nOnceFlag = pFrame->nOnceFlag;
dan165921a2009-08-28 18:53:45 +00001804 v->aOp = pFrame->aOp;
1805 v->nOp = pFrame->nOp;
1806 v->aMem = pFrame->aMem;
1807 v->nMem = pFrame->nMem;
1808 v->apCsr = pFrame->apCsr;
1809 v->nCursor = pFrame->nCursor;
dan76d462e2009-08-30 11:42:51 +00001810 v->db->lastRowid = pFrame->lastRowid;
1811 v->nChange = pFrame->nChange;
danc3da6672014-10-28 18:24:16 +00001812 v->db->nChange = pFrame->nDbChange;
dan165921a2009-08-28 18:53:45 +00001813 return pFrame->pc;
1814}
1815
drh9a324642003-09-06 20:12:01 +00001816/*
drh5f82e3c2009-07-06 00:44:08 +00001817** Close all cursors.
dan165921a2009-08-28 18:53:45 +00001818**
1819** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1820** cell array. This is necessary as the memory cell array may contain
1821** pointers to VdbeFrame objects, which may in turn contain pointers to
1822** open cursors.
drh9a324642003-09-06 20:12:01 +00001823*/
drh5f82e3c2009-07-06 00:44:08 +00001824static void closeAllCursors(Vdbe *p){
dan165921a2009-08-28 18:53:45 +00001825 if( p->pFrame ){
drh23272752011-03-06 21:54:33 +00001826 VdbeFrame *pFrame;
dan165921a2009-08-28 18:53:45 +00001827 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
1828 sqlite3VdbeFrameRestore(pFrame);
drhf526dca2014-10-13 17:42:05 +00001829 p->pFrame = 0;
1830 p->nFrame = 0;
dan165921a2009-08-28 18:53:45 +00001831 }
drhf526dca2014-10-13 17:42:05 +00001832 assert( p->nFrame==0 );
dan165921a2009-08-28 18:53:45 +00001833
dan523a0872009-08-31 05:23:32 +00001834 if( p->apCsr ){
1835 int i;
1836 for(i=0; i<p->nCursor; i++){
1837 VdbeCursor *pC = p->apCsr[i];
1838 if( pC ){
1839 sqlite3VdbeFreeCursor(p, pC);
1840 p->apCsr[i] = 0;
1841 }
danielk1977be718892006-06-23 08:05:19 +00001842 }
drh9a324642003-09-06 20:12:01 +00001843 }
dan523a0872009-08-31 05:23:32 +00001844 if( p->aMem ){
1845 releaseMemArray(&p->aMem[1], p->nMem);
1846 }
dan27106572010-12-01 08:04:47 +00001847 while( p->pDelFrame ){
1848 VdbeFrame *pDel = p->pDelFrame;
1849 p->pDelFrame = pDel->pParent;
1850 sqlite3VdbeFrameDelete(pDel);
1851 }
dan0c547792013-07-18 17:12:08 +00001852
1853 /* Delete any auxdata allocations made by the VM */
drhf526dca2014-10-13 17:42:05 +00001854 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
dan0c547792013-07-18 17:12:08 +00001855 assert( p->pAuxData==0 );
drh9a324642003-09-06 20:12:01 +00001856}
1857
1858/*
drh7abda852014-09-19 16:02:06 +00001859** Clean up the VM after a single run.
drh9a324642003-09-06 20:12:01 +00001860*/
drhc890fec2008-08-01 20:10:08 +00001861static void Cleanup(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00001862 sqlite3 *db = p->db;
dan165921a2009-08-28 18:53:45 +00001863
1864#ifdef SQLITE_DEBUG
1865 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1866 ** Vdbe.aMem[] arrays have already been cleaned up. */
1867 int i;
drhb8475df2011-12-09 16:21:19 +00001868 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
1869 if( p->aMem ){
drha5750cf2014-02-07 13:20:31 +00001870 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
drhb8475df2011-12-09 16:21:19 +00001871 }
dan165921a2009-08-28 18:53:45 +00001872#endif
1873
drh633e6d52008-07-28 19:34:53 +00001874 sqlite3DbFree(db, p->zErrMsg);
drh9a324642003-09-06 20:12:01 +00001875 p->zErrMsg = 0;
drhd4e70eb2008-01-02 00:34:36 +00001876 p->pResultSet = 0;
drh9a324642003-09-06 20:12:01 +00001877}
1878
1879/*
danielk197722322fd2004-05-25 23:35:17 +00001880** Set the number of result columns that will be returned by this SQL
1881** statement. This is now set at compile time, rather than during
1882** execution of the vdbe program so that sqlite3_column_count() can
1883** be called on an SQL statement before sqlite3_step().
1884*/
1885void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
drh76ff3a02004-09-24 22:32:30 +00001886 Mem *pColName;
1887 int n;
drh633e6d52008-07-28 19:34:53 +00001888 sqlite3 *db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001889
drhc890fec2008-08-01 20:10:08 +00001890 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
drh633e6d52008-07-28 19:34:53 +00001891 sqlite3DbFree(db, p->aColName);
danielk1977955de522006-02-10 02:27:42 +00001892 n = nResColumn*COLNAME_N;
shane36840fd2009-06-26 16:32:13 +00001893 p->nResColumn = (u16)nResColumn;
drh633e6d52008-07-28 19:34:53 +00001894 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
drh76ff3a02004-09-24 22:32:30 +00001895 if( p->aColName==0 ) return;
1896 while( n-- > 0 ){
drh4a50aac2007-08-23 02:47:53 +00001897 pColName->flags = MEM_Null;
drh153c62c2007-08-24 03:51:33 +00001898 pColName->db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001899 pColName++;
drh76ff3a02004-09-24 22:32:30 +00001900 }
danielk197722322fd2004-05-25 23:35:17 +00001901}
1902
1903/*
danielk19773cf86062004-05-26 10:11:05 +00001904** Set the name of the idx'th column to be returned by the SQL statement.
1905** zName must be a pointer to a nul terminated string.
1906**
1907** This call must be made after a call to sqlite3VdbeSetNumCols().
1908**
danielk197710fb7492008-10-31 10:53:22 +00001909** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1910** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1911** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
danielk19773cf86062004-05-26 10:11:05 +00001912*/
danielk197710fb7492008-10-31 10:53:22 +00001913int sqlite3VdbeSetColName(
1914 Vdbe *p, /* Vdbe being configured */
1915 int idx, /* Index of column zName applies to */
1916 int var, /* One of the COLNAME_* constants */
1917 const char *zName, /* Pointer to buffer containing name */
1918 void (*xDel)(void*) /* Memory management strategy for zName */
1919){
danielk19773cf86062004-05-26 10:11:05 +00001920 int rc;
1921 Mem *pColName;
danielk1977955de522006-02-10 02:27:42 +00001922 assert( idx<p->nResColumn );
1923 assert( var<COLNAME_N );
danielk197710fb7492008-10-31 10:53:22 +00001924 if( p->db->mallocFailed ){
1925 assert( !zName || xDel!=SQLITE_DYNAMIC );
1926 return SQLITE_NOMEM;
1927 }
drh76ff3a02004-09-24 22:32:30 +00001928 assert( p->aColName!=0 );
danielk1977955de522006-02-10 02:27:42 +00001929 pColName = &(p->aColName[idx+var*p->nResColumn]);
danielk197710fb7492008-10-31 10:53:22 +00001930 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
drh0793f1b2008-11-05 17:41:19 +00001931 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
danielk19773cf86062004-05-26 10:11:05 +00001932 return rc;
1933}
1934
danielk197713adf8a2004-06-03 16:08:41 +00001935/*
1936** A read or write transaction may or may not be active on database handle
1937** db. If a transaction is active, commit it. If there is a
1938** write-transaction spanning more than one database file, this routine
1939** takes care of the master journal trickery.
1940*/
danielk19773e3a84d2008-08-01 17:37:40 +00001941static int vdbeCommit(sqlite3 *db, Vdbe *p){
danielk197713adf8a2004-06-03 16:08:41 +00001942 int i;
1943 int nTrans = 0; /* Number of databases with an active write-transaction */
1944 int rc = SQLITE_OK;
1945 int needXcommit = 0;
1946
shane36840fd2009-06-26 16:32:13 +00001947#ifdef SQLITE_OMIT_VIRTUALTABLE
1948 /* With this option, sqlite3VtabSync() is defined to be simply
1949 ** SQLITE_OK so p is not used.
1950 */
1951 UNUSED_PARAMETER(p);
1952#endif
1953
danielk19775bd270b2006-07-25 15:14:52 +00001954 /* Before doing anything else, call the xSync() callback for any
1955 ** virtual module tables written in this transaction. This has to
1956 ** be done before determining whether a master journal file is
1957 ** required, as an xSync() callback may add an attached database
1958 ** to the transaction.
1959 */
dan016f7812013-08-21 17:35:48 +00001960 rc = sqlite3VtabSync(db, p);
danielk19775bd270b2006-07-25 15:14:52 +00001961
1962 /* This loop determines (a) if the commit hook should be invoked and
1963 ** (b) how many database files have open write transactions, not
1964 ** including the temp database. (b) is important because if more than
1965 ** one database file has an open write transaction, a master journal
1966 ** file is required for an atomic commit.
1967 */
drhabfb62f2010-07-30 11:20:35 +00001968 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001969 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00001970 if( sqlite3BtreeIsInTrans(pBt) ){
danielk197713adf8a2004-06-03 16:08:41 +00001971 needXcommit = 1;
1972 if( i!=1 ) nTrans++;
dan6b9bb592012-10-05 19:43:02 +00001973 sqlite3BtreeEnter(pBt);
drhabfb62f2010-07-30 11:20:35 +00001974 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
dan6b9bb592012-10-05 19:43:02 +00001975 sqlite3BtreeLeave(pBt);
danielk197713adf8a2004-06-03 16:08:41 +00001976 }
1977 }
drhabfb62f2010-07-30 11:20:35 +00001978 if( rc!=SQLITE_OK ){
1979 return rc;
1980 }
danielk197713adf8a2004-06-03 16:08:41 +00001981
1982 /* If there are any write-transactions at all, invoke the commit hook */
1983 if( needXcommit && db->xCommitCallback ){
drh92f02c32004-09-02 14:57:08 +00001984 rc = db->xCommitCallback(db->pCommitArg);
drh92f02c32004-09-02 14:57:08 +00001985 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00001986 return SQLITE_CONSTRAINT_COMMITHOOK;
danielk197713adf8a2004-06-03 16:08:41 +00001987 }
1988 }
1989
danielk197740b38dc2004-06-26 08:38:24 +00001990 /* The simple case - no more than one database file (not counting the
1991 ** TEMP database) has a transaction active. There is no need for the
drh2ac3ee92004-06-07 16:27:46 +00001992 ** master-journal.
drhc9e06862004-06-09 20:03:08 +00001993 **
danielk197740b38dc2004-06-26 08:38:24 +00001994 ** If the return value of sqlite3BtreeGetFilename() is a zero length
danielk197717b90b52008-06-06 11:11:25 +00001995 ** string, it means the main database is :memory: or a temp file. In
1996 ** that case we do not support atomic multi-file commits, so use the
1997 ** simple case then too.
danielk197713adf8a2004-06-03 16:08:41 +00001998 */
drhea678832008-12-10 19:26:22 +00001999 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
2000 || nTrans<=1
2001 ){
danielk197704103022009-02-03 16:51:24 +00002002 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002003 Btree *pBt = db->aDb[i].pBt;
2004 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002005 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
drh2ac3ee92004-06-07 16:27:46 +00002006 }
2007 }
2008
drh80e35f42007-03-30 14:06:34 +00002009 /* Do the commit only if all databases successfully complete phase 1.
2010 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
2011 ** IO error while deleting or truncating a journal file. It is unlikely,
2012 ** but could happen. In this case abandon processing and return the error.
danielk1977979f38e2007-03-27 16:19:51 +00002013 */
2014 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
2015 Btree *pBt = db->aDb[i].pBt;
2016 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002017 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
danielk197713adf8a2004-06-03 16:08:41 +00002018 }
danielk1977979f38e2007-03-27 16:19:51 +00002019 }
2020 if( rc==SQLITE_OK ){
danielk1977f9e7dda2006-06-16 16:08:53 +00002021 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002022 }
2023 }
2024
2025 /* The complex case - There is a multi-file write-transaction active.
2026 ** This requires a master journal file to ensure the transaction is
peter.d.reid60ec9142014-09-06 16:39:46 +00002027 ** committed atomically.
danielk197713adf8a2004-06-03 16:08:41 +00002028 */
danielk197744ee5bf2005-05-27 09:41:12 +00002029#ifndef SQLITE_OMIT_DISKIO
danielk197713adf8a2004-06-03 16:08:41 +00002030 else{
danielk1977b4b47412007-08-17 15:53:36 +00002031 sqlite3_vfs *pVfs = db->pVfs;
drh2c8997b2005-08-27 16:36:48 +00002032 int needSync = 0;
danielk197713adf8a2004-06-03 16:08:41 +00002033 char *zMaster = 0; /* File-name for the master journal */
2034 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
danielk1977b4b47412007-08-17 15:53:36 +00002035 sqlite3_file *pMaster = 0;
danielk197762079062007-08-15 17:08:46 +00002036 i64 offset = 0;
danielk1977861f7452008-06-05 11:39:11 +00002037 int res;
drhf5808602011-12-16 00:33:04 +00002038 int retryCount = 0;
drh5c531a42011-12-16 01:21:31 +00002039 int nMainFile;
danielk197713adf8a2004-06-03 16:08:41 +00002040
2041 /* Select a master journal file name */
drh5c531a42011-12-16 01:21:31 +00002042 nMainFile = sqlite3Strlen30(zMainFile);
drh52bcde02012-01-03 14:50:45 +00002043 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
drh5c531a42011-12-16 01:21:31 +00002044 if( zMaster==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00002045 do {
drhdc5ea5c2008-12-10 17:19:59 +00002046 u32 iRandom;
drh84968c02011-12-16 15:11:39 +00002047 if( retryCount ){
2048 if( retryCount>100 ){
2049 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
2050 sqlite3OsDelete(pVfs, zMaster, 0);
2051 break;
2052 }else if( retryCount==1 ){
2053 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
2054 }
danielk197713adf8a2004-06-03 16:08:41 +00002055 }
drh84968c02011-12-16 15:11:39 +00002056 retryCount++;
danielk197713adf8a2004-06-03 16:08:41 +00002057 sqlite3_randomness(sizeof(iRandom), &iRandom);
drh5c531a42011-12-16 01:21:31 +00002058 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
drhf5808602011-12-16 00:33:04 +00002059 (iRandom>>8)&0xffffff, iRandom&0xff);
drhf5808602011-12-16 00:33:04 +00002060 /* The antipenultimate character of the master journal name must
2061 ** be "9" to avoid name collisions when using 8+3 filenames. */
drh5c531a42011-12-16 01:21:31 +00002062 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
drh81cc5162011-05-17 20:36:21 +00002063 sqlite3FileSuffix3(zMainFile, zMaster);
danielk1977861f7452008-06-05 11:39:11 +00002064 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
2065 }while( rc==SQLITE_OK && res );
2066 if( rc==SQLITE_OK ){
drh19db9352008-03-27 22:42:51 +00002067 /* Open the master journal. */
2068 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
2069 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2070 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
2071 );
2072 }
danielk197713adf8a2004-06-03 16:08:41 +00002073 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002074 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002075 return rc;
2076 }
2077
2078 /* Write the name of each database file in the transaction into the new
2079 ** master journal file. If an error occurs at this point close
2080 ** and delete the master journal file. All the individual journal files
2081 ** still have 'null' as the master journal pointer, so they will roll
danielk1977aca790a2005-01-13 11:07:52 +00002082 ** back independently if a failure occurs.
danielk197713adf8a2004-06-03 16:08:41 +00002083 */
danielk19771e536952007-08-16 10:09:01 +00002084 for(i=0; i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002085 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002086 if( sqlite3BtreeIsInTrans(pBt) ){
danielk19775865e3d2004-06-14 06:03:57 +00002087 char const *zFile = sqlite3BtreeGetJournalname(pBt);
drh8c96a6e2010-08-31 01:09:15 +00002088 if( zFile==0 ){
drhb290e1c2009-12-08 13:36:55 +00002089 continue; /* Ignore TEMP and :memory: databases */
2090 }
drh8c96a6e2010-08-31 01:09:15 +00002091 assert( zFile[0]!=0 );
drh2c8997b2005-08-27 16:36:48 +00002092 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
2093 needSync = 1;
2094 }
drhea678832008-12-10 19:26:22 +00002095 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
2096 offset += sqlite3Strlen30(zFile)+1;
danielk197713adf8a2004-06-03 16:08:41 +00002097 if( rc!=SQLITE_OK ){
danielk1977fee2d252007-08-18 10:59:19 +00002098 sqlite3OsCloseFree(pMaster);
2099 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002100 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002101 return rc;
2102 }
2103 }
2104 }
2105
danielk19779663b8f2007-08-24 11:52:28 +00002106 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
2107 ** flag is set this is not required.
2108 */
danielk1977bea2a942009-01-20 17:06:27 +00002109 if( needSync
2110 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2111 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2112 ){
danielk1977fee2d252007-08-18 10:59:19 +00002113 sqlite3OsCloseFree(pMaster);
2114 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002115 sqlite3DbFree(db, zMaster);
danielk19775865e3d2004-06-14 06:03:57 +00002116 return rc;
2117 }
drhc9e06862004-06-09 20:03:08 +00002118
danielk197713adf8a2004-06-03 16:08:41 +00002119 /* Sync all the db files involved in the transaction. The same call
2120 ** sets the master journal pointer in each individual journal. If
2121 ** an error occurs here, do not delete the master journal file.
2122 **
drh80e35f42007-03-30 14:06:34 +00002123 ** If the error occurs during the first call to
2124 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2125 ** master journal file will be orphaned. But we cannot delete it,
2126 ** in case the master journal file name was written into the journal
shanebe217792009-03-05 04:20:31 +00002127 ** file before the failure occurred.
danielk197713adf8a2004-06-03 16:08:41 +00002128 */
danielk19775bd270b2006-07-25 15:14:52 +00002129 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002130 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002131 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002132 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002133 }
2134 }
danielk1977fee2d252007-08-18 10:59:19 +00002135 sqlite3OsCloseFree(pMaster);
drhabfb62f2010-07-30 11:20:35 +00002136 assert( rc!=SQLITE_BUSY );
danielk19775bd270b2006-07-25 15:14:52 +00002137 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002138 sqlite3DbFree(db, zMaster);
danielk19775bd270b2006-07-25 15:14:52 +00002139 return rc;
2140 }
danielk197713adf8a2004-06-03 16:08:41 +00002141
danielk1977962398d2004-06-14 09:35:16 +00002142 /* Delete the master journal file. This commits the transaction. After
2143 ** doing this the directory is synced again before any individual
2144 ** transaction files are deleted.
2145 */
drh75a4d7c2015-03-16 16:44:55 +00002146 rc = sqlite3OsDelete(pVfs, zMaster, needSync);
drh633e6d52008-07-28 19:34:53 +00002147 sqlite3DbFree(db, zMaster);
drhc416ba92007-03-30 18:42:55 +00002148 zMaster = 0;
drh29a01382006-08-13 19:04:18 +00002149 if( rc ){
2150 return rc;
2151 }
danielk197713adf8a2004-06-03 16:08:41 +00002152
2153 /* All files and directories have already been synced, so the following
drh80e35f42007-03-30 14:06:34 +00002154 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2155 ** deleting or truncating journals. If something goes wrong while
2156 ** this is happening we don't really care. The integrity of the
2157 ** transaction is already guaranteed, but some stray 'cold' journals
2158 ** may be lying around. Returning an error code won't help matters.
danielk197713adf8a2004-06-03 16:08:41 +00002159 */
danielk1977979f38e2007-03-27 16:19:51 +00002160 disable_simulated_io_errors();
danielk19772d1d86f2008-06-20 14:59:51 +00002161 sqlite3BeginBenignMalloc();
danielk197713adf8a2004-06-03 16:08:41 +00002162 for(i=0; i<db->nDb; i++){
2163 Btree *pBt = db->aDb[i].pBt;
2164 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002165 sqlite3BtreeCommitPhaseTwo(pBt, 1);
danielk197713adf8a2004-06-03 16:08:41 +00002166 }
2167 }
danielk19772d1d86f2008-06-20 14:59:51 +00002168 sqlite3EndBenignMalloc();
danielk1977979f38e2007-03-27 16:19:51 +00002169 enable_simulated_io_errors();
2170
danielk1977f9e7dda2006-06-16 16:08:53 +00002171 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002172 }
danielk197744ee5bf2005-05-27 09:41:12 +00002173#endif
danielk1977026d2702004-06-14 13:14:59 +00002174
drh2ac3ee92004-06-07 16:27:46 +00002175 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00002176}
2177
danielk19771d850a72004-05-31 08:26:49 +00002178/*
drh4f7d3a52013-06-27 23:54:02 +00002179** This routine checks that the sqlite3.nVdbeActive count variable
danielk19771d850a72004-05-31 08:26:49 +00002180** matches the number of vdbe's in the list sqlite3.pVdbe that are
2181** currently active. An assertion fails if the two counts do not match.
drh92f02c32004-09-02 14:57:08 +00002182** This is an internal self-check only - it is not an essential processing
2183** step.
danielk19771d850a72004-05-31 08:26:49 +00002184**
2185** This is a no-op if NDEBUG is defined.
2186*/
2187#ifndef NDEBUG
drh9bb575f2004-09-06 17:24:11 +00002188static void checkActiveVdbeCnt(sqlite3 *db){
danielk19771d850a72004-05-31 08:26:49 +00002189 Vdbe *p;
2190 int cnt = 0;
drhad4a4b82008-11-05 16:37:34 +00002191 int nWrite = 0;
drh4f7d3a52013-06-27 23:54:02 +00002192 int nRead = 0;
danielk19771d850a72004-05-31 08:26:49 +00002193 p = db->pVdbe;
2194 while( p ){
dan857745c2014-07-19 17:57:10 +00002195 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
danielk19771d850a72004-05-31 08:26:49 +00002196 cnt++;
drhad4a4b82008-11-05 16:37:34 +00002197 if( p->readOnly==0 ) nWrite++;
drh1713afb2013-06-28 01:24:57 +00002198 if( p->bIsReader ) nRead++;
danielk19771d850a72004-05-31 08:26:49 +00002199 }
2200 p = p->pNext;
2201 }
drh4f7d3a52013-06-27 23:54:02 +00002202 assert( cnt==db->nVdbeActive );
2203 assert( nWrite==db->nVdbeWrite );
2204 assert( nRead==db->nVdbeRead );
danielk19771d850a72004-05-31 08:26:49 +00002205}
2206#else
2207#define checkActiveVdbeCnt(x)
2208#endif
2209
danielk19773cf86062004-05-26 10:11:05 +00002210/*
danielk1977bd434552009-03-18 10:33:00 +00002211** If the Vdbe passed as the first argument opened a statement-transaction,
2212** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2213** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2214** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
drhf7b54962013-05-28 12:11:54 +00002215** statement transaction is committed.
danielk1977bd434552009-03-18 10:33:00 +00002216**
2217** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2218** Otherwise SQLITE_OK.
2219*/
2220int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
danielk1977c926b6a2009-03-20 14:42:11 +00002221 sqlite3 *const db = p->db;
danielk1977bd434552009-03-18 10:33:00 +00002222 int rc = SQLITE_OK;
danielk1977ecaecf92009-07-08 08:05:35 +00002223
danielk1977e4948172009-07-17 17:25:43 +00002224 /* If p->iStatement is greater than zero, then this Vdbe opened a
2225 ** statement transaction that should be closed here. The only exception
mistachkin48864df2013-03-21 21:20:32 +00002226 ** is that an IO error may have occurred, causing an emergency rollback.
danielk1977e4948172009-07-17 17:25:43 +00002227 ** In this case (db->nStatement==0), and there is nothing to do.
2228 */
2229 if( db->nStatement && p->iStatement ){
danielk1977bd434552009-03-18 10:33:00 +00002230 int i;
2231 const int iSavepoint = p->iStatement-1;
danielk1977bd434552009-03-18 10:33:00 +00002232
2233 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2234 assert( db->nStatement>0 );
2235 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2236
2237 for(i=0; i<db->nDb; i++){
2238 int rc2 = SQLITE_OK;
2239 Btree *pBt = db->aDb[i].pBt;
2240 if( pBt ){
2241 if( eOp==SAVEPOINT_ROLLBACK ){
2242 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2243 }
2244 if( rc2==SQLITE_OK ){
2245 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2246 }
2247 if( rc==SQLITE_OK ){
2248 rc = rc2;
2249 }
2250 }
2251 }
2252 db->nStatement--;
2253 p->iStatement = 0;
dan1da40a32009-09-19 17:00:31 +00002254
dana311b802011-04-26 19:21:34 +00002255 if( rc==SQLITE_OK ){
2256 if( eOp==SAVEPOINT_ROLLBACK ){
2257 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2258 }
2259 if( rc==SQLITE_OK ){
2260 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2261 }
2262 }
2263
dan1da40a32009-09-19 17:00:31 +00002264 /* If the statement transaction is being rolled back, also restore the
2265 ** database handles deferred constraint counter to the value it had when
2266 ** the statement transaction was opened. */
2267 if( eOp==SAVEPOINT_ROLLBACK ){
2268 db->nDeferredCons = p->nStmtDefCons;
drh648e2642013-07-11 15:03:32 +00002269 db->nDeferredImmCons = p->nStmtDefImmCons;
dan1da40a32009-09-19 17:00:31 +00002270 }
danielk1977bd434552009-03-18 10:33:00 +00002271 }
2272 return rc;
2273}
2274
2275/*
dan1da40a32009-09-19 17:00:31 +00002276** This function is called when a transaction opened by the database
2277** handle associated with the VM passed as an argument is about to be
2278** committed. If there are outstanding deferred foreign key constraint
2279** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2280**
2281** If there are outstanding FK violations and this function returns
drhd91c1a12013-02-09 13:58:25 +00002282** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2283** and write an error message to it. Then return SQLITE_ERROR.
dan1da40a32009-09-19 17:00:31 +00002284*/
2285#ifndef SQLITE_OMIT_FOREIGN_KEY
dan32b09f22009-09-23 17:29:59 +00002286int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
dan1da40a32009-09-19 17:00:31 +00002287 sqlite3 *db = p->db;
drh648e2642013-07-11 15:03:32 +00002288 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2289 || (!deferred && p->nFkConstraint>0)
2290 ){
drhd91c1a12013-02-09 13:58:25 +00002291 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan32b09f22009-09-23 17:29:59 +00002292 p->errorAction = OE_Abort;
drhf9c8ce32013-11-05 13:33:55 +00002293 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
dan1da40a32009-09-19 17:00:31 +00002294 return SQLITE_ERROR;
2295 }
2296 return SQLITE_OK;
2297}
2298#endif
2299
2300/*
drh92f02c32004-09-02 14:57:08 +00002301** This routine is called the when a VDBE tries to halt. If the VDBE
2302** has made changes and is in autocommit mode, then commit those
2303** changes. If a rollback is needed, then do the rollback.
drh9a324642003-09-06 20:12:01 +00002304**
drh92f02c32004-09-02 14:57:08 +00002305** This routine is the only way to move the state of a VM from
drhff0587c2007-08-29 17:43:19 +00002306** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2307** call this on a VM that is in the SQLITE_MAGIC_HALT state.
drh92f02c32004-09-02 14:57:08 +00002308**
2309** Return an error code. If the commit could not complete because of
2310** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2311** means the close did not happen and needs to be repeated.
drh9a324642003-09-06 20:12:01 +00002312*/
drhff0587c2007-08-29 17:43:19 +00002313int sqlite3VdbeHalt(Vdbe *p){
danielk1977bd434552009-03-18 10:33:00 +00002314 int rc; /* Used to store transient return codes */
drh9bb575f2004-09-06 17:24:11 +00002315 sqlite3 *db = p->db;
danielk197707cb5602006-01-20 10:55:05 +00002316
2317 /* This function contains the logic that determines if a statement or
2318 ** transaction will be committed or rolled back as a result of the
2319 ** execution of this virtual machine.
2320 **
drh71b890a2007-10-03 15:30:52 +00002321 ** If any of the following errors occur:
danielk197707cb5602006-01-20 10:55:05 +00002322 **
drh71b890a2007-10-03 15:30:52 +00002323 ** SQLITE_NOMEM
2324 ** SQLITE_IOERR
2325 ** SQLITE_FULL
2326 ** SQLITE_INTERRUPT
danielk197707cb5602006-01-20 10:55:05 +00002327 **
drh71b890a2007-10-03 15:30:52 +00002328 ** Then the internal cache might have been left in an inconsistent
2329 ** state. We need to rollback the statement transaction, if there is
2330 ** one, or the complete transaction if there is no statement transaction.
danielk197707cb5602006-01-20 10:55:05 +00002331 */
drh9a324642003-09-06 20:12:01 +00002332
drh17435752007-08-16 04:30:38 +00002333 if( p->db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002334 p->rc = SQLITE_NOMEM;
2335 }
drh6e856bc2011-12-09 18:06:44 +00002336 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
drh5f82e3c2009-07-06 00:44:08 +00002337 closeAllCursors(p);
drh92f02c32004-09-02 14:57:08 +00002338 if( p->magic!=VDBE_MAGIC_RUN ){
drh92f02c32004-09-02 14:57:08 +00002339 return SQLITE_OK;
drh9a324642003-09-06 20:12:01 +00002340 }
danielk19771d850a72004-05-31 08:26:49 +00002341 checkActiveVdbeCnt(db);
danielk1977261919c2005-12-06 12:52:59 +00002342
danc0537fe2013-06-28 19:41:43 +00002343 /* No commit or rollback needed if the program never started or if the
2344 ** SQL statement does not read or write a database file. */
2345 if( p->pc>=0 && p->bIsReader ){
drhaac2f552006-09-23 21:44:23 +00002346 int mrc; /* Primary error code from p->rc */
danielk1977bd434552009-03-18 10:33:00 +00002347 int eStatementOp = 0;
2348 int isSpecialError; /* Set to true if a 'special' error */
drhff0587c2007-08-29 17:43:19 +00002349
2350 /* Lock all btrees used by the statement */
drhbdaec522011-04-04 00:14:43 +00002351 sqlite3VdbeEnter(p);
drhff0587c2007-08-29 17:43:19 +00002352
drh71b890a2007-10-03 15:30:52 +00002353 /* Check for one of the special errors */
drhaac2f552006-09-23 21:44:23 +00002354 mrc = p->rc & 0xff;
drh71b890a2007-10-03 15:30:52 +00002355 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
drh77658e22007-12-04 16:54:52 +00002356 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
danielk197707cb5602006-01-20 10:55:05 +00002357 if( isSpecialError ){
dan5653e4d2010-08-12 11:25:47 +00002358 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2359 ** no rollback is necessary. Otherwise, at least a savepoint
2360 ** transaction must be rolled back to restore the database to a
2361 ** consistent state.
2362 **
2363 ** Even if the statement is read-only, it is important to perform
2364 ** a statement or transaction rollback operation. If the error
mistachkin48864df2013-03-21 21:20:32 +00002365 ** occurred while writing to the journal, sub-journal or database
dan5653e4d2010-08-12 11:25:47 +00002366 ** file as part of an effort to free up cache space (see function
2367 ** pagerStress() in pager.c), the rollback is required to restore
2368 ** the pager to a consistent state.
danielk197707cb5602006-01-20 10:55:05 +00002369 */
drhad4a4b82008-11-05 16:37:34 +00002370 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
drhfa3be902009-07-07 02:44:07 +00002371 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
danielk1977bd434552009-03-18 10:33:00 +00002372 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002373 }else{
2374 /* We are forced to roll back the active transaction. Before doing
2375 ** so, abort any other statements this handle currently has active.
2376 */
drh21021a52012-02-13 17:01:51 +00002377 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002378 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002379 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002380 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002381 }
danielk1977261919c2005-12-06 12:52:59 +00002382 }
2383 }
dan32b09f22009-09-23 17:29:59 +00002384
2385 /* Check for immediate foreign key violations. */
2386 if( p->rc==SQLITE_OK ){
2387 sqlite3VdbeCheckFk(p, 0);
2388 }
danielk197707cb5602006-01-20 10:55:05 +00002389
danielk1977bd434552009-03-18 10:33:00 +00002390 /* If the auto-commit flag is set and this is the only active writer
2391 ** VM, then we do either a commit or rollback of the current transaction.
danielk197707cb5602006-01-20 10:55:05 +00002392 **
2393 ** Note: This block also runs if one of the special errors handled
drhad4a4b82008-11-05 16:37:34 +00002394 ** above has occurred.
danielk197707cb5602006-01-20 10:55:05 +00002395 */
danielk1977093e0f62008-11-13 18:00:14 +00002396 if( !sqlite3VtabInSync(db)
2397 && db->autoCommit
drh4f7d3a52013-06-27 23:54:02 +00002398 && db->nVdbeWrite==(p->readOnly==0)
danielk1977093e0f62008-11-13 18:00:14 +00002399 ){
danielk197707cb5602006-01-20 10:55:05 +00002400 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
dan19611b12011-01-24 16:00:58 +00002401 rc = sqlite3VdbeCheckFk(p, 1);
2402 if( rc!=SQLITE_OK ){
drhe9ce5852011-02-11 22:54:28 +00002403 if( NEVER(p->readOnly) ){
drhbdaec522011-04-04 00:14:43 +00002404 sqlite3VdbeLeave(p);
dan19611b12011-01-24 16:00:58 +00002405 return SQLITE_ERROR;
2406 }
drhd91c1a12013-02-09 13:58:25 +00002407 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan19611b12011-01-24 16:00:58 +00002408 }else{
2409 /* The auto-commit flag is true, the vdbe program was successful
2410 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2411 ** key constraints to hold up the transaction. This means a commit
2412 ** is required. */
2413 rc = vdbeCommit(db, p);
dan1da40a32009-09-19 17:00:31 +00002414 }
dan19611b12011-01-24 16:00:58 +00002415 if( rc==SQLITE_BUSY && p->readOnly ){
drhbdaec522011-04-04 00:14:43 +00002416 sqlite3VdbeLeave(p);
danielk197707cb5602006-01-20 10:55:05 +00002417 return SQLITE_BUSY;
2418 }else if( rc!=SQLITE_OK ){
2419 p->rc = rc;
drh0f198a72012-02-13 16:43:16 +00002420 sqlite3RollbackAll(db, SQLITE_OK);
danc3da6672014-10-28 18:24:16 +00002421 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002422 }else{
dan1da40a32009-09-19 17:00:31 +00002423 db->nDeferredCons = 0;
drh648e2642013-07-11 15:03:32 +00002424 db->nDeferredImmCons = 0;
2425 db->flags &= ~SQLITE_DeferFKs;
danielk197707cb5602006-01-20 10:55:05 +00002426 sqlite3CommitInternalChanges(db);
2427 }
2428 }else{
drh0f198a72012-02-13 16:43:16 +00002429 sqlite3RollbackAll(db, SQLITE_OK);
danc3da6672014-10-28 18:24:16 +00002430 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002431 }
danielk1977bd434552009-03-18 10:33:00 +00002432 db->nStatement = 0;
2433 }else if( eStatementOp==0 ){
danielk197707cb5602006-01-20 10:55:05 +00002434 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
danielk1977bd434552009-03-18 10:33:00 +00002435 eStatementOp = SAVEPOINT_RELEASE;
danielk197707cb5602006-01-20 10:55:05 +00002436 }else if( p->errorAction==OE_Abort ){
danielk1977bd434552009-03-18 10:33:00 +00002437 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002438 }else{
drh21021a52012-02-13 17:01:51 +00002439 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002440 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002441 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002442 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002443 }
danielk19771d850a72004-05-31 08:26:49 +00002444 }
danielk197707cb5602006-01-20 10:55:05 +00002445
danielk1977bd434552009-03-18 10:33:00 +00002446 /* If eStatementOp is non-zero, then a statement transaction needs to
2447 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2448 ** do so. If this operation returns an error, and the current statement
drh35173242010-03-08 21:40:13 +00002449 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2450 ** current statement error code.
danielk197707cb5602006-01-20 10:55:05 +00002451 */
danielk1977bd434552009-03-18 10:33:00 +00002452 if( eStatementOp ){
2453 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
dan40ad9d22010-06-03 09:17:38 +00002454 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00002455 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
dan40ad9d22010-06-03 09:17:38 +00002456 p->rc = rc;
2457 sqlite3DbFree(db, p->zErrMsg);
2458 p->zErrMsg = 0;
2459 }
drh21021a52012-02-13 17:01:51 +00002460 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
dan40ad9d22010-06-03 09:17:38 +00002461 sqlite3CloseSavepoints(db);
2462 db->autoCommit = 1;
danc3da6672014-10-28 18:24:16 +00002463 p->nChange = 0;
danielk197707cb5602006-01-20 10:55:05 +00002464 }
danielk197777d83ba2004-05-31 10:08:14 +00002465 }
danielk197707cb5602006-01-20 10:55:05 +00002466
danielk1977bd434552009-03-18 10:33:00 +00002467 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2468 ** has been rolled back, update the database connection change-counter.
danielk197707cb5602006-01-20 10:55:05 +00002469 */
drh6be240e2009-07-14 02:33:02 +00002470 if( p->changeCntOn ){
danielk1977bd434552009-03-18 10:33:00 +00002471 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
danielk197707cb5602006-01-20 10:55:05 +00002472 sqlite3VdbeSetChanges(db, p->nChange);
2473 }else{
2474 sqlite3VdbeSetChanges(db, 0);
2475 }
2476 p->nChange = 0;
danielk1977b28af712004-06-21 06:50:26 +00002477 }
drhff0587c2007-08-29 17:43:19 +00002478
2479 /* Release the locks */
drhbdaec522011-04-04 00:14:43 +00002480 sqlite3VdbeLeave(p);
drh9a324642003-09-06 20:12:01 +00002481 }
danielk19771d850a72004-05-31 08:26:49 +00002482
danielk197765fd59f2006-06-24 11:51:33 +00002483 /* We have successfully halted and closed the VM. Record this fact. */
2484 if( p->pc>=0 ){
drh4f7d3a52013-06-27 23:54:02 +00002485 db->nVdbeActive--;
2486 if( !p->readOnly ) db->nVdbeWrite--;
drh1713afb2013-06-28 01:24:57 +00002487 if( p->bIsReader ) db->nVdbeRead--;
drh4f7d3a52013-06-27 23:54:02 +00002488 assert( db->nVdbeActive>=db->nVdbeRead );
2489 assert( db->nVdbeRead>=db->nVdbeWrite );
2490 assert( db->nVdbeWrite>=0 );
drh9a324642003-09-06 20:12:01 +00002491 }
drh92f02c32004-09-02 14:57:08 +00002492 p->magic = VDBE_MAGIC_HALT;
2493 checkActiveVdbeCnt(db);
drhff0587c2007-08-29 17:43:19 +00002494 if( p->db->mallocFailed ){
2495 p->rc = SQLITE_NOMEM;
2496 }
danielk19771d850a72004-05-31 08:26:49 +00002497
danielk1977404ca072009-03-16 13:19:36 +00002498 /* If the auto-commit flag is set to true, then any locks that were held
2499 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2500 ** to invoke any required unlock-notify callbacks.
2501 */
2502 if( db->autoCommit ){
2503 sqlite3ConnectionUnlocked(db);
2504 }
2505
drh4f7d3a52013-06-27 23:54:02 +00002506 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
dan19611b12011-01-24 16:00:58 +00002507 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
drh92f02c32004-09-02 14:57:08 +00002508}
drh4cf7c7f2007-08-28 23:28:07 +00002509
drh92f02c32004-09-02 14:57:08 +00002510
2511/*
drh3c23a882007-01-09 14:01:13 +00002512** Each VDBE holds the result of the most recent sqlite3_step() call
2513** in p->rc. This routine sets that result back to SQLITE_OK.
2514*/
2515void sqlite3VdbeResetStepResult(Vdbe *p){
2516 p->rc = SQLITE_OK;
2517}
2518
2519/*
dan029ead62011-10-27 15:19:58 +00002520** Copy the error code and error message belonging to the VDBE passed
2521** as the first argument to its database handle (so that they will be
2522** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2523**
2524** This function does not clear the VDBE error code or message, just
2525** copies them to the database handle.
2526*/
2527int sqlite3VdbeTransferError(Vdbe *p){
2528 sqlite3 *db = p->db;
2529 int rc = p->rc;
2530 if( p->zErrMsg ){
drh81bdd6d2011-10-29 01:33:24 +00002531 u8 mallocFailed = db->mallocFailed;
dan029ead62011-10-27 15:19:58 +00002532 sqlite3BeginBenignMalloc();
drha3cc0072013-12-13 16:23:55 +00002533 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
dan029ead62011-10-27 15:19:58 +00002534 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2535 sqlite3EndBenignMalloc();
drh81bdd6d2011-10-29 01:33:24 +00002536 db->mallocFailed = mallocFailed;
dan029ead62011-10-27 15:19:58 +00002537 db->errCode = rc;
2538 }else{
drh13f40da2014-08-22 18:00:11 +00002539 sqlite3Error(db, rc);
dan029ead62011-10-27 15:19:58 +00002540 }
2541 return rc;
2542}
2543
danac455932012-11-26 19:50:41 +00002544#ifdef SQLITE_ENABLE_SQLLOG
2545/*
2546** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2547** invoke it.
2548*/
2549static void vdbeInvokeSqllog(Vdbe *v){
2550 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2551 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2552 assert( v->db->init.busy==0 );
2553 if( zExpanded ){
2554 sqlite3GlobalConfig.xSqllog(
2555 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2556 );
2557 sqlite3DbFree(v->db, zExpanded);
2558 }
2559 }
2560}
2561#else
2562# define vdbeInvokeSqllog(x)
2563#endif
2564
dan029ead62011-10-27 15:19:58 +00002565/*
drh92f02c32004-09-02 14:57:08 +00002566** Clean up a VDBE after execution but do not delete the VDBE just yet.
2567** Write any error messages into *pzErrMsg. Return the result code.
2568**
2569** After this routine is run, the VDBE should be ready to be executed
2570** again.
2571**
2572** To look at it another way, this routine resets the state of the
2573** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2574** VDBE_MAGIC_INIT.
2575*/
drhc890fec2008-08-01 20:10:08 +00002576int sqlite3VdbeReset(Vdbe *p){
drh4ac285a2006-09-15 07:28:50 +00002577 sqlite3 *db;
drh4ac285a2006-09-15 07:28:50 +00002578 db = p->db;
drh92f02c32004-09-02 14:57:08 +00002579
2580 /* If the VM did not run to completion or if it encountered an
2581 ** error, then it might not have been halted properly. So halt
2582 ** it now.
2583 */
2584 sqlite3VdbeHalt(p);
2585
drhfb7e7652005-01-24 00:28:42 +00002586 /* If the VDBE has be run even partially, then transfer the error code
2587 ** and error message from the VDBE into the main database structure. But
2588 ** if the VDBE has just been set to run but has not actually executed any
2589 ** instructions yet, leave the main database error information unchanged.
drh92f02c32004-09-02 14:57:08 +00002590 */
drhfb7e7652005-01-24 00:28:42 +00002591 if( p->pc>=0 ){
danac455932012-11-26 19:50:41 +00002592 vdbeInvokeSqllog(p);
dan029ead62011-10-27 15:19:58 +00002593 sqlite3VdbeTransferError(p);
2594 sqlite3DbFree(db, p->zErrMsg);
2595 p->zErrMsg = 0;
drh4611d922010-02-25 14:47:01 +00002596 if( p->runOnlyOnce ) p->expired = 1;
danielk1977a21c6b62005-01-24 10:25:59 +00002597 }else if( p->rc && p->expired ){
2598 /* The expired flag was set on the VDBE before the first call
2599 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2600 ** called), set the database error in this case as well.
2601 */
drh13f40da2014-08-22 18:00:11 +00002602 sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
drh633e6d52008-07-28 19:34:53 +00002603 sqlite3DbFree(db, p->zErrMsg);
danielk19778e556522007-11-13 10:30:24 +00002604 p->zErrMsg = 0;
drh92f02c32004-09-02 14:57:08 +00002605 }
2606
2607 /* Reclaim all memory used by the VDBE
2608 */
drhc890fec2008-08-01 20:10:08 +00002609 Cleanup(p);
drh92f02c32004-09-02 14:57:08 +00002610
2611 /* Save profiling information from this VDBE run.
2612 */
drh9a324642003-09-06 20:12:01 +00002613#ifdef VDBE_PROFILE
2614 {
2615 FILE *out = fopen("vdbe_profile.out", "a");
2616 if( out ){
2617 int i;
2618 fprintf(out, "---- ");
2619 for(i=0; i<p->nOp; i++){
2620 fprintf(out, "%02x", p->aOp[i].opcode);
2621 }
2622 fprintf(out, "\n");
drh2926f962014-02-17 01:13:28 +00002623 if( p->zSql ){
2624 char c, pc = 0;
2625 fprintf(out, "-- ");
2626 for(i=0; (c = p->zSql[i])!=0; i++){
2627 if( pc=='\n' ) fprintf(out, "-- ");
2628 putc(c, out);
2629 pc = c;
2630 }
2631 if( pc!='\n' ) fprintf(out, "\n");
2632 }
drh9a324642003-09-06 20:12:01 +00002633 for(i=0; i<p->nOp; i++){
drh15ab9412014-02-24 14:24:01 +00002634 char zHdr[100];
2635 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
drh9a324642003-09-06 20:12:01 +00002636 p->aOp[i].cnt,
2637 p->aOp[i].cycles,
2638 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2639 );
drh15ab9412014-02-24 14:24:01 +00002640 fprintf(out, "%s", zHdr);
danielk19774adee202004-05-08 08:23:19 +00002641 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
drh9a324642003-09-06 20:12:01 +00002642 }
2643 fclose(out);
2644 }
2645 }
2646#endif
drh7fa20922013-09-17 23:36:33 +00002647 p->iCurrentTime = 0;
drh9a324642003-09-06 20:12:01 +00002648 p->magic = VDBE_MAGIC_INIT;
drh4ac285a2006-09-15 07:28:50 +00002649 return p->rc & db->errMask;
drh9a324642003-09-06 20:12:01 +00002650}
drh92f02c32004-09-02 14:57:08 +00002651
drh9a324642003-09-06 20:12:01 +00002652/*
2653** Clean up and delete a VDBE after execution. Return an integer which is
2654** the result code. Write any error message text into *pzErrMsg.
2655*/
danielk19779e6db7d2004-06-21 08:18:51 +00002656int sqlite3VdbeFinalize(Vdbe *p){
danielk1977b5548a82004-06-26 13:51:33 +00002657 int rc = SQLITE_OK;
danielk1977b5548a82004-06-26 13:51:33 +00002658 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
drhc890fec2008-08-01 20:10:08 +00002659 rc = sqlite3VdbeReset(p);
drh4ac285a2006-09-15 07:28:50 +00002660 assert( (rc & p->db->errMask)==rc );
drh9a324642003-09-06 20:12:01 +00002661 }
danielk19774adee202004-05-08 08:23:19 +00002662 sqlite3VdbeDelete(p);
drh9a324642003-09-06 20:12:01 +00002663 return rc;
2664}
2665
2666/*
dan0c547792013-07-18 17:12:08 +00002667** If parameter iOp is less than zero, then invoke the destructor for
2668** all auxiliary data pointers currently cached by the VM passed as
2669** the first argument.
2670**
2671** Or, if iOp is greater than or equal to zero, then the destructor is
2672** only invoked for those auxiliary data pointers created by the user
2673** function invoked by the OP_Function opcode at instruction iOp of
2674** VM pVdbe, and only then if:
2675**
2676** * the associated function parameter is the 32nd or later (counting
2677** from left to right), or
2678**
2679** * the corresponding bit in argument mask is clear (where the first
peter.d.reid60ec9142014-09-06 16:39:46 +00002680** function parameter corresponds to bit 0 etc.).
drhf92c7ff2004-06-19 15:40:23 +00002681*/
dan0c547792013-07-18 17:12:08 +00002682void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
2683 AuxData **pp = &pVdbe->pAuxData;
2684 while( *pp ){
2685 AuxData *pAux = *pp;
2686 if( (iOp<0)
drh693e6712014-01-24 22:58:00 +00002687 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
dan0c547792013-07-18 17:12:08 +00002688 ){
drh693e6712014-01-24 22:58:00 +00002689 testcase( pAux->iArg==31 );
drhf92c7ff2004-06-19 15:40:23 +00002690 if( pAux->xDelete ){
2691 pAux->xDelete(pAux->pAux);
2692 }
dan0c547792013-07-18 17:12:08 +00002693 *pp = pAux->pNext;
2694 sqlite3DbFree(pVdbe->db, pAux);
2695 }else{
2696 pp= &pAux->pNext;
drhf92c7ff2004-06-19 15:40:23 +00002697 }
2698 }
2699}
2700
2701/*
drhcb103b92012-10-26 00:11:23 +00002702** Free all memory associated with the Vdbe passed as the second argument,
2703** except for object itself, which is preserved.
2704**
dand46def72010-07-24 11:28:28 +00002705** The difference between this function and sqlite3VdbeDelete() is that
2706** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
drhcb103b92012-10-26 00:11:23 +00002707** the database connection and frees the object itself.
dand46def72010-07-24 11:28:28 +00002708*/
drhcb103b92012-10-26 00:11:23 +00002709void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
dand19c9332010-07-26 12:05:17 +00002710 SubProgram *pSub, *pNext;
drh124c0b42011-06-01 18:15:55 +00002711 int i;
dand46def72010-07-24 11:28:28 +00002712 assert( p->db==0 || p->db==db );
2713 releaseMemArray(p->aVar, p->nVar);
2714 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
dand19c9332010-07-26 12:05:17 +00002715 for(pSub=p->pProgram; pSub; pSub=pNext){
2716 pNext = pSub->pNext;
2717 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2718 sqlite3DbFree(db, pSub);
2719 }
drh124c0b42011-06-01 18:15:55 +00002720 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
dand46def72010-07-24 11:28:28 +00002721 vdbeFreeOpArray(db, p->aOp, p->nOp);
dand46def72010-07-24 11:28:28 +00002722 sqlite3DbFree(db, p->aColName);
2723 sqlite3DbFree(db, p->zSql);
2724 sqlite3DbFree(db, p->pFree);
dan6f9702e2014-11-01 20:38:06 +00002725#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
dan6f9702e2014-11-01 20:38:06 +00002726 for(i=0; i<p->nScan; i++){
2727 sqlite3DbFree(db, p->aScan[i].zName);
2728 }
2729 sqlite3DbFree(db, p->aScan);
2730#endif
dand46def72010-07-24 11:28:28 +00002731}
2732
2733/*
drh9a324642003-09-06 20:12:01 +00002734** Delete an entire VDBE.
2735*/
danielk19774adee202004-05-08 08:23:19 +00002736void sqlite3VdbeDelete(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00002737 sqlite3 *db;
2738
drhfa3be902009-07-07 02:44:07 +00002739 if( NEVER(p==0) ) return;
drh633e6d52008-07-28 19:34:53 +00002740 db = p->db;
drh4245c402012-06-02 14:32:21 +00002741 assert( sqlite3_mutex_held(db->mutex) );
drhcb103b92012-10-26 00:11:23 +00002742 sqlite3VdbeClearObject(db, p);
drh9a324642003-09-06 20:12:01 +00002743 if( p->pPrev ){
2744 p->pPrev->pNext = p->pNext;
2745 }else{
drh633e6d52008-07-28 19:34:53 +00002746 assert( db->pVdbe==p );
2747 db->pVdbe = p->pNext;
drh9a324642003-09-06 20:12:01 +00002748 }
2749 if( p->pNext ){
2750 p->pNext->pPrev = p->pPrev;
2751 }
drh9a324642003-09-06 20:12:01 +00002752 p->magic = VDBE_MAGIC_DEAD;
drh87f5c5f2010-01-20 01:20:56 +00002753 p->db = 0;
drhcb103b92012-10-26 00:11:23 +00002754 sqlite3DbFree(db, p);
drh9a324642003-09-06 20:12:01 +00002755}
drha11846b2004-01-07 18:52:56 +00002756
2757/*
drh6848dad2014-08-22 23:33:03 +00002758** The cursor "p" has a pending seek operation that has not yet been
2759** carried out. Seek the cursor now. If an error occurs, return
2760** the appropriate error code.
2761*/
2762static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
2763 int res, rc;
2764#ifdef SQLITE_TEST
2765 extern int sqlite3_search_count;
2766#endif
2767 assert( p->deferredMoveto );
2768 assert( p->isTable );
2769 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
2770 if( rc ) return rc;
drh6848dad2014-08-22 23:33:03 +00002771 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
drh6848dad2014-08-22 23:33:03 +00002772#ifdef SQLITE_TEST
2773 sqlite3_search_count++;
2774#endif
2775 p->deferredMoveto = 0;
2776 p->cacheStatus = CACHE_STALE;
2777 return SQLITE_OK;
2778}
2779
2780/*
2781** Something has moved cursor "p" out of place. Maybe the row it was
2782** pointed to was deleted out from under it. Or maybe the btree was
2783** rebalanced. Whatever the cause, try to restore "p" to the place it
peter.d.reid60ec9142014-09-06 16:39:46 +00002784** is supposed to be pointing. If the row was deleted out from under the
drh6848dad2014-08-22 23:33:03 +00002785** cursor, set the cursor to point to a NULL row.
2786*/
2787static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
2788 int isDifferentRow, rc;
2789 assert( p->pCursor!=0 );
2790 assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
2791 rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
2792 p->cacheStatus = CACHE_STALE;
2793 if( isDifferentRow ) p->nullRow = 1;
2794 return rc;
2795}
2796
2797/*
drhc22284f2014-10-13 16:02:20 +00002798** Check to ensure that the cursor is valid. Restore the cursor
2799** if need be. Return any I/O error from the restore operation.
2800*/
2801int sqlite3VdbeCursorRestore(VdbeCursor *p){
2802 if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
2803 return handleMovedCursor(p);
2804 }
2805 return SQLITE_OK;
2806}
2807
2808/*
drh9a65f2c2009-06-22 19:05:40 +00002809** Make sure the cursor p is ready to read or write the row to which it
2810** was last positioned. Return an error code if an OOM fault or I/O error
2811** prevents us from positioning the cursor to its correct position.
2812**
drha11846b2004-01-07 18:52:56 +00002813** If a MoveTo operation is pending on the given cursor, then do that
drh9a65f2c2009-06-22 19:05:40 +00002814** MoveTo now. If no move is pending, check to see if the row has been
2815** deleted out from under the cursor and if it has, mark the row as
2816** a NULL row.
2817**
2818** If the cursor is already pointing to the correct row and that row has
2819** not been deleted out from under the cursor, then this routine is a no-op.
drha11846b2004-01-07 18:52:56 +00002820*/
drhdfe88ec2008-11-03 20:55:06 +00002821int sqlite3VdbeCursorMoveto(VdbeCursor *p){
drha11846b2004-01-07 18:52:56 +00002822 if( p->deferredMoveto ){
drh6848dad2014-08-22 23:33:03 +00002823 return handleDeferredMoveto(p);
2824 }
drhc22284f2014-10-13 16:02:20 +00002825 if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
drh6848dad2014-08-22 23:33:03 +00002826 return handleMovedCursor(p);
drha11846b2004-01-07 18:52:56 +00002827 }
2828 return SQLITE_OK;
2829}
danielk19774adee202004-05-08 08:23:19 +00002830
drhab9f7f12004-05-08 10:56:11 +00002831/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002832** The following functions:
danielk197790e4d952004-05-10 10:05:53 +00002833**
danielk1977cfcdaef2004-05-12 07:33:33 +00002834** sqlite3VdbeSerialType()
2835** sqlite3VdbeSerialTypeLen()
danielk197790e4d952004-05-10 10:05:53 +00002836** sqlite3VdbeSerialLen()
shane92003092008-07-31 01:43:13 +00002837** sqlite3VdbeSerialPut()
2838** sqlite3VdbeSerialGet()
danielk197790e4d952004-05-10 10:05:53 +00002839**
2840** encapsulate the code that serializes values for storage in SQLite
danielk1977cfcdaef2004-05-12 07:33:33 +00002841** data and index records. Each serialized value consists of a
2842** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2843** integer, stored as a varint.
danielk197790e4d952004-05-10 10:05:53 +00002844**
danielk1977cfcdaef2004-05-12 07:33:33 +00002845** In an SQLite index record, the serial type is stored directly before
2846** the blob of data that it corresponds to. In a table record, all serial
2847** types are stored at the start of the record, and the blobs of data at
2848** the end. Hence these functions allow the caller to handle the
mistachkin48864df2013-03-21 21:20:32 +00002849** serial-type and data blob separately.
danielk1977cfcdaef2004-05-12 07:33:33 +00002850**
2851** The following table describes the various storage classes for data:
2852**
2853** serial type bytes of data type
danielk197790e4d952004-05-10 10:05:53 +00002854** -------------- --------------- ---------------
drha19b7752004-05-30 21:14:58 +00002855** 0 0 NULL
danielk197790e4d952004-05-10 10:05:53 +00002856** 1 1 signed integer
2857** 2 2 signed integer
drha19b7752004-05-30 21:14:58 +00002858** 3 3 signed integer
2859** 4 4 signed integer
2860** 5 6 signed integer
2861** 6 8 signed integer
2862** 7 8 IEEE float
drhd946db02005-12-29 19:23:06 +00002863** 8 0 Integer constant 0
2864** 9 0 Integer constant 1
2865** 10,11 reserved for expansion
danielk197790e4d952004-05-10 10:05:53 +00002866** N>=12 and even (N-12)/2 BLOB
2867** N>=13 and odd (N-13)/2 text
2868**
drh35a59652006-01-02 18:24:40 +00002869** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2870** of SQLite will not understand those serial types.
danielk197790e4d952004-05-10 10:05:53 +00002871*/
2872
2873/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002874** Return the serial-type for the value stored in pMem.
danielk1977192ac1d2004-05-10 07:17:30 +00002875*/
drhd946db02005-12-29 19:23:06 +00002876u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
danielk1977cfcdaef2004-05-12 07:33:33 +00002877 int flags = pMem->flags;
drheac5bd72014-07-25 21:35:39 +00002878 u32 n;
danielk1977cfcdaef2004-05-12 07:33:33 +00002879
2880 if( flags&MEM_Null ){
drha19b7752004-05-30 21:14:58 +00002881 return 0;
danielk197790e4d952004-05-10 10:05:53 +00002882 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002883 if( flags&MEM_Int ){
drhfe2093d2005-01-20 22:48:47 +00002884 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
drh5284a052008-05-08 15:18:10 +00002885# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
drh3c024d62007-03-30 11:23:45 +00002886 i64 i = pMem->u.i;
drhd946db02005-12-29 19:23:06 +00002887 u64 u;
drhcfd654b2011-03-05 13:54:15 +00002888 if( i<0 ){
drh1b40e632014-11-20 02:58:10 +00002889 u = ~i;
drhcfd654b2011-03-05 13:54:15 +00002890 }else{
2891 u = i;
2892 }
drh56690b32012-09-17 15:36:31 +00002893 if( u<=127 ){
2894 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
2895 }
drh5742b632005-01-26 17:47:02 +00002896 if( u<=32767 ) return 2;
2897 if( u<=8388607 ) return 3;
2898 if( u<=2147483647 ) return 4;
2899 if( u<=MAX_6BYTE ) return 5;
drha19b7752004-05-30 21:14:58 +00002900 return 6;
danielk197790e4d952004-05-10 10:05:53 +00002901 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002902 if( flags&MEM_Real ){
drha19b7752004-05-30 21:14:58 +00002903 return 7;
danielk197790e4d952004-05-10 10:05:53 +00002904 }
danielk1977e4359752008-11-03 09:39:45 +00002905 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
drheac5bd72014-07-25 21:35:39 +00002906 assert( pMem->n>=0 );
2907 n = (u32)pMem->n;
drhfdf972a2007-05-02 13:30:27 +00002908 if( flags & MEM_Zero ){
drh8df32842008-12-09 02:51:23 +00002909 n += pMem->u.nZero;
danielk197790e4d952004-05-10 10:05:53 +00002910 }
drhfdf972a2007-05-02 13:30:27 +00002911 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
danielk1977192ac1d2004-05-10 07:17:30 +00002912}
2913
2914/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002915** Return the length of the data corresponding to the supplied serial-type.
danielk1977192ac1d2004-05-10 07:17:30 +00002916*/
drh35cd6432009-06-05 14:17:21 +00002917u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
drha19b7752004-05-30 21:14:58 +00002918 if( serial_type>=12 ){
drh51846b52004-05-28 16:00:21 +00002919 return (serial_type-12)/2;
2920 }else{
drh57196282004-10-06 15:41:16 +00002921 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
drh51846b52004-05-28 16:00:21 +00002922 return aSize[serial_type];
2923 }
danielk1977192ac1d2004-05-10 07:17:30 +00002924}
2925
2926/*
drh110daac2007-05-04 11:59:31 +00002927** If we are on an architecture with mixed-endian floating
drh7a4f5022007-05-23 07:20:08 +00002928** points (ex: ARM7) then swap the lower 4 bytes with the
drh110daac2007-05-04 11:59:31 +00002929** upper 4 bytes. Return the result.
2930**
drh7a4f5022007-05-23 07:20:08 +00002931** For most architectures, this is a no-op.
2932**
2933** (later): It is reported to me that the mixed-endian problem
2934** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2935** that early versions of GCC stored the two words of a 64-bit
2936** float in the wrong order. And that error has been propagated
2937** ever since. The blame is not necessarily with GCC, though.
2938** GCC might have just copying the problem from a prior compiler.
2939** I am also told that newer versions of GCC that follow a different
2940** ABI get the byte order right.
2941**
2942** Developers using SQLite on an ARM7 should compile and run their
2943** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2944** enabled, some asserts below will ensure that the byte order of
2945** floating point values is correct.
drh60d09a72007-08-30 15:05:08 +00002946**
2947** (2007-08-30) Frank van Vugt has studied this problem closely
2948** and has send his findings to the SQLite developers. Frank
2949** writes that some Linux kernels offer floating point hardware
2950** emulation that uses only 32-bit mantissas instead of a full
2951** 48-bits as required by the IEEE standard. (This is the
2952** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2953** byte swapping becomes very complicated. To avoid problems,
2954** the necessary byte swapping is carried out using a 64-bit integer
2955** rather than a 64-bit float. Frank assures us that the code here
2956** works for him. We, the developers, have no way to independently
2957** verify this, but Frank seems to know what he is talking about
2958** so we trust him.
drh110daac2007-05-04 11:59:31 +00002959*/
2960#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
drh60d09a72007-08-30 15:05:08 +00002961static u64 floatSwap(u64 in){
drh110daac2007-05-04 11:59:31 +00002962 union {
drh60d09a72007-08-30 15:05:08 +00002963 u64 r;
drh110daac2007-05-04 11:59:31 +00002964 u32 i[2];
2965 } u;
2966 u32 t;
2967
2968 u.r = in;
2969 t = u.i[0];
2970 u.i[0] = u.i[1];
2971 u.i[1] = t;
2972 return u.r;
2973}
2974# define swapMixedEndianFloat(X) X = floatSwap(X)
2975#else
2976# define swapMixedEndianFloat(X)
2977#endif
2978
2979/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002980** Write the serialized data blob for the value stored in pMem into
2981** buf. It is assumed that the caller has allocated sufficient space.
2982** Return the number of bytes written.
drhfdf972a2007-05-02 13:30:27 +00002983**
drh038b7bc2013-12-09 23:17:22 +00002984** nBuf is the amount of space left in buf[]. The caller is responsible
2985** for allocating enough space to buf[] to hold the entire field, exclusive
2986** of the pMem->u.nZero bytes for a MEM_Zero value.
drhfdf972a2007-05-02 13:30:27 +00002987**
2988** Return the number of bytes actually written into buf[]. The number
2989** of bytes in the zero-filled tail is included in the return value only
2990** if those bytes were zeroed in buf[].
danielk1977cfcdaef2004-05-12 07:33:33 +00002991*/
drha9ab4812013-12-11 11:00:44 +00002992u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
drh35cd6432009-06-05 14:17:21 +00002993 u32 len;
danielk1977183f9f72004-05-13 05:20:26 +00002994
drh1483e142004-05-21 21:12:42 +00002995 /* Integer and Real */
drhd946db02005-12-29 19:23:06 +00002996 if( serial_type<=7 && serial_type>0 ){
drh1483e142004-05-21 21:12:42 +00002997 u64 v;
drh35cd6432009-06-05 14:17:21 +00002998 u32 i;
drha19b7752004-05-30 21:14:58 +00002999 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00003000 assert( sizeof(v)==sizeof(pMem->u.r) );
3001 memcpy(&v, &pMem->u.r, sizeof(v));
drh60d09a72007-08-30 15:05:08 +00003002 swapMixedEndianFloat(v);
drh1483e142004-05-21 21:12:42 +00003003 }else{
drh3c024d62007-03-30 11:23:45 +00003004 v = pMem->u.i;
danielk1977cfcdaef2004-05-12 07:33:33 +00003005 }
drh1483e142004-05-21 21:12:42 +00003006 len = i = sqlite3VdbeSerialTypeLen(serial_type);
drh3f5b1992014-08-22 13:22:32 +00003007 assert( i>0 );
3008 do{
3009 buf[--i] = (u8)(v&0xFF);
drh1483e142004-05-21 21:12:42 +00003010 v >>= 8;
drh3f5b1992014-08-22 13:22:32 +00003011 }while( i );
drh1483e142004-05-21 21:12:42 +00003012 return len;
danielk1977cfcdaef2004-05-12 07:33:33 +00003013 }
drhd946db02005-12-29 19:23:06 +00003014
danielk1977cfcdaef2004-05-12 07:33:33 +00003015 /* String or blob */
drhd946db02005-12-29 19:23:06 +00003016 if( serial_type>=12 ){
drh8df32842008-12-09 02:51:23 +00003017 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
shane75ac1de2009-06-09 18:58:52 +00003018 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
drhfdf972a2007-05-02 13:30:27 +00003019 len = pMem->n;
drhd946db02005-12-29 19:23:06 +00003020 memcpy(buf, pMem->z, len);
3021 return len;
3022 }
3023
3024 /* NULL or constants 0 or 1 */
3025 return 0;
danielk1977cfcdaef2004-05-12 07:33:33 +00003026}
3027
drhf926d1e2014-03-04 04:04:33 +00003028/* Input "x" is a sequence of unsigned characters that represent a
3029** big-endian integer. Return the equivalent native integer
3030*/
3031#define ONE_BYTE_INT(x) ((i8)(x)[0])
3032#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
3033#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3034#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drh8932bec2014-08-22 14:56:13 +00003035#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
drhf926d1e2014-03-04 04:04:33 +00003036
danielk1977cfcdaef2004-05-12 07:33:33 +00003037/*
3038** Deserialize the data blob pointed to by buf as serial type serial_type
3039** and store the result in pMem. Return the number of bytes read.
drh14a924a2014-08-22 14:34:05 +00003040**
3041** This function is implemented as two separate routines for performance.
3042** The few cases that require local variables are broken out into a separate
3043** routine so that in most cases the overhead of moving the stack pointer
3044** is avoided.
danielk1977cfcdaef2004-05-12 07:33:33 +00003045*/
drh14a924a2014-08-22 14:34:05 +00003046static u32 SQLITE_NOINLINE serialGet(
danielk197793d46752004-05-23 13:30:58 +00003047 const unsigned char *buf, /* Buffer to deserialize from */
drh25aa1b42004-05-28 01:39:01 +00003048 u32 serial_type, /* Serial type to deserialize */
3049 Mem *pMem /* Memory cell to write value into */
danielk1977b1bc9532004-05-22 03:05:33 +00003050){
drh8932bec2014-08-22 14:56:13 +00003051 u64 x = FOUR_BYTE_UINT(buf);
3052 u32 y = FOUR_BYTE_UINT(buf+4);
3053 x = (x<<32) + y;
drh14a924a2014-08-22 14:34:05 +00003054 if( serial_type==6 ){
drh654858d2014-11-20 02:18:14 +00003055 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3056 ** twos-complement integer. */
drh14a924a2014-08-22 14:34:05 +00003057 pMem->u.i = *(i64*)&x;
3058 pMem->flags = MEM_Int;
3059 testcase( pMem->u.i<0 );
3060 }else{
drh654858d2014-11-20 02:18:14 +00003061 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3062 ** floating point number. */
drh14a924a2014-08-22 14:34:05 +00003063#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
3064 /* Verify that integers and floating point values use the same
3065 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
3066 ** defined that 64-bit floating point values really are mixed
3067 ** endian.
3068 */
3069 static const u64 t1 = ((u64)0x3ff00000)<<32;
3070 static const double r1 = 1.0;
3071 u64 t2 = t1;
3072 swapMixedEndianFloat(t2);
3073 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
3074#endif
drh74eaba42014-09-18 17:52:15 +00003075 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
drh14a924a2014-08-22 14:34:05 +00003076 swapMixedEndianFloat(x);
drh74eaba42014-09-18 17:52:15 +00003077 memcpy(&pMem->u.r, &x, sizeof(x));
3078 pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
drh14a924a2014-08-22 14:34:05 +00003079 }
3080 return 8;
3081}
danielk1977b1bc9532004-05-22 03:05:33 +00003082u32 sqlite3VdbeSerialGet(
3083 const unsigned char *buf, /* Buffer to deserialize from */
3084 u32 serial_type, /* Serial type to deserialize */
3085 Mem *pMem /* Memory cell to write value into */
3086){
drh3c685822005-05-21 18:32:18 +00003087 switch( serial_type ){
drh3c685822005-05-21 18:32:18 +00003088 case 10: /* Reserved for future use */
3089 case 11: /* Reserved for future use */
drh654858d2014-11-20 02:18:14 +00003090 case 0: { /* Null */
3091 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
drh3c685822005-05-21 18:32:18 +00003092 pMem->flags = MEM_Null;
3093 break;
3094 }
drh654858d2014-11-20 02:18:14 +00003095 case 1: {
3096 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3097 ** integer. */
drhf926d1e2014-03-04 04:04:33 +00003098 pMem->u.i = ONE_BYTE_INT(buf);
drh1483e142004-05-21 21:12:42 +00003099 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003100 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003101 return 1;
drh1483e142004-05-21 21:12:42 +00003102 }
drh3c685822005-05-21 18:32:18 +00003103 case 2: { /* 2-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003104 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3105 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003106 pMem->u.i = TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003107 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003108 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003109 return 2;
3110 }
3111 case 3: { /* 3-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003112 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3113 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003114 pMem->u.i = THREE_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003115 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003116 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003117 return 3;
3118 }
3119 case 4: { /* 4-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003120 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3121 ** twos-complement integer. */
drh8932bec2014-08-22 14:56:13 +00003122 pMem->u.i = FOUR_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003123 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003124 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003125 return 4;
3126 }
3127 case 5: { /* 6-byte signed integer */
drh654858d2014-11-20 02:18:14 +00003128 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3129 ** twos-complement integer. */
drhf926d1e2014-03-04 04:04:33 +00003130 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
drh3c685822005-05-21 18:32:18 +00003131 pMem->flags = MEM_Int;
drhb6e8fd12014-03-06 01:56:33 +00003132 testcase( pMem->u.i<0 );
drh3c685822005-05-21 18:32:18 +00003133 return 6;
3134 }
drh91124b32005-08-18 18:15:05 +00003135 case 6: /* 8-byte signed integer */
drh3c685822005-05-21 18:32:18 +00003136 case 7: { /* IEEE floating point */
drh8932bec2014-08-22 14:56:13 +00003137 /* These use local variables, so do them in a separate routine
3138 ** to avoid having to move the frame pointer in the common case */
drh14a924a2014-08-22 14:34:05 +00003139 return serialGet(buf,serial_type,pMem);
drh3c685822005-05-21 18:32:18 +00003140 }
drhd946db02005-12-29 19:23:06 +00003141 case 8: /* Integer 0 */
3142 case 9: { /* Integer 1 */
drh654858d2014-11-20 02:18:14 +00003143 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
3144 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
drh3c024d62007-03-30 11:23:45 +00003145 pMem->u.i = serial_type-8;
drhd946db02005-12-29 19:23:06 +00003146 pMem->flags = MEM_Int;
3147 return 0;
3148 }
drh3c685822005-05-21 18:32:18 +00003149 default: {
drh654858d2014-11-20 02:18:14 +00003150 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
3151 ** length.
3152 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
3153 ** (N-13)/2 bytes in length. */
drhc138daf2013-11-19 13:55:34 +00003154 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
drh3c685822005-05-21 18:32:18 +00003155 pMem->z = (char *)buf;
drh14a924a2014-08-22 14:34:05 +00003156 pMem->n = (serial_type-12)/2;
drhc138daf2013-11-19 13:55:34 +00003157 pMem->flags = aFlag[serial_type&1];
drh14a924a2014-08-22 14:34:05 +00003158 return pMem->n;
drh696b32f2004-05-30 01:51:52 +00003159 }
danielk1977cfcdaef2004-05-12 07:33:33 +00003160 }
drh3c685822005-05-21 18:32:18 +00003161 return 0;
danielk1977192ac1d2004-05-10 07:17:30 +00003162}
drh1e968a02008-03-25 00:22:21 +00003163/*
dan03e9cfc2011-09-05 14:20:27 +00003164** This routine is used to allocate sufficient space for an UnpackedRecord
3165** structure large enough to be used with sqlite3VdbeRecordUnpack() if
3166** the first argument is a pointer to KeyInfo structure pKeyInfo.
drh1e968a02008-03-25 00:22:21 +00003167**
dan03e9cfc2011-09-05 14:20:27 +00003168** The space is either allocated using sqlite3DbMallocRaw() or from within
3169** the unaligned buffer passed via the second and third arguments (presumably
3170** stack space). If the former, then *ppFree is set to a pointer that should
3171** be eventually freed by the caller using sqlite3DbFree(). Or, if the
3172** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
3173** before returning.
drh1e968a02008-03-25 00:22:21 +00003174**
dan03e9cfc2011-09-05 14:20:27 +00003175** If an OOM error occurs, NULL is returned.
3176*/
3177UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
3178 KeyInfo *pKeyInfo, /* Description of the record */
3179 char *pSpace, /* Unaligned space available */
3180 int szSpace, /* Size of pSpace[] in bytes */
3181 char **ppFree /* OUT: Caller should free this pointer */
drh1e968a02008-03-25 00:22:21 +00003182){
dan03e9cfc2011-09-05 14:20:27 +00003183 UnpackedRecord *p; /* Unpacked record to return */
3184 int nOff; /* Increment pSpace by nOff to align it */
3185 int nByte; /* Number of bytes required for *p */
3186
3187 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
shane80167bf2009-04-10 15:42:36 +00003188 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
3189 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
3190 */
3191 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
drh8c5d1522009-04-10 00:56:28 +00003192 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
dan42acb3e2011-09-05 20:16:38 +00003193 if( nByte>szSpace+nOff ){
dan03e9cfc2011-09-05 14:20:27 +00003194 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3195 *ppFree = (char *)p;
dan42acb3e2011-09-05 20:16:38 +00003196 if( !p ) return 0;
drh1e968a02008-03-25 00:22:21 +00003197 }else{
dan42acb3e2011-09-05 20:16:38 +00003198 p = (UnpackedRecord*)&pSpace[nOff];
dan03e9cfc2011-09-05 14:20:27 +00003199 *ppFree = 0;
drh1e968a02008-03-25 00:22:21 +00003200 }
dan42acb3e2011-09-05 20:16:38 +00003201
3202 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
drhe1a022e2012-09-17 17:16:53 +00003203 assert( pKeyInfo->aSortOrder!=0 );
drh1e968a02008-03-25 00:22:21 +00003204 p->pKeyInfo = pKeyInfo;
3205 p->nField = pKeyInfo->nField + 1;
dan03e9cfc2011-09-05 14:20:27 +00003206 return p;
3207}
3208
3209/*
3210** Given the nKey-byte encoding of a record in pKey[], populate the
3211** UnpackedRecord structure indicated by the fourth argument with the
3212** contents of the decoded record.
3213*/
3214void sqlite3VdbeRecordUnpack(
3215 KeyInfo *pKeyInfo, /* Information about the record format */
3216 int nKey, /* Size of the binary record */
3217 const void *pKey, /* The binary record */
3218 UnpackedRecord *p /* Populate this structure before returning. */
3219){
3220 const unsigned char *aKey = (const unsigned char *)pKey;
3221 int d;
3222 u32 idx; /* Offset in aKey[] to read from */
3223 u16 u; /* Unsigned loop counter */
3224 u32 szHdr;
dan42acb3e2011-09-05 20:16:38 +00003225 Mem *pMem = p->aMem;
dan03e9cfc2011-09-05 14:20:27 +00003226
dan1fed5da2014-02-25 21:01:25 +00003227 p->default_rc = 0;
drh8c5d1522009-04-10 00:56:28 +00003228 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
shane3f8d5cf2008-04-24 19:15:09 +00003229 idx = getVarint32(aKey, szHdr);
drh1e968a02008-03-25 00:22:21 +00003230 d = szHdr;
shane0b8d2762008-07-22 05:18:00 +00003231 u = 0;
drh7f4b19f2014-09-16 13:30:05 +00003232 while( idx<szHdr && d<=nKey ){
drh1e968a02008-03-25 00:22:21 +00003233 u32 serial_type;
3234
danielk197700e13612008-11-17 19:18:54 +00003235 idx += getVarint32(&aKey[idx], serial_type);
drh1e968a02008-03-25 00:22:21 +00003236 pMem->enc = pKeyInfo->enc;
3237 pMem->db = pKeyInfo->db;
drhc3f1d5f2011-05-30 23:42:16 +00003238 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
drh17bcb102014-09-18 21:25:33 +00003239 pMem->szMalloc = 0;
drh1e968a02008-03-25 00:22:21 +00003240 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
drhe14006d2008-03-25 17:23:32 +00003241 pMem++;
drh7f4b19f2014-09-16 13:30:05 +00003242 if( (++u)>=p->nField ) break;
drh1e968a02008-03-25 00:22:21 +00003243 }
drh7d10d5a2008-08-20 16:35:10 +00003244 assert( u<=pKeyInfo->nField + 1 );
shane0b8d2762008-07-22 05:18:00 +00003245 p->nField = u;
drh1e968a02008-03-25 00:22:21 +00003246}
3247
dan3833e932014-03-01 19:44:56 +00003248#if SQLITE_DEBUG
dan3b9330f2014-02-27 20:44:18 +00003249/*
dan3833e932014-03-01 19:44:56 +00003250** This function compares two index or table record keys in the same way
3251** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
3252** this function deserializes and compares values using the
3253** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
3254** in assert() statements to ensure that the optimized code in
3255** sqlite3VdbeRecordCompare() returns results with these two primitives.
drh79211e12014-05-02 17:33:16 +00003256**
3257** Return true if the result of comparison is equivalent to desiredResult.
3258** Return false if there is a disagreement.
dan3b9330f2014-02-27 20:44:18 +00003259*/
dan3833e932014-03-01 19:44:56 +00003260static int vdbeRecordCompareDebug(
dan1fed5da2014-02-25 21:01:25 +00003261 int nKey1, const void *pKey1, /* Left key */
drh79211e12014-05-02 17:33:16 +00003262 const UnpackedRecord *pPKey2, /* Right key */
3263 int desiredResult /* Correct answer */
dan1fed5da2014-02-25 21:01:25 +00003264){
dan3b9330f2014-02-27 20:44:18 +00003265 u32 d1; /* Offset into aKey[] of next data element */
3266 u32 idx1; /* Offset into aKey[] of next header element */
3267 u32 szHdr1; /* Number of bytes in header */
3268 int i = 0;
3269 int rc = 0;
3270 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3271 KeyInfo *pKeyInfo;
3272 Mem mem1;
dan1fed5da2014-02-25 21:01:25 +00003273
dan3b9330f2014-02-27 20:44:18 +00003274 pKeyInfo = pPKey2->pKeyInfo;
drh84de6902014-05-02 18:46:52 +00003275 if( pKeyInfo->db==0 ) return 1;
dan3b9330f2014-02-27 20:44:18 +00003276 mem1.enc = pKeyInfo->enc;
3277 mem1.db = pKeyInfo->db;
3278 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
drh17bcb102014-09-18 21:25:33 +00003279 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003280
dan3b9330f2014-02-27 20:44:18 +00003281 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3282 ** We could initialize it, as shown here, to silence those complaints.
3283 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
3284 ** the unnecessary initialization has a measurable negative performance
3285 ** impact, since this routine is a very high runner. And so, we choose
3286 ** to ignore the compiler warnings and leave this variable uninitialized.
3287 */
3288 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
3289
3290 idx1 = getVarint32(aKey1, szHdr1);
3291 d1 = szHdr1;
3292 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
3293 assert( pKeyInfo->aSortOrder!=0 );
3294 assert( pKeyInfo->nField>0 );
3295 assert( idx1<=szHdr1 || CORRUPT_DB );
3296 do{
3297 u32 serial_type1;
dan1fed5da2014-02-25 21:01:25 +00003298
dan3b9330f2014-02-27 20:44:18 +00003299 /* Read the serial types for the next element in each key. */
3300 idx1 += getVarint32( aKey1+idx1, serial_type1 );
dan1fed5da2014-02-25 21:01:25 +00003301
dan3b9330f2014-02-27 20:44:18 +00003302 /* Verify that there is enough key space remaining to avoid
3303 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3304 ** always be greater than or equal to the amount of required key space.
3305 ** Use that approximation to avoid the more expensive call to
3306 ** sqlite3VdbeSerialTypeLen() in the common case.
3307 */
3308 if( d1+serial_type1+2>(u32)nKey1
3309 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3310 ){
3311 break;
dan1fed5da2014-02-25 21:01:25 +00003312 }
dan1fed5da2014-02-25 21:01:25 +00003313
dan3b9330f2014-02-27 20:44:18 +00003314 /* Extract the values to be compared.
3315 */
3316 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
dan1fed5da2014-02-25 21:01:25 +00003317
dan3b9330f2014-02-27 20:44:18 +00003318 /* Do the comparison
3319 */
3320 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
3321 if( rc!=0 ){
drh17bcb102014-09-18 21:25:33 +00003322 assert( mem1.szMalloc==0 ); /* See comment below */
dan3b9330f2014-02-27 20:44:18 +00003323 if( pKeyInfo->aSortOrder[i] ){
3324 rc = -rc; /* Invert the result for DESC sort order. */
dan1fed5da2014-02-25 21:01:25 +00003325 }
drh79211e12014-05-02 17:33:16 +00003326 goto debugCompareEnd;
dan1fed5da2014-02-25 21:01:25 +00003327 }
dan3b9330f2014-02-27 20:44:18 +00003328 i++;
3329 }while( idx1<szHdr1 && i<pPKey2->nField );
dan1fed5da2014-02-25 21:01:25 +00003330
dan3b9330f2014-02-27 20:44:18 +00003331 /* No memory allocation is ever used on mem1. Prove this using
3332 ** the following assert(). If the assert() fails, it indicates a
3333 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
3334 */
drh17bcb102014-09-18 21:25:33 +00003335 assert( mem1.szMalloc==0 );
dan3b9330f2014-02-27 20:44:18 +00003336
3337 /* rc==0 here means that one of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003338 ** all the fields up to that point were equal. Return the default_rc
dan3b9330f2014-02-27 20:44:18 +00003339 ** value. */
drh79211e12014-05-02 17:33:16 +00003340 rc = pPKey2->default_rc;
3341
3342debugCompareEnd:
3343 if( desiredResult==0 && rc==0 ) return 1;
3344 if( desiredResult<0 && rc<0 ) return 1;
3345 if( desiredResult>0 && rc>0 ) return 1;
3346 if( CORRUPT_DB ) return 1;
3347 if( pKeyInfo->db->mallocFailed ) return 1;
3348 return 0;
dan1fed5da2014-02-25 21:01:25 +00003349}
dan3833e932014-03-01 19:44:56 +00003350#endif
dan1fed5da2014-02-25 21:01:25 +00003351
drhe1bb8022015-01-19 19:48:52 +00003352#if SQLITE_DEBUG
3353/*
3354** Count the number of fields (a.k.a. columns) in the record given by
3355** pKey,nKey. The verify that this count is less than or equal to the
3356** limit given by pKeyInfo->nField + pKeyInfo->nXField.
3357**
3358** If this constraint is not satisfied, it means that the high-speed
3359** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
3360** not work correctly. If this assert() ever fires, it probably means
3361** that the KeyInfo.nField or KeyInfo.nXField values were computed
3362** incorrectly.
3363*/
3364static void vdbeAssertFieldCountWithinLimits(
3365 int nKey, const void *pKey, /* The record to verify */
3366 const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
3367){
3368 int nField = 0;
3369 u32 szHdr;
3370 u32 idx;
3371 u32 notUsed;
3372 const unsigned char *aKey = (const unsigned char*)pKey;
3373
3374 if( CORRUPT_DB ) return;
3375 idx = getVarint32(aKey, szHdr);
mistachkin1b3ee492015-01-21 00:51:08 +00003376 assert( nKey>=0 );
3377 assert( szHdr<=(u32)nKey );
drhe1bb8022015-01-19 19:48:52 +00003378 while( idx<szHdr ){
3379 idx += getVarint32(aKey+idx, notUsed);
3380 nField++;
3381 }
3382 assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
3383}
drh1af3c642015-01-19 20:57:19 +00003384#else
3385# define vdbeAssertFieldCountWithinLimits(A,B,C)
drhe1bb8022015-01-19 19:48:52 +00003386#endif
3387
dan3833e932014-03-01 19:44:56 +00003388/*
3389** Both *pMem1 and *pMem2 contain string values. Compare the two values
3390** using the collation sequence pColl. As usual, return a negative , zero
3391** or positive value if *pMem1 is less than, equal to or greater than
3392** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
3393*/
dan1fed5da2014-02-25 21:01:25 +00003394static int vdbeCompareMemString(
dan3833e932014-03-01 19:44:56 +00003395 const Mem *pMem1,
3396 const Mem *pMem2,
dan38fdead2014-04-01 10:19:02 +00003397 const CollSeq *pColl,
3398 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
dan1fed5da2014-02-25 21:01:25 +00003399){
3400 if( pMem1->enc==pColl->enc ){
3401 /* The strings are already in the correct encoding. Call the
3402 ** comparison function directly */
3403 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
3404 }else{
3405 int rc;
3406 const void *v1, *v2;
3407 int n1, n2;
3408 Mem c1;
3409 Mem c2;
drh17bcb102014-09-18 21:25:33 +00003410 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
3411 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
dan1fed5da2014-02-25 21:01:25 +00003412 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
3413 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
3414 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
3415 n1 = v1==0 ? 0 : c1.n;
3416 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
3417 n2 = v2==0 ? 0 : c2.n;
3418 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
3419 sqlite3VdbeMemRelease(&c1);
3420 sqlite3VdbeMemRelease(&c2);
dan38fdead2014-04-01 10:19:02 +00003421 if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
dan1fed5da2014-02-25 21:01:25 +00003422 return rc;
3423 }
3424}
3425
3426/*
drh982ff722014-09-16 03:24:43 +00003427** Compare two blobs. Return negative, zero, or positive if the first
3428** is less than, equal to, or greater than the second, respectively.
3429** If one blob is a prefix of the other, then the shorter is the lessor.
3430*/
3431static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
3432 int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
3433 if( c ) return c;
3434 return pB1->n - pB2->n;
3435}
3436
3437
3438/*
dan1fed5da2014-02-25 21:01:25 +00003439** Compare the values contained by the two memory cells, returning
3440** negative, zero or positive if pMem1 is less than, equal to, or greater
3441** than pMem2. Sorting order is NULL's first, followed by numbers (integers
3442** and reals) sorted numerically, followed by text ordered by the collating
3443** sequence pColl and finally blob's ordered by memcmp().
3444**
3445** Two NULL values are considered equal by this function.
3446*/
3447int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
dan1fed5da2014-02-25 21:01:25 +00003448 int f1, f2;
3449 int combined_flags;
3450
3451 f1 = pMem1->flags;
3452 f2 = pMem2->flags;
3453 combined_flags = f1|f2;
3454 assert( (combined_flags & MEM_RowSet)==0 );
3455
3456 /* If one value is NULL, it is less than the other. If both values
3457 ** are NULL, return 0.
3458 */
3459 if( combined_flags&MEM_Null ){
3460 return (f2&MEM_Null) - (f1&MEM_Null);
3461 }
3462
3463 /* If one value is a number and the other is not, the number is less.
3464 ** If both are numbers, compare as reals if one is a real, or as integers
3465 ** if both values are integers.
3466 */
3467 if( combined_flags&(MEM_Int|MEM_Real) ){
3468 double r1, r2;
3469 if( (f1 & f2 & MEM_Int)!=0 ){
3470 if( pMem1->u.i < pMem2->u.i ) return -1;
3471 if( pMem1->u.i > pMem2->u.i ) return 1;
3472 return 0;
3473 }
3474 if( (f1&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003475 r1 = pMem1->u.r;
dan1fed5da2014-02-25 21:01:25 +00003476 }else if( (f1&MEM_Int)!=0 ){
3477 r1 = (double)pMem1->u.i;
3478 }else{
3479 return 1;
3480 }
3481 if( (f2&MEM_Real)!=0 ){
drh74eaba42014-09-18 17:52:15 +00003482 r2 = pMem2->u.r;
dan1fed5da2014-02-25 21:01:25 +00003483 }else if( (f2&MEM_Int)!=0 ){
3484 r2 = (double)pMem2->u.i;
3485 }else{
3486 return -1;
3487 }
3488 if( r1<r2 ) return -1;
3489 if( r1>r2 ) return 1;
3490 return 0;
3491 }
3492
3493 /* If one value is a string and the other is a blob, the string is less.
3494 ** If both are strings, compare using the collating functions.
3495 */
3496 if( combined_flags&MEM_Str ){
3497 if( (f1 & MEM_Str)==0 ){
3498 return 1;
3499 }
3500 if( (f2 & MEM_Str)==0 ){
3501 return -1;
3502 }
3503
3504 assert( pMem1->enc==pMem2->enc );
3505 assert( pMem1->enc==SQLITE_UTF8 ||
3506 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
3507
3508 /* The collation sequence must be defined at this point, even if
3509 ** the user deletes the collation sequence after the vdbe program is
3510 ** compiled (this was not always the case).
3511 */
3512 assert( !pColl || pColl->xCmp );
3513
3514 if( pColl ){
dan38fdead2014-04-01 10:19:02 +00003515 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
dan1fed5da2014-02-25 21:01:25 +00003516 }
3517 /* If a NULL pointer was passed as the collate function, fall through
3518 ** to the blob case and use memcmp(). */
3519 }
3520
3521 /* Both values must be blobs. Compare using memcmp(). */
drh982ff722014-09-16 03:24:43 +00003522 return sqlite3BlobCompare(pMem1, pMem2);
dan1fed5da2014-02-25 21:01:25 +00003523}
3524
3525
dan3833e932014-03-01 19:44:56 +00003526/*
3527** The first argument passed to this function is a serial-type that
3528** corresponds to an integer - all values between 1 and 9 inclusive
3529** except 7. The second points to a buffer containing an integer value
3530** serialized according to serial_type. This function deserializes
3531** and returns the value.
3532*/
dan3b9330f2014-02-27 20:44:18 +00003533static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
drhf926d1e2014-03-04 04:04:33 +00003534 u32 y;
dan3833e932014-03-01 19:44:56 +00003535 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
dan3b9330f2014-02-27 20:44:18 +00003536 switch( serial_type ){
dan3833e932014-03-01 19:44:56 +00003537 case 0:
dan3b9330f2014-02-27 20:44:18 +00003538 case 1:
drhb6e8fd12014-03-06 01:56:33 +00003539 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003540 return ONE_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003541 case 2:
drhb6e8fd12014-03-06 01:56:33 +00003542 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003543 return TWO_BYTE_INT(aKey);
dan3b9330f2014-02-27 20:44:18 +00003544 case 3:
drhb6e8fd12014-03-06 01:56:33 +00003545 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003546 return THREE_BYTE_INT(aKey);
3547 case 4: {
drhb6e8fd12014-03-06 01:56:33 +00003548 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003549 y = FOUR_BYTE_UINT(aKey);
3550 return (i64)*(int*)&y;
3551 }
dan3b9330f2014-02-27 20:44:18 +00003552 case 5: {
drhb6e8fd12014-03-06 01:56:33 +00003553 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003554 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhaf5b2af2013-08-05 15:32:09 +00003555 }
dan3b9330f2014-02-27 20:44:18 +00003556 case 6: {
drhf926d1e2014-03-04 04:04:33 +00003557 u64 x = FOUR_BYTE_UINT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003558 testcase( aKey[0]&0x80 );
drhf926d1e2014-03-04 04:04:33 +00003559 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3560 return (i64)*(i64*)&x;
drh1e968a02008-03-25 00:22:21 +00003561 }
dan3b9330f2014-02-27 20:44:18 +00003562 }
drh407414c2009-07-14 14:15:27 +00003563
dan3b9330f2014-02-27 20:44:18 +00003564 return (serial_type - 8);
drh1e968a02008-03-25 00:22:21 +00003565}
danielk1977eb015e02004-05-18 01:31:14 +00003566
dan3833e932014-03-01 19:44:56 +00003567/*
3568** This function compares the two table rows or index records
3569** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
3570** or positive integer if key1 is less than, equal to or
3571** greater than key2. The {nKey1, pKey1} key must be a blob
peter.d.reid60ec9142014-09-06 16:39:46 +00003572** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
dan3833e932014-03-01 19:44:56 +00003573** key must be a parsed key such as obtained from
3574** sqlite3VdbeParseRecord.
3575**
3576** If argument bSkip is non-zero, it is assumed that the caller has already
3577** determined that the first fields of the keys are equal.
3578**
3579** Key1 and Key2 do not have to contain the same number of fields. If all
3580** fields that appear in both keys are equal, then pPKey2->default_rc is
3581** returned.
drha1f7c0a2014-03-28 03:12:48 +00003582**
dan38fdead2014-04-01 10:19:02 +00003583** If database corruption is discovered, set pPKey2->errCode to
3584** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
3585** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
3586** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
dan3833e932014-03-01 19:44:56 +00003587*/
drh75179de2014-09-16 14:37:35 +00003588static int vdbeRecordCompareWithSkip(
dan3833e932014-03-01 19:44:56 +00003589 int nKey1, const void *pKey1, /* Left key */
drha1f7c0a2014-03-28 03:12:48 +00003590 UnpackedRecord *pPKey2, /* Right key */
dan3833e932014-03-01 19:44:56 +00003591 int bSkip /* If true, skip the first field */
dan1fed5da2014-02-25 21:01:25 +00003592){
dan3833e932014-03-01 19:44:56 +00003593 u32 d1; /* Offset into aKey[] of next data element */
3594 int i; /* Index of next field to compare */
mistachkinffe6bc22014-03-04 11:16:20 +00003595 u32 szHdr1; /* Size of record header in bytes */
dan3833e932014-03-01 19:44:56 +00003596 u32 idx1; /* Offset of first type in header */
3597 int rc = 0; /* Return value */
3598 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
dan1fed5da2014-02-25 21:01:25 +00003599 KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
3600 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3601 Mem mem1;
3602
dan3833e932014-03-01 19:44:56 +00003603 /* If bSkip is true, then the caller has already determined that the first
3604 ** two elements in the keys are equal. Fix the various stack variables so
dan3b9330f2014-02-27 20:44:18 +00003605 ** that this routine begins comparing at the second field. */
dan3833e932014-03-01 19:44:56 +00003606 if( bSkip ){
dan3b9330f2014-02-27 20:44:18 +00003607 u32 s1;
dan3b9330f2014-02-27 20:44:18 +00003608 idx1 = 1 + getVarint32(&aKey1[1], s1);
dan3833e932014-03-01 19:44:56 +00003609 szHdr1 = aKey1[0];
3610 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
dan3b9330f2014-02-27 20:44:18 +00003611 i = 1;
3612 pRhs++;
dan3833e932014-03-01 19:44:56 +00003613 }else{
3614 idx1 = getVarint32(aKey1, szHdr1);
3615 d1 = szHdr1;
drha1f7c0a2014-03-28 03:12:48 +00003616 if( d1>(unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003617 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003618 return 0; /* Corruption */
3619 }
dan3833e932014-03-01 19:44:56 +00003620 i = 0;
dan3b9330f2014-02-27 20:44:18 +00003621 }
3622
drh17bcb102014-09-18 21:25:33 +00003623 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
dan1fed5da2014-02-25 21:01:25 +00003624 assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
3625 || CORRUPT_DB );
3626 assert( pPKey2->pKeyInfo->aSortOrder!=0 );
3627 assert( pPKey2->pKeyInfo->nField>0 );
3628 assert( idx1<=szHdr1 || CORRUPT_DB );
3629 do{
dan1fed5da2014-02-25 21:01:25 +00003630 u32 serial_type;
3631
3632 /* RHS is an integer */
3633 if( pRhs->flags & MEM_Int ){
3634 serial_type = aKey1[idx1];
drhb6e8fd12014-03-06 01:56:33 +00003635 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003636 if( serial_type>=12 ){
3637 rc = +1;
3638 }else if( serial_type==0 ){
3639 rc = -1;
dan3b9330f2014-02-27 20:44:18 +00003640 }else if( serial_type==7 ){
3641 double rhs = (double)pRhs->u.i;
dan1fed5da2014-02-25 21:01:25 +00003642 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
drh74eaba42014-09-18 17:52:15 +00003643 if( mem1.u.r<rhs ){
dan3b9330f2014-02-27 20:44:18 +00003644 rc = -1;
drh74eaba42014-09-18 17:52:15 +00003645 }else if( mem1.u.r>rhs ){
dan3b9330f2014-02-27 20:44:18 +00003646 rc = +1;
3647 }
3648 }else{
3649 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
3650 i64 rhs = pRhs->u.i;
3651 if( lhs<rhs ){
3652 rc = -1;
3653 }else if( lhs>rhs ){
3654 rc = +1;
dan1fed5da2014-02-25 21:01:25 +00003655 }
3656 }
3657 }
3658
3659 /* RHS is real */
3660 else if( pRhs->flags & MEM_Real ){
3661 serial_type = aKey1[idx1];
3662 if( serial_type>=12 ){
3663 rc = +1;
3664 }else if( serial_type==0 ){
3665 rc = -1;
3666 }else{
drh74eaba42014-09-18 17:52:15 +00003667 double rhs = pRhs->u.r;
dan1fed5da2014-02-25 21:01:25 +00003668 double lhs;
3669 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
3670 if( serial_type==7 ){
drh74eaba42014-09-18 17:52:15 +00003671 lhs = mem1.u.r;
dan1fed5da2014-02-25 21:01:25 +00003672 }else{
drh295aedf2014-03-03 18:25:24 +00003673 lhs = (double)mem1.u.i;
dan1fed5da2014-02-25 21:01:25 +00003674 }
3675 if( lhs<rhs ){
3676 rc = -1;
3677 }else if( lhs>rhs ){
3678 rc = +1;
3679 }
3680 }
3681 }
3682
3683 /* RHS is a string */
3684 else if( pRhs->flags & MEM_Str ){
3685 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003686 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003687 if( serial_type<12 ){
3688 rc = -1;
3689 }else if( !(serial_type & 0x01) ){
3690 rc = +1;
3691 }else{
3692 mem1.n = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003693 testcase( (d1+mem1.n)==(unsigned)nKey1 );
3694 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003695 if( (d1+mem1.n) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003696 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003697 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003698 }else if( pKeyInfo->aColl[i] ){
3699 mem1.enc = pKeyInfo->enc;
3700 mem1.db = pKeyInfo->db;
3701 mem1.flags = MEM_Str;
drhfcb44a82014-03-03 15:13:27 +00003702 mem1.z = (char*)&aKey1[d1];
dan38fdead2014-04-01 10:19:02 +00003703 rc = vdbeCompareMemString(
3704 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
3705 );
dan1fed5da2014-02-25 21:01:25 +00003706 }else{
3707 int nCmp = MIN(mem1.n, pRhs->n);
3708 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3709 if( rc==0 ) rc = mem1.n - pRhs->n;
3710 }
3711 }
3712 }
3713
3714 /* RHS is a blob */
3715 else if( pRhs->flags & MEM_Blob ){
3716 getVarint32(&aKey1[idx1], serial_type);
drhb6e8fd12014-03-06 01:56:33 +00003717 testcase( serial_type==12 );
dan1fed5da2014-02-25 21:01:25 +00003718 if( serial_type<12 || (serial_type & 0x01) ){
3719 rc = -1;
3720 }else{
3721 int nStr = (serial_type - 12) / 2;
drhb6e8fd12014-03-06 01:56:33 +00003722 testcase( (d1+nStr)==(unsigned)nKey1 );
3723 testcase( (d1+nStr+1)==(unsigned)nKey1 );
drh295aedf2014-03-03 18:25:24 +00003724 if( (d1+nStr) > (unsigned)nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003725 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003726 return 0; /* Corruption */
dan1fed5da2014-02-25 21:01:25 +00003727 }else{
3728 int nCmp = MIN(nStr, pRhs->n);
3729 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
3730 if( rc==0 ) rc = nStr - pRhs->n;
3731 }
3732 }
3733 }
3734
3735 /* RHS is null */
3736 else{
3737 serial_type = aKey1[idx1];
3738 rc = (serial_type!=0);
3739 }
3740
3741 if( rc!=0 ){
dan1fed5da2014-02-25 21:01:25 +00003742 if( pKeyInfo->aSortOrder[i] ){
3743 rc = -rc;
dan1fed5da2014-02-25 21:01:25 +00003744 }
drh79211e12014-05-02 17:33:16 +00003745 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
drh17bcb102014-09-18 21:25:33 +00003746 assert( mem1.szMalloc==0 ); /* See comment below */
dan1fed5da2014-02-25 21:01:25 +00003747 return rc;
3748 }
3749
3750 i++;
dan3b9330f2014-02-27 20:44:18 +00003751 pRhs++;
dan1fed5da2014-02-25 21:01:25 +00003752 d1 += sqlite3VdbeSerialTypeLen(serial_type);
3753 idx1 += sqlite3VarintLen(serial_type);
drh295aedf2014-03-03 18:25:24 +00003754 }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
dan1fed5da2014-02-25 21:01:25 +00003755
3756 /* No memory allocation is ever used on mem1. Prove this using
3757 ** the following assert(). If the assert() fails, it indicates a
dan3833e932014-03-01 19:44:56 +00003758 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
drh17bcb102014-09-18 21:25:33 +00003759 assert( mem1.szMalloc==0 );
dan1fed5da2014-02-25 21:01:25 +00003760
3761 /* rc==0 here means that one or both of the keys ran out of fields and
peter.d.reid60ec9142014-09-06 16:39:46 +00003762 ** all the fields up to that point were equal. Return the default_rc
dan1fed5da2014-02-25 21:01:25 +00003763 ** value. */
dan3833e932014-03-01 19:44:56 +00003764 assert( CORRUPT_DB
drh66141812014-06-30 20:25:03 +00003765 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
dan6696ba32014-06-28 19:06:49 +00003766 || pKeyInfo->db->mallocFailed
dan3833e932014-03-01 19:44:56 +00003767 );
dan1fed5da2014-02-25 21:01:25 +00003768 return pPKey2->default_rc;
3769}
drh75179de2014-09-16 14:37:35 +00003770int sqlite3VdbeRecordCompare(
3771 int nKey1, const void *pKey1, /* Left key */
3772 UnpackedRecord *pPKey2 /* Right key */
3773){
3774 return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
3775}
3776
dan1fed5da2014-02-25 21:01:25 +00003777
dan3833e932014-03-01 19:44:56 +00003778/*
3779** This function is an optimized version of sqlite3VdbeRecordCompare()
3780** that (a) the first field of pPKey2 is an integer, and (b) the
3781** size-of-header varint at the start of (pKey1/nKey1) fits in a single
3782** byte (i.e. is less than 128).
drhe2ac5062014-03-26 12:02:38 +00003783**
3784** To avoid concerns about buffer overreads, this routine is only used
3785** on schemas where the maximum valid header size is 63 bytes or less.
dan3833e932014-03-01 19:44:56 +00003786*/
dan3b9330f2014-02-27 20:44:18 +00003787static int vdbeRecordCompareInt(
3788 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003789 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003790){
dan9b8afef2014-03-03 20:48:50 +00003791 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
dan3b9330f2014-02-27 20:44:18 +00003792 int serial_type = ((const u8*)pKey1)[1];
3793 int res;
drhf926d1e2014-03-04 04:04:33 +00003794 u32 y;
3795 u64 x;
dan3b9330f2014-02-27 20:44:18 +00003796 i64 v = pPKey2->aMem[0].u.i;
3797 i64 lhs;
3798
drhe1bb8022015-01-19 19:48:52 +00003799 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
drhe2ac5062014-03-26 12:02:38 +00003800 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
dan3833e932014-03-01 19:44:56 +00003801 switch( serial_type ){
drhf926d1e2014-03-04 04:04:33 +00003802 case 1: { /* 1-byte signed integer */
3803 lhs = ONE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003804 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003805 break;
3806 }
drhf926d1e2014-03-04 04:04:33 +00003807 case 2: { /* 2-byte signed integer */
3808 lhs = TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003809 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003810 break;
3811 }
3812 case 3: { /* 3-byte signed integer */
3813 lhs = THREE_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003814 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003815 break;
3816 }
3817 case 4: { /* 4-byte signed integer */
3818 y = FOUR_BYTE_UINT(aKey);
3819 lhs = (i64)*(int*)&y;
drhb6e8fd12014-03-06 01:56:33 +00003820 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003821 break;
3822 }
3823 case 5: { /* 6-byte signed integer */
3824 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
drhb6e8fd12014-03-06 01:56:33 +00003825 testcase( lhs<0 );
drhf926d1e2014-03-04 04:04:33 +00003826 break;
3827 }
3828 case 6: { /* 8-byte signed integer */
3829 x = FOUR_BYTE_UINT(aKey);
3830 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
3831 lhs = *(i64*)&x;
drhb6e8fd12014-03-06 01:56:33 +00003832 testcase( lhs<0 );
dan3b9330f2014-02-27 20:44:18 +00003833 break;
3834 }
dan3b9330f2014-02-27 20:44:18 +00003835 case 8:
3836 lhs = 0;
3837 break;
dan3b9330f2014-02-27 20:44:18 +00003838 case 9:
3839 lhs = 1;
3840 break;
3841
dan063d4a02014-02-28 09:48:30 +00003842 /* This case could be removed without changing the results of running
3843 ** this code. Including it causes gcc to generate a faster switch
3844 ** statement (since the range of switch targets now starts at zero and
dan597515d2014-02-28 18:39:51 +00003845 ** is contiguous) but does not cause any duplicate code to be generated
dan063d4a02014-02-28 09:48:30 +00003846 ** (as gcc is clever enough to combine the two like cases). Other
3847 ** compilers might be similar. */
3848 case 0: case 7:
drh75179de2014-09-16 14:37:35 +00003849 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan063d4a02014-02-28 09:48:30 +00003850
dan3b9330f2014-02-27 20:44:18 +00003851 default:
drh75179de2014-09-16 14:37:35 +00003852 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
dan3b9330f2014-02-27 20:44:18 +00003853 }
3854
3855 if( v>lhs ){
3856 res = pPKey2->r1;
3857 }else if( v<lhs ){
3858 res = pPKey2->r2;
3859 }else if( pPKey2->nField>1 ){
dan063d4a02014-02-28 09:48:30 +00003860 /* The first fields of the two keys are equal. Compare the trailing
3861 ** fields. */
drh75179de2014-09-16 14:37:35 +00003862 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003863 }else{
dan063d4a02014-02-28 09:48:30 +00003864 /* The first fields of the two keys are equal and there are no trailing
3865 ** fields. Return pPKey2->default_rc in this case. */
dan3b9330f2014-02-27 20:44:18 +00003866 res = pPKey2->default_rc;
3867 }
3868
drh79211e12014-05-02 17:33:16 +00003869 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
dan3b9330f2014-02-27 20:44:18 +00003870 return res;
3871}
3872
dan3833e932014-03-01 19:44:56 +00003873/*
3874** This function is an optimized version of sqlite3VdbeRecordCompare()
3875** that (a) the first field of pPKey2 is a string, that (b) the first field
3876** uses the collation sequence BINARY and (c) that the size-of-header varint
3877** at the start of (pKey1/nKey1) fits in a single byte.
3878*/
dan3b9330f2014-02-27 20:44:18 +00003879static int vdbeRecordCompareString(
3880 int nKey1, const void *pKey1, /* Left key */
drh75179de2014-09-16 14:37:35 +00003881 UnpackedRecord *pPKey2 /* Right key */
dan3b9330f2014-02-27 20:44:18 +00003882){
3883 const u8 *aKey1 = (const u8*)pKey1;
3884 int serial_type;
3885 int res;
3886
drhe1bb8022015-01-19 19:48:52 +00003887 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
dan3b9330f2014-02-27 20:44:18 +00003888 getVarint32(&aKey1[1], serial_type);
dan3b9330f2014-02-27 20:44:18 +00003889 if( serial_type<12 ){
3890 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
3891 }else if( !(serial_type & 0x01) ){
3892 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
3893 }else{
3894 int nCmp;
3895 int nStr;
dan3833e932014-03-01 19:44:56 +00003896 int szHdr = aKey1[0];
dan3b9330f2014-02-27 20:44:18 +00003897
3898 nStr = (serial_type-12) / 2;
drha1f7c0a2014-03-28 03:12:48 +00003899 if( (szHdr + nStr) > nKey1 ){
dan38fdead2014-04-01 10:19:02 +00003900 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
drha1f7c0a2014-03-28 03:12:48 +00003901 return 0; /* Corruption */
3902 }
dan3b9330f2014-02-27 20:44:18 +00003903 nCmp = MIN( pPKey2->aMem[0].n, nStr );
dan3833e932014-03-01 19:44:56 +00003904 res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
dan3b9330f2014-02-27 20:44:18 +00003905
3906 if( res==0 ){
3907 res = nStr - pPKey2->aMem[0].n;
3908 if( res==0 ){
3909 if( pPKey2->nField>1 ){
drh75179de2014-09-16 14:37:35 +00003910 res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
dan3b9330f2014-02-27 20:44:18 +00003911 }else{
3912 res = pPKey2->default_rc;
3913 }
3914 }else if( res>0 ){
3915 res = pPKey2->r2;
3916 }else{
3917 res = pPKey2->r1;
3918 }
3919 }else if( res>0 ){
3920 res = pPKey2->r2;
3921 }else{
3922 res = pPKey2->r1;
3923 }
3924 }
3925
drh66141812014-06-30 20:25:03 +00003926 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
dan3b9330f2014-02-27 20:44:18 +00003927 || CORRUPT_DB
dan6696ba32014-06-28 19:06:49 +00003928 || pPKey2->pKeyInfo->db->mallocFailed
dan3b9330f2014-02-27 20:44:18 +00003929 );
3930 return res;
3931}
3932
dan3833e932014-03-01 19:44:56 +00003933/*
3934** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
3935** suitable for comparing serialized records to the unpacked record passed
3936** as the only argument.
3937*/
dan1fed5da2014-02-25 21:01:25 +00003938RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
dan9b8afef2014-03-03 20:48:50 +00003939 /* varintRecordCompareInt() and varintRecordCompareString() both assume
3940 ** that the size-of-header varint that occurs at the start of each record
3941 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
3942 ** also assumes that it is safe to overread a buffer by at least the
3943 ** maximum possible legal header size plus 8 bytes. Because there is
3944 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
3945 ** buffer passed to varintRecordCompareInt() this makes it convenient to
3946 ** limit the size of the header to 64 bytes in cases where the first field
3947 ** is an integer.
3948 **
3949 ** The easiest way to enforce this limit is to consider only records with
3950 ** 13 fields or less. If the first field is an integer, the maximum legal
3951 ** header size is (12*5 + 1 + 1) bytes. */
3952 if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
dan1fed5da2014-02-25 21:01:25 +00003953 int flags = p->aMem[0].flags;
dan3b9330f2014-02-27 20:44:18 +00003954 if( p->pKeyInfo->aSortOrder[0] ){
3955 p->r1 = 1;
3956 p->r2 = -1;
3957 }else{
3958 p->r1 = -1;
3959 p->r2 = 1;
3960 }
dan1fed5da2014-02-25 21:01:25 +00003961 if( (flags & MEM_Int) ){
3962 return vdbeRecordCompareInt;
dan3b9330f2014-02-27 20:44:18 +00003963 }
drhb6e8fd12014-03-06 01:56:33 +00003964 testcase( flags & MEM_Real );
3965 testcase( flags & MEM_Null );
3966 testcase( flags & MEM_Blob );
3967 if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
3968 assert( flags & MEM_Str );
dan1fed5da2014-02-25 21:01:25 +00003969 return vdbeRecordCompareString;
3970 }
3971 }
dan3b9330f2014-02-27 20:44:18 +00003972
dan3833e932014-03-01 19:44:56 +00003973 return sqlite3VdbeRecordCompare;
dan3b9330f2014-02-27 20:44:18 +00003974}
dan1fed5da2014-02-25 21:01:25 +00003975
danielk1977eb015e02004-05-18 01:31:14 +00003976/*
drh7a224de2004-06-02 01:22:02 +00003977** pCur points at an index entry created using the OP_MakeRecord opcode.
3978** Read the rowid (the last field in the record) and store it in *rowid.
3979** Return SQLITE_OK if everything works, or an error code otherwise.
drh88a003e2008-12-11 16:17:03 +00003980**
3981** pCur might be pointing to text obtained from a corrupt database file.
3982** So the content cannot be trusted. Do appropriate checks on the content.
danielk1977183f9f72004-05-13 05:20:26 +00003983*/
drhd3b74202014-09-17 16:41:15 +00003984int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
drh61fc5952007-04-01 23:49:51 +00003985 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003986 int rc;
drhd5788202004-05-28 08:21:05 +00003987 u32 szHdr; /* Size of the header */
3988 u32 typeRowid; /* Serial type of the rowid */
3989 u32 lenRowid; /* Size of the rowid */
3990 Mem m, v;
danielk1977183f9f72004-05-13 05:20:26 +00003991
drh88a003e2008-12-11 16:17:03 +00003992 /* Get the size of the index entry. Only indices entries of less
drh7b746032009-06-26 12:15:22 +00003993 ** than 2GiB are support - anything large must be database corruption.
3994 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
drhc27ae612009-07-14 18:35:44 +00003995 ** this code can safely assume that nCellKey is 32-bits
3996 */
drhea8ffdf2009-07-22 00:35:23 +00003997 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003998 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003999 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh7b746032009-06-26 12:15:22 +00004000 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
drh88a003e2008-12-11 16:17:03 +00004001
4002 /* Read in the complete content of the index entry */
drhd3b74202014-09-17 16:41:15 +00004003 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00004004 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
drhd5788202004-05-28 08:21:05 +00004005 if( rc ){
danielk1977183f9f72004-05-13 05:20:26 +00004006 return rc;
4007 }
drh88a003e2008-12-11 16:17:03 +00004008
4009 /* The index entry must begin with a header size */
shane3f8d5cf2008-04-24 19:15:09 +00004010 (void)getVarint32((u8*)m.z, szHdr);
drh7b746032009-06-26 12:15:22 +00004011 testcase( szHdr==3 );
drh88a003e2008-12-11 16:17:03 +00004012 testcase( szHdr==m.n );
drh7b746032009-06-26 12:15:22 +00004013 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
drh88a003e2008-12-11 16:17:03 +00004014 goto idx_rowid_corruption;
4015 }
4016
4017 /* The last field of the index should be an integer - the ROWID.
4018 ** Verify that the last entry really is an integer. */
shane3f8d5cf2008-04-24 19:15:09 +00004019 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
drh88a003e2008-12-11 16:17:03 +00004020 testcase( typeRowid==1 );
4021 testcase( typeRowid==2 );
4022 testcase( typeRowid==3 );
4023 testcase( typeRowid==4 );
4024 testcase( typeRowid==5 );
4025 testcase( typeRowid==6 );
4026 testcase( typeRowid==8 );
4027 testcase( typeRowid==9 );
4028 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
4029 goto idx_rowid_corruption;
4030 }
drhd5788202004-05-28 08:21:05 +00004031 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
drheeb844a2009-08-08 18:01:07 +00004032 testcase( (u32)m.n==szHdr+lenRowid );
4033 if( unlikely((u32)m.n<szHdr+lenRowid) ){
drh88a003e2008-12-11 16:17:03 +00004034 goto idx_rowid_corruption;
4035 }
4036
4037 /* Fetch the integer off the end of the index record */
drh2646da72005-12-09 20:02:05 +00004038 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
drh3c024d62007-03-30 11:23:45 +00004039 *rowid = v.u.i;
danielk1977d8123362004-06-12 09:25:12 +00004040 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00004041 return SQLITE_OK;
drh88a003e2008-12-11 16:17:03 +00004042
4043 /* Jump here if database corruption is detected after m has been
4044 ** allocated. Free the m object and return SQLITE_CORRUPT. */
4045idx_rowid_corruption:
drh17bcb102014-09-18 21:25:33 +00004046 testcase( m.szMalloc!=0 );
drh88a003e2008-12-11 16:17:03 +00004047 sqlite3VdbeMemRelease(&m);
4048 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00004049}
4050
drh7cf6e4d2004-05-19 14:56:55 +00004051/*
drh5f82e3c2009-07-06 00:44:08 +00004052** Compare the key of the index entry that cursor pC is pointing to against
4053** the key string in pUnpacked. Write into *pRes a number
drh7cf6e4d2004-05-19 14:56:55 +00004054** that is negative, zero, or positive if pC is less than, equal to,
drh5f82e3c2009-07-06 00:44:08 +00004055** or greater than pUnpacked. Return SQLITE_OK on success.
drhd3d39e92004-05-20 22:16:29 +00004056**
drh5f82e3c2009-07-06 00:44:08 +00004057** pUnpacked is either created without a rowid or is truncated so that it
drhd5788202004-05-28 08:21:05 +00004058** omits the rowid at the end. The rowid at the end of the index entry
drhec1fc802008-08-13 14:07:40 +00004059** is ignored as well. Hence, this routine only compares the prefixes
4060** of the keys prior to the final rowid, not the entire key.
drh7cf6e4d2004-05-19 14:56:55 +00004061*/
danielk1977183f9f72004-05-13 05:20:26 +00004062int sqlite3VdbeIdxKeyCompare(
drhd3b74202014-09-17 16:41:15 +00004063 sqlite3 *db, /* Database connection */
drh295aedf2014-03-03 18:25:24 +00004064 VdbeCursor *pC, /* The cursor to compare against */
drha1f7c0a2014-03-28 03:12:48 +00004065 UnpackedRecord *pUnpacked, /* Unpacked version of key */
drh295aedf2014-03-03 18:25:24 +00004066 int *res /* Write the comparison result here */
danielk1977183f9f72004-05-13 05:20:26 +00004067){
drh61fc5952007-04-01 23:49:51 +00004068 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00004069 int rc;
danielk19773d1bfea2004-05-14 11:00:53 +00004070 BtCursor *pCur = pC->pCursor;
drhd5788202004-05-28 08:21:05 +00004071 Mem m;
danielk1977183f9f72004-05-13 05:20:26 +00004072
drhea8ffdf2009-07-22 00:35:23 +00004073 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00004074 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00004075 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh56689692014-03-03 19:29:28 +00004076 /* nCellKey will always be between 0 and 0xffffffff because of the way
drh407414c2009-07-14 14:15:27 +00004077 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
drhc27ae612009-07-14 18:35:44 +00004078 if( nCellKey<=0 || nCellKey>0x7fffffff ){
danielk1977183f9f72004-05-13 05:20:26 +00004079 *res = 0;
drh9978c972010-02-23 17:36:32 +00004080 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00004081 }
drhd3b74202014-09-17 16:41:15 +00004082 sqlite3VdbeMemInit(&m, db, 0);
drh501932c2013-11-21 21:59:53 +00004083 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
drhec1fc802008-08-13 14:07:40 +00004084 if( rc ){
drhd5788202004-05-28 08:21:05 +00004085 return rc;
danielk1977183f9f72004-05-13 05:20:26 +00004086 }
drh75179de2014-09-16 14:37:35 +00004087 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
danielk1977d8123362004-06-12 09:25:12 +00004088 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00004089 return SQLITE_OK;
4090}
danielk1977b28af712004-06-21 06:50:26 +00004091
4092/*
4093** This routine sets the value to be returned by subsequent calls to
4094** sqlite3_changes() on the database handle 'db'.
4095*/
4096void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
drhb21c8cd2007-08-21 19:33:56 +00004097 assert( sqlite3_mutex_held(db->mutex) );
danielk1977b28af712004-06-21 06:50:26 +00004098 db->nChange = nChange;
4099 db->nTotalChange += nChange;
4100}
4101
4102/*
4103** Set a flag in the vdbe to update the change counter when it is finalised
4104** or reset.
4105*/
drh4794f732004-11-05 17:17:50 +00004106void sqlite3VdbeCountChanges(Vdbe *v){
4107 v->changeCntOn = 1;
danielk1977b28af712004-06-21 06:50:26 +00004108}
drhd89bd002005-01-22 03:03:54 +00004109
4110/*
4111** Mark every prepared statement associated with a database connection
4112** as expired.
4113**
4114** An expired statement means that recompilation of the statement is
4115** recommend. Statements expire when things happen that make their
4116** programs obsolete. Removing user-defined functions or collating
4117** sequences, or changing an authorization function are the types of
4118** things that make prepared statements obsolete.
4119*/
4120void sqlite3ExpirePreparedStatements(sqlite3 *db){
4121 Vdbe *p;
4122 for(p = db->pVdbe; p; p=p->pNext){
4123 p->expired = 1;
4124 }
4125}
danielk1977aee18ef2005-03-09 12:26:50 +00004126
4127/*
4128** Return the database associated with the Vdbe.
4129*/
4130sqlite3 *sqlite3VdbeDb(Vdbe *v){
4131 return v->db;
4132}
dan937d0de2009-10-15 18:35:38 +00004133
4134/*
4135** Return a pointer to an sqlite3_value structure containing the value bound
4136** parameter iVar of VM v. Except, if the value is an SQL NULL, return
4137** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
4138** constants) to the value before returning it.
4139**
4140** The returned value must be freed by the caller using sqlite3ValueFree().
4141*/
drhcf0fd4a2013-08-01 12:21:58 +00004142sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
dan937d0de2009-10-15 18:35:38 +00004143 assert( iVar>0 );
4144 if( v ){
4145 Mem *pMem = &v->aVar[iVar-1];
4146 if( 0==(pMem->flags & MEM_Null) ){
4147 sqlite3_value *pRet = sqlite3ValueNew(v->db);
4148 if( pRet ){
4149 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
4150 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
dan937d0de2009-10-15 18:35:38 +00004151 }
4152 return pRet;
4153 }
4154 }
4155 return 0;
4156}
4157
4158/*
4159** Configure SQL variable iVar so that binding a new value to it signals
4160** to sqlite3_reoptimize() that re-preparing the statement may result
4161** in a better query plan.
4162*/
dan1d2ce4f2009-10-19 18:11:09 +00004163void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
dan937d0de2009-10-15 18:35:38 +00004164 assert( iVar>0 );
4165 if( iVar>32 ){
dan1d2ce4f2009-10-19 18:11:09 +00004166 v->expmask = 0xffffffff;
dan937d0de2009-10-15 18:35:38 +00004167 }else{
dan1d2ce4f2009-10-19 18:11:09 +00004168 v->expmask |= ((u32)1 << (iVar-1));
dan937d0de2009-10-15 18:35:38 +00004169 }
4170}
dan016f7812013-08-21 17:35:48 +00004171
4172#ifndef SQLITE_OMIT_VIRTUALTABLE
4173/*
4174** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
4175** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
4176** in memory obtained from sqlite3DbMalloc).
4177*/
4178void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
4179 sqlite3 *db = p->db;
4180 sqlite3DbFree(db, p->zErrMsg);
4181 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
4182 sqlite3_free(pVtab->zErrMsg);
4183 pVtab->zErrMsg = 0;
4184}
4185#endif /* SQLITE_OMIT_VIRTUALTABLE */