blob: 166cf7508fe2d68298c93f511f62a4e85120c5be [file] [log] [blame]
drh9a324642003-09-06 20:12:01 +00001/*
2** 2003 September 6
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code used for creating, destroying, and populating
danielk1977fc57d7b2004-05-26 02:04:57 +000013** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
drh9a324642003-09-06 20:12:01 +000014** to version 2.8.7, all this code was combined into the vdbe.c source file.
15** But that file was getting too big so this subroutines were split out.
16*/
17#include "sqliteInt.h"
drh9a324642003-09-06 20:12:01 +000018#include "vdbeInt.h"
19
drh9a324642003-09-06 20:12:01 +000020/*
21** Create a new virtual database engine.
22*/
drh9bb575f2004-09-06 17:24:11 +000023Vdbe *sqlite3VdbeCreate(sqlite3 *db){
drh9a324642003-09-06 20:12:01 +000024 Vdbe *p;
drh17435752007-08-16 04:30:38 +000025 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
drh9a324642003-09-06 20:12:01 +000026 if( p==0 ) return 0;
27 p->db = db;
28 if( db->pVdbe ){
29 db->pVdbe->pPrev = p;
30 }
31 p->pNext = db->pVdbe;
32 p->pPrev = 0;
33 db->pVdbe = p;
34 p->magic = VDBE_MAGIC_INIT;
35 return p;
36}
37
38/*
drhb900aaf2006-11-09 00:24:53 +000039** Remember the SQL string for a prepared statement.
40*/
danielk19776ab3a2e2009-02-19 14:39:25 +000041void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
dan1d2ce4f2009-10-19 18:11:09 +000042 assert( isPrepareV2==1 || isPrepareV2==0 );
drhb900aaf2006-11-09 00:24:53 +000043 if( p==0 ) return;
danac455932012-11-26 19:50:41 +000044#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
danielk19776ab3a2e2009-02-19 14:39:25 +000045 if( !isPrepareV2 ) return;
46#endif
drhb900aaf2006-11-09 00:24:53 +000047 assert( p->zSql==0 );
drh17435752007-08-16 04:30:38 +000048 p->zSql = sqlite3DbStrNDup(p->db, z, n);
shanef639c402009-11-03 19:42:30 +000049 p->isPrepareV2 = (u8)isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000050}
51
52/*
53** Return the SQL associated with a prepared statement
54*/
danielk1977d0e2a852007-11-14 06:48:48 +000055const char *sqlite3_sql(sqlite3_stmt *pStmt){
danielk19776ab3a2e2009-02-19 14:39:25 +000056 Vdbe *p = (Vdbe *)pStmt;
drh87f5c5f2010-01-20 01:20:56 +000057 return (p && p->isPrepareV2) ? p->zSql : 0;
drhb900aaf2006-11-09 00:24:53 +000058}
59
60/*
drhc5155252007-01-08 21:07:17 +000061** Swap all content between two VDBE structures.
drhb900aaf2006-11-09 00:24:53 +000062*/
drhc5155252007-01-08 21:07:17 +000063void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
64 Vdbe tmp, *pTmp;
65 char *zTmp;
drhc5155252007-01-08 21:07:17 +000066 tmp = *pA;
67 *pA = *pB;
68 *pB = tmp;
69 pTmp = pA->pNext;
70 pA->pNext = pB->pNext;
71 pB->pNext = pTmp;
72 pTmp = pA->pPrev;
73 pA->pPrev = pB->pPrev;
74 pB->pPrev = pTmp;
75 zTmp = pA->zSql;
76 pA->zSql = pB->zSql;
77 pB->zSql = zTmp;
danielk19776ab3a2e2009-02-19 14:39:25 +000078 pB->isPrepareV2 = pA->isPrepareV2;
drhb900aaf2006-11-09 00:24:53 +000079}
80
drh9a324642003-09-06 20:12:01 +000081/*
danielk197700e13612008-11-17 19:18:54 +000082** Resize the Vdbe.aOp array so that it is at least one op larger than
83** it was.
danielk1977ace3eb22006-01-26 10:35:04 +000084**
danielk197700e13612008-11-17 19:18:54 +000085** If an out-of-memory error occurs while resizing the array, return
86** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
87** unchanged (this is so that any opcodes already allocated can be
88** correctly deallocated along with the rest of the Vdbe).
drh76ff3a02004-09-24 22:32:30 +000089*/
danielk197700e13612008-11-17 19:18:54 +000090static int growOpArray(Vdbe *p){
drha4e5d582007-10-20 15:41:57 +000091 VdbeOp *pNew;
danielk197700e13612008-11-17 19:18:54 +000092 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
93 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
drha4e5d582007-10-20 15:41:57 +000094 if( pNew ){
drhb45f65d2009-03-01 19:42:11 +000095 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
drha4e5d582007-10-20 15:41:57 +000096 p->aOp = pNew;
drh76ff3a02004-09-24 22:32:30 +000097 }
danielk197700e13612008-11-17 19:18:54 +000098 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
drh76ff3a02004-09-24 22:32:30 +000099}
100
drh313619f2013-10-31 20:34:06 +0000101#ifdef SQLITE_DEBUG
102/* This routine is just a convenient place to set a breakpoint that will
103** fire after each opcode is inserted and displayed using
104** "PRAGMA vdbe_addoptrace=on".
105*/
106static void test_addop_breakpoint(void){
107 static int n = 0;
108 n++;
109}
110#endif
111
drh76ff3a02004-09-24 22:32:30 +0000112/*
drh9a324642003-09-06 20:12:01 +0000113** Add a new instruction to the list of instructions current in the
114** VDBE. Return the address of the new instruction.
115**
116** Parameters:
117**
118** p Pointer to the VDBE
119**
120** op The opcode for this instruction
121**
drh66a51672008-01-03 00:01:23 +0000122** p1, p2, p3 Operands
drh9a324642003-09-06 20:12:01 +0000123**
danielk19774adee202004-05-08 08:23:19 +0000124** Use the sqlite3VdbeResolveLabel() function to fix an address and
drh66a51672008-01-03 00:01:23 +0000125** the sqlite3VdbeChangeP4() function to change the value of the P4
drh9a324642003-09-06 20:12:01 +0000126** operand.
127*/
drh66a51672008-01-03 00:01:23 +0000128int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
drh9a324642003-09-06 20:12:01 +0000129 int i;
drh701a0ae2004-02-22 20:05:00 +0000130 VdbeOp *pOp;
drh9a324642003-09-06 20:12:01 +0000131
132 i = p->nOp;
drh9a324642003-09-06 20:12:01 +0000133 assert( p->magic==VDBE_MAGIC_INIT );
drh8df32842008-12-09 02:51:23 +0000134 assert( op>0 && op<0xff );
drhfd2d26b2006-03-15 22:44:36 +0000135 if( p->nOpAlloc<=i ){
danielk197700e13612008-11-17 19:18:54 +0000136 if( growOpArray(p) ){
drhc42ed162009-06-26 14:04:51 +0000137 return 1;
drhfd2d26b2006-03-15 22:44:36 +0000138 }
drh9a324642003-09-06 20:12:01 +0000139 }
danielk197701256832007-04-18 14:24:32 +0000140 p->nOp++;
drh701a0ae2004-02-22 20:05:00 +0000141 pOp = &p->aOp[i];
drh8df32842008-12-09 02:51:23 +0000142 pOp->opcode = (u8)op;
drh26c9b5e2008-04-11 14:56:53 +0000143 pOp->p5 = 0;
drh701a0ae2004-02-22 20:05:00 +0000144 pOp->p1 = p1;
drh701a0ae2004-02-22 20:05:00 +0000145 pOp->p2 = p2;
drh66a51672008-01-03 00:01:23 +0000146 pOp->p3 = p3;
147 pOp->p4.p = 0;
148 pOp->p4type = P4_NOTUSED;
drhc7379ce2013-10-30 02:28:23 +0000149#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000150 pOp->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000151#endif
152#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000153 if( p->db->flags & SQLITE_VdbeAddopTrace ){
154 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
drh313619f2013-10-31 20:34:06 +0000155 test_addop_breakpoint();
drhe0962052013-01-29 19:14:31 +0000156 }
drh9a324642003-09-06 20:12:01 +0000157#endif
drh26c9b5e2008-04-11 14:56:53 +0000158#ifdef VDBE_PROFILE
159 pOp->cycles = 0;
160 pOp->cnt = 0;
161#endif
drh9a324642003-09-06 20:12:01 +0000162 return i;
163}
drh66a51672008-01-03 00:01:23 +0000164int sqlite3VdbeAddOp0(Vdbe *p, int op){
165 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
166}
167int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
168 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
169}
170int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
171 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
drh701a0ae2004-02-22 20:05:00 +0000172}
173
drh66a51672008-01-03 00:01:23 +0000174
drh701a0ae2004-02-22 20:05:00 +0000175/*
drh66a51672008-01-03 00:01:23 +0000176** Add an opcode that includes the p4 value as a pointer.
drhd4e70eb2008-01-02 00:34:36 +0000177*/
drh66a51672008-01-03 00:01:23 +0000178int sqlite3VdbeAddOp4(
drhd4e70eb2008-01-02 00:34:36 +0000179 Vdbe *p, /* Add the opcode to this VM */
180 int op, /* The new opcode */
drh66a51672008-01-03 00:01:23 +0000181 int p1, /* The P1 operand */
182 int p2, /* The P2 operand */
183 int p3, /* The P3 operand */
184 const char *zP4, /* The P4 operand */
185 int p4type /* P4 operand type */
drhd4e70eb2008-01-02 00:34:36 +0000186){
drh66a51672008-01-03 00:01:23 +0000187 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
188 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
drhd4e70eb2008-01-02 00:34:36 +0000189 return addr;
190}
191
192/*
drh5d9c9da2011-06-03 20:11:17 +0000193** Add an OP_ParseSchema opcode. This routine is broken out from
drhe4c88c02012-01-04 12:57:45 +0000194** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
195** as having been used.
drh5d9c9da2011-06-03 20:11:17 +0000196**
197** The zWhere string must have been obtained from sqlite3_malloc().
198** This routine will take ownership of the allocated memory.
199*/
200void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
201 int j;
202 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
203 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
204 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
205}
206
207/*
drh8cff69d2009-11-12 19:59:44 +0000208** Add an opcode that includes the p4 value as an integer.
209*/
210int sqlite3VdbeAddOp4Int(
211 Vdbe *p, /* Add the opcode to this VM */
212 int op, /* The new opcode */
213 int p1, /* The P1 operand */
214 int p2, /* The P2 operand */
215 int p3, /* The P3 operand */
216 int p4 /* The P4 operand as an integer */
217){
218 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
219 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
220 return addr;
221}
222
223/*
drh9a324642003-09-06 20:12:01 +0000224** Create a new symbolic label for an instruction that has yet to be
225** coded. The symbolic label is really just a negative number. The
226** label can be used as the P2 value of an operation. Later, when
227** the label is resolved to a specific address, the VDBE will scan
228** through its operation list and change all values of P2 which match
229** the label into the resolved address.
230**
231** The VDBE knows that a P2 value is a label because labels are
232** always negative and P2 values are suppose to be non-negative.
233** Hence, a negative P2 value is a label that has yet to be resolved.
danielk1977b5548a82004-06-26 13:51:33 +0000234**
235** Zero is returned if a malloc() fails.
drh9a324642003-09-06 20:12:01 +0000236*/
danielk19774adee202004-05-08 08:23:19 +0000237int sqlite3VdbeMakeLabel(Vdbe *p){
drhc35f3d52012-02-01 19:03:38 +0000238 int i = p->nLabel++;
drh9a324642003-09-06 20:12:01 +0000239 assert( p->magic==VDBE_MAGIC_INIT );
drhc35f3d52012-02-01 19:03:38 +0000240 if( (i & (i-1))==0 ){
241 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
242 (i*2+1)*sizeof(p->aLabel[0]));
drh9a324642003-09-06 20:12:01 +0000243 }
drh76ff3a02004-09-24 22:32:30 +0000244 if( p->aLabel ){
245 p->aLabel[i] = -1;
drh9a324642003-09-06 20:12:01 +0000246 }
drh9a324642003-09-06 20:12:01 +0000247 return -1-i;
248}
249
250/*
251** Resolve label "x" to be the address of the next instruction to
252** be inserted. The parameter "x" must have been obtained from
danielk19774adee202004-05-08 08:23:19 +0000253** a prior call to sqlite3VdbeMakeLabel().
drh9a324642003-09-06 20:12:01 +0000254*/
danielk19774adee202004-05-08 08:23:19 +0000255void sqlite3VdbeResolveLabel(Vdbe *p, int x){
drh76ff3a02004-09-24 22:32:30 +0000256 int j = -1-x;
drh9a324642003-09-06 20:12:01 +0000257 assert( p->magic==VDBE_MAGIC_INIT );
drhb2b9d3d2013-08-01 01:14:43 +0000258 assert( j<p->nLabel );
259 if( j>=0 && p->aLabel ){
drh76ff3a02004-09-24 22:32:30 +0000260 p->aLabel[j] = p->nOp;
drh9a324642003-09-06 20:12:01 +0000261 }
262}
263
drh4611d922010-02-25 14:47:01 +0000264/*
265** Mark the VDBE as one that can only be run one time.
266*/
267void sqlite3VdbeRunOnlyOnce(Vdbe *p){
268 p->runOnlyOnce = 1;
269}
270
drhff738bc2009-09-24 00:09:58 +0000271#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
dan144926d2009-09-09 11:37:20 +0000272
273/*
274** The following type and function are used to iterate through all opcodes
275** in a Vdbe main program and each of the sub-programs (triggers) it may
276** invoke directly or indirectly. It should be used as follows:
277**
278** Op *pOp;
279** VdbeOpIter sIter;
280**
281** memset(&sIter, 0, sizeof(sIter));
282** sIter.v = v; // v is of type Vdbe*
283** while( (pOp = opIterNext(&sIter)) ){
284** // Do something with pOp
285** }
286** sqlite3DbFree(v->db, sIter.apSub);
287**
288*/
289typedef struct VdbeOpIter VdbeOpIter;
290struct VdbeOpIter {
291 Vdbe *v; /* Vdbe to iterate through the opcodes of */
292 SubProgram **apSub; /* Array of subprograms */
293 int nSub; /* Number of entries in apSub */
294 int iAddr; /* Address of next instruction to return */
295 int iSub; /* 0 = main program, 1 = first sub-program etc. */
296};
297static Op *opIterNext(VdbeOpIter *p){
298 Vdbe *v = p->v;
299 Op *pRet = 0;
300 Op *aOp;
301 int nOp;
302
303 if( p->iSub<=p->nSub ){
304
305 if( p->iSub==0 ){
306 aOp = v->aOp;
307 nOp = v->nOp;
308 }else{
309 aOp = p->apSub[p->iSub-1]->aOp;
310 nOp = p->apSub[p->iSub-1]->nOp;
311 }
312 assert( p->iAddr<nOp );
313
314 pRet = &aOp[p->iAddr];
315 p->iAddr++;
316 if( p->iAddr==nOp ){
317 p->iSub++;
318 p->iAddr = 0;
319 }
320
321 if( pRet->p4type==P4_SUBPROGRAM ){
322 int nByte = (p->nSub+1)*sizeof(SubProgram*);
323 int j;
324 for(j=0; j<p->nSub; j++){
325 if( p->apSub[j]==pRet->p4.pProgram ) break;
326 }
327 if( j==p->nSub ){
328 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
329 if( !p->apSub ){
330 pRet = 0;
331 }else{
332 p->apSub[p->nSub++] = pRet->p4.pProgram;
333 }
334 }
335 }
336 }
337
338 return pRet;
339}
340
341/*
danf3677212009-09-10 16:14:50 +0000342** Check if the program stored in the VM associated with pParse may
drhff738bc2009-09-24 00:09:58 +0000343** throw an ABORT exception (causing the statement, but not entire transaction
dan144926d2009-09-09 11:37:20 +0000344** to be rolled back). This condition is true if the main program or any
345** sub-programs contains any of the following:
346**
347** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
348** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
349** * OP_Destroy
350** * OP_VUpdate
351** * OP_VRename
dan32b09f22009-09-23 17:29:59 +0000352** * OP_FkCounter with P2==0 (immediate foreign key constraint)
dan144926d2009-09-09 11:37:20 +0000353**
danf3677212009-09-10 16:14:50 +0000354** Then check that the value of Parse.mayAbort is true if an
355** ABORT may be thrown, or false otherwise. Return true if it does
356** match, or false otherwise. This function is intended to be used as
357** part of an assert statement in the compiler. Similar to:
358**
359** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
dan144926d2009-09-09 11:37:20 +0000360*/
danf3677212009-09-10 16:14:50 +0000361int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
362 int hasAbort = 0;
dan144926d2009-09-09 11:37:20 +0000363 Op *pOp;
364 VdbeOpIter sIter;
365 memset(&sIter, 0, sizeof(sIter));
366 sIter.v = v;
367
368 while( (pOp = opIterNext(&sIter))!=0 ){
369 int opcode = pOp->opcode;
370 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
dan32b09f22009-09-23 17:29:59 +0000371#ifndef SQLITE_OMIT_FOREIGN_KEY
dan0ff297e2009-09-25 17:03:14 +0000372 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
dan32b09f22009-09-23 17:29:59 +0000373#endif
dan144926d2009-09-09 11:37:20 +0000374 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
drhd91c1a12013-02-09 13:58:25 +0000375 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
dan144926d2009-09-09 11:37:20 +0000376 ){
danf3677212009-09-10 16:14:50 +0000377 hasAbort = 1;
dan144926d2009-09-09 11:37:20 +0000378 break;
379 }
380 }
dan144926d2009-09-09 11:37:20 +0000381 sqlite3DbFree(v->db, sIter.apSub);
danf3677212009-09-10 16:14:50 +0000382
mistachkin48864df2013-03-21 21:20:32 +0000383 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
danf3677212009-09-10 16:14:50 +0000384 ** If malloc failed, then the while() loop above may not have iterated
385 ** through all opcodes and hasAbort may be set incorrectly. Return
386 ** true for this case to prevent the assert() in the callers frame
387 ** from failing. */
388 return ( v->db->mallocFailed || hasAbort==mayAbort );
dan144926d2009-09-09 11:37:20 +0000389}
drhff738bc2009-09-24 00:09:58 +0000390#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
dan144926d2009-09-09 11:37:20 +0000391
drh9a324642003-09-06 20:12:01 +0000392/*
drh9cbf3422008-01-17 16:22:13 +0000393** Loop through the program looking for P2 values that are negative
394** on jump instructions. Each such value is a label. Resolve the
395** label by setting the P2 value to its correct non-zero value.
drh76ff3a02004-09-24 22:32:30 +0000396**
397** This routine is called once after all opcodes have been inserted.
danielk1977634f2982005-03-28 08:44:07 +0000398**
drh13449892005-09-07 21:22:45 +0000399** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
danielk1977399918f2006-06-14 13:03:23 +0000400** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
danielk1977634f2982005-03-28 08:44:07 +0000401** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
drha6c2ed92009-11-14 23:22:23 +0000402**
403** The Op.opflags field is set on all opcodes.
drh76ff3a02004-09-24 22:32:30 +0000404*/
drh9cbf3422008-01-17 16:22:13 +0000405static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
drh76ff3a02004-09-24 22:32:30 +0000406 int i;
dan165921a2009-08-28 18:53:45 +0000407 int nMaxArgs = *pMaxFuncArgs;
drh76ff3a02004-09-24 22:32:30 +0000408 Op *pOp;
409 int *aLabel = p->aLabel;
drhad4a4b82008-11-05 16:37:34 +0000410 p->readOnly = 1;
drh1713afb2013-06-28 01:24:57 +0000411 p->bIsReader = 0;
drh76ff3a02004-09-24 22:32:30 +0000412 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
danielk1977634f2982005-03-28 08:44:07 +0000413 u8 opcode = pOp->opcode;
414
drh8c8a8c42013-08-06 07:45:08 +0000415 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
416 ** cases from this switch! */
417 switch( opcode ){
418 case OP_Function:
419 case OP_AggStep: {
420 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
421 break;
422 }
423 case OP_Transaction: {
424 if( pOp->p2!=0 ) p->readOnly = 0;
425 /* fall thru */
426 }
427 case OP_AutoCommit:
428 case OP_Savepoint: {
429 p->bIsReader = 1;
430 break;
431 }
dand9031542013-07-05 16:54:30 +0000432#ifndef SQLITE_OMIT_WAL
drh8c8a8c42013-08-06 07:45:08 +0000433 case OP_Checkpoint:
drh9e92a472013-06-27 17:40:30 +0000434#endif
drh8c8a8c42013-08-06 07:45:08 +0000435 case OP_Vacuum:
436 case OP_JournalMode: {
437 p->readOnly = 0;
438 p->bIsReader = 1;
439 break;
440 }
danielk1977182c4ba2007-06-27 15:53:34 +0000441#ifndef SQLITE_OMIT_VIRTUALTABLE
drh8c8a8c42013-08-06 07:45:08 +0000442 case OP_VUpdate: {
443 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
444 break;
445 }
446 case OP_VFilter: {
447 int n;
448 assert( p->nOp - i >= 3 );
449 assert( pOp[-1].opcode==OP_Integer );
450 n = pOp[-1].p1;
451 if( n>nMaxArgs ) nMaxArgs = n;
452 break;
453 }
danielk1977182c4ba2007-06-27 15:53:34 +0000454#endif
drh8c8a8c42013-08-06 07:45:08 +0000455 case OP_Next:
456 case OP_SorterNext: {
457 pOp->p4.xAdvance = sqlite3BtreeNext;
458 pOp->p4type = P4_ADVANCE;
459 break;
460 }
461 case OP_Prev: {
462 pOp->p4.xAdvance = sqlite3BtreePrevious;
463 pOp->p4type = P4_ADVANCE;
464 break;
465 }
danielk1977bc04f852005-03-29 08:26:13 +0000466 }
danielk1977634f2982005-03-28 08:44:07 +0000467
drh8c8a8c42013-08-06 07:45:08 +0000468 pOp->opflags = sqlite3OpcodeProperty[opcode];
drha6c2ed92009-11-14 23:22:23 +0000469 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
drhd2981512008-01-04 19:33:49 +0000470 assert( -1-pOp->p2<p->nLabel );
471 pOp->p2 = aLabel[-1-pOp->p2];
472 }
drh76ff3a02004-09-24 22:32:30 +0000473 }
drh633e6d52008-07-28 19:34:53 +0000474 sqlite3DbFree(p->db, p->aLabel);
drh76ff3a02004-09-24 22:32:30 +0000475 p->aLabel = 0;
danielk1977bc04f852005-03-29 08:26:13 +0000476 *pMaxFuncArgs = nMaxArgs;
danc0537fe2013-06-28 19:41:43 +0000477 assert( p->bIsReader!=0 || p->btreeMask==0 );
drh76ff3a02004-09-24 22:32:30 +0000478}
479
480/*
drh9a324642003-09-06 20:12:01 +0000481** Return the address of the next instruction to be inserted.
482*/
danielk19774adee202004-05-08 08:23:19 +0000483int sqlite3VdbeCurrentAddr(Vdbe *p){
drh9a324642003-09-06 20:12:01 +0000484 assert( p->magic==VDBE_MAGIC_INIT );
485 return p->nOp;
486}
487
dan65a7cd12009-09-01 12:16:01 +0000488/*
489** This function returns a pointer to the array of opcodes associated with
490** the Vdbe passed as the first argument. It is the callers responsibility
491** to arrange for the returned array to be eventually freed using the
492** vdbeFreeOpArray() function.
493**
494** Before returning, *pnOp is set to the number of entries in the returned
495** array. Also, *pnMaxArg is set to the larger of its current value and
496** the number of entries in the Vdbe.apArg[] array required to execute the
497** returned program.
498*/
dan165921a2009-08-28 18:53:45 +0000499VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
500 VdbeOp *aOp = p->aOp;
dan523a0872009-08-31 05:23:32 +0000501 assert( aOp && !p->db->mallocFailed );
dan65a7cd12009-09-01 12:16:01 +0000502
503 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
drhbdaec522011-04-04 00:14:43 +0000504 assert( p->btreeMask==0 );
dan65a7cd12009-09-01 12:16:01 +0000505
dan165921a2009-08-28 18:53:45 +0000506 resolveP2Values(p, pnMaxArg);
507 *pnOp = p->nOp;
508 p->aOp = 0;
509 return aOp;
510}
511
drh9a324642003-09-06 20:12:01 +0000512/*
513** Add a whole list of operations to the operation stack. Return the
514** address of the first operation added.
515*/
danielk19774adee202004-05-08 08:23:19 +0000516int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
drh9a324642003-09-06 20:12:01 +0000517 int addr;
518 assert( p->magic==VDBE_MAGIC_INIT );
danielk197700e13612008-11-17 19:18:54 +0000519 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
drh76ff3a02004-09-24 22:32:30 +0000520 return 0;
drh9a324642003-09-06 20:12:01 +0000521 }
522 addr = p->nOp;
drh7b746032009-06-26 12:15:22 +0000523 if( ALWAYS(nOp>0) ){
drh9a324642003-09-06 20:12:01 +0000524 int i;
drh905793e2004-02-21 13:31:09 +0000525 VdbeOpList const *pIn = aOp;
526 for(i=0; i<nOp; i++, pIn++){
527 int p2 = pIn->p2;
528 VdbeOp *pOut = &p->aOp[i+addr];
529 pOut->opcode = pIn->opcode;
530 pOut->p1 = pIn->p1;
drh4308e342013-11-11 16:55:52 +0000531 if( p2<0 ){
532 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
drh8558cde2008-01-05 05:20:10 +0000533 pOut->p2 = addr + ADDR(p2);
534 }else{
535 pOut->p2 = p2;
536 }
drh24003452008-01-03 01:28:59 +0000537 pOut->p3 = pIn->p3;
538 pOut->p4type = P4_NOTUSED;
539 pOut->p4.p = 0;
540 pOut->p5 = 0;
drhc7379ce2013-10-30 02:28:23 +0000541#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh26c9b5e2008-04-11 14:56:53 +0000542 pOut->zComment = 0;
drhc7379ce2013-10-30 02:28:23 +0000543#endif
544#ifdef SQLITE_DEBUG
drhe0962052013-01-29 19:14:31 +0000545 if( p->db->flags & SQLITE_VdbeAddopTrace ){
danielk19774adee202004-05-08 08:23:19 +0000546 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
drh9a324642003-09-06 20:12:01 +0000547 }
548#endif
549 }
550 p->nOp += nOp;
551 }
552 return addr;
553}
554
555/*
556** Change the value of the P1 operand for a specific instruction.
557** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000558** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000559** few minor changes to the program.
560*/
drh88caeac2011-08-24 15:12:08 +0000561void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000562 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000563 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000564 p->aOp[addr].p1 = val;
565 }
566}
567
568/*
569** Change the value of the P2 operand for a specific instruction.
570** This routine is useful for setting a jump destination.
571*/
drh88caeac2011-08-24 15:12:08 +0000572void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000573 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000574 if( ((u32)p->nOp)>addr ){
drh9a324642003-09-06 20:12:01 +0000575 p->aOp[addr].p2 = val;
576 }
577}
578
drhd654be82005-09-20 17:42:23 +0000579/*
danielk19771f4aa332008-01-03 09:51:55 +0000580** Change the value of the P3 operand for a specific instruction.
danielk1977207872a2008-01-03 07:54:23 +0000581*/
drh88caeac2011-08-24 15:12:08 +0000582void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
drh7b746032009-06-26 12:15:22 +0000583 assert( p!=0 );
drh88caeac2011-08-24 15:12:08 +0000584 if( ((u32)p->nOp)>addr ){
danielk1977207872a2008-01-03 07:54:23 +0000585 p->aOp[addr].p3 = val;
586 }
587}
588
589/*
drh35573352008-01-08 23:54:25 +0000590** Change the value of the P5 operand for the most recently
591** added operation.
danielk19771f4aa332008-01-03 09:51:55 +0000592*/
drh35573352008-01-08 23:54:25 +0000593void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
drh7b746032009-06-26 12:15:22 +0000594 assert( p!=0 );
595 if( p->aOp ){
drh35573352008-01-08 23:54:25 +0000596 assert( p->nOp>0 );
597 p->aOp[p->nOp-1].p5 = val;
danielk19771f4aa332008-01-03 09:51:55 +0000598 }
599}
600
601/*
drhf8875402006-03-17 13:56:34 +0000602** Change the P2 operand of instruction addr so that it points to
drhd654be82005-09-20 17:42:23 +0000603** the address of the next instruction to be coded.
604*/
605void sqlite3VdbeJumpHere(Vdbe *p, int addr){
drhe0c7efd2013-08-02 20:11:19 +0000606 if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
drhd654be82005-09-20 17:42:23 +0000607}
drhb38ad992005-09-16 00:27:01 +0000608
drhb7f6f682006-07-08 17:06:43 +0000609
610/*
611** If the input FuncDef structure is ephemeral, then free it. If
612** the FuncDef is not ephermal, then do nothing.
613*/
drh633e6d52008-07-28 19:34:53 +0000614static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
drhd36e1042013-09-06 13:10:12 +0000615 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
drh633e6d52008-07-28 19:34:53 +0000616 sqlite3DbFree(db, pDef);
drhb7f6f682006-07-08 17:06:43 +0000617 }
618}
619
dand46def72010-07-24 11:28:28 +0000620static void vdbeFreeOpArray(sqlite3 *, Op *, int);
621
drhb38ad992005-09-16 00:27:01 +0000622/*
drh66a51672008-01-03 00:01:23 +0000623** Delete a P4 value if necessary.
drhb38ad992005-09-16 00:27:01 +0000624*/
drh633e6d52008-07-28 19:34:53 +0000625static void freeP4(sqlite3 *db, int p4type, void *p4){
drh0acb7e42008-06-25 00:12:41 +0000626 if( p4 ){
dand46def72010-07-24 11:28:28 +0000627 assert( db );
drh66a51672008-01-03 00:01:23 +0000628 switch( p4type ){
629 case P4_REAL:
630 case P4_INT64:
drh66a51672008-01-03 00:01:23 +0000631 case P4_DYNAMIC:
drh2ec2fb22013-11-06 19:59:23 +0000632 case P4_INTARRAY: {
drh633e6d52008-07-28 19:34:53 +0000633 sqlite3DbFree(db, p4);
drhac1733d2005-09-17 17:58:22 +0000634 break;
635 }
drh2ec2fb22013-11-06 19:59:23 +0000636 case P4_KEYINFO: {
637 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
638 break;
639 }
drhb9755982010-07-24 16:34:37 +0000640 case P4_MPRINTF: {
drh7043db92010-07-26 12:38:12 +0000641 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
drhb9755982010-07-24 16:34:37 +0000642 break;
643 }
drh66a51672008-01-03 00:01:23 +0000644 case P4_FUNCDEF: {
drh633e6d52008-07-28 19:34:53 +0000645 freeEphemeralFunction(db, (FuncDef*)p4);
drhb7f6f682006-07-08 17:06:43 +0000646 break;
647 }
drh66a51672008-01-03 00:01:23 +0000648 case P4_MEM: {
drhc176c272010-07-26 13:57:59 +0000649 if( db->pnBytesFreed==0 ){
650 sqlite3ValueFree((sqlite3_value*)p4);
651 }else{
drhf37c68e2010-07-26 14:20:06 +0000652 Mem *p = (Mem*)p4;
653 sqlite3DbFree(db, p->zMalloc);
654 sqlite3DbFree(db, p);
drhc176c272010-07-26 13:57:59 +0000655 }
drhac1733d2005-09-17 17:58:22 +0000656 break;
657 }
danielk1977595a5232009-07-24 17:58:53 +0000658 case P4_VTAB : {
dand46def72010-07-24 11:28:28 +0000659 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
danielk1977595a5232009-07-24 17:58:53 +0000660 break;
661 }
drhb38ad992005-09-16 00:27:01 +0000662 }
663 }
664}
665
dan65a7cd12009-09-01 12:16:01 +0000666/*
667** Free the space allocated for aOp and any p4 values allocated for the
668** opcodes contained within. If aOp is not NULL it is assumed to contain
669** nOp entries.
670*/
dan165921a2009-08-28 18:53:45 +0000671static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
672 if( aOp ){
673 Op *pOp;
674 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
675 freeP4(db, pOp->p4type, pOp->p4.p);
drhc7379ce2013-10-30 02:28:23 +0000676#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
dan165921a2009-08-28 18:53:45 +0000677 sqlite3DbFree(db, pOp->zComment);
678#endif
679 }
680 }
681 sqlite3DbFree(db, aOp);
682}
683
dan65a7cd12009-09-01 12:16:01 +0000684/*
dand19c9332010-07-26 12:05:17 +0000685** Link the SubProgram object passed as the second argument into the linked
686** list at Vdbe.pSubProgram. This list is used to delete all sub-program
687** objects when the VM is no longer required.
dan65a7cd12009-09-01 12:16:01 +0000688*/
dand19c9332010-07-26 12:05:17 +0000689void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
690 p->pNext = pVdbe->pProgram;
691 pVdbe->pProgram = p;
dan165921a2009-08-28 18:53:45 +0000692}
693
drh9a324642003-09-06 20:12:01 +0000694/*
drh48f2d3b2011-09-16 01:34:43 +0000695** Change the opcode at addr into OP_Noop
drhf8875402006-03-17 13:56:34 +0000696*/
drh48f2d3b2011-09-16 01:34:43 +0000697void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
drh7b746032009-06-26 12:15:22 +0000698 if( p->aOp ){
danielk197792d4d7a2007-05-04 12:05:56 +0000699 VdbeOp *pOp = &p->aOp[addr];
drh633e6d52008-07-28 19:34:53 +0000700 sqlite3 *db = p->db;
drh48f2d3b2011-09-16 01:34:43 +0000701 freeP4(db, pOp->p4type, pOp->p4.p);
702 memset(pOp, 0, sizeof(pOp[0]));
703 pOp->opcode = OP_Noop;
drh313619f2013-10-31 20:34:06 +0000704 if( addr==p->nOp-1 ) p->nOp--;
drhf8875402006-03-17 13:56:34 +0000705 }
706}
707
708/*
drh66a51672008-01-03 00:01:23 +0000709** Change the value of the P4 operand for a specific instruction.
drh9a324642003-09-06 20:12:01 +0000710** This routine is useful when a large program is loaded from a
danielk19774adee202004-05-08 08:23:19 +0000711** static array using sqlite3VdbeAddOpList but we want to make a
drh9a324642003-09-06 20:12:01 +0000712** few minor changes to the program.
713**
drh66a51672008-01-03 00:01:23 +0000714** If n>=0 then the P4 operand is dynamic, meaning that a copy of
drh17435752007-08-16 04:30:38 +0000715** the string is made into memory obtained from sqlite3_malloc().
drh66a51672008-01-03 00:01:23 +0000716** A value of n==0 means copy bytes of zP4 up to and including the
717** first null byte. If n>0 then copy n+1 bytes of zP4.
danielk19771f55c052005-05-19 08:42:59 +0000718**
drh66a51672008-01-03 00:01:23 +0000719** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
danielk19771f55c052005-05-19 08:42:59 +0000720** to a string or structure that is guaranteed to exist for the lifetime of
721** the Vdbe. In these cases we can just copy the pointer.
drh9a324642003-09-06 20:12:01 +0000722**
drh66a51672008-01-03 00:01:23 +0000723** If addr<0 then change P4 on the most recently inserted instruction.
drh9a324642003-09-06 20:12:01 +0000724*/
drh66a51672008-01-03 00:01:23 +0000725void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
drh9a324642003-09-06 20:12:01 +0000726 Op *pOp;
drh633e6d52008-07-28 19:34:53 +0000727 sqlite3 *db;
drh91fd4d42008-01-19 20:11:25 +0000728 assert( p!=0 );
drh633e6d52008-07-28 19:34:53 +0000729 db = p->db;
drh91fd4d42008-01-19 20:11:25 +0000730 assert( p->magic==VDBE_MAGIC_INIT );
drh633e6d52008-07-28 19:34:53 +0000731 if( p->aOp==0 || db->mallocFailed ){
drh2ec2fb22013-11-06 19:59:23 +0000732 if( n!=P4_VTAB ){
drh633e6d52008-07-28 19:34:53 +0000733 freeP4(db, n, (void*)*(char**)&zP4);
danielk1977261919c2005-12-06 12:52:59 +0000734 }
danielk1977d5d56522005-03-16 12:15:20 +0000735 return;
736 }
drh7b746032009-06-26 12:15:22 +0000737 assert( p->nOp>0 );
drh91fd4d42008-01-19 20:11:25 +0000738 assert( addr<p->nOp );
739 if( addr<0 ){
drh9a324642003-09-06 20:12:01 +0000740 addr = p->nOp - 1;
drh9a324642003-09-06 20:12:01 +0000741 }
742 pOp = &p->aOp[addr];
drhfc5e5462012-12-03 17:04:40 +0000743 assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
drh633e6d52008-07-28 19:34:53 +0000744 freeP4(db, pOp->p4type, pOp->p4.p);
drh66a51672008-01-03 00:01:23 +0000745 pOp->p4.p = 0;
drh98757152008-01-09 23:04:12 +0000746 if( n==P4_INT32 ){
mlcreech12d40822008-03-06 07:35:21 +0000747 /* Note: this cast is safe, because the origin data point was an int
748 ** that was cast to a (const char *). */
shane1fc41292008-07-08 22:28:48 +0000749 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
drh8df32842008-12-09 02:51:23 +0000750 pOp->p4type = P4_INT32;
drh98757152008-01-09 23:04:12 +0000751 }else if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +0000752 pOp->p4.p = 0;
753 pOp->p4type = P4_NOTUSED;
754 }else if( n==P4_KEYINFO ){
danielk19772dca4ac2008-01-03 11:50:29 +0000755 pOp->p4.p = (void*)zP4;
drh66a51672008-01-03 00:01:23 +0000756 pOp->p4type = P4_KEYINFO;
danielk1977595a5232009-07-24 17:58:53 +0000757 }else if( n==P4_VTAB ){
758 pOp->p4.p = (void*)zP4;
759 pOp->p4type = P4_VTAB;
760 sqlite3VtabLock((VTable *)zP4);
761 assert( ((VTable *)zP4)->db==p->db );
drh9a324642003-09-06 20:12:01 +0000762 }else if( n<0 ){
danielk19772dca4ac2008-01-03 11:50:29 +0000763 pOp->p4.p = (void*)zP4;
drh8df32842008-12-09 02:51:23 +0000764 pOp->p4type = (signed char)n;
drh9a324642003-09-06 20:12:01 +0000765 }else{
drhea678832008-12-10 19:26:22 +0000766 if( n==0 ) n = sqlite3Strlen30(zP4);
danielk19772dca4ac2008-01-03 11:50:29 +0000767 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
drh66a51672008-01-03 00:01:23 +0000768 pOp->p4type = P4_DYNAMIC;
drh9a324642003-09-06 20:12:01 +0000769 }
770}
771
drh2ec2fb22013-11-06 19:59:23 +0000772/*
773** Set the P4 on the most recently added opcode to the KeyInfo for the
774** index given.
775*/
776void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
777 Vdbe *v = pParse->pVdbe;
778 assert( v!=0 );
779 assert( pIdx!=0 );
780 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
781 P4_KEYINFO);
782}
783
drhc7379ce2013-10-30 02:28:23 +0000784#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drhad6d9462004-09-19 02:15:24 +0000785/*
mistachkind5578432012-08-25 10:01:29 +0000786** Change the comment on the most recently coded instruction. Or
drh16ee60f2008-06-20 18:13:25 +0000787** insert a No-op and add the comment to that new instruction. This
788** makes the code easier to read during debugging. None of this happens
789** in a production build.
drhad6d9462004-09-19 02:15:24 +0000790*/
drhb07028f2011-10-14 21:49:18 +0000791static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
danielk197701256832007-04-18 14:24:32 +0000792 assert( p->nOp>0 || p->aOp==0 );
drhd4e70eb2008-01-02 00:34:36 +0000793 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
danielk1977dba01372008-01-05 18:44:29 +0000794 if( p->nOp ){
drhb07028f2011-10-14 21:49:18 +0000795 assert( p->aOp );
796 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
797 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
798 }
799}
800void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
801 va_list ap;
802 if( p ){
danielk1977dba01372008-01-05 18:44:29 +0000803 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000804 vdbeVComment(p, zFormat, ap);
danielk1977dba01372008-01-05 18:44:29 +0000805 va_end(ap);
806 }
drhad6d9462004-09-19 02:15:24 +0000807}
drh16ee60f2008-06-20 18:13:25 +0000808void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
809 va_list ap;
drhb07028f2011-10-14 21:49:18 +0000810 if( p ){
811 sqlite3VdbeAddOp0(p, OP_Noop);
drh16ee60f2008-06-20 18:13:25 +0000812 va_start(ap, zFormat);
drhb07028f2011-10-14 21:49:18 +0000813 vdbeVComment(p, zFormat, ap);
drh16ee60f2008-06-20 18:13:25 +0000814 va_end(ap);
815 }
816}
817#endif /* NDEBUG */
drhad6d9462004-09-19 02:15:24 +0000818
drh9a324642003-09-06 20:12:01 +0000819/*
drh20411ea2009-05-29 19:00:12 +0000820** Return the opcode for a given address. If the address is -1, then
821** return the most recently inserted opcode.
822**
823** If a memory allocation error has occurred prior to the calling of this
824** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
drhf83dc1e2010-06-03 12:09:52 +0000825** is readable but not writable, though it is cast to a writable value.
826** The return of a dummy opcode allows the call to continue functioning
827** after a OOM fault without having to check to see if the return from
828** this routine is a valid pointer. But because the dummy.opcode is 0,
829** dummy will never be written to. This is verified by code inspection and
830** by running with Valgrind.
drh37b89a02009-06-19 00:33:31 +0000831**
832** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
833** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
834** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
835** a new VDBE is created. So we are free to set addr to p->nOp-1 without
836** having to double-check to make sure that the result is non-negative. But
837** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
838** check the value of p->nOp-1 before continuing.
drh9a324642003-09-06 20:12:01 +0000839*/
danielk19774adee202004-05-08 08:23:19 +0000840VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
drha0b75da2010-07-02 18:44:37 +0000841 /* C89 specifies that the constant "dummy" will be initialized to all
842 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
mistachkin0fe5f952011-09-14 18:19:08 +0000843 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
drh9a324642003-09-06 20:12:01 +0000844 assert( p->magic==VDBE_MAGIC_INIT );
drh37b89a02009-06-19 00:33:31 +0000845 if( addr<0 ){
846#ifdef SQLITE_OMIT_TRACE
drhf83dc1e2010-06-03 12:09:52 +0000847 if( p->nOp==0 ) return (VdbeOp*)&dummy;
drh37b89a02009-06-19 00:33:31 +0000848#endif
849 addr = p->nOp - 1;
850 }
drh17435752007-08-16 04:30:38 +0000851 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +0000852 if( p->db->mallocFailed ){
drhf83dc1e2010-06-03 12:09:52 +0000853 return (VdbeOp*)&dummy;
drh20411ea2009-05-29 19:00:12 +0000854 }else{
855 return &p->aOp[addr];
856 }
drh9a324642003-09-06 20:12:01 +0000857}
858
drhc7379ce2013-10-30 02:28:23 +0000859#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
drh81316f82013-10-29 20:40:47 +0000860/*
drhf63552b2013-10-30 00:25:03 +0000861** Return an integer value for one of the parameters to the opcode pOp
862** determined by character c.
863*/
864static int translateP(char c, const Op *pOp){
865 if( c=='1' ) return pOp->p1;
866 if( c=='2' ) return pOp->p2;
867 if( c=='3' ) return pOp->p3;
868 if( c=='4' ) return pOp->p4.i;
869 return pOp->p5;
870}
871
drh81316f82013-10-29 20:40:47 +0000872/*
873** Compute a string for the "comment" field of a VDBE opcode listing
874*/
drhf63552b2013-10-30 00:25:03 +0000875static int displayComment(
876 const Op *pOp, /* The opcode to be commented */
877 const char *zP4, /* Previously obtained value for P4 */
878 char *zTemp, /* Write result here */
879 int nTemp /* Space available in zTemp[] */
880){
drh81316f82013-10-29 20:40:47 +0000881 const char *zOpName;
882 const char *zSynopsis;
883 int nOpName;
884 int ii, jj;
885 zOpName = sqlite3OpcodeName(pOp->opcode);
886 nOpName = sqlite3Strlen30(zOpName);
887 if( zOpName[nOpName+1] ){
888 int seenCom = 0;
drhf63552b2013-10-30 00:25:03 +0000889 char c;
drh81316f82013-10-29 20:40:47 +0000890 zSynopsis = zOpName += nOpName + 1;
drhf63552b2013-10-30 00:25:03 +0000891 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
892 if( c=='P' ){
893 c = zSynopsis[++ii];
894 if( c=='4' ){
895 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
896 }else if( c=='X' ){
897 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
898 seenCom = 1;
drh81316f82013-10-29 20:40:47 +0000899 }else{
drhf63552b2013-10-30 00:25:03 +0000900 int v1 = translateP(c, pOp);
901 int v2;
902 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
903 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
904 ii += 3;
905 jj += sqlite3Strlen30(zTemp+jj);
906 v2 = translateP(zSynopsis[ii], pOp);
907 if( v2>1 ) sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
908 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
909 ii += 4;
910 }
drh81316f82013-10-29 20:40:47 +0000911 }
912 jj += sqlite3Strlen30(zTemp+jj);
913 }else{
drhf63552b2013-10-30 00:25:03 +0000914 zTemp[jj++] = c;
drh81316f82013-10-29 20:40:47 +0000915 }
916 }
917 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
918 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
919 jj += sqlite3Strlen30(zTemp+jj);
920 }
921 if( jj<nTemp ) zTemp[jj] = 0;
922 }else if( pOp->zComment ){
923 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
924 jj = sqlite3Strlen30(zTemp);
925 }else{
926 zTemp[0] = 0;
927 jj = 0;
928 }
929 return jj;
930}
931#endif /* SQLITE_DEBUG */
932
933
drhb7f91642004-10-31 02:22:47 +0000934#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
935 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +0000936/*
drh66a51672008-01-03 00:01:23 +0000937** Compute a string that describes the P4 parameter for an opcode.
drhd3d39e92004-05-20 22:16:29 +0000938** Use zTemp for any required temporary buffer space.
939*/
drh66a51672008-01-03 00:01:23 +0000940static char *displayP4(Op *pOp, char *zTemp, int nTemp){
941 char *zP4 = zTemp;
drhd3d39e92004-05-20 22:16:29 +0000942 assert( nTemp>=20 );
drh66a51672008-01-03 00:01:23 +0000943 switch( pOp->p4type ){
944 case P4_KEYINFO: {
drhd3d39e92004-05-20 22:16:29 +0000945 int i, j;
danielk19772dca4ac2008-01-03 11:50:29 +0000946 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
drhe1a022e2012-09-17 17:16:53 +0000947 assert( pKeyInfo->aSortOrder!=0 );
drh5b843aa2013-10-30 13:46:01 +0000948 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
drhea678832008-12-10 19:26:22 +0000949 i = sqlite3Strlen30(zTemp);
drhd3d39e92004-05-20 22:16:29 +0000950 for(j=0; j<pKeyInfo->nField; j++){
951 CollSeq *pColl = pKeyInfo->aColl[j];
drh261d8a52012-12-08 21:36:26 +0000952 const char *zColl = pColl ? pColl->zName : "nil";
953 int n = sqlite3Strlen30(zColl);
drh5b843aa2013-10-30 13:46:01 +0000954 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
955 zColl = "B";
956 n = 1;
957 }
drh261d8a52012-12-08 21:36:26 +0000958 if( i+n>nTemp-6 ){
959 memcpy(&zTemp[i],",...",4);
960 break;
drhd3d39e92004-05-20 22:16:29 +0000961 }
drh261d8a52012-12-08 21:36:26 +0000962 zTemp[i++] = ',';
963 if( pKeyInfo->aSortOrder[j] ){
964 zTemp[i++] = '-';
965 }
966 memcpy(&zTemp[i], zColl, n+1);
967 i += n;
drhd3d39e92004-05-20 22:16:29 +0000968 }
969 zTemp[i++] = ')';
970 zTemp[i] = 0;
971 assert( i<nTemp );
drhd3d39e92004-05-20 22:16:29 +0000972 break;
973 }
drh66a51672008-01-03 00:01:23 +0000974 case P4_COLLSEQ: {
danielk19772dca4ac2008-01-03 11:50:29 +0000975 CollSeq *pColl = pOp->p4.pColl;
drh5e6790c2013-11-12 20:18:14 +0000976 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
drhd3d39e92004-05-20 22:16:29 +0000977 break;
978 }
drh66a51672008-01-03 00:01:23 +0000979 case P4_FUNCDEF: {
danielk19772dca4ac2008-01-03 11:50:29 +0000980 FuncDef *pDef = pOp->p4.pFunc;
drha967e882006-06-13 01:04:52 +0000981 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
drhf9b596e2004-05-26 16:54:42 +0000982 break;
983 }
drh66a51672008-01-03 00:01:23 +0000984 case P4_INT64: {
danielk19772dca4ac2008-01-03 11:50:29 +0000985 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
drhd4e70eb2008-01-02 00:34:36 +0000986 break;
987 }
drh66a51672008-01-03 00:01:23 +0000988 case P4_INT32: {
989 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
drh598f1342007-10-23 15:39:45 +0000990 break;
991 }
drh66a51672008-01-03 00:01:23 +0000992 case P4_REAL: {
danielk19772dca4ac2008-01-03 11:50:29 +0000993 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
drhd4e70eb2008-01-02 00:34:36 +0000994 break;
995 }
drh66a51672008-01-03 00:01:23 +0000996 case P4_MEM: {
danielk19772dca4ac2008-01-03 11:50:29 +0000997 Mem *pMem = pOp->p4.pMem;
drhd4e70eb2008-01-02 00:34:36 +0000998 if( pMem->flags & MEM_Str ){
drh66a51672008-01-03 00:01:23 +0000999 zP4 = pMem->z;
drhd4e70eb2008-01-02 00:34:36 +00001000 }else if( pMem->flags & MEM_Int ){
1001 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
1002 }else if( pMem->flags & MEM_Real ){
1003 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
drhb8475df2011-12-09 16:21:19 +00001004 }else if( pMem->flags & MEM_Null ){
1005 sqlite3_snprintf(nTemp, zTemp, "NULL");
drh56016892009-08-25 14:24:04 +00001006 }else{
1007 assert( pMem->flags & MEM_Blob );
1008 zP4 = "(blob)";
drhd4e70eb2008-01-02 00:34:36 +00001009 }
drh598f1342007-10-23 15:39:45 +00001010 break;
1011 }
drha967e882006-06-13 01:04:52 +00001012#ifndef SQLITE_OMIT_VIRTUALTABLE
drh66a51672008-01-03 00:01:23 +00001013 case P4_VTAB: {
danielk1977595a5232009-07-24 17:58:53 +00001014 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
drh19146192006-06-26 19:10:32 +00001015 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
drha967e882006-06-13 01:04:52 +00001016 break;
1017 }
1018#endif
drh0acb7e42008-06-25 00:12:41 +00001019 case P4_INTARRAY: {
1020 sqlite3_snprintf(nTemp, zTemp, "intarray");
1021 break;
1022 }
dan165921a2009-08-28 18:53:45 +00001023 case P4_SUBPROGRAM: {
1024 sqlite3_snprintf(nTemp, zTemp, "program");
1025 break;
1026 }
drh4a6f3aa2011-08-28 00:19:26 +00001027 case P4_ADVANCE: {
1028 zTemp[0] = 0;
1029 break;
1030 }
drhd3d39e92004-05-20 22:16:29 +00001031 default: {
danielk19772dca4ac2008-01-03 11:50:29 +00001032 zP4 = pOp->p4.z;
drh949f9cd2008-01-12 21:35:57 +00001033 if( zP4==0 ){
drh66a51672008-01-03 00:01:23 +00001034 zP4 = zTemp;
drhd4e70eb2008-01-02 00:34:36 +00001035 zTemp[0] = 0;
drhd3d39e92004-05-20 22:16:29 +00001036 }
1037 }
1038 }
drh66a51672008-01-03 00:01:23 +00001039 assert( zP4!=0 );
drh66a51672008-01-03 00:01:23 +00001040 return zP4;
drhd3d39e92004-05-20 22:16:29 +00001041}
drhb7f91642004-10-31 02:22:47 +00001042#endif
drhd3d39e92004-05-20 22:16:29 +00001043
drh900b31e2007-08-28 02:27:51 +00001044/*
drhd0679ed2007-08-28 22:24:34 +00001045** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
drh3ebaee92010-05-06 21:37:22 +00001046**
drhbdaec522011-04-04 00:14:43 +00001047** The prepared statements need to know in advance the complete set of
drhe4c88c02012-01-04 12:57:45 +00001048** attached databases that will be use. A mask of these databases
1049** is maintained in p->btreeMask. The p->lockMask value is the subset of
1050** p->btreeMask of databases that will require a lock.
drh900b31e2007-08-28 02:27:51 +00001051*/
drhfb982642007-08-30 01:19:59 +00001052void sqlite3VdbeUsesBtree(Vdbe *p, int i){
drhfcd71b62011-04-05 22:08:24 +00001053 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
danielk197700e13612008-11-17 19:18:54 +00001054 assert( i<(int)sizeof(p->btreeMask)*8 );
drhbdaec522011-04-04 00:14:43 +00001055 p->btreeMask |= ((yDbMask)1)<<i;
drhdc5b0472011-04-06 22:05:53 +00001056 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
1057 p->lockMask |= ((yDbMask)1)<<i;
1058 }
drh900b31e2007-08-28 02:27:51 +00001059}
1060
drhe54e0512011-04-05 17:31:56 +00001061#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001062/*
1063** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1064** this routine obtains the mutex associated with each BtShared structure
1065** that may be accessed by the VM passed as an argument. In doing so it also
1066** sets the BtShared.db member of each of the BtShared structures, ensuring
1067** that the correct busy-handler callback is invoked if required.
1068**
1069** If SQLite is not threadsafe but does support shared-cache mode, then
1070** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1071** of all of BtShared structures accessible via the database handle
1072** associated with the VM.
1073**
1074** If SQLite is not threadsafe and does not support shared-cache mode, this
1075** function is a no-op.
1076**
1077** The p->btreeMask field is a bitmask of all btrees that the prepared
1078** statement p will ever use. Let N be the number of bits in p->btreeMask
1079** corresponding to btrees that use shared cache. Then the runtime of
1080** this routine is N*N. But as N is rarely more than 1, this should not
1081** be a problem.
1082*/
1083void sqlite3VdbeEnter(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001084 int i;
1085 yDbMask mask;
drhdc5b0472011-04-06 22:05:53 +00001086 sqlite3 *db;
1087 Db *aDb;
1088 int nDb;
1089 if( p->lockMask==0 ) return; /* The common case */
1090 db = p->db;
1091 aDb = db->aDb;
1092 nDb = db->nDb;
drhbdaec522011-04-04 00:14:43 +00001093 for(i=0, mask=1; i<nDb; i++, mask += mask){
drhdc5b0472011-04-06 22:05:53 +00001094 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001095 sqlite3BtreeEnter(aDb[i].pBt);
1096 }
1097 }
drhbdaec522011-04-04 00:14:43 +00001098}
drhe54e0512011-04-05 17:31:56 +00001099#endif
drhbdaec522011-04-04 00:14:43 +00001100
drhe54e0512011-04-05 17:31:56 +00001101#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
drhbdaec522011-04-04 00:14:43 +00001102/*
1103** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1104*/
1105void sqlite3VdbeLeave(Vdbe *p){
drhbdaec522011-04-04 00:14:43 +00001106 int i;
1107 yDbMask mask;
drhdc5b0472011-04-06 22:05:53 +00001108 sqlite3 *db;
1109 Db *aDb;
1110 int nDb;
1111 if( p->lockMask==0 ) return; /* The common case */
1112 db = p->db;
1113 aDb = db->aDb;
1114 nDb = db->nDb;
drhbdaec522011-04-04 00:14:43 +00001115 for(i=0, mask=1; i<nDb; i++, mask += mask){
drhdc5b0472011-04-06 22:05:53 +00001116 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
drhbdaec522011-04-04 00:14:43 +00001117 sqlite3BtreeLeave(aDb[i].pBt);
1118 }
1119 }
drhbdaec522011-04-04 00:14:43 +00001120}
drhbdaec522011-04-04 00:14:43 +00001121#endif
drhd3d39e92004-05-20 22:16:29 +00001122
danielk19778b60e0f2005-01-12 09:10:39 +00001123#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
drh9a324642003-09-06 20:12:01 +00001124/*
1125** Print a single opcode. This routine is used for debugging only.
1126*/
danielk19774adee202004-05-08 08:23:19 +00001127void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
drh66a51672008-01-03 00:01:23 +00001128 char *zP4;
drhd3d39e92004-05-20 22:16:29 +00001129 char zPtr[50];
drh81316f82013-10-29 20:40:47 +00001130 char zCom[100];
drh26198bb2013-10-31 11:15:09 +00001131 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
drh9a324642003-09-06 20:12:01 +00001132 if( pOut==0 ) pOut = stdout;
drh66a51672008-01-03 00:01:23 +00001133 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
drhc7379ce2013-10-30 02:28:23 +00001134#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001135 displayComment(pOp, zP4, zCom, sizeof(zCom));
1136#else
1137 zCom[0] = 0
1138#endif
danielk197711641c12008-01-03 08:18:30 +00001139 fprintf(pOut, zFormat1, pc,
drh1db639c2008-01-17 02:36:28 +00001140 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
drh81316f82013-10-29 20:40:47 +00001141 zCom
drh1db639c2008-01-17 02:36:28 +00001142 );
drh9a324642003-09-06 20:12:01 +00001143 fflush(pOut);
1144}
1145#endif
1146
1147/*
drh76ff3a02004-09-24 22:32:30 +00001148** Release an array of N Mem elements
1149*/
drhc890fec2008-08-01 20:10:08 +00001150static void releaseMemArray(Mem *p, int N){
danielk1977a7a8e142008-02-13 18:25:27 +00001151 if( p && N ){
danielk1977e972e032008-09-19 18:32:26 +00001152 Mem *pEnd;
danielk1977a7a8e142008-02-13 18:25:27 +00001153 sqlite3 *db = p->db;
drh8df32842008-12-09 02:51:23 +00001154 u8 malloc_failed = db->mallocFailed;
dand46def72010-07-24 11:28:28 +00001155 if( db->pnBytesFreed ){
1156 for(pEnd=&p[N]; p<pEnd; p++){
1157 sqlite3DbFree(db, p->zMalloc);
1158 }
drhc176c272010-07-26 13:57:59 +00001159 return;
1160 }
danielk1977e972e032008-09-19 18:32:26 +00001161 for(pEnd=&p[N]; p<pEnd; p++){
1162 assert( (&p[1])==pEnd || p[0].db==p[1].db );
1163
1164 /* This block is really an inlined version of sqlite3VdbeMemRelease()
1165 ** that takes advantage of the fact that the memory cell value is
1166 ** being set to NULL after releasing any dynamic resources.
1167 **
1168 ** The justification for duplicating code is that according to
1169 ** callgrind, this causes a certain test case to hit the CPU 4.7
1170 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
1171 ** sqlite3MemRelease() were called from here. With -O2, this jumps
1172 ** to 6.6 percent. The test case is inserting 1000 rows into a table
1173 ** with no indexes using a single prepared INSERT statement, bind()
1174 ** and reset(). Inserts are grouped into a transaction.
1175 */
dan165921a2009-08-28 18:53:45 +00001176 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
danielk1977e972e032008-09-19 18:32:26 +00001177 sqlite3VdbeMemRelease(p);
1178 }else if( p->zMalloc ){
1179 sqlite3DbFree(db, p->zMalloc);
1180 p->zMalloc = 0;
1181 }
1182
drhb8475df2011-12-09 16:21:19 +00001183 p->flags = MEM_Invalid;
drh76ff3a02004-09-24 22:32:30 +00001184 }
danielk1977a7a8e142008-02-13 18:25:27 +00001185 db->mallocFailed = malloc_failed;
drh76ff3a02004-09-24 22:32:30 +00001186 }
1187}
1188
dan65a7cd12009-09-01 12:16:01 +00001189/*
1190** Delete a VdbeFrame object and its contents. VdbeFrame objects are
1191** allocated by the OP_Program opcode in sqlite3VdbeExec().
1192*/
dan165921a2009-08-28 18:53:45 +00001193void sqlite3VdbeFrameDelete(VdbeFrame *p){
1194 int i;
1195 Mem *aMem = VdbeFrameMem(p);
1196 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
1197 for(i=0; i<p->nChildCsr; i++){
1198 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
1199 }
1200 releaseMemArray(aMem, p->nChildMem);
1201 sqlite3DbFree(p->v->db, p);
1202}
1203
drhb7f91642004-10-31 02:22:47 +00001204#ifndef SQLITE_OMIT_EXPLAIN
drh76ff3a02004-09-24 22:32:30 +00001205/*
drh9a324642003-09-06 20:12:01 +00001206** Give a listing of the program in the virtual machine.
1207**
danielk19774adee202004-05-08 08:23:19 +00001208** The interface is the same as sqlite3VdbeExec(). But instead of
drh9a324642003-09-06 20:12:01 +00001209** running the code, it invokes the callback once for each instruction.
1210** This feature is used to implement "EXPLAIN".
drh9cbf3422008-01-17 16:22:13 +00001211**
1212** When p->explain==1, each instruction is listed. When
1213** p->explain==2, only OP_Explain instructions are listed and these
1214** are shown in a different format. p->explain==2 is used to implement
1215** EXPLAIN QUERY PLAN.
drh5cfa5842009-12-31 20:35:08 +00001216**
1217** When p->explain==1, first the main program is listed, then each of
1218** the trigger subprograms are listed one by one.
drh9a324642003-09-06 20:12:01 +00001219*/
danielk19774adee202004-05-08 08:23:19 +00001220int sqlite3VdbeList(
drh9a324642003-09-06 20:12:01 +00001221 Vdbe *p /* The VDBE */
1222){
drh5cfa5842009-12-31 20:35:08 +00001223 int nRow; /* Stop when row count reaches this */
dan165921a2009-08-28 18:53:45 +00001224 int nSub = 0; /* Number of sub-vdbes seen so far */
1225 SubProgram **apSub = 0; /* Array of sub-vdbes */
drh5cfa5842009-12-31 20:35:08 +00001226 Mem *pSub = 0; /* Memory cell hold array of subprogs */
1227 sqlite3 *db = p->db; /* The database connection */
1228 int i; /* Loop counter */
1229 int rc = SQLITE_OK; /* Return code */
drh9734e6e2011-10-07 18:24:25 +00001230 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
drh9a324642003-09-06 20:12:01 +00001231
drh9a324642003-09-06 20:12:01 +00001232 assert( p->explain );
drh5f82e3c2009-07-06 00:44:08 +00001233 assert( p->magic==VDBE_MAGIC_RUN );
danielk19776c359f02008-11-21 16:58:03 +00001234 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
danielk197718f41892004-05-22 07:27:46 +00001235
drh9cbf3422008-01-17 16:22:13 +00001236 /* Even though this opcode does not use dynamic strings for
1237 ** the result, result columns may become dynamic if the user calls
drh4f26d6c2004-05-26 23:25:30 +00001238 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
danielk197718f41892004-05-22 07:27:46 +00001239 */
dan165921a2009-08-28 18:53:45 +00001240 releaseMemArray(pMem, 8);
drh9734e6e2011-10-07 18:24:25 +00001241 p->pResultSet = 0;
danielk197718f41892004-05-22 07:27:46 +00001242
danielk19776c359f02008-11-21 16:58:03 +00001243 if( p->rc==SQLITE_NOMEM ){
1244 /* This happens if a malloc() inside a call to sqlite3_column_text() or
1245 ** sqlite3_column_text16() failed. */
1246 db->mallocFailed = 1;
1247 return SQLITE_ERROR;
1248 }
1249
drh5cfa5842009-12-31 20:35:08 +00001250 /* When the number of output rows reaches nRow, that means the
1251 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
1252 ** nRow is the sum of the number of rows in the main program, plus
1253 ** the sum of the number of rows in all trigger subprograms encountered
1254 ** so far. The nRow value will increase as new trigger subprograms are
1255 ** encountered, but p->pc will eventually catch up to nRow.
1256 */
dan165921a2009-08-28 18:53:45 +00001257 nRow = p->nOp;
1258 if( p->explain==1 ){
drh5cfa5842009-12-31 20:35:08 +00001259 /* The first 8 memory cells are used for the result set. So we will
1260 ** commandeer the 9th cell to use as storage for an array of pointers
1261 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
1262 ** cells. */
1263 assert( p->nMem>9 );
dan165921a2009-08-28 18:53:45 +00001264 pSub = &p->aMem[9];
1265 if( pSub->flags&MEM_Blob ){
drh5cfa5842009-12-31 20:35:08 +00001266 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
1267 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
dan165921a2009-08-28 18:53:45 +00001268 nSub = pSub->n/sizeof(Vdbe*);
1269 apSub = (SubProgram **)pSub->z;
1270 }
1271 for(i=0; i<nSub; i++){
1272 nRow += apSub[i]->nOp;
1273 }
1274 }
1275
drhecc92422005-09-10 16:46:12 +00001276 do{
1277 i = p->pc++;
dan165921a2009-08-28 18:53:45 +00001278 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
1279 if( i>=nRow ){
drh826fb5a2004-02-14 23:59:57 +00001280 p->rc = SQLITE_OK;
1281 rc = SQLITE_DONE;
drh881feaa2006-07-26 01:39:30 +00001282 }else if( db->u1.isInterrupted ){
drhc5cdca62005-01-11 16:54:14 +00001283 p->rc = SQLITE_INTERRUPT;
drh826fb5a2004-02-14 23:59:57 +00001284 rc = SQLITE_ERROR;
drhf089aa42008-07-08 19:34:06 +00001285 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
drh826fb5a2004-02-14 23:59:57 +00001286 }else{
drh81316f82013-10-29 20:40:47 +00001287 char *zP4;
dan165921a2009-08-28 18:53:45 +00001288 Op *pOp;
1289 if( i<p->nOp ){
drh5cfa5842009-12-31 20:35:08 +00001290 /* The output line number is small enough that we are still in the
1291 ** main program. */
dan165921a2009-08-28 18:53:45 +00001292 pOp = &p->aOp[i];
1293 }else{
drh5cfa5842009-12-31 20:35:08 +00001294 /* We are currently listing subprograms. Figure out which one and
1295 ** pick up the appropriate opcode. */
dan165921a2009-08-28 18:53:45 +00001296 int j;
1297 i -= p->nOp;
1298 for(j=0; i>=apSub[j]->nOp; j++){
1299 i -= apSub[j]->nOp;
1300 }
1301 pOp = &apSub[j]->aOp[i];
1302 }
danielk19770d78bae2008-01-03 07:09:48 +00001303 if( p->explain==1 ){
1304 pMem->flags = MEM_Int;
1305 pMem->type = SQLITE_INTEGER;
1306 pMem->u.i = i; /* Program counter */
1307 pMem++;
1308
1309 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001310 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
danielk19770d78bae2008-01-03 07:09:48 +00001311 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001312 pMem->n = sqlite3Strlen30(pMem->z);
danielk19770d78bae2008-01-03 07:09:48 +00001313 pMem->type = SQLITE_TEXT;
1314 pMem->enc = SQLITE_UTF8;
1315 pMem++;
dan165921a2009-08-28 18:53:45 +00001316
drh5cfa5842009-12-31 20:35:08 +00001317 /* When an OP_Program opcode is encounter (the only opcode that has
1318 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
1319 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
1320 ** has not already been seen.
1321 */
dan165921a2009-08-28 18:53:45 +00001322 if( pOp->p4type==P4_SUBPROGRAM ){
1323 int nByte = (nSub+1)*sizeof(SubProgram*);
1324 int j;
1325 for(j=0; j<nSub; j++){
1326 if( apSub[j]==pOp->p4.pProgram ) break;
1327 }
dan2b9ee772012-03-31 09:59:44 +00001328 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
dan165921a2009-08-28 18:53:45 +00001329 apSub = (SubProgram **)pSub->z;
1330 apSub[nSub++] = pOp->p4.pProgram;
1331 pSub->flags |= MEM_Blob;
1332 pSub->n = nSub*sizeof(SubProgram*);
1333 }
1334 }
danielk19770d78bae2008-01-03 07:09:48 +00001335 }
drheb2e1762004-05-27 01:53:56 +00001336
1337 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001338 pMem->u.i = pOp->p1; /* P1 */
drh9c054832004-05-31 18:51:57 +00001339 pMem->type = SQLITE_INTEGER;
drheb2e1762004-05-27 01:53:56 +00001340 pMem++;
1341
1342 pMem->flags = MEM_Int;
drh3c024d62007-03-30 11:23:45 +00001343 pMem->u.i = pOp->p2; /* P2 */
drh9c054832004-05-31 18:51:57 +00001344 pMem->type = SQLITE_INTEGER;
drheb2e1762004-05-27 01:53:56 +00001345 pMem++;
1346
dan2ce22452010-11-08 19:01:16 +00001347 pMem->flags = MEM_Int;
1348 pMem->u.i = pOp->p3; /* P3 */
1349 pMem->type = SQLITE_INTEGER;
1350 pMem++;
danielk19770d78bae2008-01-03 07:09:48 +00001351
danielk1977a7a8e142008-02-13 18:25:27 +00001352 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
danielk1977357864e2009-03-25 15:43:08 +00001353 assert( p->db->mallocFailed );
1354 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001355 }
1356 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
drh81316f82013-10-29 20:40:47 +00001357 zP4 = displayP4(pOp, pMem->z, 32);
1358 if( zP4!=pMem->z ){
1359 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
danielk1977a7a8e142008-02-13 18:25:27 +00001360 }else{
1361 assert( pMem->z!=0 );
drhea678832008-12-10 19:26:22 +00001362 pMem->n = sqlite3Strlen30(pMem->z);
danielk1977a7a8e142008-02-13 18:25:27 +00001363 pMem->enc = SQLITE_UTF8;
1364 }
drh9c054832004-05-31 18:51:57 +00001365 pMem->type = SQLITE_TEXT;
danielk19770d78bae2008-01-03 07:09:48 +00001366 pMem++;
drheb2e1762004-05-27 01:53:56 +00001367
danielk19770d78bae2008-01-03 07:09:48 +00001368 if( p->explain==1 ){
drh85e5f0d2008-02-19 18:28:13 +00001369 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
danielk1977357864e2009-03-25 15:43:08 +00001370 assert( p->db->mallocFailed );
1371 return SQLITE_ERROR;
danielk1977a7a8e142008-02-13 18:25:27 +00001372 }
1373 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
drh85e5f0d2008-02-19 18:28:13 +00001374 pMem->n = 2;
1375 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
danielk19770d78bae2008-01-03 07:09:48 +00001376 pMem->type = SQLITE_TEXT;
1377 pMem->enc = SQLITE_UTF8;
1378 pMem++;
1379
drhc7379ce2013-10-30 02:28:23 +00001380#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
drh81316f82013-10-29 20:40:47 +00001381 if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
1382 assert( p->db->mallocFailed );
1383 return SQLITE_ERROR;
drh52391cb2008-02-14 23:44:13 +00001384 }
drh81316f82013-10-29 20:40:47 +00001385 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
1386 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
1387 pMem->type = SQLITE_TEXT;
1388 pMem->enc = SQLITE_UTF8;
1389#else
1390 pMem->flags = MEM_Null; /* Comment */
1391 pMem->type = SQLITE_NULL;
1392#endif
danielk19770d78bae2008-01-03 07:09:48 +00001393 }
1394
dan2ce22452010-11-08 19:01:16 +00001395 p->nResColumn = 8 - 4*(p->explain-1);
drh9734e6e2011-10-07 18:24:25 +00001396 p->pResultSet = &p->aMem[1];
drh826fb5a2004-02-14 23:59:57 +00001397 p->rc = SQLITE_OK;
1398 rc = SQLITE_ROW;
drh9a324642003-09-06 20:12:01 +00001399 }
drh826fb5a2004-02-14 23:59:57 +00001400 return rc;
drh9a324642003-09-06 20:12:01 +00001401}
drhb7f91642004-10-31 02:22:47 +00001402#endif /* SQLITE_OMIT_EXPLAIN */
drh9a324642003-09-06 20:12:01 +00001403
drh7c4ac0c2007-04-05 11:25:58 +00001404#ifdef SQLITE_DEBUG
drh9a324642003-09-06 20:12:01 +00001405/*
drh3f7d4e42004-07-24 14:35:58 +00001406** Print the SQL that was used to generate a VDBE program.
1407*/
1408void sqlite3VdbePrintSql(Vdbe *p){
drh84e55a82013-11-13 17:58:23 +00001409 const char *z = 0;
1410 if( p->zSql ){
1411 z = p->zSql;
1412 }else if( p->nOp>=1 ){
1413 const VdbeOp *pOp = &p->aOp[0];
1414 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
1415 z = pOp->p4.z;
1416 while( sqlite3Isspace(*z) ) z++;
1417 }
drh3f7d4e42004-07-24 14:35:58 +00001418 }
drh84e55a82013-11-13 17:58:23 +00001419 if( z ) printf("SQL: [%s]\n", z);
drh3f7d4e42004-07-24 14:35:58 +00001420}
drh7c4ac0c2007-04-05 11:25:58 +00001421#endif
drh3f7d4e42004-07-24 14:35:58 +00001422
drh602c2372007-03-01 00:29:13 +00001423#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
1424/*
1425** Print an IOTRACE message showing SQL content.
1426*/
1427void sqlite3VdbeIOTraceSql(Vdbe *p){
1428 int nOp = p->nOp;
1429 VdbeOp *pOp;
mlcreech3a00f902008-03-04 17:45:01 +00001430 if( sqlite3IoTrace==0 ) return;
drh602c2372007-03-01 00:29:13 +00001431 if( nOp<1 ) return;
drh949f9cd2008-01-12 21:35:57 +00001432 pOp = &p->aOp[0];
1433 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
drh602c2372007-03-01 00:29:13 +00001434 int i, j;
drh00a18e42007-08-13 11:10:34 +00001435 char z[1000];
drh949f9cd2008-01-12 21:35:57 +00001436 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
danielk197778ca0e72009-01-20 16:53:39 +00001437 for(i=0; sqlite3Isspace(z[i]); i++){}
drh602c2372007-03-01 00:29:13 +00001438 for(j=0; z[i]; i++){
danielk197778ca0e72009-01-20 16:53:39 +00001439 if( sqlite3Isspace(z[i]) ){
drh602c2372007-03-01 00:29:13 +00001440 if( z[i-1]!=' ' ){
1441 z[j++] = ' ';
1442 }
1443 }else{
1444 z[j++] = z[i];
1445 }
1446 }
1447 z[j] = 0;
mlcreech3a00f902008-03-04 17:45:01 +00001448 sqlite3IoTrace("SQL %s\n", z);
drh602c2372007-03-01 00:29:13 +00001449 }
1450}
1451#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
1452
drhb2771ce2009-02-20 01:28:59 +00001453/*
drh4800b2e2009-12-08 15:35:22 +00001454** Allocate space from a fixed size buffer and return a pointer to
1455** that space. If insufficient space is available, return NULL.
1456**
1457** The pBuf parameter is the initial value of a pointer which will
1458** receive the new memory. pBuf is normally NULL. If pBuf is not
1459** NULL, it means that memory space has already been allocated and that
1460** this routine should not allocate any new memory. When pBuf is not
1461** NULL simply return pBuf. Only allocate new memory space when pBuf
1462** is NULL.
drhb2771ce2009-02-20 01:28:59 +00001463**
1464** nByte is the number of bytes of space needed.
1465**
drh19875c82009-12-08 19:58:19 +00001466** *ppFrom points to available space and pEnd points to the end of the
1467** available space. When space is allocated, *ppFrom is advanced past
1468** the end of the allocated space.
drhb2771ce2009-02-20 01:28:59 +00001469**
1470** *pnByte is a counter of the number of bytes of space that have failed
1471** to allocate. If there is insufficient space in *ppFrom to satisfy the
danielk1977d336e222009-02-20 10:58:41 +00001472** request, then increment *pnByte by the amount of the request.
drhb2771ce2009-02-20 01:28:59 +00001473*/
drh4800b2e2009-12-08 15:35:22 +00001474static void *allocSpace(
1475 void *pBuf, /* Where return pointer will be stored */
drhb2771ce2009-02-20 01:28:59 +00001476 int nByte, /* Number of bytes to allocate */
1477 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
danielk1977d336e222009-02-20 10:58:41 +00001478 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
drhb2771ce2009-02-20 01:28:59 +00001479 int *pnByte /* If allocation cannot be made, increment *pnByte */
1480){
drhea598cb2009-04-05 12:22:08 +00001481 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
drh4800b2e2009-12-08 15:35:22 +00001482 if( pBuf ) return pBuf;
1483 nByte = ROUND8(nByte);
1484 if( &(*ppFrom)[nByte] <= pEnd ){
1485 pBuf = (void*)*ppFrom;
1486 *ppFrom += nByte;
1487 }else{
1488 *pnByte += nByte;
drhb2771ce2009-02-20 01:28:59 +00001489 }
drh4800b2e2009-12-08 15:35:22 +00001490 return pBuf;
drhb2771ce2009-02-20 01:28:59 +00001491}
drh602c2372007-03-01 00:29:13 +00001492
drh3f7d4e42004-07-24 14:35:58 +00001493/*
drh124c0b42011-06-01 18:15:55 +00001494** Rewind the VDBE back to the beginning in preparation for
1495** running it.
drh9a324642003-09-06 20:12:01 +00001496*/
drh124c0b42011-06-01 18:15:55 +00001497void sqlite3VdbeRewind(Vdbe *p){
1498#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
1499 int i;
1500#endif
drh9a324642003-09-06 20:12:01 +00001501 assert( p!=0 );
drh9a324642003-09-06 20:12:01 +00001502 assert( p->magic==VDBE_MAGIC_INIT );
1503
drhc16a03b2004-09-15 13:38:10 +00001504 /* There should be at least one opcode.
drh9a324642003-09-06 20:12:01 +00001505 */
drhc16a03b2004-09-15 13:38:10 +00001506 assert( p->nOp>0 );
drh9a324642003-09-06 20:12:01 +00001507
danielk197700e13612008-11-17 19:18:54 +00001508 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
danielk1977634f2982005-03-28 08:44:07 +00001509 p->magic = VDBE_MAGIC_RUN;
1510
drh124c0b42011-06-01 18:15:55 +00001511#ifdef SQLITE_DEBUG
1512 for(i=1; i<p->nMem; i++){
1513 assert( p->aMem[i].db==p->db );
1514 }
1515#endif
1516 p->pc = -1;
1517 p->rc = SQLITE_OK;
1518 p->errorAction = OE_Abort;
1519 p->magic = VDBE_MAGIC_RUN;
1520 p->nChange = 0;
1521 p->cacheCtr = 1;
1522 p->minWriteFileFormat = 255;
1523 p->iStatement = 0;
1524 p->nFkConstraint = 0;
1525#ifdef VDBE_PROFILE
1526 for(i=0; i<p->nOp; i++){
1527 p->aOp[i].cnt = 0;
1528 p->aOp[i].cycles = 0;
1529 }
1530#endif
1531}
1532
1533/*
1534** Prepare a virtual machine for execution for the first time after
1535** creating the virtual machine. This involves things such
1536** as allocating stack space and initializing the program counter.
1537** After the VDBE has be prepped, it can be executed by one or more
1538** calls to sqlite3VdbeExec().
1539**
1540** This function may be called exact once on a each virtual machine.
1541** After this routine is called the VM has been "packaged" and is ready
1542** to run. After this routine is called, futher calls to
1543** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
1544** the Vdbe from the Parse object that helped generate it so that the
1545** the Vdbe becomes an independent entity and the Parse object can be
1546** destroyed.
1547**
1548** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
1549** to its initial state after it has been run.
1550*/
1551void sqlite3VdbeMakeReady(
1552 Vdbe *p, /* The VDBE */
1553 Parse *pParse /* Parsing context */
1554){
1555 sqlite3 *db; /* The database connection */
1556 int nVar; /* Number of parameters */
1557 int nMem; /* Number of VM memory registers */
1558 int nCursor; /* Number of cursors required */
1559 int nArg; /* Number of arguments in subprograms */
dan1d8cb212011-12-09 13:24:16 +00001560 int nOnce; /* Number of OP_Once instructions */
drh124c0b42011-06-01 18:15:55 +00001561 int n; /* Loop counter */
1562 u8 *zCsr; /* Memory available for allocation */
1563 u8 *zEnd; /* First byte past allocated memory */
1564 int nByte; /* How much extra memory is needed */
1565
1566 assert( p!=0 );
1567 assert( p->nOp>0 );
1568 assert( pParse!=0 );
1569 assert( p->magic==VDBE_MAGIC_INIT );
1570 db = p->db;
1571 assert( db->mallocFailed==0 );
1572 nVar = pParse->nVar;
1573 nMem = pParse->nMem;
1574 nCursor = pParse->nTab;
1575 nArg = pParse->nMaxArg;
dan1d8cb212011-12-09 13:24:16 +00001576 nOnce = pParse->nOnce;
drh20e226d2012-01-01 13:58:53 +00001577 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
drh124c0b42011-06-01 18:15:55 +00001578
danielk1977cd3e8f72008-03-25 09:47:35 +00001579 /* For each cursor required, also allocate a memory cell. Memory
1580 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
1581 ** the vdbe program. Instead they are used to allocate space for
drhdfe88ec2008-11-03 20:55:06 +00001582 ** VdbeCursor/BtCursor structures. The blob of memory associated with
danielk1977cd3e8f72008-03-25 09:47:35 +00001583 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
1584 ** stores the blob of memory associated with cursor 1, etc.
1585 **
1586 ** See also: allocateCursor().
1587 */
1588 nMem += nCursor;
1589
danielk19776ab3a2e2009-02-19 14:39:25 +00001590 /* Allocate space for memory registers, SQL variables, VDBE cursors and
drh124c0b42011-06-01 18:15:55 +00001591 ** an array to marshal SQL function arguments in.
drh9a324642003-09-06 20:12:01 +00001592 */
drh124c0b42011-06-01 18:15:55 +00001593 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
1594 zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
drh19875c82009-12-08 19:58:19 +00001595
drh124c0b42011-06-01 18:15:55 +00001596 resolveP2Values(p, &nArg);
1597 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
1598 if( pParse->explain && nMem<10 ){
1599 nMem = 10;
1600 }
1601 memset(zCsr, 0, zEnd-zCsr);
1602 zCsr += (zCsr - (u8*)0)&7;
1603 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
drhaab910c2011-06-27 00:01:22 +00001604 p->expired = 0;
drh124c0b42011-06-01 18:15:55 +00001605
1606 /* Memory for registers, parameters, cursor, etc, is allocated in two
1607 ** passes. On the first pass, we try to reuse unused space at the
1608 ** end of the opcode array. If we are unable to satisfy all memory
1609 ** requirements by reusing the opcode array tail, then the second
1610 ** pass will fill in the rest using a fresh allocation.
1611 **
1612 ** This two-pass approach that reuses as much memory as possible from
1613 ** the leftover space at the end of the opcode array can significantly
1614 ** reduce the amount of memory held by a prepared statement.
1615 */
1616 do {
1617 nByte = 0;
1618 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
1619 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
1620 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
1621 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
1622 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
1623 &zCsr, zEnd, &nByte);
drhb8475df2011-12-09 16:21:19 +00001624 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
drh124c0b42011-06-01 18:15:55 +00001625 if( nByte ){
1626 p->pFree = sqlite3DbMallocZero(db, nByte);
drh0f7eb612006-08-08 13:51:43 +00001627 }
drh124c0b42011-06-01 18:15:55 +00001628 zCsr = p->pFree;
1629 zEnd = &zCsr[nByte];
1630 }while( nByte && !db->mallocFailed );
drhb2771ce2009-02-20 01:28:59 +00001631
drhd2a56232013-01-28 19:00:20 +00001632 p->nCursor = nCursor;
dan1d8cb212011-12-09 13:24:16 +00001633 p->nOnceFlag = nOnce;
drh124c0b42011-06-01 18:15:55 +00001634 if( p->aVar ){
1635 p->nVar = (ynVar)nVar;
1636 for(n=0; n<nVar; n++){
1637 p->aVar[n].flags = MEM_Null;
1638 p->aVar[n].db = db;
danielk197754db47e2004-05-19 10:36:43 +00001639 }
drh82a48512003-09-06 22:45:20 +00001640 }
drh124c0b42011-06-01 18:15:55 +00001641 if( p->azVar ){
1642 p->nzVar = pParse->nzVar;
1643 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
1644 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
danielk1977b3bce662005-01-29 08:32:43 +00001645 }
drh124c0b42011-06-01 18:15:55 +00001646 if( p->aMem ){
1647 p->aMem--; /* aMem[] goes from 1..nMem */
1648 p->nMem = nMem; /* not from 0..nMem-1 */
1649 for(n=1; n<=nMem; n++){
drhb8475df2011-12-09 16:21:19 +00001650 p->aMem[n].flags = MEM_Invalid;
drh124c0b42011-06-01 18:15:55 +00001651 p->aMem[n].db = db;
drhcf64d8b2003-12-31 17:57:10 +00001652 }
drh9a324642003-09-06 20:12:01 +00001653 }
drh124c0b42011-06-01 18:15:55 +00001654 p->explain = pParse->explain;
1655 sqlite3VdbeRewind(p);
drh9a324642003-09-06 20:12:01 +00001656}
1657
drh9a324642003-09-06 20:12:01 +00001658/*
danielk1977cd3e8f72008-03-25 09:47:35 +00001659** Close a VDBE cursor and release all the resources that cursor
1660** happens to hold.
drh9a324642003-09-06 20:12:01 +00001661*/
drhdfe88ec2008-11-03 20:55:06 +00001662void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
drh4774b132004-06-12 20:12:51 +00001663 if( pCx==0 ){
1664 return;
1665 }
dana20fde62011-07-12 14:28:05 +00001666 sqlite3VdbeSorterClose(p->db, pCx);
drh9a324642003-09-06 20:12:01 +00001667 if( pCx->pBt ){
danielk19774adee202004-05-08 08:23:19 +00001668 sqlite3BtreeClose(pCx->pBt);
drh34004ce2008-07-11 16:15:17 +00001669 /* The pCx->pCursor will be close automatically, if it exists, by
1670 ** the call above. */
1671 }else if( pCx->pCursor ){
1672 sqlite3BtreeCloseCursor(pCx->pCursor);
drh9a324642003-09-06 20:12:01 +00001673 }
drh9eff6162006-06-12 21:59:13 +00001674#ifndef SQLITE_OMIT_VIRTUALTABLE
1675 if( pCx->pVtabCursor ){
1676 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
danielk1977be718892006-06-23 08:05:19 +00001677 const sqlite3_module *pModule = pCx->pModule;
1678 p->inVtabMethod = 1;
drh9eff6162006-06-12 21:59:13 +00001679 pModule->xClose(pVtabCursor);
danielk1977be718892006-06-23 08:05:19 +00001680 p->inVtabMethod = 0;
drh9eff6162006-06-12 21:59:13 +00001681 }
1682#endif
drh9a324642003-09-06 20:12:01 +00001683}
1684
dan65a7cd12009-09-01 12:16:01 +00001685/*
1686** Copy the values stored in the VdbeFrame structure to its Vdbe. This
1687** is used, for example, when a trigger sub-program is halted to restore
1688** control to the main program.
1689*/
dan165921a2009-08-28 18:53:45 +00001690int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
1691 Vdbe *v = pFrame->v;
dan1d8cb212011-12-09 13:24:16 +00001692 v->aOnceFlag = pFrame->aOnceFlag;
1693 v->nOnceFlag = pFrame->nOnceFlag;
dan165921a2009-08-28 18:53:45 +00001694 v->aOp = pFrame->aOp;
1695 v->nOp = pFrame->nOp;
1696 v->aMem = pFrame->aMem;
1697 v->nMem = pFrame->nMem;
1698 v->apCsr = pFrame->apCsr;
1699 v->nCursor = pFrame->nCursor;
dan76d462e2009-08-30 11:42:51 +00001700 v->db->lastRowid = pFrame->lastRowid;
1701 v->nChange = pFrame->nChange;
dan165921a2009-08-28 18:53:45 +00001702 return pFrame->pc;
1703}
1704
drh9a324642003-09-06 20:12:01 +00001705/*
drh5f82e3c2009-07-06 00:44:08 +00001706** Close all cursors.
dan165921a2009-08-28 18:53:45 +00001707**
1708** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
1709** cell array. This is necessary as the memory cell array may contain
1710** pointers to VdbeFrame objects, which may in turn contain pointers to
1711** open cursors.
drh9a324642003-09-06 20:12:01 +00001712*/
drh5f82e3c2009-07-06 00:44:08 +00001713static void closeAllCursors(Vdbe *p){
dan165921a2009-08-28 18:53:45 +00001714 if( p->pFrame ){
drh23272752011-03-06 21:54:33 +00001715 VdbeFrame *pFrame;
dan165921a2009-08-28 18:53:45 +00001716 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
1717 sqlite3VdbeFrameRestore(pFrame);
1718 }
1719 p->pFrame = 0;
1720 p->nFrame = 0;
1721
dan523a0872009-08-31 05:23:32 +00001722 if( p->apCsr ){
1723 int i;
1724 for(i=0; i<p->nCursor; i++){
1725 VdbeCursor *pC = p->apCsr[i];
1726 if( pC ){
1727 sqlite3VdbeFreeCursor(p, pC);
1728 p->apCsr[i] = 0;
1729 }
danielk1977be718892006-06-23 08:05:19 +00001730 }
drh9a324642003-09-06 20:12:01 +00001731 }
dan523a0872009-08-31 05:23:32 +00001732 if( p->aMem ){
1733 releaseMemArray(&p->aMem[1], p->nMem);
1734 }
dan27106572010-12-01 08:04:47 +00001735 while( p->pDelFrame ){
1736 VdbeFrame *pDel = p->pDelFrame;
1737 p->pDelFrame = pDel->pParent;
1738 sqlite3VdbeFrameDelete(pDel);
1739 }
dan0c547792013-07-18 17:12:08 +00001740
1741 /* Delete any auxdata allocations made by the VM */
1742 sqlite3VdbeDeleteAuxData(p, -1, 0);
1743 assert( p->pAuxData==0 );
drh9a324642003-09-06 20:12:01 +00001744}
1745
1746/*
drh9a324642003-09-06 20:12:01 +00001747** Clean up the VM after execution.
1748**
1749** This routine will automatically close any cursors, lists, and/or
1750** sorters that were left open. It also deletes the values of
drh5a12e682004-05-19 11:24:25 +00001751** variables in the aVar[] array.
drh9a324642003-09-06 20:12:01 +00001752*/
drhc890fec2008-08-01 20:10:08 +00001753static void Cleanup(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00001754 sqlite3 *db = p->db;
dan165921a2009-08-28 18:53:45 +00001755
1756#ifdef SQLITE_DEBUG
1757 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
1758 ** Vdbe.aMem[] arrays have already been cleaned up. */
1759 int i;
drhb8475df2011-12-09 16:21:19 +00001760 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
1761 if( p->aMem ){
1762 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
1763 }
dan165921a2009-08-28 18:53:45 +00001764#endif
1765
drh633e6d52008-07-28 19:34:53 +00001766 sqlite3DbFree(db, p->zErrMsg);
drh9a324642003-09-06 20:12:01 +00001767 p->zErrMsg = 0;
drhd4e70eb2008-01-02 00:34:36 +00001768 p->pResultSet = 0;
drh9a324642003-09-06 20:12:01 +00001769}
1770
1771/*
danielk197722322fd2004-05-25 23:35:17 +00001772** Set the number of result columns that will be returned by this SQL
1773** statement. This is now set at compile time, rather than during
1774** execution of the vdbe program so that sqlite3_column_count() can
1775** be called on an SQL statement before sqlite3_step().
1776*/
1777void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
drh76ff3a02004-09-24 22:32:30 +00001778 Mem *pColName;
1779 int n;
drh633e6d52008-07-28 19:34:53 +00001780 sqlite3 *db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001781
drhc890fec2008-08-01 20:10:08 +00001782 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
drh633e6d52008-07-28 19:34:53 +00001783 sqlite3DbFree(db, p->aColName);
danielk1977955de522006-02-10 02:27:42 +00001784 n = nResColumn*COLNAME_N;
shane36840fd2009-06-26 16:32:13 +00001785 p->nResColumn = (u16)nResColumn;
drh633e6d52008-07-28 19:34:53 +00001786 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
drh76ff3a02004-09-24 22:32:30 +00001787 if( p->aColName==0 ) return;
1788 while( n-- > 0 ){
drh4a50aac2007-08-23 02:47:53 +00001789 pColName->flags = MEM_Null;
drh153c62c2007-08-24 03:51:33 +00001790 pColName->db = p->db;
drh4a50aac2007-08-23 02:47:53 +00001791 pColName++;
drh76ff3a02004-09-24 22:32:30 +00001792 }
danielk197722322fd2004-05-25 23:35:17 +00001793}
1794
1795/*
danielk19773cf86062004-05-26 10:11:05 +00001796** Set the name of the idx'th column to be returned by the SQL statement.
1797** zName must be a pointer to a nul terminated string.
1798**
1799** This call must be made after a call to sqlite3VdbeSetNumCols().
1800**
danielk197710fb7492008-10-31 10:53:22 +00001801** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
1802** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
1803** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
danielk19773cf86062004-05-26 10:11:05 +00001804*/
danielk197710fb7492008-10-31 10:53:22 +00001805int sqlite3VdbeSetColName(
1806 Vdbe *p, /* Vdbe being configured */
1807 int idx, /* Index of column zName applies to */
1808 int var, /* One of the COLNAME_* constants */
1809 const char *zName, /* Pointer to buffer containing name */
1810 void (*xDel)(void*) /* Memory management strategy for zName */
1811){
danielk19773cf86062004-05-26 10:11:05 +00001812 int rc;
1813 Mem *pColName;
danielk1977955de522006-02-10 02:27:42 +00001814 assert( idx<p->nResColumn );
1815 assert( var<COLNAME_N );
danielk197710fb7492008-10-31 10:53:22 +00001816 if( p->db->mallocFailed ){
1817 assert( !zName || xDel!=SQLITE_DYNAMIC );
1818 return SQLITE_NOMEM;
1819 }
drh76ff3a02004-09-24 22:32:30 +00001820 assert( p->aColName!=0 );
danielk1977955de522006-02-10 02:27:42 +00001821 pColName = &(p->aColName[idx+var*p->nResColumn]);
danielk197710fb7492008-10-31 10:53:22 +00001822 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
drh0793f1b2008-11-05 17:41:19 +00001823 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
danielk19773cf86062004-05-26 10:11:05 +00001824 return rc;
1825}
1826
danielk197713adf8a2004-06-03 16:08:41 +00001827/*
1828** A read or write transaction may or may not be active on database handle
1829** db. If a transaction is active, commit it. If there is a
1830** write-transaction spanning more than one database file, this routine
1831** takes care of the master journal trickery.
1832*/
danielk19773e3a84d2008-08-01 17:37:40 +00001833static int vdbeCommit(sqlite3 *db, Vdbe *p){
danielk197713adf8a2004-06-03 16:08:41 +00001834 int i;
1835 int nTrans = 0; /* Number of databases with an active write-transaction */
1836 int rc = SQLITE_OK;
1837 int needXcommit = 0;
1838
shane36840fd2009-06-26 16:32:13 +00001839#ifdef SQLITE_OMIT_VIRTUALTABLE
1840 /* With this option, sqlite3VtabSync() is defined to be simply
1841 ** SQLITE_OK so p is not used.
1842 */
1843 UNUSED_PARAMETER(p);
1844#endif
1845
danielk19775bd270b2006-07-25 15:14:52 +00001846 /* Before doing anything else, call the xSync() callback for any
1847 ** virtual module tables written in this transaction. This has to
1848 ** be done before determining whether a master journal file is
1849 ** required, as an xSync() callback may add an attached database
1850 ** to the transaction.
1851 */
dan016f7812013-08-21 17:35:48 +00001852 rc = sqlite3VtabSync(db, p);
danielk19775bd270b2006-07-25 15:14:52 +00001853
1854 /* This loop determines (a) if the commit hook should be invoked and
1855 ** (b) how many database files have open write transactions, not
1856 ** including the temp database. (b) is important because if more than
1857 ** one database file has an open write transaction, a master journal
1858 ** file is required for an atomic commit.
1859 */
drhabfb62f2010-07-30 11:20:35 +00001860 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001861 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00001862 if( sqlite3BtreeIsInTrans(pBt) ){
danielk197713adf8a2004-06-03 16:08:41 +00001863 needXcommit = 1;
1864 if( i!=1 ) nTrans++;
dan6b9bb592012-10-05 19:43:02 +00001865 sqlite3BtreeEnter(pBt);
drhabfb62f2010-07-30 11:20:35 +00001866 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
dan6b9bb592012-10-05 19:43:02 +00001867 sqlite3BtreeLeave(pBt);
danielk197713adf8a2004-06-03 16:08:41 +00001868 }
1869 }
drhabfb62f2010-07-30 11:20:35 +00001870 if( rc!=SQLITE_OK ){
1871 return rc;
1872 }
danielk197713adf8a2004-06-03 16:08:41 +00001873
1874 /* If there are any write-transactions at all, invoke the commit hook */
1875 if( needXcommit && db->xCommitCallback ){
drh92f02c32004-09-02 14:57:08 +00001876 rc = db->xCommitCallback(db->pCommitArg);
drh92f02c32004-09-02 14:57:08 +00001877 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00001878 return SQLITE_CONSTRAINT_COMMITHOOK;
danielk197713adf8a2004-06-03 16:08:41 +00001879 }
1880 }
1881
danielk197740b38dc2004-06-26 08:38:24 +00001882 /* The simple case - no more than one database file (not counting the
1883 ** TEMP database) has a transaction active. There is no need for the
drh2ac3ee92004-06-07 16:27:46 +00001884 ** master-journal.
drhc9e06862004-06-09 20:03:08 +00001885 **
danielk197740b38dc2004-06-26 08:38:24 +00001886 ** If the return value of sqlite3BtreeGetFilename() is a zero length
danielk197717b90b52008-06-06 11:11:25 +00001887 ** string, it means the main database is :memory: or a temp file. In
1888 ** that case we do not support atomic multi-file commits, so use the
1889 ** simple case then too.
danielk197713adf8a2004-06-03 16:08:41 +00001890 */
drhea678832008-12-10 19:26:22 +00001891 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
1892 || nTrans<=1
1893 ){
danielk197704103022009-02-03 16:51:24 +00001894 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001895 Btree *pBt = db->aDb[i].pBt;
1896 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00001897 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
drh2ac3ee92004-06-07 16:27:46 +00001898 }
1899 }
1900
drh80e35f42007-03-30 14:06:34 +00001901 /* Do the commit only if all databases successfully complete phase 1.
1902 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
1903 ** IO error while deleting or truncating a journal file. It is unlikely,
1904 ** but could happen. In this case abandon processing and return the error.
danielk1977979f38e2007-03-27 16:19:51 +00001905 */
1906 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
1907 Btree *pBt = db->aDb[i].pBt;
1908 if( pBt ){
dan60939d02011-03-29 15:40:55 +00001909 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
danielk197713adf8a2004-06-03 16:08:41 +00001910 }
danielk1977979f38e2007-03-27 16:19:51 +00001911 }
1912 if( rc==SQLITE_OK ){
danielk1977f9e7dda2006-06-16 16:08:53 +00001913 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00001914 }
1915 }
1916
1917 /* The complex case - There is a multi-file write-transaction active.
1918 ** This requires a master journal file to ensure the transaction is
1919 ** committed atomicly.
1920 */
danielk197744ee5bf2005-05-27 09:41:12 +00001921#ifndef SQLITE_OMIT_DISKIO
danielk197713adf8a2004-06-03 16:08:41 +00001922 else{
danielk1977b4b47412007-08-17 15:53:36 +00001923 sqlite3_vfs *pVfs = db->pVfs;
drh2c8997b2005-08-27 16:36:48 +00001924 int needSync = 0;
danielk197713adf8a2004-06-03 16:08:41 +00001925 char *zMaster = 0; /* File-name for the master journal */
1926 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
danielk1977b4b47412007-08-17 15:53:36 +00001927 sqlite3_file *pMaster = 0;
danielk197762079062007-08-15 17:08:46 +00001928 i64 offset = 0;
danielk1977861f7452008-06-05 11:39:11 +00001929 int res;
drhf5808602011-12-16 00:33:04 +00001930 int retryCount = 0;
drh5c531a42011-12-16 01:21:31 +00001931 int nMainFile;
danielk197713adf8a2004-06-03 16:08:41 +00001932
1933 /* Select a master journal file name */
drh5c531a42011-12-16 01:21:31 +00001934 nMainFile = sqlite3Strlen30(zMainFile);
drh52bcde02012-01-03 14:50:45 +00001935 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
drh5c531a42011-12-16 01:21:31 +00001936 if( zMaster==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00001937 do {
drhdc5ea5c2008-12-10 17:19:59 +00001938 u32 iRandom;
drh84968c02011-12-16 15:11:39 +00001939 if( retryCount ){
1940 if( retryCount>100 ){
1941 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
1942 sqlite3OsDelete(pVfs, zMaster, 0);
1943 break;
1944 }else if( retryCount==1 ){
1945 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
1946 }
danielk197713adf8a2004-06-03 16:08:41 +00001947 }
drh84968c02011-12-16 15:11:39 +00001948 retryCount++;
danielk197713adf8a2004-06-03 16:08:41 +00001949 sqlite3_randomness(sizeof(iRandom), &iRandom);
drh5c531a42011-12-16 01:21:31 +00001950 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
drhf5808602011-12-16 00:33:04 +00001951 (iRandom>>8)&0xffffff, iRandom&0xff);
drhf5808602011-12-16 00:33:04 +00001952 /* The antipenultimate character of the master journal name must
1953 ** be "9" to avoid name collisions when using 8+3 filenames. */
drh5c531a42011-12-16 01:21:31 +00001954 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
drh81cc5162011-05-17 20:36:21 +00001955 sqlite3FileSuffix3(zMainFile, zMaster);
danielk1977861f7452008-06-05 11:39:11 +00001956 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
1957 }while( rc==SQLITE_OK && res );
1958 if( rc==SQLITE_OK ){
drh19db9352008-03-27 22:42:51 +00001959 /* Open the master journal. */
1960 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
1961 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
1962 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
1963 );
1964 }
danielk197713adf8a2004-06-03 16:08:41 +00001965 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00001966 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00001967 return rc;
1968 }
1969
1970 /* Write the name of each database file in the transaction into the new
1971 ** master journal file. If an error occurs at this point close
1972 ** and delete the master journal file. All the individual journal files
1973 ** still have 'null' as the master journal pointer, so they will roll
danielk1977aca790a2005-01-13 11:07:52 +00001974 ** back independently if a failure occurs.
danielk197713adf8a2004-06-03 16:08:41 +00001975 */
danielk19771e536952007-08-16 10:09:01 +00001976 for(i=0; i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00001977 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00001978 if( sqlite3BtreeIsInTrans(pBt) ){
danielk19775865e3d2004-06-14 06:03:57 +00001979 char const *zFile = sqlite3BtreeGetJournalname(pBt);
drh8c96a6e2010-08-31 01:09:15 +00001980 if( zFile==0 ){
drhb290e1c2009-12-08 13:36:55 +00001981 continue; /* Ignore TEMP and :memory: databases */
1982 }
drh8c96a6e2010-08-31 01:09:15 +00001983 assert( zFile[0]!=0 );
drh2c8997b2005-08-27 16:36:48 +00001984 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
1985 needSync = 1;
1986 }
drhea678832008-12-10 19:26:22 +00001987 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
1988 offset += sqlite3Strlen30(zFile)+1;
danielk197713adf8a2004-06-03 16:08:41 +00001989 if( rc!=SQLITE_OK ){
danielk1977fee2d252007-08-18 10:59:19 +00001990 sqlite3OsCloseFree(pMaster);
1991 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00001992 sqlite3DbFree(db, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00001993 return rc;
1994 }
1995 }
1996 }
1997
danielk19779663b8f2007-08-24 11:52:28 +00001998 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
1999 ** flag is set this is not required.
2000 */
danielk1977bea2a942009-01-20 17:06:27 +00002001 if( needSync
2002 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
2003 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
2004 ){
danielk1977fee2d252007-08-18 10:59:19 +00002005 sqlite3OsCloseFree(pMaster);
2006 sqlite3OsDelete(pVfs, zMaster, 0);
drh633e6d52008-07-28 19:34:53 +00002007 sqlite3DbFree(db, zMaster);
danielk19775865e3d2004-06-14 06:03:57 +00002008 return rc;
2009 }
drhc9e06862004-06-09 20:03:08 +00002010
danielk197713adf8a2004-06-03 16:08:41 +00002011 /* Sync all the db files involved in the transaction. The same call
2012 ** sets the master journal pointer in each individual journal. If
2013 ** an error occurs here, do not delete the master journal file.
2014 **
drh80e35f42007-03-30 14:06:34 +00002015 ** If the error occurs during the first call to
2016 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2017 ** master journal file will be orphaned. But we cannot delete it,
2018 ** in case the master journal file name was written into the journal
shanebe217792009-03-05 04:20:31 +00002019 ** file before the failure occurred.
danielk197713adf8a2004-06-03 16:08:41 +00002020 */
danielk19775bd270b2006-07-25 15:14:52 +00002021 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
danielk197713adf8a2004-06-03 16:08:41 +00002022 Btree *pBt = db->aDb[i].pBt;
drhd0679ed2007-08-28 22:24:34 +00002023 if( pBt ){
drh80e35f42007-03-30 14:06:34 +00002024 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
danielk197713adf8a2004-06-03 16:08:41 +00002025 }
2026 }
danielk1977fee2d252007-08-18 10:59:19 +00002027 sqlite3OsCloseFree(pMaster);
drhabfb62f2010-07-30 11:20:35 +00002028 assert( rc!=SQLITE_BUSY );
danielk19775bd270b2006-07-25 15:14:52 +00002029 if( rc!=SQLITE_OK ){
drh633e6d52008-07-28 19:34:53 +00002030 sqlite3DbFree(db, zMaster);
danielk19775bd270b2006-07-25 15:14:52 +00002031 return rc;
2032 }
danielk197713adf8a2004-06-03 16:08:41 +00002033
danielk1977962398d2004-06-14 09:35:16 +00002034 /* Delete the master journal file. This commits the transaction. After
2035 ** doing this the directory is synced again before any individual
2036 ** transaction files are deleted.
2037 */
danielk1977fee2d252007-08-18 10:59:19 +00002038 rc = sqlite3OsDelete(pVfs, zMaster, 1);
drh633e6d52008-07-28 19:34:53 +00002039 sqlite3DbFree(db, zMaster);
drhc416ba92007-03-30 18:42:55 +00002040 zMaster = 0;
drh29a01382006-08-13 19:04:18 +00002041 if( rc ){
2042 return rc;
2043 }
danielk197713adf8a2004-06-03 16:08:41 +00002044
2045 /* All files and directories have already been synced, so the following
drh80e35f42007-03-30 14:06:34 +00002046 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
2047 ** deleting or truncating journals. If something goes wrong while
2048 ** this is happening we don't really care. The integrity of the
2049 ** transaction is already guaranteed, but some stray 'cold' journals
2050 ** may be lying around. Returning an error code won't help matters.
danielk197713adf8a2004-06-03 16:08:41 +00002051 */
danielk1977979f38e2007-03-27 16:19:51 +00002052 disable_simulated_io_errors();
danielk19772d1d86f2008-06-20 14:59:51 +00002053 sqlite3BeginBenignMalloc();
danielk197713adf8a2004-06-03 16:08:41 +00002054 for(i=0; i<db->nDb; i++){
2055 Btree *pBt = db->aDb[i].pBt;
2056 if( pBt ){
dan60939d02011-03-29 15:40:55 +00002057 sqlite3BtreeCommitPhaseTwo(pBt, 1);
danielk197713adf8a2004-06-03 16:08:41 +00002058 }
2059 }
danielk19772d1d86f2008-06-20 14:59:51 +00002060 sqlite3EndBenignMalloc();
danielk1977979f38e2007-03-27 16:19:51 +00002061 enable_simulated_io_errors();
2062
danielk1977f9e7dda2006-06-16 16:08:53 +00002063 sqlite3VtabCommit(db);
danielk197713adf8a2004-06-03 16:08:41 +00002064 }
danielk197744ee5bf2005-05-27 09:41:12 +00002065#endif
danielk1977026d2702004-06-14 13:14:59 +00002066
drh2ac3ee92004-06-07 16:27:46 +00002067 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00002068}
2069
danielk19771d850a72004-05-31 08:26:49 +00002070/*
drh4f7d3a52013-06-27 23:54:02 +00002071** This routine checks that the sqlite3.nVdbeActive count variable
danielk19771d850a72004-05-31 08:26:49 +00002072** matches the number of vdbe's in the list sqlite3.pVdbe that are
2073** currently active. An assertion fails if the two counts do not match.
drh92f02c32004-09-02 14:57:08 +00002074** This is an internal self-check only - it is not an essential processing
2075** step.
danielk19771d850a72004-05-31 08:26:49 +00002076**
2077** This is a no-op if NDEBUG is defined.
2078*/
2079#ifndef NDEBUG
drh9bb575f2004-09-06 17:24:11 +00002080static void checkActiveVdbeCnt(sqlite3 *db){
danielk19771d850a72004-05-31 08:26:49 +00002081 Vdbe *p;
2082 int cnt = 0;
drhad4a4b82008-11-05 16:37:34 +00002083 int nWrite = 0;
drh4f7d3a52013-06-27 23:54:02 +00002084 int nRead = 0;
danielk19771d850a72004-05-31 08:26:49 +00002085 p = db->pVdbe;
2086 while( p ){
drh92f02c32004-09-02 14:57:08 +00002087 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
danielk19771d850a72004-05-31 08:26:49 +00002088 cnt++;
drhad4a4b82008-11-05 16:37:34 +00002089 if( p->readOnly==0 ) nWrite++;
drh1713afb2013-06-28 01:24:57 +00002090 if( p->bIsReader ) nRead++;
danielk19771d850a72004-05-31 08:26:49 +00002091 }
2092 p = p->pNext;
2093 }
drh4f7d3a52013-06-27 23:54:02 +00002094 assert( cnt==db->nVdbeActive );
2095 assert( nWrite==db->nVdbeWrite );
2096 assert( nRead==db->nVdbeRead );
danielk19771d850a72004-05-31 08:26:49 +00002097}
2098#else
2099#define checkActiveVdbeCnt(x)
2100#endif
2101
danielk19773cf86062004-05-26 10:11:05 +00002102/*
danielk1977bd434552009-03-18 10:33:00 +00002103** If the Vdbe passed as the first argument opened a statement-transaction,
2104** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
2105** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
2106** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
drhf7b54962013-05-28 12:11:54 +00002107** statement transaction is committed.
danielk1977bd434552009-03-18 10:33:00 +00002108**
2109** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
2110** Otherwise SQLITE_OK.
2111*/
2112int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
danielk1977c926b6a2009-03-20 14:42:11 +00002113 sqlite3 *const db = p->db;
danielk1977bd434552009-03-18 10:33:00 +00002114 int rc = SQLITE_OK;
danielk1977ecaecf92009-07-08 08:05:35 +00002115
danielk1977e4948172009-07-17 17:25:43 +00002116 /* If p->iStatement is greater than zero, then this Vdbe opened a
2117 ** statement transaction that should be closed here. The only exception
mistachkin48864df2013-03-21 21:20:32 +00002118 ** is that an IO error may have occurred, causing an emergency rollback.
danielk1977e4948172009-07-17 17:25:43 +00002119 ** In this case (db->nStatement==0), and there is nothing to do.
2120 */
2121 if( db->nStatement && p->iStatement ){
danielk1977bd434552009-03-18 10:33:00 +00002122 int i;
2123 const int iSavepoint = p->iStatement-1;
danielk1977bd434552009-03-18 10:33:00 +00002124
2125 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
2126 assert( db->nStatement>0 );
2127 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
2128
2129 for(i=0; i<db->nDb; i++){
2130 int rc2 = SQLITE_OK;
2131 Btree *pBt = db->aDb[i].pBt;
2132 if( pBt ){
2133 if( eOp==SAVEPOINT_ROLLBACK ){
2134 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
2135 }
2136 if( rc2==SQLITE_OK ){
2137 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
2138 }
2139 if( rc==SQLITE_OK ){
2140 rc = rc2;
2141 }
2142 }
2143 }
2144 db->nStatement--;
2145 p->iStatement = 0;
dan1da40a32009-09-19 17:00:31 +00002146
dana311b802011-04-26 19:21:34 +00002147 if( rc==SQLITE_OK ){
2148 if( eOp==SAVEPOINT_ROLLBACK ){
2149 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
2150 }
2151 if( rc==SQLITE_OK ){
2152 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
2153 }
2154 }
2155
dan1da40a32009-09-19 17:00:31 +00002156 /* If the statement transaction is being rolled back, also restore the
2157 ** database handles deferred constraint counter to the value it had when
2158 ** the statement transaction was opened. */
2159 if( eOp==SAVEPOINT_ROLLBACK ){
2160 db->nDeferredCons = p->nStmtDefCons;
drh648e2642013-07-11 15:03:32 +00002161 db->nDeferredImmCons = p->nStmtDefImmCons;
dan1da40a32009-09-19 17:00:31 +00002162 }
danielk1977bd434552009-03-18 10:33:00 +00002163 }
2164 return rc;
2165}
2166
2167/*
dan1da40a32009-09-19 17:00:31 +00002168** This function is called when a transaction opened by the database
2169** handle associated with the VM passed as an argument is about to be
2170** committed. If there are outstanding deferred foreign key constraint
2171** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
2172**
2173** If there are outstanding FK violations and this function returns
drhd91c1a12013-02-09 13:58:25 +00002174** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
2175** and write an error message to it. Then return SQLITE_ERROR.
dan1da40a32009-09-19 17:00:31 +00002176*/
2177#ifndef SQLITE_OMIT_FOREIGN_KEY
dan32b09f22009-09-23 17:29:59 +00002178int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
dan1da40a32009-09-19 17:00:31 +00002179 sqlite3 *db = p->db;
drh648e2642013-07-11 15:03:32 +00002180 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
2181 || (!deferred && p->nFkConstraint>0)
2182 ){
drhd91c1a12013-02-09 13:58:25 +00002183 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan32b09f22009-09-23 17:29:59 +00002184 p->errorAction = OE_Abort;
drhf9c8ce32013-11-05 13:33:55 +00002185 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
dan1da40a32009-09-19 17:00:31 +00002186 return SQLITE_ERROR;
2187 }
2188 return SQLITE_OK;
2189}
2190#endif
2191
2192/*
drh92f02c32004-09-02 14:57:08 +00002193** This routine is called the when a VDBE tries to halt. If the VDBE
2194** has made changes and is in autocommit mode, then commit those
2195** changes. If a rollback is needed, then do the rollback.
drh9a324642003-09-06 20:12:01 +00002196**
drh92f02c32004-09-02 14:57:08 +00002197** This routine is the only way to move the state of a VM from
drhff0587c2007-08-29 17:43:19 +00002198** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
2199** call this on a VM that is in the SQLITE_MAGIC_HALT state.
drh92f02c32004-09-02 14:57:08 +00002200**
2201** Return an error code. If the commit could not complete because of
2202** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
2203** means the close did not happen and needs to be repeated.
drh9a324642003-09-06 20:12:01 +00002204*/
drhff0587c2007-08-29 17:43:19 +00002205int sqlite3VdbeHalt(Vdbe *p){
danielk1977bd434552009-03-18 10:33:00 +00002206 int rc; /* Used to store transient return codes */
drh9bb575f2004-09-06 17:24:11 +00002207 sqlite3 *db = p->db;
danielk197707cb5602006-01-20 10:55:05 +00002208
2209 /* This function contains the logic that determines if a statement or
2210 ** transaction will be committed or rolled back as a result of the
2211 ** execution of this virtual machine.
2212 **
drh71b890a2007-10-03 15:30:52 +00002213 ** If any of the following errors occur:
danielk197707cb5602006-01-20 10:55:05 +00002214 **
drh71b890a2007-10-03 15:30:52 +00002215 ** SQLITE_NOMEM
2216 ** SQLITE_IOERR
2217 ** SQLITE_FULL
2218 ** SQLITE_INTERRUPT
danielk197707cb5602006-01-20 10:55:05 +00002219 **
drh71b890a2007-10-03 15:30:52 +00002220 ** Then the internal cache might have been left in an inconsistent
2221 ** state. We need to rollback the statement transaction, if there is
2222 ** one, or the complete transaction if there is no statement transaction.
danielk197707cb5602006-01-20 10:55:05 +00002223 */
drh9a324642003-09-06 20:12:01 +00002224
drh17435752007-08-16 04:30:38 +00002225 if( p->db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002226 p->rc = SQLITE_NOMEM;
2227 }
drh6e856bc2011-12-09 18:06:44 +00002228 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
drh5f82e3c2009-07-06 00:44:08 +00002229 closeAllCursors(p);
drh92f02c32004-09-02 14:57:08 +00002230 if( p->magic!=VDBE_MAGIC_RUN ){
drh92f02c32004-09-02 14:57:08 +00002231 return SQLITE_OK;
drh9a324642003-09-06 20:12:01 +00002232 }
danielk19771d850a72004-05-31 08:26:49 +00002233 checkActiveVdbeCnt(db);
danielk1977261919c2005-12-06 12:52:59 +00002234
danc0537fe2013-06-28 19:41:43 +00002235 /* No commit or rollback needed if the program never started or if the
2236 ** SQL statement does not read or write a database file. */
2237 if( p->pc>=0 && p->bIsReader ){
drhaac2f552006-09-23 21:44:23 +00002238 int mrc; /* Primary error code from p->rc */
danielk1977bd434552009-03-18 10:33:00 +00002239 int eStatementOp = 0;
2240 int isSpecialError; /* Set to true if a 'special' error */
drhff0587c2007-08-29 17:43:19 +00002241
2242 /* Lock all btrees used by the statement */
drhbdaec522011-04-04 00:14:43 +00002243 sqlite3VdbeEnter(p);
drhff0587c2007-08-29 17:43:19 +00002244
drh71b890a2007-10-03 15:30:52 +00002245 /* Check for one of the special errors */
drhaac2f552006-09-23 21:44:23 +00002246 mrc = p->rc & 0xff;
drhfa3be902009-07-07 02:44:07 +00002247 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
drh71b890a2007-10-03 15:30:52 +00002248 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
drh77658e22007-12-04 16:54:52 +00002249 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
danielk197707cb5602006-01-20 10:55:05 +00002250 if( isSpecialError ){
dan5653e4d2010-08-12 11:25:47 +00002251 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
2252 ** no rollback is necessary. Otherwise, at least a savepoint
2253 ** transaction must be rolled back to restore the database to a
2254 ** consistent state.
2255 **
2256 ** Even if the statement is read-only, it is important to perform
2257 ** a statement or transaction rollback operation. If the error
mistachkin48864df2013-03-21 21:20:32 +00002258 ** occurred while writing to the journal, sub-journal or database
dan5653e4d2010-08-12 11:25:47 +00002259 ** file as part of an effort to free up cache space (see function
2260 ** pagerStress() in pager.c), the rollback is required to restore
2261 ** the pager to a consistent state.
danielk197707cb5602006-01-20 10:55:05 +00002262 */
drhad4a4b82008-11-05 16:37:34 +00002263 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
drhfa3be902009-07-07 02:44:07 +00002264 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
danielk1977bd434552009-03-18 10:33:00 +00002265 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002266 }else{
2267 /* We are forced to roll back the active transaction. Before doing
2268 ** so, abort any other statements this handle currently has active.
2269 */
drh21021a52012-02-13 17:01:51 +00002270 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002271 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002272 db->autoCommit = 1;
2273 }
danielk1977261919c2005-12-06 12:52:59 +00002274 }
2275 }
dan32b09f22009-09-23 17:29:59 +00002276
2277 /* Check for immediate foreign key violations. */
2278 if( p->rc==SQLITE_OK ){
2279 sqlite3VdbeCheckFk(p, 0);
2280 }
danielk197707cb5602006-01-20 10:55:05 +00002281
danielk1977bd434552009-03-18 10:33:00 +00002282 /* If the auto-commit flag is set and this is the only active writer
2283 ** VM, then we do either a commit or rollback of the current transaction.
danielk197707cb5602006-01-20 10:55:05 +00002284 **
2285 ** Note: This block also runs if one of the special errors handled
drhad4a4b82008-11-05 16:37:34 +00002286 ** above has occurred.
danielk197707cb5602006-01-20 10:55:05 +00002287 */
danielk1977093e0f62008-11-13 18:00:14 +00002288 if( !sqlite3VtabInSync(db)
2289 && db->autoCommit
drh4f7d3a52013-06-27 23:54:02 +00002290 && db->nVdbeWrite==(p->readOnly==0)
danielk1977093e0f62008-11-13 18:00:14 +00002291 ){
danielk197707cb5602006-01-20 10:55:05 +00002292 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
dan19611b12011-01-24 16:00:58 +00002293 rc = sqlite3VdbeCheckFk(p, 1);
2294 if( rc!=SQLITE_OK ){
drhe9ce5852011-02-11 22:54:28 +00002295 if( NEVER(p->readOnly) ){
drhbdaec522011-04-04 00:14:43 +00002296 sqlite3VdbeLeave(p);
dan19611b12011-01-24 16:00:58 +00002297 return SQLITE_ERROR;
2298 }
drhd91c1a12013-02-09 13:58:25 +00002299 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
dan19611b12011-01-24 16:00:58 +00002300 }else{
2301 /* The auto-commit flag is true, the vdbe program was successful
2302 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
2303 ** key constraints to hold up the transaction. This means a commit
2304 ** is required. */
2305 rc = vdbeCommit(db, p);
dan1da40a32009-09-19 17:00:31 +00002306 }
dan19611b12011-01-24 16:00:58 +00002307 if( rc==SQLITE_BUSY && p->readOnly ){
drhbdaec522011-04-04 00:14:43 +00002308 sqlite3VdbeLeave(p);
danielk197707cb5602006-01-20 10:55:05 +00002309 return SQLITE_BUSY;
2310 }else if( rc!=SQLITE_OK ){
2311 p->rc = rc;
drh0f198a72012-02-13 16:43:16 +00002312 sqlite3RollbackAll(db, SQLITE_OK);
danielk197707cb5602006-01-20 10:55:05 +00002313 }else{
dan1da40a32009-09-19 17:00:31 +00002314 db->nDeferredCons = 0;
drh648e2642013-07-11 15:03:32 +00002315 db->nDeferredImmCons = 0;
2316 db->flags &= ~SQLITE_DeferFKs;
danielk197707cb5602006-01-20 10:55:05 +00002317 sqlite3CommitInternalChanges(db);
2318 }
2319 }else{
drh0f198a72012-02-13 16:43:16 +00002320 sqlite3RollbackAll(db, SQLITE_OK);
danielk197707cb5602006-01-20 10:55:05 +00002321 }
danielk1977bd434552009-03-18 10:33:00 +00002322 db->nStatement = 0;
2323 }else if( eStatementOp==0 ){
danielk197707cb5602006-01-20 10:55:05 +00002324 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
danielk1977bd434552009-03-18 10:33:00 +00002325 eStatementOp = SAVEPOINT_RELEASE;
danielk197707cb5602006-01-20 10:55:05 +00002326 }else if( p->errorAction==OE_Abort ){
danielk1977bd434552009-03-18 10:33:00 +00002327 eStatementOp = SAVEPOINT_ROLLBACK;
danielk197707cb5602006-01-20 10:55:05 +00002328 }else{
drh21021a52012-02-13 17:01:51 +00002329 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
danielk1977fc158bf2009-01-07 08:12:16 +00002330 sqlite3CloseSavepoints(db);
danielk197707cb5602006-01-20 10:55:05 +00002331 db->autoCommit = 1;
2332 }
danielk19771d850a72004-05-31 08:26:49 +00002333 }
danielk197707cb5602006-01-20 10:55:05 +00002334
danielk1977bd434552009-03-18 10:33:00 +00002335 /* If eStatementOp is non-zero, then a statement transaction needs to
2336 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
2337 ** do so. If this operation returns an error, and the current statement
drh35173242010-03-08 21:40:13 +00002338 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
2339 ** current statement error code.
danielk197707cb5602006-01-20 10:55:05 +00002340 */
danielk1977bd434552009-03-18 10:33:00 +00002341 if( eStatementOp ){
2342 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
dan40ad9d22010-06-03 09:17:38 +00002343 if( rc ){
drhd91c1a12013-02-09 13:58:25 +00002344 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
dan40ad9d22010-06-03 09:17:38 +00002345 p->rc = rc;
2346 sqlite3DbFree(db, p->zErrMsg);
2347 p->zErrMsg = 0;
2348 }
drh21021a52012-02-13 17:01:51 +00002349 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
dan40ad9d22010-06-03 09:17:38 +00002350 sqlite3CloseSavepoints(db);
2351 db->autoCommit = 1;
danielk197707cb5602006-01-20 10:55:05 +00002352 }
danielk197777d83ba2004-05-31 10:08:14 +00002353 }
danielk197707cb5602006-01-20 10:55:05 +00002354
danielk1977bd434552009-03-18 10:33:00 +00002355 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
2356 ** has been rolled back, update the database connection change-counter.
danielk197707cb5602006-01-20 10:55:05 +00002357 */
drh6be240e2009-07-14 02:33:02 +00002358 if( p->changeCntOn ){
danielk1977bd434552009-03-18 10:33:00 +00002359 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
danielk197707cb5602006-01-20 10:55:05 +00002360 sqlite3VdbeSetChanges(db, p->nChange);
2361 }else{
2362 sqlite3VdbeSetChanges(db, 0);
2363 }
2364 p->nChange = 0;
danielk1977b28af712004-06-21 06:50:26 +00002365 }
drhff0587c2007-08-29 17:43:19 +00002366
2367 /* Release the locks */
drhbdaec522011-04-04 00:14:43 +00002368 sqlite3VdbeLeave(p);
drh9a324642003-09-06 20:12:01 +00002369 }
danielk19771d850a72004-05-31 08:26:49 +00002370
danielk197765fd59f2006-06-24 11:51:33 +00002371 /* We have successfully halted and closed the VM. Record this fact. */
2372 if( p->pc>=0 ){
drh4f7d3a52013-06-27 23:54:02 +00002373 db->nVdbeActive--;
2374 if( !p->readOnly ) db->nVdbeWrite--;
drh1713afb2013-06-28 01:24:57 +00002375 if( p->bIsReader ) db->nVdbeRead--;
drh4f7d3a52013-06-27 23:54:02 +00002376 assert( db->nVdbeActive>=db->nVdbeRead );
2377 assert( db->nVdbeRead>=db->nVdbeWrite );
2378 assert( db->nVdbeWrite>=0 );
drh9a324642003-09-06 20:12:01 +00002379 }
drh92f02c32004-09-02 14:57:08 +00002380 p->magic = VDBE_MAGIC_HALT;
2381 checkActiveVdbeCnt(db);
drhff0587c2007-08-29 17:43:19 +00002382 if( p->db->mallocFailed ){
2383 p->rc = SQLITE_NOMEM;
2384 }
danielk19771d850a72004-05-31 08:26:49 +00002385
danielk1977404ca072009-03-16 13:19:36 +00002386 /* If the auto-commit flag is set to true, then any locks that were held
2387 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
2388 ** to invoke any required unlock-notify callbacks.
2389 */
2390 if( db->autoCommit ){
2391 sqlite3ConnectionUnlocked(db);
2392 }
2393
drh4f7d3a52013-06-27 23:54:02 +00002394 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
dan19611b12011-01-24 16:00:58 +00002395 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
drh92f02c32004-09-02 14:57:08 +00002396}
drh4cf7c7f2007-08-28 23:28:07 +00002397
drh92f02c32004-09-02 14:57:08 +00002398
2399/*
drh3c23a882007-01-09 14:01:13 +00002400** Each VDBE holds the result of the most recent sqlite3_step() call
2401** in p->rc. This routine sets that result back to SQLITE_OK.
2402*/
2403void sqlite3VdbeResetStepResult(Vdbe *p){
2404 p->rc = SQLITE_OK;
2405}
2406
2407/*
dan029ead62011-10-27 15:19:58 +00002408** Copy the error code and error message belonging to the VDBE passed
2409** as the first argument to its database handle (so that they will be
2410** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
2411**
2412** This function does not clear the VDBE error code or message, just
2413** copies them to the database handle.
2414*/
2415int sqlite3VdbeTransferError(Vdbe *p){
2416 sqlite3 *db = p->db;
2417 int rc = p->rc;
2418 if( p->zErrMsg ){
drh81bdd6d2011-10-29 01:33:24 +00002419 u8 mallocFailed = db->mallocFailed;
dan029ead62011-10-27 15:19:58 +00002420 sqlite3BeginBenignMalloc();
2421 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2422 sqlite3EndBenignMalloc();
drh81bdd6d2011-10-29 01:33:24 +00002423 db->mallocFailed = mallocFailed;
dan029ead62011-10-27 15:19:58 +00002424 db->errCode = rc;
2425 }else{
2426 sqlite3Error(db, rc, 0);
2427 }
2428 return rc;
2429}
2430
danac455932012-11-26 19:50:41 +00002431#ifdef SQLITE_ENABLE_SQLLOG
2432/*
2433** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
2434** invoke it.
2435*/
2436static void vdbeInvokeSqllog(Vdbe *v){
2437 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
2438 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
2439 assert( v->db->init.busy==0 );
2440 if( zExpanded ){
2441 sqlite3GlobalConfig.xSqllog(
2442 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
2443 );
2444 sqlite3DbFree(v->db, zExpanded);
2445 }
2446 }
2447}
2448#else
2449# define vdbeInvokeSqllog(x)
2450#endif
2451
dan029ead62011-10-27 15:19:58 +00002452/*
drh92f02c32004-09-02 14:57:08 +00002453** Clean up a VDBE after execution but do not delete the VDBE just yet.
2454** Write any error messages into *pzErrMsg. Return the result code.
2455**
2456** After this routine is run, the VDBE should be ready to be executed
2457** again.
2458**
2459** To look at it another way, this routine resets the state of the
2460** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
2461** VDBE_MAGIC_INIT.
2462*/
drhc890fec2008-08-01 20:10:08 +00002463int sqlite3VdbeReset(Vdbe *p){
drh4ac285a2006-09-15 07:28:50 +00002464 sqlite3 *db;
drh4ac285a2006-09-15 07:28:50 +00002465 db = p->db;
drh92f02c32004-09-02 14:57:08 +00002466
2467 /* If the VM did not run to completion or if it encountered an
2468 ** error, then it might not have been halted properly. So halt
2469 ** it now.
2470 */
2471 sqlite3VdbeHalt(p);
2472
drhfb7e7652005-01-24 00:28:42 +00002473 /* If the VDBE has be run even partially, then transfer the error code
2474 ** and error message from the VDBE into the main database structure. But
2475 ** if the VDBE has just been set to run but has not actually executed any
2476 ** instructions yet, leave the main database error information unchanged.
drh92f02c32004-09-02 14:57:08 +00002477 */
drhfb7e7652005-01-24 00:28:42 +00002478 if( p->pc>=0 ){
danac455932012-11-26 19:50:41 +00002479 vdbeInvokeSqllog(p);
dan029ead62011-10-27 15:19:58 +00002480 sqlite3VdbeTransferError(p);
2481 sqlite3DbFree(db, p->zErrMsg);
2482 p->zErrMsg = 0;
drh4611d922010-02-25 14:47:01 +00002483 if( p->runOnlyOnce ) p->expired = 1;
danielk1977a21c6b62005-01-24 10:25:59 +00002484 }else if( p->rc && p->expired ){
2485 /* The expired flag was set on the VDBE before the first call
2486 ** to sqlite3_step(). For consistency (since sqlite3_step() was
2487 ** called), set the database error in this case as well.
2488 */
drh4ac285a2006-09-15 07:28:50 +00002489 sqlite3Error(db, p->rc, 0);
drh633e6d52008-07-28 19:34:53 +00002490 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
2491 sqlite3DbFree(db, p->zErrMsg);
danielk19778e556522007-11-13 10:30:24 +00002492 p->zErrMsg = 0;
drh92f02c32004-09-02 14:57:08 +00002493 }
2494
2495 /* Reclaim all memory used by the VDBE
2496 */
drhc890fec2008-08-01 20:10:08 +00002497 Cleanup(p);
drh92f02c32004-09-02 14:57:08 +00002498
2499 /* Save profiling information from this VDBE run.
2500 */
drh9a324642003-09-06 20:12:01 +00002501#ifdef VDBE_PROFILE
2502 {
2503 FILE *out = fopen("vdbe_profile.out", "a");
2504 if( out ){
2505 int i;
2506 fprintf(out, "---- ");
2507 for(i=0; i<p->nOp; i++){
2508 fprintf(out, "%02x", p->aOp[i].opcode);
2509 }
2510 fprintf(out, "\n");
2511 for(i=0; i<p->nOp; i++){
2512 fprintf(out, "%6d %10lld %8lld ",
2513 p->aOp[i].cnt,
2514 p->aOp[i].cycles,
2515 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
2516 );
danielk19774adee202004-05-08 08:23:19 +00002517 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
drh9a324642003-09-06 20:12:01 +00002518 }
2519 fclose(out);
2520 }
2521 }
2522#endif
drh7fa20922013-09-17 23:36:33 +00002523 p->iCurrentTime = 0;
drh9a324642003-09-06 20:12:01 +00002524 p->magic = VDBE_MAGIC_INIT;
drh4ac285a2006-09-15 07:28:50 +00002525 return p->rc & db->errMask;
drh9a324642003-09-06 20:12:01 +00002526}
drh92f02c32004-09-02 14:57:08 +00002527
drh9a324642003-09-06 20:12:01 +00002528/*
2529** Clean up and delete a VDBE after execution. Return an integer which is
2530** the result code. Write any error message text into *pzErrMsg.
2531*/
danielk19779e6db7d2004-06-21 08:18:51 +00002532int sqlite3VdbeFinalize(Vdbe *p){
danielk1977b5548a82004-06-26 13:51:33 +00002533 int rc = SQLITE_OK;
danielk1977b5548a82004-06-26 13:51:33 +00002534 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
drhc890fec2008-08-01 20:10:08 +00002535 rc = sqlite3VdbeReset(p);
drh4ac285a2006-09-15 07:28:50 +00002536 assert( (rc & p->db->errMask)==rc );
drh9a324642003-09-06 20:12:01 +00002537 }
danielk19774adee202004-05-08 08:23:19 +00002538 sqlite3VdbeDelete(p);
drh9a324642003-09-06 20:12:01 +00002539 return rc;
2540}
2541
2542/*
dan0c547792013-07-18 17:12:08 +00002543** If parameter iOp is less than zero, then invoke the destructor for
2544** all auxiliary data pointers currently cached by the VM passed as
2545** the first argument.
2546**
2547** Or, if iOp is greater than or equal to zero, then the destructor is
2548** only invoked for those auxiliary data pointers created by the user
2549** function invoked by the OP_Function opcode at instruction iOp of
2550** VM pVdbe, and only then if:
2551**
2552** * the associated function parameter is the 32nd or later (counting
2553** from left to right), or
2554**
2555** * the corresponding bit in argument mask is clear (where the first
2556** function parameter corrsponds to bit 0 etc.).
drhf92c7ff2004-06-19 15:40:23 +00002557*/
dan0c547792013-07-18 17:12:08 +00002558void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
2559 AuxData **pp = &pVdbe->pAuxData;
2560 while( *pp ){
2561 AuxData *pAux = *pp;
2562 if( (iOp<0)
2563 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
2564 ){
drhf92c7ff2004-06-19 15:40:23 +00002565 if( pAux->xDelete ){
2566 pAux->xDelete(pAux->pAux);
2567 }
dan0c547792013-07-18 17:12:08 +00002568 *pp = pAux->pNext;
2569 sqlite3DbFree(pVdbe->db, pAux);
2570 }else{
2571 pp= &pAux->pNext;
drhf92c7ff2004-06-19 15:40:23 +00002572 }
2573 }
2574}
2575
2576/*
drhcb103b92012-10-26 00:11:23 +00002577** Free all memory associated with the Vdbe passed as the second argument,
2578** except for object itself, which is preserved.
2579**
dand46def72010-07-24 11:28:28 +00002580** The difference between this function and sqlite3VdbeDelete() is that
2581** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
drhcb103b92012-10-26 00:11:23 +00002582** the database connection and frees the object itself.
dand46def72010-07-24 11:28:28 +00002583*/
drhcb103b92012-10-26 00:11:23 +00002584void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
dand19c9332010-07-26 12:05:17 +00002585 SubProgram *pSub, *pNext;
drh124c0b42011-06-01 18:15:55 +00002586 int i;
dand46def72010-07-24 11:28:28 +00002587 assert( p->db==0 || p->db==db );
2588 releaseMemArray(p->aVar, p->nVar);
2589 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
dand19c9332010-07-26 12:05:17 +00002590 for(pSub=p->pProgram; pSub; pSub=pNext){
2591 pNext = pSub->pNext;
2592 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
2593 sqlite3DbFree(db, pSub);
2594 }
drh124c0b42011-06-01 18:15:55 +00002595 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
dand46def72010-07-24 11:28:28 +00002596 vdbeFreeOpArray(db, p->aOp, p->nOp);
2597 sqlite3DbFree(db, p->aLabel);
2598 sqlite3DbFree(db, p->aColName);
2599 sqlite3DbFree(db, p->zSql);
2600 sqlite3DbFree(db, p->pFree);
drh678a9aa2011-12-10 15:55:01 +00002601#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
drh25fe97a2013-01-23 18:44:22 +00002602 sqlite3DbFree(db, p->zExplain);
drh678a9aa2011-12-10 15:55:01 +00002603 sqlite3DbFree(db, p->pExplain);
drh7e02e5e2011-12-06 19:44:51 +00002604#endif
dand46def72010-07-24 11:28:28 +00002605}
2606
2607/*
drh9a324642003-09-06 20:12:01 +00002608** Delete an entire VDBE.
2609*/
danielk19774adee202004-05-08 08:23:19 +00002610void sqlite3VdbeDelete(Vdbe *p){
drh633e6d52008-07-28 19:34:53 +00002611 sqlite3 *db;
2612
drhfa3be902009-07-07 02:44:07 +00002613 if( NEVER(p==0) ) return;
drh633e6d52008-07-28 19:34:53 +00002614 db = p->db;
drh4245c402012-06-02 14:32:21 +00002615 assert( sqlite3_mutex_held(db->mutex) );
drhcb103b92012-10-26 00:11:23 +00002616 sqlite3VdbeClearObject(db, p);
drh9a324642003-09-06 20:12:01 +00002617 if( p->pPrev ){
2618 p->pPrev->pNext = p->pNext;
2619 }else{
drh633e6d52008-07-28 19:34:53 +00002620 assert( db->pVdbe==p );
2621 db->pVdbe = p->pNext;
drh9a324642003-09-06 20:12:01 +00002622 }
2623 if( p->pNext ){
2624 p->pNext->pPrev = p->pPrev;
2625 }
drh9a324642003-09-06 20:12:01 +00002626 p->magic = VDBE_MAGIC_DEAD;
drh87f5c5f2010-01-20 01:20:56 +00002627 p->db = 0;
drhcb103b92012-10-26 00:11:23 +00002628 sqlite3DbFree(db, p);
drh9a324642003-09-06 20:12:01 +00002629}
drha11846b2004-01-07 18:52:56 +00002630
2631/*
drh9a65f2c2009-06-22 19:05:40 +00002632** Make sure the cursor p is ready to read or write the row to which it
2633** was last positioned. Return an error code if an OOM fault or I/O error
2634** prevents us from positioning the cursor to its correct position.
2635**
drha11846b2004-01-07 18:52:56 +00002636** If a MoveTo operation is pending on the given cursor, then do that
drh9a65f2c2009-06-22 19:05:40 +00002637** MoveTo now. If no move is pending, check to see if the row has been
2638** deleted out from under the cursor and if it has, mark the row as
2639** a NULL row.
2640**
2641** If the cursor is already pointing to the correct row and that row has
2642** not been deleted out from under the cursor, then this routine is a no-op.
drha11846b2004-01-07 18:52:56 +00002643*/
drhdfe88ec2008-11-03 20:55:06 +00002644int sqlite3VdbeCursorMoveto(VdbeCursor *p){
drha11846b2004-01-07 18:52:56 +00002645 if( p->deferredMoveto ){
drh536065a2005-01-26 21:55:31 +00002646 int res, rc;
adamd4fc93082006-09-14 16:57:19 +00002647#ifdef SQLITE_TEST
danielk1977132872b2004-05-10 10:37:18 +00002648 extern int sqlite3_search_count;
adamd4fc93082006-09-14 16:57:19 +00002649#endif
drhf0863fe2005-06-12 21:35:51 +00002650 assert( p->isTable );
drhe63d9992008-08-13 19:11:48 +00002651 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
drh536065a2005-01-26 21:55:31 +00002652 if( rc ) return rc;
drhaa736092009-06-22 00:55:30 +00002653 p->lastRowid = p->movetoTarget;
drhbe0b2372010-07-30 18:40:55 +00002654 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
2655 p->rowidIsValid = 1;
drh10cfdd52006-08-08 15:42:59 +00002656#ifdef SQLITE_TEST
danielk1977132872b2004-05-10 10:37:18 +00002657 sqlite3_search_count++;
drh10cfdd52006-08-08 15:42:59 +00002658#endif
drha11846b2004-01-07 18:52:56 +00002659 p->deferredMoveto = 0;
drh76873ab2006-01-07 18:48:26 +00002660 p->cacheStatus = CACHE_STALE;
drh6be240e2009-07-14 02:33:02 +00002661 }else if( ALWAYS(p->pCursor) ){
drha3460582008-07-11 21:02:53 +00002662 int hasMoved;
2663 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
2664 if( rc ) return rc;
2665 if( hasMoved ){
2666 p->cacheStatus = CACHE_STALE;
2667 p->nullRow = 1;
2668 }
drha11846b2004-01-07 18:52:56 +00002669 }
2670 return SQLITE_OK;
2671}
danielk19774adee202004-05-08 08:23:19 +00002672
drhab9f7f12004-05-08 10:56:11 +00002673/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002674** The following functions:
danielk197790e4d952004-05-10 10:05:53 +00002675**
danielk1977cfcdaef2004-05-12 07:33:33 +00002676** sqlite3VdbeSerialType()
2677** sqlite3VdbeSerialTypeLen()
danielk197790e4d952004-05-10 10:05:53 +00002678** sqlite3VdbeSerialLen()
shane92003092008-07-31 01:43:13 +00002679** sqlite3VdbeSerialPut()
2680** sqlite3VdbeSerialGet()
danielk197790e4d952004-05-10 10:05:53 +00002681**
2682** encapsulate the code that serializes values for storage in SQLite
danielk1977cfcdaef2004-05-12 07:33:33 +00002683** data and index records. Each serialized value consists of a
2684** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
2685** integer, stored as a varint.
danielk197790e4d952004-05-10 10:05:53 +00002686**
danielk1977cfcdaef2004-05-12 07:33:33 +00002687** In an SQLite index record, the serial type is stored directly before
2688** the blob of data that it corresponds to. In a table record, all serial
2689** types are stored at the start of the record, and the blobs of data at
2690** the end. Hence these functions allow the caller to handle the
mistachkin48864df2013-03-21 21:20:32 +00002691** serial-type and data blob separately.
danielk1977cfcdaef2004-05-12 07:33:33 +00002692**
2693** The following table describes the various storage classes for data:
2694**
2695** serial type bytes of data type
danielk197790e4d952004-05-10 10:05:53 +00002696** -------------- --------------- ---------------
drha19b7752004-05-30 21:14:58 +00002697** 0 0 NULL
danielk197790e4d952004-05-10 10:05:53 +00002698** 1 1 signed integer
2699** 2 2 signed integer
drha19b7752004-05-30 21:14:58 +00002700** 3 3 signed integer
2701** 4 4 signed integer
2702** 5 6 signed integer
2703** 6 8 signed integer
2704** 7 8 IEEE float
drhd946db02005-12-29 19:23:06 +00002705** 8 0 Integer constant 0
2706** 9 0 Integer constant 1
2707** 10,11 reserved for expansion
danielk197790e4d952004-05-10 10:05:53 +00002708** N>=12 and even (N-12)/2 BLOB
2709** N>=13 and odd (N-13)/2 text
2710**
drh35a59652006-01-02 18:24:40 +00002711** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
2712** of SQLite will not understand those serial types.
danielk197790e4d952004-05-10 10:05:53 +00002713*/
2714
2715/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002716** Return the serial-type for the value stored in pMem.
danielk1977192ac1d2004-05-10 07:17:30 +00002717*/
drhd946db02005-12-29 19:23:06 +00002718u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
danielk1977cfcdaef2004-05-12 07:33:33 +00002719 int flags = pMem->flags;
drhfdf972a2007-05-02 13:30:27 +00002720 int n;
danielk1977cfcdaef2004-05-12 07:33:33 +00002721
2722 if( flags&MEM_Null ){
drha19b7752004-05-30 21:14:58 +00002723 return 0;
danielk197790e4d952004-05-10 10:05:53 +00002724 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002725 if( flags&MEM_Int ){
drhfe2093d2005-01-20 22:48:47 +00002726 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
drh5284a052008-05-08 15:18:10 +00002727# define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
drh3c024d62007-03-30 11:23:45 +00002728 i64 i = pMem->u.i;
drhd946db02005-12-29 19:23:06 +00002729 u64 u;
drhcfd654b2011-03-05 13:54:15 +00002730 if( i<0 ){
2731 if( i<(-MAX_6BYTE) ) return 6;
2732 /* Previous test prevents: u = -(-9223372036854775808) */
2733 u = -i;
2734 }else{
2735 u = i;
2736 }
drh56690b32012-09-17 15:36:31 +00002737 if( u<=127 ){
2738 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
2739 }
drh5742b632005-01-26 17:47:02 +00002740 if( u<=32767 ) return 2;
2741 if( u<=8388607 ) return 3;
2742 if( u<=2147483647 ) return 4;
2743 if( u<=MAX_6BYTE ) return 5;
drha19b7752004-05-30 21:14:58 +00002744 return 6;
danielk197790e4d952004-05-10 10:05:53 +00002745 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002746 if( flags&MEM_Real ){
drha19b7752004-05-30 21:14:58 +00002747 return 7;
danielk197790e4d952004-05-10 10:05:53 +00002748 }
danielk1977e4359752008-11-03 09:39:45 +00002749 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
drhfdf972a2007-05-02 13:30:27 +00002750 n = pMem->n;
2751 if( flags & MEM_Zero ){
drh8df32842008-12-09 02:51:23 +00002752 n += pMem->u.nZero;
danielk197790e4d952004-05-10 10:05:53 +00002753 }
drhfdf972a2007-05-02 13:30:27 +00002754 assert( n>=0 );
2755 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
danielk1977192ac1d2004-05-10 07:17:30 +00002756}
2757
2758/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002759** Return the length of the data corresponding to the supplied serial-type.
danielk1977192ac1d2004-05-10 07:17:30 +00002760*/
drh35cd6432009-06-05 14:17:21 +00002761u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
drha19b7752004-05-30 21:14:58 +00002762 if( serial_type>=12 ){
drh51846b52004-05-28 16:00:21 +00002763 return (serial_type-12)/2;
2764 }else{
drh57196282004-10-06 15:41:16 +00002765 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
drh51846b52004-05-28 16:00:21 +00002766 return aSize[serial_type];
2767 }
danielk1977192ac1d2004-05-10 07:17:30 +00002768}
2769
2770/*
drh110daac2007-05-04 11:59:31 +00002771** If we are on an architecture with mixed-endian floating
drh7a4f5022007-05-23 07:20:08 +00002772** points (ex: ARM7) then swap the lower 4 bytes with the
drh110daac2007-05-04 11:59:31 +00002773** upper 4 bytes. Return the result.
2774**
drh7a4f5022007-05-23 07:20:08 +00002775** For most architectures, this is a no-op.
2776**
2777** (later): It is reported to me that the mixed-endian problem
2778** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
2779** that early versions of GCC stored the two words of a 64-bit
2780** float in the wrong order. And that error has been propagated
2781** ever since. The blame is not necessarily with GCC, though.
2782** GCC might have just copying the problem from a prior compiler.
2783** I am also told that newer versions of GCC that follow a different
2784** ABI get the byte order right.
2785**
2786** Developers using SQLite on an ARM7 should compile and run their
2787** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
2788** enabled, some asserts below will ensure that the byte order of
2789** floating point values is correct.
drh60d09a72007-08-30 15:05:08 +00002790**
2791** (2007-08-30) Frank van Vugt has studied this problem closely
2792** and has send his findings to the SQLite developers. Frank
2793** writes that some Linux kernels offer floating point hardware
2794** emulation that uses only 32-bit mantissas instead of a full
2795** 48-bits as required by the IEEE standard. (This is the
2796** CONFIG_FPE_FASTFPE option.) On such systems, floating point
2797** byte swapping becomes very complicated. To avoid problems,
2798** the necessary byte swapping is carried out using a 64-bit integer
2799** rather than a 64-bit float. Frank assures us that the code here
2800** works for him. We, the developers, have no way to independently
2801** verify this, but Frank seems to know what he is talking about
2802** so we trust him.
drh110daac2007-05-04 11:59:31 +00002803*/
2804#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
drh60d09a72007-08-30 15:05:08 +00002805static u64 floatSwap(u64 in){
drh110daac2007-05-04 11:59:31 +00002806 union {
drh60d09a72007-08-30 15:05:08 +00002807 u64 r;
drh110daac2007-05-04 11:59:31 +00002808 u32 i[2];
2809 } u;
2810 u32 t;
2811
2812 u.r = in;
2813 t = u.i[0];
2814 u.i[0] = u.i[1];
2815 u.i[1] = t;
2816 return u.r;
2817}
2818# define swapMixedEndianFloat(X) X = floatSwap(X)
2819#else
2820# define swapMixedEndianFloat(X)
2821#endif
2822
2823/*
danielk1977cfcdaef2004-05-12 07:33:33 +00002824** Write the serialized data blob for the value stored in pMem into
2825** buf. It is assumed that the caller has allocated sufficient space.
2826** Return the number of bytes written.
drhfdf972a2007-05-02 13:30:27 +00002827**
2828** nBuf is the amount of space left in buf[]. nBuf must always be
2829** large enough to hold the entire field. Except, if the field is
2830** a blob with a zero-filled tail, then buf[] might be just the right
2831** size to hold everything except for the zero-filled tail. If buf[]
2832** is only big enough to hold the non-zero prefix, then only write that
2833** prefix into buf[]. But if buf[] is large enough to hold both the
2834** prefix and the tail then write the prefix and set the tail to all
2835** zeros.
2836**
2837** Return the number of bytes actually written into buf[]. The number
2838** of bytes in the zero-filled tail is included in the return value only
2839** if those bytes were zeroed in buf[].
danielk1977cfcdaef2004-05-12 07:33:33 +00002840*/
drh35cd6432009-06-05 14:17:21 +00002841u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
drhd946db02005-12-29 19:23:06 +00002842 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
drh35cd6432009-06-05 14:17:21 +00002843 u32 len;
danielk1977183f9f72004-05-13 05:20:26 +00002844
drh1483e142004-05-21 21:12:42 +00002845 /* Integer and Real */
drhd946db02005-12-29 19:23:06 +00002846 if( serial_type<=7 && serial_type>0 ){
drh1483e142004-05-21 21:12:42 +00002847 u64 v;
drh35cd6432009-06-05 14:17:21 +00002848 u32 i;
drha19b7752004-05-30 21:14:58 +00002849 if( serial_type==7 ){
drh4f0c5872007-03-26 22:05:01 +00002850 assert( sizeof(v)==sizeof(pMem->r) );
2851 memcpy(&v, &pMem->r, sizeof(v));
drh60d09a72007-08-30 15:05:08 +00002852 swapMixedEndianFloat(v);
drh1483e142004-05-21 21:12:42 +00002853 }else{
drh3c024d62007-03-30 11:23:45 +00002854 v = pMem->u.i;
danielk1977cfcdaef2004-05-12 07:33:33 +00002855 }
drh1483e142004-05-21 21:12:42 +00002856 len = i = sqlite3VdbeSerialTypeLen(serial_type);
shane75ac1de2009-06-09 18:58:52 +00002857 assert( len<=(u32)nBuf );
drh1483e142004-05-21 21:12:42 +00002858 while( i-- ){
drh8df32842008-12-09 02:51:23 +00002859 buf[i] = (u8)(v&0xFF);
drh1483e142004-05-21 21:12:42 +00002860 v >>= 8;
2861 }
2862 return len;
danielk1977cfcdaef2004-05-12 07:33:33 +00002863 }
drhd946db02005-12-29 19:23:06 +00002864
danielk1977cfcdaef2004-05-12 07:33:33 +00002865 /* String or blob */
drhd946db02005-12-29 19:23:06 +00002866 if( serial_type>=12 ){
drh8df32842008-12-09 02:51:23 +00002867 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
shane75ac1de2009-06-09 18:58:52 +00002868 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
drhfdf972a2007-05-02 13:30:27 +00002869 assert( pMem->n<=nBuf );
2870 len = pMem->n;
drhd946db02005-12-29 19:23:06 +00002871 memcpy(buf, pMem->z, len);
drhfdf972a2007-05-02 13:30:27 +00002872 if( pMem->flags & MEM_Zero ){
drh8df32842008-12-09 02:51:23 +00002873 len += pMem->u.nZero;
drh35cd6432009-06-05 14:17:21 +00002874 assert( nBuf>=0 );
2875 if( len > (u32)nBuf ){
2876 len = (u32)nBuf;
drhfdf972a2007-05-02 13:30:27 +00002877 }
2878 memset(&buf[pMem->n], 0, len-pMem->n);
2879 }
drhd946db02005-12-29 19:23:06 +00002880 return len;
2881 }
2882
2883 /* NULL or constants 0 or 1 */
2884 return 0;
danielk1977cfcdaef2004-05-12 07:33:33 +00002885}
2886
2887/*
2888** Deserialize the data blob pointed to by buf as serial type serial_type
2889** and store the result in pMem. Return the number of bytes read.
2890*/
drh35cd6432009-06-05 14:17:21 +00002891u32 sqlite3VdbeSerialGet(
danielk197793d46752004-05-23 13:30:58 +00002892 const unsigned char *buf, /* Buffer to deserialize from */
drh25aa1b42004-05-28 01:39:01 +00002893 u32 serial_type, /* Serial type to deserialize */
2894 Mem *pMem /* Memory cell to write value into */
danielk1977b1bc9532004-05-22 03:05:33 +00002895){
drh3c685822005-05-21 18:32:18 +00002896 switch( serial_type ){
drh3c685822005-05-21 18:32:18 +00002897 case 10: /* Reserved for future use */
2898 case 11: /* Reserved for future use */
2899 case 0: { /* NULL */
2900 pMem->flags = MEM_Null;
2901 break;
2902 }
2903 case 1: { /* 1-byte signed integer */
drh3c024d62007-03-30 11:23:45 +00002904 pMem->u.i = (signed char)buf[0];
drh1483e142004-05-21 21:12:42 +00002905 pMem->flags = MEM_Int;
drh3c685822005-05-21 18:32:18 +00002906 return 1;
drh1483e142004-05-21 21:12:42 +00002907 }
drh3c685822005-05-21 18:32:18 +00002908 case 2: { /* 2-byte signed integer */
drh3c024d62007-03-30 11:23:45 +00002909 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
drh3c685822005-05-21 18:32:18 +00002910 pMem->flags = MEM_Int;
2911 return 2;
2912 }
2913 case 3: { /* 3-byte signed integer */
drh3c024d62007-03-30 11:23:45 +00002914 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
drh3c685822005-05-21 18:32:18 +00002915 pMem->flags = MEM_Int;
2916 return 3;
2917 }
2918 case 4: { /* 4-byte signed integer */
drh3c024d62007-03-30 11:23:45 +00002919 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
drh3c685822005-05-21 18:32:18 +00002920 pMem->flags = MEM_Int;
2921 return 4;
2922 }
2923 case 5: { /* 6-byte signed integer */
2924 u64 x = (((signed char)buf[0])<<8) | buf[1];
2925 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
2926 x = (x<<32) | y;
drh3c024d62007-03-30 11:23:45 +00002927 pMem->u.i = *(i64*)&x;
drh3c685822005-05-21 18:32:18 +00002928 pMem->flags = MEM_Int;
2929 return 6;
2930 }
drh91124b32005-08-18 18:15:05 +00002931 case 6: /* 8-byte signed integer */
drh3c685822005-05-21 18:32:18 +00002932 case 7: { /* IEEE floating point */
drhd81bd4e2005-09-05 20:06:49 +00002933 u64 x;
2934 u32 y;
drh2a3e4a72006-01-23 21:44:53 +00002935#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
drhde941c62005-08-28 01:34:21 +00002936 /* Verify that integers and floating point values use the same
drh110daac2007-05-04 11:59:31 +00002937 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
2938 ** defined that 64-bit floating point values really are mixed
2939 ** endian.
drhbfd6b032005-08-28 01:38:44 +00002940 */
drhde941c62005-08-28 01:34:21 +00002941 static const u64 t1 = ((u64)0x3ff00000)<<32;
drh4f0c5872007-03-26 22:05:01 +00002942 static const double r1 = 1.0;
drh60d09a72007-08-30 15:05:08 +00002943 u64 t2 = t1;
2944 swapMixedEndianFloat(t2);
2945 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
drhde941c62005-08-28 01:34:21 +00002946#endif
drhbfd6b032005-08-28 01:38:44 +00002947
drhd81bd4e2005-09-05 20:06:49 +00002948 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
2949 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
drh3c685822005-05-21 18:32:18 +00002950 x = (x<<32) | y;
2951 if( serial_type==6 ){
drh3c024d62007-03-30 11:23:45 +00002952 pMem->u.i = *(i64*)&x;
drh3c685822005-05-21 18:32:18 +00002953 pMem->flags = MEM_Int;
2954 }else{
drh4f0c5872007-03-26 22:05:01 +00002955 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
drh60d09a72007-08-30 15:05:08 +00002956 swapMixedEndianFloat(x);
drh4f0c5872007-03-26 22:05:01 +00002957 memcpy(&pMem->r, &x, sizeof(x));
drh2eaf93d2008-04-29 00:15:20 +00002958 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
drh3c685822005-05-21 18:32:18 +00002959 }
2960 return 8;
2961 }
drhd946db02005-12-29 19:23:06 +00002962 case 8: /* Integer 0 */
2963 case 9: { /* Integer 1 */
drh3c024d62007-03-30 11:23:45 +00002964 pMem->u.i = serial_type-8;
drhd946db02005-12-29 19:23:06 +00002965 pMem->flags = MEM_Int;
2966 return 0;
2967 }
drh3c685822005-05-21 18:32:18 +00002968 default: {
drh35cd6432009-06-05 14:17:21 +00002969 u32 len = (serial_type-12)/2;
drh3c685822005-05-21 18:32:18 +00002970 pMem->z = (char *)buf;
2971 pMem->n = len;
2972 pMem->xDel = 0;
2973 if( serial_type&0x01 ){
2974 pMem->flags = MEM_Str | MEM_Ephem;
2975 }else{
2976 pMem->flags = MEM_Blob | MEM_Ephem;
2977 }
2978 return len;
drh696b32f2004-05-30 01:51:52 +00002979 }
danielk1977cfcdaef2004-05-12 07:33:33 +00002980 }
drh3c685822005-05-21 18:32:18 +00002981 return 0;
danielk1977192ac1d2004-05-10 07:17:30 +00002982}
2983
drh1e968a02008-03-25 00:22:21 +00002984/*
dan03e9cfc2011-09-05 14:20:27 +00002985** This routine is used to allocate sufficient space for an UnpackedRecord
2986** structure large enough to be used with sqlite3VdbeRecordUnpack() if
2987** the first argument is a pointer to KeyInfo structure pKeyInfo.
drh1e968a02008-03-25 00:22:21 +00002988**
dan03e9cfc2011-09-05 14:20:27 +00002989** The space is either allocated using sqlite3DbMallocRaw() or from within
2990** the unaligned buffer passed via the second and third arguments (presumably
2991** stack space). If the former, then *ppFree is set to a pointer that should
2992** be eventually freed by the caller using sqlite3DbFree(). Or, if the
2993** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
2994** before returning.
drh1e968a02008-03-25 00:22:21 +00002995**
dan03e9cfc2011-09-05 14:20:27 +00002996** If an OOM error occurs, NULL is returned.
2997*/
2998UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
2999 KeyInfo *pKeyInfo, /* Description of the record */
3000 char *pSpace, /* Unaligned space available */
3001 int szSpace, /* Size of pSpace[] in bytes */
3002 char **ppFree /* OUT: Caller should free this pointer */
drh1e968a02008-03-25 00:22:21 +00003003){
dan03e9cfc2011-09-05 14:20:27 +00003004 UnpackedRecord *p; /* Unpacked record to return */
3005 int nOff; /* Increment pSpace by nOff to align it */
3006 int nByte; /* Number of bytes required for *p */
3007
3008 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
shane80167bf2009-04-10 15:42:36 +00003009 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
3010 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
3011 */
3012 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
drh8c5d1522009-04-10 00:56:28 +00003013 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
dan42acb3e2011-09-05 20:16:38 +00003014 if( nByte>szSpace+nOff ){
dan03e9cfc2011-09-05 14:20:27 +00003015 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
3016 *ppFree = (char *)p;
dan42acb3e2011-09-05 20:16:38 +00003017 if( !p ) return 0;
drh1e968a02008-03-25 00:22:21 +00003018 }else{
dan42acb3e2011-09-05 20:16:38 +00003019 p = (UnpackedRecord*)&pSpace[nOff];
dan03e9cfc2011-09-05 14:20:27 +00003020 *ppFree = 0;
drh1e968a02008-03-25 00:22:21 +00003021 }
dan42acb3e2011-09-05 20:16:38 +00003022
3023 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
drhe1a022e2012-09-17 17:16:53 +00003024 assert( pKeyInfo->aSortOrder!=0 );
drh1e968a02008-03-25 00:22:21 +00003025 p->pKeyInfo = pKeyInfo;
3026 p->nField = pKeyInfo->nField + 1;
dan03e9cfc2011-09-05 14:20:27 +00003027 return p;
3028}
3029
3030/*
3031** Given the nKey-byte encoding of a record in pKey[], populate the
3032** UnpackedRecord structure indicated by the fourth argument with the
3033** contents of the decoded record.
3034*/
3035void sqlite3VdbeRecordUnpack(
3036 KeyInfo *pKeyInfo, /* Information about the record format */
3037 int nKey, /* Size of the binary record */
3038 const void *pKey, /* The binary record */
3039 UnpackedRecord *p /* Populate this structure before returning. */
3040){
3041 const unsigned char *aKey = (const unsigned char *)pKey;
3042 int d;
3043 u32 idx; /* Offset in aKey[] to read from */
3044 u16 u; /* Unsigned loop counter */
3045 u32 szHdr;
dan42acb3e2011-09-05 20:16:38 +00003046 Mem *pMem = p->aMem;
dan03e9cfc2011-09-05 14:20:27 +00003047
3048 p->flags = 0;
drh8c5d1522009-04-10 00:56:28 +00003049 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
shane3f8d5cf2008-04-24 19:15:09 +00003050 idx = getVarint32(aKey, szHdr);
drh1e968a02008-03-25 00:22:21 +00003051 d = szHdr;
shane0b8d2762008-07-22 05:18:00 +00003052 u = 0;
drh2fa34d32009-07-15 16:30:50 +00003053 while( idx<szHdr && u<p->nField && d<=nKey ){
drh1e968a02008-03-25 00:22:21 +00003054 u32 serial_type;
3055
danielk197700e13612008-11-17 19:18:54 +00003056 idx += getVarint32(&aKey[idx], serial_type);
drh1e968a02008-03-25 00:22:21 +00003057 pMem->enc = pKeyInfo->enc;
3058 pMem->db = pKeyInfo->db;
drhc3f1d5f2011-05-30 23:42:16 +00003059 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
danielk19775f096132008-03-28 15:44:09 +00003060 pMem->zMalloc = 0;
drh1e968a02008-03-25 00:22:21 +00003061 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
drhe14006d2008-03-25 17:23:32 +00003062 pMem++;
shane0b8d2762008-07-22 05:18:00 +00003063 u++;
drh1e968a02008-03-25 00:22:21 +00003064 }
drh7d10d5a2008-08-20 16:35:10 +00003065 assert( u<=pKeyInfo->nField + 1 );
shane0b8d2762008-07-22 05:18:00 +00003066 p->nField = u;
drh1e968a02008-03-25 00:22:21 +00003067}
3068
3069/*
3070** This function compares the two table rows or index records
3071** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
drhe63d9992008-08-13 19:11:48 +00003072** or positive integer if key1 is less than, equal to or
3073** greater than key2. The {nKey1, pKey1} key must be a blob
drh1e968a02008-03-25 00:22:21 +00003074** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
3075** key must be a parsed key such as obtained from
3076** sqlite3VdbeParseRecord.
3077**
3078** Key1 and Key2 do not have to contain the same number of fields.
drhe63d9992008-08-13 19:11:48 +00003079** The key with fewer fields is usually compares less than the
3080** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
3081** and the common prefixes are equal, then key1 is less than key2.
3082** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
3083** equal, then the keys are considered to be equal and
drhec1fc802008-08-13 14:07:40 +00003084** the parts beyond the common prefix are ignored.
drh1e968a02008-03-25 00:22:21 +00003085*/
drhe14006d2008-03-25 17:23:32 +00003086int sqlite3VdbeRecordCompare(
drhec1fc802008-08-13 14:07:40 +00003087 int nKey1, const void *pKey1, /* Left key */
drhec1fc802008-08-13 14:07:40 +00003088 UnpackedRecord *pPKey2 /* Right key */
drh1e968a02008-03-25 00:22:21 +00003089){
drhdf003d62013-08-01 19:17:39 +00003090 u32 d1; /* Offset into aKey[] of next data element */
drh1e968a02008-03-25 00:22:21 +00003091 u32 idx1; /* Offset into aKey[] of next header element */
3092 u32 szHdr1; /* Number of bytes in header */
3093 int i = 0;
drh1e968a02008-03-25 00:22:21 +00003094 int rc = 0;
3095 const unsigned char *aKey1 = (const unsigned char *)pKey1;
3096 KeyInfo *pKeyInfo;
3097 Mem mem1;
3098
3099 pKeyInfo = pPKey2->pKeyInfo;
3100 mem1.enc = pKeyInfo->enc;
drh37272632009-11-16 21:28:45 +00003101 mem1.db = pKeyInfo->db;
drhd93a8b22009-11-16 03:13:40 +00003102 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
3103 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
drh8b249a82009-11-16 02:14:00 +00003104
3105 /* Compilers may complain that mem1.u.i is potentially uninitialized.
3106 ** We could initialize it, as shown here, to silence those complaints.
drh5275d2e2011-04-27 01:00:17 +00003107 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
drh8b249a82009-11-16 02:14:00 +00003108 ** the unnecessary initialization has a measurable negative performance
3109 ** impact, since this routine is a very high runner. And so, we choose
3110 ** to ignore the compiler warnings and leave this variable uninitialized.
3111 */
3112 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
drh1e968a02008-03-25 00:22:21 +00003113
shane3f8d5cf2008-04-24 19:15:09 +00003114 idx1 = getVarint32(aKey1, szHdr1);
drh1e968a02008-03-25 00:22:21 +00003115 d1 = szHdr1;
drh72ffd092013-10-30 15:52:32 +00003116 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField );
drhe1a022e2012-09-17 17:16:53 +00003117 assert( pKeyInfo->aSortOrder!=0 );
drh1e968a02008-03-25 00:22:21 +00003118 while( idx1<szHdr1 && i<pPKey2->nField ){
3119 u32 serial_type1;
3120
3121 /* Read the serial types for the next element in each key. */
shane3f8d5cf2008-04-24 19:15:09 +00003122 idx1 += getVarint32( aKey1+idx1, serial_type1 );
drhaf5b2af2013-08-05 15:32:09 +00003123
3124 /* Verify that there is enough key space remaining to avoid
3125 ** a buffer overread. The "d1+serial_type1+2" subexpression will
3126 ** always be greater than or equal to the amount of required key space.
3127 ** Use that approximation to avoid the more expensive call to
3128 ** sqlite3VdbeSerialTypeLen() in the common case.
3129 */
3130 if( d1+serial_type1+2>(u32)nKey1
3131 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
3132 ){
3133 break;
3134 }
drh1e968a02008-03-25 00:22:21 +00003135
3136 /* Extract the values to be compared.
3137 */
3138 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
3139
3140 /* Do the comparison
3141 */
drh323df792013-08-05 19:11:29 +00003142 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
drh1e968a02008-03-25 00:22:21 +00003143 if( rc!=0 ){
drh8b249a82009-11-16 02:14:00 +00003144 assert( mem1.zMalloc==0 ); /* See comment below */
drh323df792013-08-05 19:11:29 +00003145 if( pKeyInfo->aSortOrder[i] ){
drh6f225d02013-10-26 13:36:51 +00003146 rc = -rc; /* Invert the result for DESC sort order. */
drh8b249a82009-11-16 02:14:00 +00003147 }
drh8b249a82009-11-16 02:14:00 +00003148 return rc;
drh1e968a02008-03-25 00:22:21 +00003149 }
3150 i++;
3151 }
drh407414c2009-07-14 14:15:27 +00003152
drh8b249a82009-11-16 02:14:00 +00003153 /* No memory allocation is ever used on mem1. Prove this using
3154 ** the following assert(). If the assert() fails, it indicates a
3155 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
danielk1977de630352009-05-04 11:42:29 +00003156 */
drh8b249a82009-11-16 02:14:00 +00003157 assert( mem1.zMalloc==0 );
danielk1977de630352009-05-04 11:42:29 +00003158
drh8b249a82009-11-16 02:14:00 +00003159 /* rc==0 here means that one of the keys ran out of fields and
3160 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
3161 ** flag is set, then break the tie by treating key2 as larger.
3162 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
3163 ** are considered to be equal. Otherwise, the longer key is the
3164 ** larger. As it happens, the pPKey2 will always be the longer
3165 ** if there is a difference.
3166 */
3167 assert( rc==0 );
3168 if( pPKey2->flags & UNPACKED_INCRKEY ){
3169 rc = -1;
3170 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
3171 /* Leave rc==0 */
3172 }else if( idx1<szHdr1 ){
3173 rc = 1;
drh1e968a02008-03-25 00:22:21 +00003174 }
drh1e968a02008-03-25 00:22:21 +00003175 return rc;
3176}
drhec1fc802008-08-13 14:07:40 +00003177
danielk1977eb015e02004-05-18 01:31:14 +00003178
3179/*
drh7a224de2004-06-02 01:22:02 +00003180** pCur points at an index entry created using the OP_MakeRecord opcode.
3181** Read the rowid (the last field in the record) and store it in *rowid.
3182** Return SQLITE_OK if everything works, or an error code otherwise.
drh88a003e2008-12-11 16:17:03 +00003183**
3184** pCur might be pointing to text obtained from a corrupt database file.
3185** So the content cannot be trusted. Do appropriate checks on the content.
danielk1977183f9f72004-05-13 05:20:26 +00003186*/
drh35f6b932009-06-23 14:15:04 +00003187int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
drh61fc5952007-04-01 23:49:51 +00003188 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003189 int rc;
drhd5788202004-05-28 08:21:05 +00003190 u32 szHdr; /* Size of the header */
3191 u32 typeRowid; /* Serial type of the rowid */
3192 u32 lenRowid; /* Size of the rowid */
3193 Mem m, v;
danielk1977183f9f72004-05-13 05:20:26 +00003194
shanecea72b22009-09-07 04:38:36 +00003195 UNUSED_PARAMETER(db);
3196
drh88a003e2008-12-11 16:17:03 +00003197 /* Get the size of the index entry. Only indices entries of less
drh7b746032009-06-26 12:15:22 +00003198 ** than 2GiB are support - anything large must be database corruption.
3199 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
drhc27ae612009-07-14 18:35:44 +00003200 ** this code can safely assume that nCellKey is 32-bits
3201 */
drhea8ffdf2009-07-22 00:35:23 +00003202 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003203 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003204 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh7b746032009-06-26 12:15:22 +00003205 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
drh88a003e2008-12-11 16:17:03 +00003206
3207 /* Read in the complete content of the index entry */
drhff104c12009-08-25 13:10:27 +00003208 memset(&m, 0, sizeof(m));
drh8df32842008-12-09 02:51:23 +00003209 rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
drhd5788202004-05-28 08:21:05 +00003210 if( rc ){
danielk1977183f9f72004-05-13 05:20:26 +00003211 return rc;
3212 }
drh88a003e2008-12-11 16:17:03 +00003213
3214 /* The index entry must begin with a header size */
shane3f8d5cf2008-04-24 19:15:09 +00003215 (void)getVarint32((u8*)m.z, szHdr);
drh7b746032009-06-26 12:15:22 +00003216 testcase( szHdr==3 );
drh88a003e2008-12-11 16:17:03 +00003217 testcase( szHdr==m.n );
drh7b746032009-06-26 12:15:22 +00003218 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
drh88a003e2008-12-11 16:17:03 +00003219 goto idx_rowid_corruption;
3220 }
3221
3222 /* The last field of the index should be an integer - the ROWID.
3223 ** Verify that the last entry really is an integer. */
shane3f8d5cf2008-04-24 19:15:09 +00003224 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
drh88a003e2008-12-11 16:17:03 +00003225 testcase( typeRowid==1 );
3226 testcase( typeRowid==2 );
3227 testcase( typeRowid==3 );
3228 testcase( typeRowid==4 );
3229 testcase( typeRowid==5 );
3230 testcase( typeRowid==6 );
3231 testcase( typeRowid==8 );
3232 testcase( typeRowid==9 );
3233 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
3234 goto idx_rowid_corruption;
3235 }
drhd5788202004-05-28 08:21:05 +00003236 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
drheeb844a2009-08-08 18:01:07 +00003237 testcase( (u32)m.n==szHdr+lenRowid );
3238 if( unlikely((u32)m.n<szHdr+lenRowid) ){
drh88a003e2008-12-11 16:17:03 +00003239 goto idx_rowid_corruption;
3240 }
3241
3242 /* Fetch the integer off the end of the index record */
drh2646da72005-12-09 20:02:05 +00003243 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
drh3c024d62007-03-30 11:23:45 +00003244 *rowid = v.u.i;
danielk1977d8123362004-06-12 09:25:12 +00003245 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00003246 return SQLITE_OK;
drh88a003e2008-12-11 16:17:03 +00003247
3248 /* Jump here if database corruption is detected after m has been
3249 ** allocated. Free the m object and return SQLITE_CORRUPT. */
3250idx_rowid_corruption:
3251 testcase( m.zMalloc!=0 );
3252 sqlite3VdbeMemRelease(&m);
3253 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00003254}
3255
drh7cf6e4d2004-05-19 14:56:55 +00003256/*
drh5f82e3c2009-07-06 00:44:08 +00003257** Compare the key of the index entry that cursor pC is pointing to against
3258** the key string in pUnpacked. Write into *pRes a number
drh7cf6e4d2004-05-19 14:56:55 +00003259** that is negative, zero, or positive if pC is less than, equal to,
drh5f82e3c2009-07-06 00:44:08 +00003260** or greater than pUnpacked. Return SQLITE_OK on success.
drhd3d39e92004-05-20 22:16:29 +00003261**
drh5f82e3c2009-07-06 00:44:08 +00003262** pUnpacked is either created without a rowid or is truncated so that it
drhd5788202004-05-28 08:21:05 +00003263** omits the rowid at the end. The rowid at the end of the index entry
drhec1fc802008-08-13 14:07:40 +00003264** is ignored as well. Hence, this routine only compares the prefixes
3265** of the keys prior to the final rowid, not the entire key.
drh7cf6e4d2004-05-19 14:56:55 +00003266*/
danielk1977183f9f72004-05-13 05:20:26 +00003267int sqlite3VdbeIdxKeyCompare(
drhdfe88ec2008-11-03 20:55:06 +00003268 VdbeCursor *pC, /* The cursor to compare against */
drh5f82e3c2009-07-06 00:44:08 +00003269 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
drh7cf6e4d2004-05-19 14:56:55 +00003270 int *res /* Write the comparison result here */
danielk1977183f9f72004-05-13 05:20:26 +00003271){
drh61fc5952007-04-01 23:49:51 +00003272 i64 nCellKey = 0;
danielk1977183f9f72004-05-13 05:20:26 +00003273 int rc;
danielk19773d1bfea2004-05-14 11:00:53 +00003274 BtCursor *pCur = pC->pCursor;
drhd5788202004-05-28 08:21:05 +00003275 Mem m;
danielk1977183f9f72004-05-13 05:20:26 +00003276
drhea8ffdf2009-07-22 00:35:23 +00003277 assert( sqlite3BtreeCursorIsValid(pCur) );
drhb07028f2011-10-14 21:49:18 +00003278 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
drhc27ae612009-07-14 18:35:44 +00003279 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
drh407414c2009-07-14 14:15:27 +00003280 /* nCellKey will always be between 0 and 0xffffffff because of the say
3281 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
drhc27ae612009-07-14 18:35:44 +00003282 if( nCellKey<=0 || nCellKey>0x7fffffff ){
danielk1977183f9f72004-05-13 05:20:26 +00003283 *res = 0;
drh9978c972010-02-23 17:36:32 +00003284 return SQLITE_CORRUPT_BKPT;
danielk1977183f9f72004-05-13 05:20:26 +00003285 }
drhfd3ca1c2009-08-25 12:11:00 +00003286 memset(&m, 0, sizeof(m));
drh8df32842008-12-09 02:51:23 +00003287 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
drhec1fc802008-08-13 14:07:40 +00003288 if( rc ){
drhd5788202004-05-28 08:21:05 +00003289 return rc;
danielk1977183f9f72004-05-13 05:20:26 +00003290 }
dan6f133232011-11-16 15:41:29 +00003291 assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
drhe63d9992008-08-13 19:11:48 +00003292 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
danielk1977d8123362004-06-12 09:25:12 +00003293 sqlite3VdbeMemRelease(&m);
danielk1977183f9f72004-05-13 05:20:26 +00003294 return SQLITE_OK;
3295}
danielk1977b28af712004-06-21 06:50:26 +00003296
3297/*
3298** This routine sets the value to be returned by subsequent calls to
3299** sqlite3_changes() on the database handle 'db'.
3300*/
3301void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
drhb21c8cd2007-08-21 19:33:56 +00003302 assert( sqlite3_mutex_held(db->mutex) );
danielk1977b28af712004-06-21 06:50:26 +00003303 db->nChange = nChange;
3304 db->nTotalChange += nChange;
3305}
3306
3307/*
3308** Set a flag in the vdbe to update the change counter when it is finalised
3309** or reset.
3310*/
drh4794f732004-11-05 17:17:50 +00003311void sqlite3VdbeCountChanges(Vdbe *v){
3312 v->changeCntOn = 1;
danielk1977b28af712004-06-21 06:50:26 +00003313}
drhd89bd002005-01-22 03:03:54 +00003314
3315/*
3316** Mark every prepared statement associated with a database connection
3317** as expired.
3318**
3319** An expired statement means that recompilation of the statement is
3320** recommend. Statements expire when things happen that make their
3321** programs obsolete. Removing user-defined functions or collating
3322** sequences, or changing an authorization function are the types of
3323** things that make prepared statements obsolete.
3324*/
3325void sqlite3ExpirePreparedStatements(sqlite3 *db){
3326 Vdbe *p;
3327 for(p = db->pVdbe; p; p=p->pNext){
3328 p->expired = 1;
3329 }
3330}
danielk1977aee18ef2005-03-09 12:26:50 +00003331
3332/*
3333** Return the database associated with the Vdbe.
3334*/
3335sqlite3 *sqlite3VdbeDb(Vdbe *v){
3336 return v->db;
3337}
dan937d0de2009-10-15 18:35:38 +00003338
3339/*
3340** Return a pointer to an sqlite3_value structure containing the value bound
3341** parameter iVar of VM v. Except, if the value is an SQL NULL, return
3342** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
3343** constants) to the value before returning it.
3344**
3345** The returned value must be freed by the caller using sqlite3ValueFree().
3346*/
drhcf0fd4a2013-08-01 12:21:58 +00003347sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
dan937d0de2009-10-15 18:35:38 +00003348 assert( iVar>0 );
3349 if( v ){
3350 Mem *pMem = &v->aVar[iVar-1];
3351 if( 0==(pMem->flags & MEM_Null) ){
3352 sqlite3_value *pRet = sqlite3ValueNew(v->db);
3353 if( pRet ){
3354 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
3355 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
3356 sqlite3VdbeMemStoreType((Mem *)pRet);
3357 }
3358 return pRet;
3359 }
3360 }
3361 return 0;
3362}
3363
3364/*
3365** Configure SQL variable iVar so that binding a new value to it signals
3366** to sqlite3_reoptimize() that re-preparing the statement may result
3367** in a better query plan.
3368*/
dan1d2ce4f2009-10-19 18:11:09 +00003369void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
dan937d0de2009-10-15 18:35:38 +00003370 assert( iVar>0 );
3371 if( iVar>32 ){
dan1d2ce4f2009-10-19 18:11:09 +00003372 v->expmask = 0xffffffff;
dan937d0de2009-10-15 18:35:38 +00003373 }else{
dan1d2ce4f2009-10-19 18:11:09 +00003374 v->expmask |= ((u32)1 << (iVar-1));
dan937d0de2009-10-15 18:35:38 +00003375 }
3376}
dan016f7812013-08-21 17:35:48 +00003377
3378#ifndef SQLITE_OMIT_VIRTUALTABLE
3379/*
3380** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
3381** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
3382** in memory obtained from sqlite3DbMalloc).
3383*/
3384void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
3385 sqlite3 *db = p->db;
3386 sqlite3DbFree(db, p->zErrMsg);
3387 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
3388 sqlite3_free(pVtab->zErrMsg);
3389 pVtab->zErrMsg = 0;
3390}
3391#endif /* SQLITE_OMIT_VIRTUALTABLE */