19a32464bSdrh /*
29a32464bSdrh ** 2003 September 6
39a32464bSdrh **
49a32464bSdrh ** The author disclaims copyright to this source code. In place of
59a32464bSdrh ** a legal notice, here is a blessing:
69a32464bSdrh **
79a32464bSdrh ** May you do good and not evil.
89a32464bSdrh ** May you find forgiveness for yourself and forgive others.
99a32464bSdrh ** May you share freely, never taking more than you give.
109a32464bSdrh **
119a32464bSdrh *************************************************************************
129a32464bSdrh ** This file contains code used for creating, destroying, and populating
137abda856Sdrh ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
149a32464bSdrh */
159a32464bSdrh #include "sqliteInt.h"
169a32464bSdrh #include "vdbeInt.h"
179a32464bSdrh
18920cf596Sdrh /* Forward references */
19920cf596Sdrh static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
20920cf596Sdrh static void vdbeFreeOpArray(sqlite3 *, Op *, int);
21920cf596Sdrh
229a32464bSdrh /*
239a32464bSdrh ** Create a new virtual database engine.
249a32464bSdrh */
sqlite3VdbeCreate(Parse * pParse)259ac7962aSdrh Vdbe *sqlite3VdbeCreate(Parse *pParse){
269ac7962aSdrh sqlite3 *db = pParse->db;
279a32464bSdrh Vdbe *p;
28d8e4b132Sdrh p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
299a32464bSdrh if( p==0 ) return 0;
30ab3182f7Sdrh memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
319a32464bSdrh p->db = db;
329a32464bSdrh if( db->pVdbe ){
33e5928b17Sdrh db->pVdbe->ppVPrev = &p->pVNext;
349a32464bSdrh }
35e5928b17Sdrh p->pVNext = db->pVdbe;
36e5928b17Sdrh p->ppVPrev = &db->pVdbe;
379a32464bSdrh db->pVdbe = p;
3866181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
399ac7962aSdrh p->pParse = pParse;
4055965619Sdrh pParse->pVdbe = p;
4173d5b8f5Sdrh assert( pParse->aLabel==0 );
4273d5b8f5Sdrh assert( pParse->nLabel==0 );
43b6991796Sdrh assert( p->nOpAlloc==0 );
44bd57308eSdrh assert( pParse->szOpAlloc==0 );
4555965619Sdrh sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
469a32464bSdrh return p;
479a32464bSdrh }
489a32464bSdrh
499a32464bSdrh /*
506df9c4b9Sdrh ** Return the Parse object that owns a Vdbe object.
516df9c4b9Sdrh */
sqlite3VdbeParser(Vdbe * p)526df9c4b9Sdrh Parse *sqlite3VdbeParser(Vdbe *p){
536df9c4b9Sdrh return p->pParse;
546df9c4b9Sdrh }
556df9c4b9Sdrh
566df9c4b9Sdrh /*
5722c17b8bSdrh ** Change the error string stored in Vdbe.zErrMsg
5822c17b8bSdrh */
sqlite3VdbeError(Vdbe * p,const char * zFormat,...)5922c17b8bSdrh void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
6022c17b8bSdrh va_list ap;
6122c17b8bSdrh sqlite3DbFree(p->db, p->zErrMsg);
6222c17b8bSdrh va_start(ap, zFormat);
6322c17b8bSdrh p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
6422c17b8bSdrh va_end(ap);
6522c17b8bSdrh }
6622c17b8bSdrh
6722c17b8bSdrh /*
68b900aaf3Sdrh ** Remember the SQL string for a prepared statement.
69b900aaf3Sdrh */
sqlite3VdbeSetSql(Vdbe * p,const char * z,int n,u8 prepFlags)702c2f392dSdrh void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
71b900aaf3Sdrh if( p==0 ) return;
722c2f392dSdrh p->prepFlags = prepFlags;
732c2f392dSdrh if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
742c2f392dSdrh p->expmask = 0;
752c2f392dSdrh }
76b900aaf3Sdrh assert( p->zSql==0 );
7717435752Sdrh p->zSql = sqlite3DbStrNDup(p->db, z, n);
78b900aaf3Sdrh }
79b900aaf3Sdrh
80893bd375Sdrh #ifdef SQLITE_ENABLE_NORMALIZE
81893bd375Sdrh /*
82893bd375Sdrh ** Add a new element to the Vdbe->pDblStr list.
83893bd375Sdrh */
sqlite3VdbeAddDblquoteStr(sqlite3 * db,Vdbe * p,const char * z)84893bd375Sdrh void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
85893bd375Sdrh if( p ){
86893bd375Sdrh int n = sqlite3Strlen30(z);
87893bd375Sdrh DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
88893bd375Sdrh sizeof(*pStr)+n+1-sizeof(pStr->z));
89893bd375Sdrh if( pStr ){
90893bd375Sdrh pStr->pNextStr = p->pDblStr;
91893bd375Sdrh p->pDblStr = pStr;
92893bd375Sdrh memcpy(pStr->z, z, n+1);
93893bd375Sdrh }
94893bd375Sdrh }
95893bd375Sdrh }
96893bd375Sdrh #endif
97893bd375Sdrh
98893bd375Sdrh #ifdef SQLITE_ENABLE_NORMALIZE
99893bd375Sdrh /*
100893bd375Sdrh ** zId of length nId is a double-quoted identifier. Check to see if
101893bd375Sdrh ** that identifier is really used as a string literal.
102893bd375Sdrh */
sqlite3VdbeUsesDoubleQuotedString(Vdbe * pVdbe,const char * zId)103893bd375Sdrh int sqlite3VdbeUsesDoubleQuotedString(
104893bd375Sdrh Vdbe *pVdbe, /* The prepared statement */
105643d855dSdrh const char *zId /* The double-quoted identifier, already dequoted */
106893bd375Sdrh ){
107893bd375Sdrh DblquoteStr *pStr;
108893bd375Sdrh assert( zId!=0 );
109893bd375Sdrh if( pVdbe->pDblStr==0 ) return 0;
110893bd375Sdrh for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
111643d855dSdrh if( strcmp(zId, pStr->z)==0 ) return 1;
112893bd375Sdrh }
113643d855dSdrh return 0;
114893bd375Sdrh }
115893bd375Sdrh #endif
116893bd375Sdrh
117b900aaf3Sdrh /*
118a57ac0a8Sdrh ** Swap byte-code between two VDBE structures.
119a57ac0a8Sdrh **
120a57ac0a8Sdrh ** This happens after pB was previously run and returned
121a57ac0a8Sdrh ** SQLITE_SCHEMA. The statement was then reprepared in pA.
122a57ac0a8Sdrh ** This routine transfers the new bytecode in pA over to pB
123a57ac0a8Sdrh ** so that pB can be run again. The old pB byte code is
124a57ac0a8Sdrh ** moved back to pA so that it will be cleaned up when pA is
125a57ac0a8Sdrh ** finalized.
126b900aaf3Sdrh */
sqlite3VdbeSwap(Vdbe * pA,Vdbe * pB)127c5155257Sdrh void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
128e5928b17Sdrh Vdbe tmp, *pTmp, **ppTmp;
129c5155257Sdrh char *zTmp;
1300639c34eSdrh assert( pA->db==pB->db );
131c5155257Sdrh tmp = *pA;
132c5155257Sdrh *pA = *pB;
133c5155257Sdrh *pB = tmp;
134e5928b17Sdrh pTmp = pA->pVNext;
135e5928b17Sdrh pA->pVNext = pB->pVNext;
136e5928b17Sdrh pB->pVNext = pTmp;
137e5928b17Sdrh ppTmp = pA->ppVPrev;
138e5928b17Sdrh pA->ppVPrev = pB->ppVPrev;
139e5928b17Sdrh pB->ppVPrev = ppTmp;
140c5155257Sdrh zTmp = pA->zSql;
141c5155257Sdrh pA->zSql = pB->zSql;
142c5155257Sdrh pB->zSql = zTmp;
1434a4c1bf8Smistachkin #ifdef SQLITE_ENABLE_NORMALIZE
1448bee11a4Smistachkin zTmp = pA->zNormSql;
1458bee11a4Smistachkin pA->zNormSql = pB->zNormSql;
1468bee11a4Smistachkin pB->zNormSql = zTmp;
1478bee11a4Smistachkin #endif
14876adb239Sdrh pB->expmask = pA->expmask;
1492c2f392dSdrh pB->prepFlags = pA->prepFlags;
15000d11d40Sdrh memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
15100d11d40Sdrh pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
152b900aaf3Sdrh }
153b900aaf3Sdrh
1549a32464bSdrh /*
15576ccd89dSdan ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
15681e069eeSdrh ** than its current size. nOp is guaranteed to be less than or equal
15781e069eeSdrh ** to 1024/sizeof(Op).
158ace3eb21Sdanielk1977 **
15900e13613Sdanielk1977 ** If an out-of-memory error occurs while resizing the array, return
160b6991796Sdrh ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
16100e13613Sdanielk1977 ** unchanged (this is so that any opcodes already allocated can be
16200e13613Sdanielk1977 ** correctly deallocated along with the rest of the Vdbe).
16376ff3a0eSdrh */
growOpArray(Vdbe * v,int nOp)16476ccd89dSdan static int growOpArray(Vdbe *v, int nOp){
165b38ad999Sdrh VdbeOp *pNew;
16673d5b8f5Sdrh Parse *p = v->pParse;
16776ccd89dSdan
16881e069eeSdrh /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
16981e069eeSdrh ** more frequent reallocs and hence provide more opportunities for
17081e069eeSdrh ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
17181e069eeSdrh ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
17281e069eeSdrh ** by the minimum* amount required until the size reaches 512. Normal
17381e069eeSdrh ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
17481e069eeSdrh ** size of the op array or add 1KB of space, whichever is smaller. */
17576ccd89dSdan #ifdef SQLITE_TEST_REALLOC_STRESS
1760aa3231fSdrh sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
1770aa3231fSdrh : (sqlite3_int64)v->nOpAlloc+nOp);
17876ccd89dSdan #else
1790aa3231fSdrh sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
180f6ad201aSdrh : (sqlite3_int64)(1024/sizeof(Op)));
18176ccd89dSdan UNUSED_PARAMETER(nOp);
18276ccd89dSdan #endif
18376ccd89dSdan
1841cb0266dSdrh /* Ensure that the size of a VDBE does not grow too large */
1851cb0266dSdrh if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
1861cb0266dSdrh sqlite3OomFault(p->db);
1871cb0266dSdrh return SQLITE_NOMEM;
1881cb0266dSdrh }
1891cb0266dSdrh
190e684ac6fSdrh assert( nOp<=(int)(1024/sizeof(Op)) );
191b6991796Sdrh assert( nNew>=(v->nOpAlloc+nOp) );
19273d5b8f5Sdrh pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
193b38ad999Sdrh if( pNew ){
194bd57308eSdrh p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
195b6991796Sdrh v->nOpAlloc = p->szOpAlloc/sizeof(Op);
19673d5b8f5Sdrh v->aOp = pNew;
19776ff3a0eSdrh }
198fad3039cSmistachkin return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
19976ff3a0eSdrh }
20076ff3a0eSdrh
201313619f5Sdrh #ifdef SQLITE_DEBUG
202313619f5Sdrh /* This routine is just a convenient place to set a breakpoint that will
203313619f5Sdrh ** fire after each opcode is inserted and displayed using
20452f11b88Sdrh ** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and
20552f11b88Sdrh ** pOp are available to make the breakpoint conditional.
20652f11b88Sdrh **
20752f11b88Sdrh ** Other useful labels for breakpoints include:
20852f11b88Sdrh ** test_trace_breakpoint(pc,pOp)
20952f11b88Sdrh ** sqlite3CorruptError(lineno)
21052f11b88Sdrh ** sqlite3MisuseError(lineno)
21152f11b88Sdrh ** sqlite3CantopenError(lineno)
212313619f5Sdrh */
test_addop_breakpoint(int pc,Op * pOp)21352f11b88Sdrh static void test_addop_breakpoint(int pc, Op *pOp){
214313619f5Sdrh static int n = 0;
215313619f5Sdrh n++;
216313619f5Sdrh }
217313619f5Sdrh #endif
218313619f5Sdrh
21976ff3a0eSdrh /*
2209a32464bSdrh ** Add a new instruction to the list of instructions current in the
2219a32464bSdrh ** VDBE. Return the address of the new instruction.
2229a32464bSdrh **
2239a32464bSdrh ** Parameters:
2249a32464bSdrh **
2259a32464bSdrh ** p Pointer to the VDBE
2269a32464bSdrh **
2279a32464bSdrh ** op The opcode for this instruction
2289a32464bSdrh **
22966a5167bSdrh ** p1, p2, p3 Operands
2309a32464bSdrh **
2314adee20fSdanielk1977 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
23266a5167bSdrh ** the sqlite3VdbeChangeP4() function to change the value of the P4
2339a32464bSdrh ** operand.
2349a32464bSdrh */
growOp3(Vdbe * p,int op,int p1,int p2,int p3)235d797035aSdrh static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
236b6991796Sdrh assert( p->nOpAlloc<=p->nOp );
237d797035aSdrh if( growOpArray(p, 1) ) return 1;
238b6991796Sdrh assert( p->nOpAlloc>p->nOp );
239d797035aSdrh return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
240d797035aSdrh }
sqlite3VdbeAddOp3(Vdbe * p,int op,int p1,int p2,int p3)24166a5167bSdrh int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
2429a32464bSdrh int i;
243701a0aebSdrh VdbeOp *pOp;
2449a32464bSdrh
2459a32464bSdrh i = p->nOp;
24666181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
247ed94af5eSdrh assert( op>=0 && op<0xff );
248b6991796Sdrh if( p->nOpAlloc<=i ){
249d797035aSdrh return growOp3(p, op, p1, p2, p3);
250fd2d26bbSdrh }
251c59ffa8cSdrh assert( p->aOp!=0 );
25201256832Sdanielk1977 p->nOp++;
253701a0aebSdrh pOp = &p->aOp[i];
254c59ffa8cSdrh assert( pOp!=0 );
2558df32841Sdrh pOp->opcode = (u8)op;
25626c9b5eaSdrh pOp->p5 = 0;
257701a0aebSdrh pOp->p1 = p1;
258701a0aebSdrh pOp->p2 = p2;
25966a5167bSdrh pOp->p3 = p3;
26066a5167bSdrh pOp->p4.p = 0;
26166a5167bSdrh pOp->p4type = P4_NOTUSED;
262c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
26326c9b5eaSdrh pOp->zComment = 0;
264c7379ce4Sdrh #endif
265c7379ce4Sdrh #ifdef SQLITE_DEBUG
266e096205aSdrh if( p->db->flags & SQLITE_VdbeAddopTrace ){
267e096205aSdrh sqlite3VdbePrintOp(0, i, &p->aOp[i]);
26852f11b88Sdrh test_addop_breakpoint(i, &p->aOp[i]);
269e096205aSdrh }
2709a32464bSdrh #endif
27126c9b5eaSdrh #ifdef VDBE_PROFILE
27226c9b5eaSdrh pOp->cycles = 0;
27326c9b5eaSdrh pOp->cnt = 0;
27426c9b5eaSdrh #endif
275688852abSdrh #ifdef SQLITE_VDBE_COVERAGE
276688852abSdrh pOp->iSrcLine = 0;
277688852abSdrh #endif
2789a32464bSdrh return i;
2799a32464bSdrh }
sqlite3VdbeAddOp0(Vdbe * p,int op)28066a5167bSdrh int sqlite3VdbeAddOp0(Vdbe *p, int op){
28166a5167bSdrh return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
28266a5167bSdrh }
sqlite3VdbeAddOp1(Vdbe * p,int op,int p1)28366a5167bSdrh int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
28466a5167bSdrh return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
28566a5167bSdrh }
sqlite3VdbeAddOp2(Vdbe * p,int op,int p1,int p2)28666a5167bSdrh int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
28766a5167bSdrh return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
288701a0aebSdrh }
289701a0aebSdrh
290076e85f5Sdrh /* Generate code for an unconditional jump to instruction iDest
291076e85f5Sdrh */
sqlite3VdbeGoto(Vdbe * p,int iDest)292076e85f5Sdrh int sqlite3VdbeGoto(Vdbe *p, int iDest){
2932991ba05Sdrh return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
2942991ba05Sdrh }
295701a0aebSdrh
296076e85f5Sdrh /* Generate code to cause the string zStr to be loaded into
297076e85f5Sdrh ** register iDest
298076e85f5Sdrh */
sqlite3VdbeLoadString(Vdbe * p,int iDest,const char * zStr)299076e85f5Sdrh int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
300076e85f5Sdrh return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
301076e85f5Sdrh }
302076e85f5Sdrh
303076e85f5Sdrh /*
304076e85f5Sdrh ** Generate code that initializes multiple registers to string or integer
305076e85f5Sdrh ** constants. The registers begin with iDest and increase consecutively.
306076e85f5Sdrh ** One register is initialized for each characgter in zTypes[]. For each
307076e85f5Sdrh ** "s" character in zTypes[], the register is a string if the argument is
308076e85f5Sdrh ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
309076e85f5Sdrh ** in zTypes[], the register is initialized to an integer.
31040cf27cbSdrh **
31140cf27cbSdrh ** If the input string does not end with "X" then an OP_ResultRow instruction
31240cf27cbSdrh ** is generated for the values inserted.
313076e85f5Sdrh */
sqlite3VdbeMultiLoad(Vdbe * p,int iDest,const char * zTypes,...)314076e85f5Sdrh void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
315076e85f5Sdrh va_list ap;
316076e85f5Sdrh int i;
317076e85f5Sdrh char c;
318076e85f5Sdrh va_start(ap, zTypes);
319076e85f5Sdrh for(i=0; (c = zTypes[i])!=0; i++){
320076e85f5Sdrh if( c=='s' ){
321076e85f5Sdrh const char *z = va_arg(ap, const char*);
32240cf27cbSdrh sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
32340cf27cbSdrh }else if( c=='i' ){
32440cf27cbSdrh sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
325076e85f5Sdrh }else{
32640cf27cbSdrh goto skip_op_resultrow;
327076e85f5Sdrh }
328076e85f5Sdrh }
32940cf27cbSdrh sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
33040cf27cbSdrh skip_op_resultrow:
331076e85f5Sdrh va_end(ap);
332076e85f5Sdrh }
33366a5167bSdrh
334701a0aebSdrh /*
33566a5167bSdrh ** Add an opcode that includes the p4 value as a pointer.
336d4e70ebdSdrh */
sqlite3VdbeAddOp4(Vdbe * p,int op,int p1,int p2,int p3,const char * zP4,int p4type)33766a5167bSdrh int sqlite3VdbeAddOp4(
338d4e70ebdSdrh Vdbe *p, /* Add the opcode to this VM */
339d4e70ebdSdrh int op, /* The new opcode */
34066a5167bSdrh int p1, /* The P1 operand */
34166a5167bSdrh int p2, /* The P2 operand */
34266a5167bSdrh int p3, /* The P3 operand */
34366a5167bSdrh const char *zP4, /* The P4 operand */
34466a5167bSdrh int p4type /* P4 operand type */
345d4e70ebdSdrh ){
34666a5167bSdrh int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
34766a5167bSdrh sqlite3VdbeChangeP4(p, addr, zP4, p4type);
348d4e70ebdSdrh return addr;
349d4e70ebdSdrh }
350d4e70ebdSdrh
351d4e70ebdSdrh /*
352920cf596Sdrh ** Add an OP_Function or OP_PureFunc opcode.
353920cf596Sdrh **
354920cf596Sdrh ** The eCallCtx argument is information (typically taken from Expr.op2)
355920cf596Sdrh ** that describes the calling context of the function. 0 means a general
356920cf596Sdrh ** function call. NC_IsCheck means called by a check constraint,
357920cf596Sdrh ** NC_IdxExpr means called as part of an index expression. NC_PartIdx
358920cf596Sdrh ** means in the WHERE clause of a partial index. NC_GenCol means called
359920cf596Sdrh ** while computing a generated column value. 0 is the usual case.
360920cf596Sdrh */
sqlite3VdbeAddFunctionCall(Parse * pParse,int p1,int p2,int p3,int nArg,const FuncDef * pFunc,int eCallCtx)361920cf596Sdrh int sqlite3VdbeAddFunctionCall(
362920cf596Sdrh Parse *pParse, /* Parsing context */
363920cf596Sdrh int p1, /* Constant argument mask */
364920cf596Sdrh int p2, /* First argument register */
365920cf596Sdrh int p3, /* Register into which results are written */
366920cf596Sdrh int nArg, /* Number of argument */
367920cf596Sdrh const FuncDef *pFunc, /* The function to be invoked */
368920cf596Sdrh int eCallCtx /* Calling context */
369920cf596Sdrh ){
370920cf596Sdrh Vdbe *v = pParse->pVdbe;
371920cf596Sdrh int nByte;
372920cf596Sdrh int addr;
373920cf596Sdrh sqlite3_context *pCtx;
374920cf596Sdrh assert( v );
375920cf596Sdrh nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
376920cf596Sdrh pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
377920cf596Sdrh if( pCtx==0 ){
378920cf596Sdrh assert( pParse->db->mallocFailed );
379920cf596Sdrh freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
380920cf596Sdrh return 0;
381920cf596Sdrh }
382920cf596Sdrh pCtx->pOut = 0;
383920cf596Sdrh pCtx->pFunc = (FuncDef*)pFunc;
38420cee7d0Sdrh pCtx->pVdbe = 0;
385920cf596Sdrh pCtx->isError = 0;
386920cf596Sdrh pCtx->argc = nArg;
387f2b9d7c6Sdrh pCtx->iOp = sqlite3VdbeCurrentAddr(v);
388920cf596Sdrh addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
389920cf596Sdrh p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
39020cee7d0Sdrh sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
3914d288308Sdrh sqlite3MayAbort(pParse);
392920cf596Sdrh return addr;
393920cf596Sdrh }
394920cf596Sdrh
395920cf596Sdrh /*
3967cc023c7Sdrh ** Add an opcode that includes the p4 value with a P4_INT64 or
3977cc023c7Sdrh ** P4_REAL type.
39897bae794Sdrh */
sqlite3VdbeAddOp4Dup8(Vdbe * p,int op,int p1,int p2,int p3,const u8 * zP4,int p4type)39997bae794Sdrh int sqlite3VdbeAddOp4Dup8(
40097bae794Sdrh Vdbe *p, /* Add the opcode to this VM */
40197bae794Sdrh int op, /* The new opcode */
40297bae794Sdrh int p1, /* The P1 operand */
40397bae794Sdrh int p2, /* The P2 operand */
40497bae794Sdrh int p3, /* The P3 operand */
40597bae794Sdrh const u8 *zP4, /* The P4 operand */
40697bae794Sdrh int p4type /* P4 operand type */
40797bae794Sdrh ){
408575fad65Sdrh char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
40997bae794Sdrh if( p4copy ) memcpy(p4copy, zP4, 8);
41097bae794Sdrh return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
41197bae794Sdrh }
41297bae794Sdrh
413e2ca99c9Sdrh #ifndef SQLITE_OMIT_EXPLAIN
414e2ca99c9Sdrh /*
415e2ca99c9Sdrh ** Return the address of the current EXPLAIN QUERY PLAN baseline.
416e2ca99c9Sdrh ** 0 means "none".
417e2ca99c9Sdrh */
sqlite3VdbeExplainParent(Parse * pParse)418e2ca99c9Sdrh int sqlite3VdbeExplainParent(Parse *pParse){
419e2ca99c9Sdrh VdbeOp *pOp;
420e2ca99c9Sdrh if( pParse->addrExplain==0 ) return 0;
421e2ca99c9Sdrh pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
422e2ca99c9Sdrh return pOp->p2;
423e2ca99c9Sdrh }
424e2ca99c9Sdrh
425e2ca99c9Sdrh /*
426bd462bccSdrh ** Set a debugger breakpoint on the following routine in order to
427bd462bccSdrh ** monitor the EXPLAIN QUERY PLAN code generation.
428bd462bccSdrh */
429bd462bccSdrh #if defined(SQLITE_DEBUG)
sqlite3ExplainBreakpoint(const char * z1,const char * z2)430bd462bccSdrh void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
431bd462bccSdrh (void)z1;
432bd462bccSdrh (void)z2;
433bd462bccSdrh }
434bd462bccSdrh #endif
435bd462bccSdrh
436bd462bccSdrh /*
43791a23dc2Sdrh ** Add a new OP_Explain opcode.
438e2ca99c9Sdrh **
439e2ca99c9Sdrh ** If the bPush flag is true, then make this opcode the parent for
440e2ca99c9Sdrh ** subsequent Explains until sqlite3VdbeExplainPop() is called.
441e2ca99c9Sdrh */
sqlite3VdbeExplain(Parse * pParse,u8 bPush,const char * zFmt,...)442e2ca99c9Sdrh void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
443c310c53eSdrh #ifndef SQLITE_DEBUG
444c310c53eSdrh /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
445c310c53eSdrh ** But omit them (for performance) during production builds */
446bd462bccSdrh if( pParse->explain==2 )
447bd462bccSdrh #endif
448bd462bccSdrh {
449e2ca99c9Sdrh char *zMsg;
450c4ceea72Sdrh Vdbe *v;
451e2ca99c9Sdrh va_list ap;
452e2ca99c9Sdrh int iThis;
453e2ca99c9Sdrh va_start(ap, zFmt);
454e2ca99c9Sdrh zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
455e2ca99c9Sdrh va_end(ap);
456e2ca99c9Sdrh v = pParse->pVdbe;
457e2ca99c9Sdrh iThis = v->nOp;
458e2ca99c9Sdrh sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
459e2ca99c9Sdrh zMsg, P4_DYNAMIC);
460058e9950Sdrh sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
461bd462bccSdrh if( bPush){
462bd462bccSdrh pParse->addrExplain = iThis;
463bd462bccSdrh }
464e2ca99c9Sdrh }
465e2ca99c9Sdrh }
466e2ca99c9Sdrh
467e2ca99c9Sdrh /*
468e2ca99c9Sdrh ** Pop the EXPLAIN QUERY PLAN stack one level.
469e2ca99c9Sdrh */
sqlite3VdbeExplainPop(Parse * pParse)470e2ca99c9Sdrh void sqlite3VdbeExplainPop(Parse *pParse){
471bd462bccSdrh sqlite3ExplainBreakpoint("POP", 0);
472e2ca99c9Sdrh pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
473e2ca99c9Sdrh }
474e2ca99c9Sdrh #endif /* SQLITE_OMIT_EXPLAIN */
475e2ca99c9Sdrh
47697bae794Sdrh /*
4775d9c9da6Sdrh ** Add an OP_ParseSchema opcode. This routine is broken out from
478e4c88c0cSdrh ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
479e4c88c0cSdrh ** as having been used.
4805d9c9da6Sdrh **
4815d9c9da6Sdrh ** The zWhere string must have been obtained from sqlite3_malloc().
4825d9c9da6Sdrh ** This routine will take ownership of the allocated memory.
4835d9c9da6Sdrh */
sqlite3VdbeAddParseSchemaOp(Vdbe * p,int iDb,char * zWhere,u16 p5)4846a5a13dfSdan void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){
4855d9c9da6Sdrh int j;
48600dcecabSdrh sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
4876a5a13dfSdan sqlite3VdbeChangeP5(p, p5);
4885d9c9da6Sdrh for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
489ed7974deSdrh sqlite3MayAbort(p->pParse);
4905d9c9da6Sdrh }
4915d9c9da6Sdrh
4925d9c9da6Sdrh /*
4938cff69dfSdrh ** Add an opcode that includes the p4 value as an integer.
4948cff69dfSdrh */
sqlite3VdbeAddOp4Int(Vdbe * p,int op,int p1,int p2,int p3,int p4)4958cff69dfSdrh int sqlite3VdbeAddOp4Int(
4968cff69dfSdrh Vdbe *p, /* Add the opcode to this VM */
4978cff69dfSdrh int op, /* The new opcode */
4988cff69dfSdrh int p1, /* The P1 operand */
4998cff69dfSdrh int p2, /* The P2 operand */
5008cff69dfSdrh int p3, /* The P3 operand */
5018cff69dfSdrh int p4 /* The P4 operand as an integer */
5028cff69dfSdrh ){
5038cff69dfSdrh int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
504bdaa1ee2Sdrh if( p->db->mallocFailed==0 ){
505bdaa1ee2Sdrh VdbeOp *pOp = &p->aOp[addr];
506bdaa1ee2Sdrh pOp->p4type = P4_INT32;
507bdaa1ee2Sdrh pOp->p4.i = p4;
508bdaa1ee2Sdrh }
5098cff69dfSdrh return addr;
5108cff69dfSdrh }
5118cff69dfSdrh
5122fade2f7Sdrh /* Insert the end of a co-routine
5132fade2f7Sdrh */
sqlite3VdbeEndCoroutine(Vdbe * v,int regYield)5142fade2f7Sdrh void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
5152fade2f7Sdrh sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
5162fade2f7Sdrh
5172fade2f7Sdrh /* Clear the temporary register cache, thereby ensuring that each
5182fade2f7Sdrh ** co-routine has its own independent set of registers, because co-routines
5192fade2f7Sdrh ** might expect their registers to be preserved across an OP_Yield, and
5202fade2f7Sdrh ** that could cause problems if two or more co-routines are using the same
5212fade2f7Sdrh ** temporary register.
5222fade2f7Sdrh */
5232fade2f7Sdrh v->pParse->nTempReg = 0;
5242fade2f7Sdrh v->pParse->nRangeReg = 0;
5252fade2f7Sdrh }
5262fade2f7Sdrh
5278cff69dfSdrh /*
5289a32464bSdrh ** Create a new symbolic label for an instruction that has yet to be
5299a32464bSdrh ** coded. The symbolic label is really just a negative number. The
5309a32464bSdrh ** label can be used as the P2 value of an operation. Later, when
5319a32464bSdrh ** the label is resolved to a specific address, the VDBE will scan
5329a32464bSdrh ** through its operation list and change all values of P2 which match
5339a32464bSdrh ** the label into the resolved address.
5349a32464bSdrh **
5359a32464bSdrh ** The VDBE knows that a P2 value is a label because labels are
5369a32464bSdrh ** always negative and P2 values are suppose to be non-negative.
5379a32464bSdrh ** Hence, a negative P2 value is a label that has yet to be resolved.
538d1d158bfSdrh ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
539d1d158bfSdrh ** property.
540b5548a8bSdanielk1977 **
541d1d158bfSdrh ** Variable usage notes:
542d1d158bfSdrh **
543d1d158bfSdrh ** Parse.aLabel[x] Stores the address that the x-th label resolves
544d1d158bfSdrh ** into. For testing (SQLITE_DEBUG), unresolved
545d1d158bfSdrh ** labels stores -1, but that is not required.
546d1d158bfSdrh ** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
547d1d158bfSdrh ** Parse.nLabel The *negative* of the number of labels that have
548d1d158bfSdrh ** been issued. The negative is stored because
549d1d158bfSdrh ** that gives a performance improvement over storing
550d1d158bfSdrh ** the equivalent positive value.
5519a32464bSdrh */
sqlite3VdbeMakeLabel(Parse * pParse)552ec4ccdbcSdrh int sqlite3VdbeMakeLabel(Parse *pParse){
553d1d158bfSdrh return --pParse->nLabel;
5549a32464bSdrh }
5559a32464bSdrh
5569a32464bSdrh /*
5579a32464bSdrh ** Resolve label "x" to be the address of the next instruction to
5589a32464bSdrh ** be inserted. The parameter "x" must have been obtained from
5594adee20fSdanielk1977 ** a prior call to sqlite3VdbeMakeLabel().
5609a32464bSdrh */
resizeResolveLabel(Parse * p,Vdbe * v,int j)561ec4ccdbcSdrh static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
562d1d158bfSdrh int nNewSize = 10 - p->nLabel;
563ec4ccdbcSdrh p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
564ec4ccdbcSdrh nNewSize*sizeof(p->aLabel[0]));
565ec4ccdbcSdrh if( p->aLabel==0 ){
566ec4ccdbcSdrh p->nLabelAlloc = 0;
567ec4ccdbcSdrh }else{
568ec4ccdbcSdrh #ifdef SQLITE_DEBUG
569ec4ccdbcSdrh int i;
570ec4ccdbcSdrh for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
571ec4ccdbcSdrh #endif
572ec4ccdbcSdrh p->nLabelAlloc = nNewSize;
573ec4ccdbcSdrh p->aLabel[j] = v->nOp;
574ec4ccdbcSdrh }
575ec4ccdbcSdrh }
sqlite3VdbeResolveLabel(Vdbe * v,int x)57673d5b8f5Sdrh void sqlite3VdbeResolveLabel(Vdbe *v, int x){
57773d5b8f5Sdrh Parse *p = v->pParse;
5785ef09bf9Sdrh int j = ADDR(x);
57966181ce2Sdrh assert( v->eVdbeState==VDBE_INIT_STATE );
580d1d158bfSdrh assert( j<-p->nLabel );
581ef41dfe5Sdrh assert( j>=0 );
5822928546dSdrh #ifdef SQLITE_DEBUG
5832928546dSdrh if( p->db->flags & SQLITE_VdbeAddopTrace ){
5842928546dSdrh printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
5852928546dSdrh }
5862928546dSdrh #endif
587d1d158bfSdrh if( p->nLabelAlloc + p->nLabel < 0 ){
588ec4ccdbcSdrh resizeResolveLabel(p,v,j);
589ec4ccdbcSdrh }else{
5907ef8a3e6Sdrh assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
59173d5b8f5Sdrh p->aLabel[j] = v->nOp;
5929a32464bSdrh }
5939a32464bSdrh }
59476ff3a0eSdrh
5954611d925Sdrh /*
5964611d925Sdrh ** Mark the VDBE as one that can only be run one time.
5974611d925Sdrh */
sqlite3VdbeRunOnlyOnce(Vdbe * p)5984611d925Sdrh void sqlite3VdbeRunOnlyOnce(Vdbe *p){
59918bcfb99Sdrh sqlite3VdbeAddOp2(p, OP_Expire, 1, 1);
6004611d925Sdrh }
6014611d925Sdrh
602f71a3664Sdrh /*
603861ac67aSdrh ** Mark the VDBE as one that can be run multiple times.
604f71a3664Sdrh */
sqlite3VdbeReusable(Vdbe * p)605f71a3664Sdrh void sqlite3VdbeReusable(Vdbe *p){
60618bcfb99Sdrh int i;
60718bcfb99Sdrh for(i=1; ALWAYS(i<p->nOp); i++){
60850f22d17Sdrh if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
60918bcfb99Sdrh p->aOp[1].opcode = OP_Noop;
61018bcfb99Sdrh break;
61118bcfb99Sdrh }
61218bcfb99Sdrh }
613f71a3664Sdrh }
614f71a3664Sdrh
615ff738bceSdrh #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
616144926d8Sdan
617144926d8Sdan /*
618144926d8Sdan ** The following type and function are used to iterate through all opcodes
619144926d8Sdan ** in a Vdbe main program and each of the sub-programs (triggers) it may
620144926d8Sdan ** invoke directly or indirectly. It should be used as follows:
621144926d8Sdan **
622144926d8Sdan ** Op *pOp;
623144926d8Sdan ** VdbeOpIter sIter;
624144926d8Sdan **
625144926d8Sdan ** memset(&sIter, 0, sizeof(sIter));
626144926d8Sdan ** sIter.v = v; // v is of type Vdbe*
627144926d8Sdan ** while( (pOp = opIterNext(&sIter)) ){
628144926d8Sdan ** // Do something with pOp
629144926d8Sdan ** }
630144926d8Sdan ** sqlite3DbFree(v->db, sIter.apSub);
631144926d8Sdan **
632144926d8Sdan */
633144926d8Sdan typedef struct VdbeOpIter VdbeOpIter;
634144926d8Sdan struct VdbeOpIter {
635144926d8Sdan Vdbe *v; /* Vdbe to iterate through the opcodes of */
636144926d8Sdan SubProgram **apSub; /* Array of subprograms */
637144926d8Sdan int nSub; /* Number of entries in apSub */
638144926d8Sdan int iAddr; /* Address of next instruction to return */
639144926d8Sdan int iSub; /* 0 = main program, 1 = first sub-program etc. */
640144926d8Sdan };
opIterNext(VdbeOpIter * p)641144926d8Sdan static Op *opIterNext(VdbeOpIter *p){
642144926d8Sdan Vdbe *v = p->v;
643144926d8Sdan Op *pRet = 0;
644144926d8Sdan Op *aOp;
645144926d8Sdan int nOp;
646144926d8Sdan
647144926d8Sdan if( p->iSub<=p->nSub ){
648144926d8Sdan
649144926d8Sdan if( p->iSub==0 ){
650144926d8Sdan aOp = v->aOp;
651144926d8Sdan nOp = v->nOp;
652144926d8Sdan }else{
653144926d8Sdan aOp = p->apSub[p->iSub-1]->aOp;
654144926d8Sdan nOp = p->apSub[p->iSub-1]->nOp;
655144926d8Sdan }
656144926d8Sdan assert( p->iAddr<nOp );
657144926d8Sdan
658144926d8Sdan pRet = &aOp[p->iAddr];
659144926d8Sdan p->iAddr++;
660144926d8Sdan if( p->iAddr==nOp ){
661144926d8Sdan p->iSub++;
662144926d8Sdan p->iAddr = 0;
663144926d8Sdan }
664144926d8Sdan
665144926d8Sdan if( pRet->p4type==P4_SUBPROGRAM ){
666144926d8Sdan int nByte = (p->nSub+1)*sizeof(SubProgram*);
667144926d8Sdan int j;
668144926d8Sdan for(j=0; j<p->nSub; j++){
669144926d8Sdan if( p->apSub[j]==pRet->p4.pProgram ) break;
670144926d8Sdan }
671144926d8Sdan if( j==p->nSub ){
672144926d8Sdan p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
673144926d8Sdan if( !p->apSub ){
674144926d8Sdan pRet = 0;
675144926d8Sdan }else{
676144926d8Sdan p->apSub[p->nSub++] = pRet->p4.pProgram;
677144926d8Sdan }
678144926d8Sdan }
679144926d8Sdan }
680144926d8Sdan }
681144926d8Sdan
682144926d8Sdan return pRet;
683144926d8Sdan }
684144926d8Sdan
685144926d8Sdan /*
686f3677212Sdan ** Check if the program stored in the VM associated with pParse may
687ff738bceSdrh ** throw an ABORT exception (causing the statement, but not entire transaction
688144926d8Sdan ** to be rolled back). This condition is true if the main program or any
689144926d8Sdan ** sub-programs contains any of the following:
690144926d8Sdan **
691144926d8Sdan ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
692144926d8Sdan ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
693144926d8Sdan ** * OP_Destroy
694144926d8Sdan ** * OP_VUpdate
6958e8c8896Sdrh ** * OP_VCreate
696144926d8Sdan ** * OP_VRename
69732b09f29Sdan ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
6980f3f7664Sdrh ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
6990f3f7664Sdrh ** (for CREATE TABLE AS SELECT ...)
700144926d8Sdan **
701f3677212Sdan ** Then check that the value of Parse.mayAbort is true if an
702f3677212Sdan ** ABORT may be thrown, or false otherwise. Return true if it does
703f3677212Sdan ** match, or false otherwise. This function is intended to be used as
704f3677212Sdan ** part of an assert statement in the compiler. Similar to:
705f3677212Sdan **
706f3677212Sdan ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
707144926d8Sdan */
sqlite3VdbeAssertMayAbort(Vdbe * v,int mayAbort)708f3677212Sdan int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
709f3677212Sdan int hasAbort = 0;
71004668833Sdan int hasFkCounter = 0;
7110dd5cdaeSdrh int hasCreateTable = 0;
712ef14abbfSdan int hasCreateIndex = 0;
7130dd5cdaeSdrh int hasInitCoroutine = 0;
714144926d8Sdan Op *pOp;
715144926d8Sdan VdbeOpIter sIter;
716c4c0ff86Sdrh
717c4c0ff86Sdrh if( v==0 ) return 0;
718144926d8Sdan memset(&sIter, 0, sizeof(sIter));
719144926d8Sdan sIter.v = v;
720144926d8Sdan
721144926d8Sdan while( (pOp = opIterNext(&sIter))!=0 ){
722144926d8Sdan int opcode = pOp->opcode;
723144926d8Sdan if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
7241d4b1640Sdan || opcode==OP_VDestroy
7258e8c8896Sdrh || opcode==OP_VCreate
726ed7974deSdrh || opcode==OP_ParseSchema
7274d288308Sdrh || opcode==OP_Function || opcode==OP_PureFunc
728144926d8Sdan || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
729211a0857Sdrh && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
730144926d8Sdan ){
731f3677212Sdan hasAbort = 1;
732144926d8Sdan break;
733144926d8Sdan }
7340f3f7664Sdrh if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
7357ed6c068Sdan if( mayAbort ){
7367ed6c068Sdan /* hasCreateIndex may also be set for some DELETE statements that use
7377ed6c068Sdan ** OP_Clear. So this routine may end up returning true in the case
7387ed6c068Sdan ** where a "DELETE FROM tbl" has a statement-journal but does not
7397ed6c068Sdan ** require one. This is not so bad - it is an inefficiency, not a bug. */
740ef14abbfSdan if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
7417ed6c068Sdan if( opcode==OP_Clear ) hasCreateIndex = 1;
7427ed6c068Sdan }
7430dd5cdaeSdrh if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
74404668833Sdan #ifndef SQLITE_OMIT_FOREIGN_KEY
74504668833Sdan if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
74604668833Sdan hasFkCounter = 1;
74704668833Sdan }
74804668833Sdan #endif
749144926d8Sdan }
750144926d8Sdan sqlite3DbFree(v->db, sIter.apSub);
751f3677212Sdan
75248864df9Smistachkin /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
753f3677212Sdan ** If malloc failed, then the while() loop above may not have iterated
754f3677212Sdan ** through all opcodes and hasAbort may be set incorrectly. Return
755f3677212Sdan ** true for this case to prevent the assert() in the callers frame
756f3677212Sdan ** from failing. */
7570dd5cdaeSdrh return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
758ef14abbfSdan || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
759ef14abbfSdan );
760144926d8Sdan }
761ff738bceSdrh #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
762144926d8Sdan
7634031bafaSdrh #ifdef SQLITE_DEBUG
7644031bafaSdrh /*
7654031bafaSdrh ** Increment the nWrite counter in the VDBE if the cursor is not an
7664031bafaSdrh ** ephemeral cursor, or if the cursor argument is NULL.
7674031bafaSdrh */
sqlite3VdbeIncrWriteCounter(Vdbe * p,VdbeCursor * pC)7684031bafaSdrh void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
7694031bafaSdrh if( pC==0
7704031bafaSdrh || (pC->eCurType!=CURTYPE_SORTER
7714031bafaSdrh && pC->eCurType!=CURTYPE_PSEUDO
7724031bafaSdrh && !pC->isEphemeral)
7734031bafaSdrh ){
7744031bafaSdrh p->nWrite++;
7754031bafaSdrh }
7764031bafaSdrh }
7774031bafaSdrh #endif
7784031bafaSdrh
7794031bafaSdrh #ifdef SQLITE_DEBUG
7804031bafaSdrh /*
7814031bafaSdrh ** Assert if an Abort at this point in time might result in a corrupt
7824031bafaSdrh ** database.
7834031bafaSdrh */
sqlite3VdbeAssertAbortable(Vdbe * p)7844031bafaSdrh void sqlite3VdbeAssertAbortable(Vdbe *p){
7854031bafaSdrh assert( p->nWrite==0 || p->usesStmtJournal );
7864031bafaSdrh }
7874031bafaSdrh #endif
7884031bafaSdrh
78976ff3a0eSdrh /*
790ef41dfe5Sdrh ** This routine is called after all opcodes have been inserted. It loops
791ef41dfe5Sdrh ** through all the opcodes and fixes up some details.
79276ff3a0eSdrh **
793ef41dfe5Sdrh ** (1) For each jump instruction with a negative P2 value (a label)
794ef41dfe5Sdrh ** resolve the P2 value to an actual address.
795634f298cSdanielk1977 **
796ef41dfe5Sdrh ** (2) Compute the maximum number of arguments used by any SQL function
797ef41dfe5Sdrh ** and store that value in *pMaxFuncArgs.
798a6c2ed91Sdrh **
799ef41dfe5Sdrh ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
800ef41dfe5Sdrh ** indicate what the prepared statement actually does.
801ef41dfe5Sdrh **
802a7c9dd54Sdrh ** (4) (discontinued)
803ef41dfe5Sdrh **
804ef41dfe5Sdrh ** (5) Reclaim the memory allocated for storing labels.
8057cc84c2cSdrh **
8067cc84c2cSdrh ** This routine will only function correctly if the mkopcodeh.tcl generator
8077cc84c2cSdrh ** script numbers the opcodes correctly. Changes to this routine must be
8087cc84c2cSdrh ** coordinated with changes to mkopcodeh.tcl.
80976ff3a0eSdrh */
resolveP2Values(Vdbe * p,int * pMaxFuncArgs)8109cbf3425Sdrh static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
811165921a7Sdan int nMaxArgs = *pMaxFuncArgs;
81276ff3a0eSdrh Op *pOp;
81373d5b8f5Sdrh Parse *pParse = p->pParse;
81473d5b8f5Sdrh int *aLabel = pParse->aLabel;
815ad4a4b80Sdrh p->readOnly = 1;
8161713afb0Sdrh p->bIsReader = 0;
8177cc84c2cSdrh pOp = &p->aOp[p->nOp-1];
818064390b2Sdrh assert( p->aOp[0].opcode==OP_Init );
819064390b2Sdrh while( 1 /* Loop termates when it reaches the OP_Init opcode */ ){
8207cc84c2cSdrh /* Only JUMP opcodes and the short list of special opcodes in the switch
8217cc84c2cSdrh ** below need to be considered. The mkopcodeh.tcl generator script groups
8227cc84c2cSdrh ** all these opcodes together near the front of the opcode list. Skip
8237cc84c2cSdrh ** any opcode that does not need processing by virtual of the fact that
824c310db39Sdrh ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
8257cc84c2cSdrh */
826c310db39Sdrh if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
827b0c88651Sdrh /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
8288c8a8c45Sdrh ** cases from this switch! */
8297cc84c2cSdrh switch( pOp->opcode ){
8308c8a8c45Sdrh case OP_Transaction: {
8319e92a47bSdrh if( pOp->p2!=0 ) p->readOnly = 0;
83208b92086Sdrh /* no break */ deliberate_fall_through
8338c8a8c45Sdrh }
8348c8a8c45Sdrh case OP_AutoCommit:
8358c8a8c45Sdrh case OP_Savepoint: {
8361713afb0Sdrh p->bIsReader = 1;
8378c8a8c45Sdrh break;
8388c8a8c45Sdrh }
839d903154eSdan #ifndef SQLITE_OMIT_WAL
8408c8a8c45Sdrh case OP_Checkpoint:
8419e92a47bSdrh #endif
8428c8a8c45Sdrh case OP_Vacuum:
8438c8a8c45Sdrh case OP_JournalMode: {
844ad4a4b80Sdrh p->readOnly = 0;
8451713afb0Sdrh p->bIsReader = 1;
8468c8a8c45Sdrh break;
8478c8a8c45Sdrh }
848064390b2Sdrh case OP_Init: {
849064390b2Sdrh assert( pOp->p2>=0 );
850064390b2Sdrh goto resolve_p2_values_loop_exit;
851064390b2Sdrh }
852182c4ba9Sdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
8538c8a8c45Sdrh case OP_VUpdate: {
854a6c2ed91Sdrh if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
8558c8a8c45Sdrh break;
8568c8a8c45Sdrh }
8578c8a8c45Sdrh case OP_VFilter: {
8584be8b51eSdrh int n;
8597cc84c2cSdrh assert( (pOp - p->aOp) >= 3 );
8604c583128Sdrh assert( pOp[-1].opcode==OP_Integer );
8616dbee818Sdanielk1977 n = pOp[-1].p1;
8624be8b51eSdrh if( n>nMaxArgs ) nMaxArgs = n;
8636a8700b9Sdrh /* Fall through into the default case */
86408b92086Sdrh /* no break */ deliberate_fall_through
8658c8a8c45Sdrh }
866182c4ba9Sdanielk1977 #endif
8676a8700b9Sdrh default: {
8686a8700b9Sdrh if( pOp->p2<0 ){
8696a8700b9Sdrh /* The mkopcodeh.tcl script has so arranged things that the only
8706a8700b9Sdrh ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
8716a8700b9Sdrh ** have non-negative values for P2. */
8726a8700b9Sdrh assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
873d1d158bfSdrh assert( ADDR(pOp->p2)<-pParse->nLabel );
8745ef09bf9Sdrh pOp->p2 = aLabel[ADDR(pOp->p2)];
87576ff3a0eSdrh }
8766a8700b9Sdrh break;
8776a8700b9Sdrh }
8786a8700b9Sdrh }
8796a8700b9Sdrh /* The mkopcodeh.tcl script has so arranged things that the only
8806a8700b9Sdrh ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
8816a8700b9Sdrh ** have non-negative values for P2. */
8826a8700b9Sdrh assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
883d2981515Sdrh }
884064390b2Sdrh assert( pOp>p->aOp );
8857cc84c2cSdrh pOp--;
8867cc84c2cSdrh }
887064390b2Sdrh resolve_p2_values_loop_exit:
888cea170ecSdrh if( aLabel ){
88941ce47c4Sdrh sqlite3DbNNFreeNN(p->db, pParse->aLabel);
89073d5b8f5Sdrh pParse->aLabel = 0;
891cea170ecSdrh }
89273d5b8f5Sdrh pParse->nLabel = 0;
893bc04f852Sdanielk1977 *pMaxFuncArgs = nMaxArgs;
894a7ab6d81Sdrh assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
8959a32464bSdrh }
8969a32464bSdrh
897b77c3129Sdrh #ifdef SQLITE_DEBUG
898b77c3129Sdrh /*
899b77c3129Sdrh ** Check to see if a subroutine contains a jump to a location outside of
900b77c3129Sdrh ** the subroutine. If a jump outside the subroutine is detected, add code
901b77c3129Sdrh ** that will cause the program to halt with an error message.
902b77c3129Sdrh **
903b77c3129Sdrh ** The subroutine consists of opcodes between iFirst and iLast. Jumps to
904b77c3129Sdrh ** locations within the subroutine are acceptable. iRetReg is a register
905b77c3129Sdrh ** that contains the return address. Jumps to outside the range of iFirst
906b77c3129Sdrh ** through iLast are also acceptable as long as the jump destination is
907b77c3129Sdrh ** an OP_Return to iReturnAddr.
908b77c3129Sdrh **
9096c7e89b4Sdrh ** A jump to an unresolved label means that the jump destination will be
9106c7e89b4Sdrh ** beyond the current address. That is normally a jump to an early
9116c7e89b4Sdrh ** termination and is consider acceptable.
912b77c3129Sdrh **
913b77c3129Sdrh ** This routine only runs during debug builds. The purpose is (of course)
914b77c3129Sdrh ** to detect invalid escapes out of a subroutine. The OP_Halt opcode
915b77c3129Sdrh ** is generated rather than an assert() or other error, so that ".eqp full"
916b77c3129Sdrh ** will still work to show the original bytecode, to aid in debugging.
917b77c3129Sdrh */
sqlite3VdbeNoJumpsOutsideSubrtn(Vdbe * v,int iFirst,int iLast,int iRetReg)918b77c3129Sdrh void sqlite3VdbeNoJumpsOutsideSubrtn(
919b77c3129Sdrh Vdbe *v, /* The byte-code program under construction */
920b77c3129Sdrh int iFirst, /* First opcode of the subroutine */
921b77c3129Sdrh int iLast, /* Last opcode of the subroutine */
922b77c3129Sdrh int iRetReg /* Subroutine return address register */
923b77c3129Sdrh ){
924b77c3129Sdrh VdbeOp *pOp;
925b77c3129Sdrh Parse *pParse;
926b77c3129Sdrh int i;
927b77c3129Sdrh sqlite3_str *pErr = 0;
928b77c3129Sdrh assert( v!=0 );
929b77c3129Sdrh pParse = v->pParse;
930b77c3129Sdrh assert( pParse!=0 );
931b77c3129Sdrh if( pParse->nErr ) return;
932b77c3129Sdrh assert( iLast>=iFirst );
933b77c3129Sdrh assert( iLast<v->nOp );
934b77c3129Sdrh pOp = &v->aOp[iFirst];
935b77c3129Sdrh for(i=iFirst; i<=iLast; i++, pOp++){
936b77c3129Sdrh if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
937b77c3129Sdrh int iDest = pOp->p2; /* Jump destination */
938b77c3129Sdrh if( iDest==0 ) continue;
9396c7e89b4Sdrh if( pOp->opcode==OP_Gosub ) continue;
940b77c3129Sdrh if( iDest<0 ){
941b77c3129Sdrh int j = ADDR(iDest);
942b77c3129Sdrh assert( j>=0 );
943b77c3129Sdrh if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
944b77c3129Sdrh continue;
945b77c3129Sdrh }
946b77c3129Sdrh iDest = pParse->aLabel[j];
947b77c3129Sdrh }
948b77c3129Sdrh if( iDest<iFirst || iDest>iLast ){
949b77c3129Sdrh int j = iDest;
950b77c3129Sdrh for(; j<v->nOp; j++){
951b77c3129Sdrh VdbeOp *pX = &v->aOp[j];
952b77c3129Sdrh if( pX->opcode==OP_Return ){
953b77c3129Sdrh if( pX->p1==iRetReg ) break;
954b77c3129Sdrh continue;
955b77c3129Sdrh }
956b77c3129Sdrh if( pX->opcode==OP_Noop ) continue;
957b77c3129Sdrh if( pX->opcode==OP_Explain ) continue;
958b77c3129Sdrh if( pErr==0 ){
959b77c3129Sdrh pErr = sqlite3_str_new(0);
960b77c3129Sdrh }else{
961b77c3129Sdrh sqlite3_str_appendchar(pErr, 1, '\n');
962b77c3129Sdrh }
963b77c3129Sdrh sqlite3_str_appendf(pErr,
964b77c3129Sdrh "Opcode at %d jumps to %d which is outside the "
965b77c3129Sdrh "subroutine at %d..%d",
966b77c3129Sdrh i, iDest, iFirst, iLast);
967b77c3129Sdrh break;
968b77c3129Sdrh }
969b77c3129Sdrh }
970b77c3129Sdrh }
971b77c3129Sdrh }
972b77c3129Sdrh if( pErr ){
973b77c3129Sdrh char *zErr = sqlite3_str_finish(pErr);
974b77c3129Sdrh sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_INTERNAL, OE_Abort, 0, zErr, 0);
975b77c3129Sdrh sqlite3_free(zErr);
976b77c3129Sdrh sqlite3MayAbort(pParse);
977b77c3129Sdrh }
978b77c3129Sdrh }
979b77c3129Sdrh #endif /* SQLITE_DEBUG */
980b77c3129Sdrh
9819a32464bSdrh /*
9829a32464bSdrh ** Return the address of the next instruction to be inserted.
9839a32464bSdrh */
sqlite3VdbeCurrentAddr(Vdbe * p)9844adee20fSdanielk1977 int sqlite3VdbeCurrentAddr(Vdbe *p){
98566181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
9869a32464bSdrh return p->nOp;
9879a32464bSdrh }
9889a32464bSdrh
98965a7cd16Sdan /*
9902ce1865dSdrh ** Verify that at least N opcode slots are available in p without
991dad300d8Sdrh ** having to malloc for more space (except when compiled using
992dad300d8Sdrh ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
993dad300d8Sdrh ** to verify that certain calls to sqlite3VdbeAddOpList() can never
994dad300d8Sdrh ** fail due to a OOM fault and hence that the return value from
995dad300d8Sdrh ** sqlite3VdbeAddOpList() will always be non-NULL.
9962ce1865dSdrh */
997dad300d8Sdrh #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
sqlite3VdbeVerifyNoMallocRequired(Vdbe * p,int N)998dad300d8Sdrh void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
999b6991796Sdrh assert( p->nOp + N <= p->nOpAlloc );
10002ce1865dSdrh }
10012ce1865dSdrh #endif
10022ce1865dSdrh
10032ce1865dSdrh /*
10049e1ab1a8Sdan ** Verify that the VM passed as the only argument does not contain
10059e1ab1a8Sdan ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
10069e1ab1a8Sdan ** by code in pragma.c to ensure that the implementation of certain
10079e1ab1a8Sdan ** pragmas comports with the flags specified in the mkpragmatab.tcl
10089e1ab1a8Sdan ** script.
10099e1ab1a8Sdan */
10109e1ab1a8Sdan #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
sqlite3VdbeVerifyNoResultRow(Vdbe * p)10119e1ab1a8Sdan void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
10129e1ab1a8Sdan int i;
10139e1ab1a8Sdan for(i=0; i<p->nOp; i++){
10149e1ab1a8Sdan assert( p->aOp[i].opcode!=OP_ResultRow );
10159e1ab1a8Sdan }
10169e1ab1a8Sdan }
10179e1ab1a8Sdan #endif
10189e1ab1a8Sdan
10199e1ab1a8Sdan /*
10204031bafaSdrh ** Generate code (a single OP_Abortable opcode) that will
10214031bafaSdrh ** verify that the VDBE program can safely call Abort in the current
10224031bafaSdrh ** context.
10234031bafaSdrh */
10244031bafaSdrh #if defined(SQLITE_DEBUG)
sqlite3VdbeVerifyAbortable(Vdbe * p,int onError)10254031bafaSdrh void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
10264031bafaSdrh if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
10274031bafaSdrh }
10284031bafaSdrh #endif
10294031bafaSdrh
10304031bafaSdrh /*
103165a7cd16Sdan ** This function returns a pointer to the array of opcodes associated with
103265a7cd16Sdan ** the Vdbe passed as the first argument. It is the callers responsibility
103365a7cd16Sdan ** to arrange for the returned array to be eventually freed using the
103465a7cd16Sdan ** vdbeFreeOpArray() function.
103565a7cd16Sdan **
103665a7cd16Sdan ** Before returning, *pnOp is set to the number of entries in the returned
103765a7cd16Sdan ** array. Also, *pnMaxArg is set to the larger of its current value and
103865a7cd16Sdan ** the number of entries in the Vdbe.apArg[] array required to execute the
103965a7cd16Sdan ** returned program.
104065a7cd16Sdan */
sqlite3VdbeTakeOpArray(Vdbe * p,int * pnOp,int * pnMaxArg)1041165921a7Sdan VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
1042165921a7Sdan VdbeOp *aOp = p->aOp;
1043523a087bSdan assert( aOp && !p->db->mallocFailed );
104465a7cd16Sdan
104565a7cd16Sdan /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
1046a7ab6d81Sdrh assert( DbMaskAllZero(p->btreeMask) );
104765a7cd16Sdan
1048165921a7Sdan resolveP2Values(p, pnMaxArg);
1049165921a7Sdan *pnOp = p->nOp;
1050165921a7Sdan p->aOp = 0;
1051165921a7Sdan return aOp;
1052165921a7Sdan }
1053165921a7Sdan
10549a32464bSdrh /*
10552ce1865dSdrh ** Add a whole list of operations to the operation stack. Return a
10562ce1865dSdrh ** pointer to the first operation inserted.
10571b32554bSdrh **
10581b32554bSdrh ** Non-zero P2 arguments to jump instructions are automatically adjusted
10591b32554bSdrh ** so that the jump target is relative to the first operation inserted.
10609a32464bSdrh */
sqlite3VdbeAddOpList(Vdbe * p,int nOp,VdbeOpList const * aOp,int iLineno)10612ce1865dSdrh VdbeOp *sqlite3VdbeAddOpList(
10622ce1865dSdrh Vdbe *p, /* Add opcodes to the prepared statement */
10632ce1865dSdrh int nOp, /* Number of opcodes to add */
10642ce1865dSdrh VdbeOpList const *aOp, /* The opcodes to be added */
10652ce1865dSdrh int iLineno /* Source-file line number of first opcode */
10662ce1865dSdrh ){
10672ce1865dSdrh int i;
10682ce1865dSdrh VdbeOp *pOut, *pFirst;
1069ef41dfe5Sdrh assert( nOp>0 );
107066181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
1071b6991796Sdrh if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
10729a32464bSdrh return 0;
10739a32464bSdrh }
10742ce1865dSdrh pFirst = pOut = &p->aOp[p->nOp];
1075ef41dfe5Sdrh for(i=0; i<nOp; i++, aOp++, pOut++){
1076ef41dfe5Sdrh pOut->opcode = aOp->opcode;
1077ef41dfe5Sdrh pOut->p1 = aOp->p1;
10785ef09bf9Sdrh pOut->p2 = aOp->p2;
10795ef09bf9Sdrh assert( aOp->p2>=0 );
10801b32554bSdrh if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
10811b32554bSdrh pOut->p2 += p->nOp;
10821b32554bSdrh }
1083ef41dfe5Sdrh pOut->p3 = aOp->p3;
10842400345aSdrh pOut->p4type = P4_NOTUSED;
10852400345aSdrh pOut->p4.p = 0;
10862400345aSdrh pOut->p5 = 0;
1087c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
108826c9b5eaSdrh pOut->zComment = 0;
1089c7379ce4Sdrh #endif
1090688852abSdrh #ifdef SQLITE_VDBE_COVERAGE
1091688852abSdrh pOut->iSrcLine = iLineno+i;
1092688852abSdrh #else
1093688852abSdrh (void)iLineno;
1094688852abSdrh #endif
1095c7379ce4Sdrh #ifdef SQLITE_DEBUG
1096e096205aSdrh if( p->db->flags & SQLITE_VdbeAddopTrace ){
10972ce1865dSdrh sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
10989a32464bSdrh }
10999a32464bSdrh #endif
11009a32464bSdrh }
11019a32464bSdrh p->nOp += nOp;
11022ce1865dSdrh return pFirst;
11039a32464bSdrh }
11049a32464bSdrh
11056f9702edSdan #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
11066f9702edSdan /*
11076f9702edSdan ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
11086f9702edSdan */
sqlite3VdbeScanStatus(Vdbe * p,int addrExplain,int addrLoop,int addrVisit,LogEst nEst,const char * zName)1109037b5324Sdan void sqlite3VdbeScanStatus(
11106f9702edSdan Vdbe *p, /* VM to add scanstatus() to */
11116f9702edSdan int addrExplain, /* Address of OP_Explain (or 0) */
11126f9702edSdan int addrLoop, /* Address of loop counter */
11136f9702edSdan int addrVisit, /* Address of rows visited counter */
1114518140edSdrh LogEst nEst, /* Estimated number of output rows */
11156f9702edSdan const char *zName /* Name of table or index being scanned */
11166f9702edSdan ){
11170aa3231fSdrh sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
1118037b5324Sdan ScanStatus *aNew;
1119037b5324Sdan aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
11206f9702edSdan if( aNew ){
1121037b5324Sdan ScanStatus *pNew = &aNew[p->nScan++];
11226f9702edSdan pNew->addrExplain = addrExplain;
11236f9702edSdan pNew->addrLoop = addrLoop;
11246f9702edSdan pNew->addrVisit = addrVisit;
11256f9702edSdan pNew->nEst = nEst;
11266f9702edSdan pNew->zName = sqlite3DbStrDup(p->db, zName);
11276f9702edSdan p->aScan = aNew;
11286f9702edSdan }
11296f9702edSdan }
11306f9702edSdan #endif
11316f9702edSdan
11326f9702edSdan
11339a32464bSdrh /*
11340ff287fbSdrh ** Change the value of the opcode, or P1, P2, P3, or P5 operands
11350ff287fbSdrh ** for a specific instruction.
11369a32464bSdrh */
sqlite3VdbeChangeOpcode(Vdbe * p,int addr,u8 iNewOpcode)1137044388cfSmistachkin void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
1138058e9950Sdrh assert( addr>=0 );
11390ff287fbSdrh sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
11400ff287fbSdrh }
sqlite3VdbeChangeP1(Vdbe * p,int addr,int val)11413728b84cSdrh void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
1142058e9950Sdrh assert( addr>=0 );
11430ff287fbSdrh sqlite3VdbeGetOp(p,addr)->p1 = val;
11449a32464bSdrh }
sqlite3VdbeChangeP2(Vdbe * p,int addr,int val)11453728b84cSdrh void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
1146e6710e83Sdrh assert( addr>=0 || p->db->mallocFailed );
11470ff287fbSdrh sqlite3VdbeGetOp(p,addr)->p2 = val;
11489a32464bSdrh }
sqlite3VdbeChangeP3(Vdbe * p,int addr,int val)11493728b84cSdrh void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
1150058e9950Sdrh assert( addr>=0 );
11510ff287fbSdrh sqlite3VdbeGetOp(p,addr)->p3 = val;
1152207872a4Sdanielk1977 }
sqlite3VdbeChangeP5(Vdbe * p,u16 p5)1153585ce192Sdrh void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
1154dd3bfe86Sdrh assert( p->nOp>0 || p->db->mallocFailed );
1155dd3bfe86Sdrh if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
11561f4aa337Sdanielk1977 }
11571f4aa337Sdanielk1977
11581f4aa337Sdanielk1977 /*
1159e995d2c2Sdrh ** If the previous opcode is an OP_Column that delivers results
1160921acff9Sdrh ** into register iDest, then add the OPFLAG_TYPEOFARG flag to that
1161e995d2c2Sdrh ** opcode.
1162e995d2c2Sdrh */
sqlite3VdbeTypeofColumn(Vdbe * p,int iDest)1163e995d2c2Sdrh void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){
1164bd1c6345Sdrh VdbeOp *pOp = sqlite3VdbeGetLastOp(p);
1165bd1c6345Sdrh if( pOp->p3==iDest && pOp->opcode==OP_Column ){
1166e995d2c2Sdrh pOp->p5 |= OPFLAG_TYPEOFARG;
1167e995d2c2Sdrh }
1168e995d2c2Sdrh }
1169e995d2c2Sdrh
1170e995d2c2Sdrh /*
1171f8875400Sdrh ** Change the P2 operand of instruction addr so that it points to
1172d654be80Sdrh ** the address of the next instruction to be coded.
1173d654be80Sdrh */
sqlite3VdbeJumpHere(Vdbe * p,int addr)1174d654be80Sdrh void sqlite3VdbeJumpHere(Vdbe *p, int addr){
11750ff287fbSdrh sqlite3VdbeChangeP2(p, addr, p->nOp);
1176d654be80Sdrh }
1177b38ad999Sdrh
1178dc4f6fc0Sdrh /*
1179dc4f6fc0Sdrh ** Change the P2 operand of the jump instruction at addr so that
1180dc4f6fc0Sdrh ** the jump lands on the next opcode. Or if the jump instruction was
1181dc4f6fc0Sdrh ** the previous opcode (and is thus a no-op) then simply back up
1182dc4f6fc0Sdrh ** the next instruction counter by one slot so that the jump is
1183dc4f6fc0Sdrh ** overwritten by the next inserted opcode.
1184dc4f6fc0Sdrh **
1185dc4f6fc0Sdrh ** This routine is an optimization of sqlite3VdbeJumpHere() that
1186dc4f6fc0Sdrh ** strives to omit useless byte-code like this:
1187dc4f6fc0Sdrh **
1188dc4f6fc0Sdrh ** 7 Once 0 8 0
1189dc4f6fc0Sdrh ** 8 ...
1190dc4f6fc0Sdrh */
sqlite3VdbeJumpHereOrPopInst(Vdbe * p,int addr)1191dc4f6fc0Sdrh void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
1192dc4f6fc0Sdrh if( addr==p->nOp-1 ){
1193dc4f6fc0Sdrh assert( p->aOp[addr].opcode==OP_Once
1194dc4f6fc0Sdrh || p->aOp[addr].opcode==OP_If
1195dc4f6fc0Sdrh || p->aOp[addr].opcode==OP_FkIfZero );
1196dc4f6fc0Sdrh assert( p->aOp[addr].p4type==0 );
1197dc4f6fc0Sdrh #ifdef SQLITE_VDBE_COVERAGE
1198058e9950Sdrh sqlite3VdbeGetLastOp(p)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
1199dc4f6fc0Sdrh #endif
1200dc4f6fc0Sdrh p->nOp--;
1201dc4f6fc0Sdrh }else{
1202dc4f6fc0Sdrh sqlite3VdbeChangeP2(p, addr, p->nOp);
1203dc4f6fc0Sdrh }
1204dc4f6fc0Sdrh }
1205dc4f6fc0Sdrh
1206b7f6f68fSdrh
1207b7f6f68fSdrh /*
1208b7f6f68fSdrh ** If the input FuncDef structure is ephemeral, then free it. If
1209b7f6f68fSdrh ** the FuncDef is not ephermal, then do nothing.
1210b7f6f68fSdrh */
freeEphemeralFunction(sqlite3 * db,FuncDef * pDef)1211633e6d57Sdrh static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
121241ce47c4Sdrh assert( db!=0 );
1213f431a87cSdrh if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
121441ce47c4Sdrh sqlite3DbNNFreeNN(db, pDef);
1215b7f6f68fSdrh }
1216b7f6f68fSdrh }
1217b7f6f68fSdrh
1218b38ad999Sdrh /*
121966a5167bSdrh ** Delete a P4 value if necessary.
1220b38ad999Sdrh */
freeP4Mem(sqlite3 * db,Mem * p)1221f431a87cSdrh static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
1222f431a87cSdrh if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
122341ce47c4Sdrh sqlite3DbNNFreeNN(db, p);
1224f431a87cSdrh }
freeP4FuncCtx(sqlite3 * db,sqlite3_context * p)1225f431a87cSdrh static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
122641ce47c4Sdrh assert( db!=0 );
1227f431a87cSdrh freeEphemeralFunction(db, p->pFunc);
122841ce47c4Sdrh sqlite3DbNNFreeNN(db, p);
1229f431a87cSdrh }
freeP4(sqlite3 * db,int p4type,void * p4)1230633e6d57Sdrh static void freeP4(sqlite3 *db, int p4type, void *p4){
1231d46def77Sdan assert( db );
123266a5167bSdrh switch( p4type ){
12339c7c913cSdrh case P4_FUNCCTX: {
1234f431a87cSdrh freeP4FuncCtx(db, (sqlite3_context*)p4);
1235f431a87cSdrh break;
12369c7c913cSdrh }
123766a5167bSdrh case P4_REAL:
123866a5167bSdrh case P4_INT64:
123966a5167bSdrh case P4_DYNAMIC:
12402ec2fb22Sdrh case P4_INTARRAY: {
124141ce47c4Sdrh if( p4 ) sqlite3DbNNFreeNN(db, p4);
1242ac1733d4Sdrh break;
1243b38ad999Sdrh }
12442ec2fb22Sdrh case P4_KEYINFO: {
12452ec2fb22Sdrh if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
12462ec2fb22Sdrh break;
12472ec2fb22Sdrh }
124828935364Sdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
124928935364Sdrh case P4_EXPR: {
125028935364Sdrh sqlite3ExprDelete(db, (Expr*)p4);
125128935364Sdrh break;
125228935364Sdrh }
125328935364Sdrh #endif
125466a5167bSdrh case P4_FUNCDEF: {
1255633e6d57Sdrh freeEphemeralFunction(db, (FuncDef*)p4);
1256b7f6f68fSdrh break;
1257b7f6f68fSdrh }
125866a5167bSdrh case P4_MEM: {
1259c176c27cSdrh if( db->pnBytesFreed==0 ){
12600acb7e48Sdrh sqlite3ValueFree((sqlite3_value*)p4);
1261c176c27cSdrh }else{
1262f431a87cSdrh freeP4Mem(db, (Mem*)p4);
1263c176c27cSdrh }
1264ac1733d4Sdrh break;
1265ac1733d4Sdrh }
1266595a523aSdanielk1977 case P4_VTAB : {
1267d46def77Sdan if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
1268595a523aSdanielk1977 break;
1269595a523aSdanielk1977 }
1270b38ad999Sdrh }
1271b38ad999Sdrh }
1272165921a7Sdan
127365a7cd16Sdan /*
127465a7cd16Sdan ** Free the space allocated for aOp and any p4 values allocated for the
127565a7cd16Sdan ** opcodes contained within. If aOp is not NULL it is assumed to contain
127665a7cd16Sdan ** nOp entries.
127765a7cd16Sdan */
vdbeFreeOpArray(sqlite3 * db,Op * aOp,int nOp)1278165921a7Sdan static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
127960a512d9Sdrh assert( nOp>=0 );
128041ce47c4Sdrh assert( db!=0 );
1281165921a7Sdan if( aOp ){
128260a512d9Sdrh Op *pOp = &aOp[nOp-1];
128360a512d9Sdrh while(1){ /* Exit via break */
12840c243300Sdrh if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
1285c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1286165921a7Sdan sqlite3DbFree(db, pOp->zComment);
1287165921a7Sdan #endif
128860a512d9Sdrh if( pOp==aOp ) break;
128960a512d9Sdrh pOp--;
1290165921a7Sdan }
129141ce47c4Sdrh sqlite3DbNNFreeNN(db, aOp);
1292165921a7Sdan }
1293165921a7Sdan }
1294165921a7Sdan
129565a7cd16Sdan /*
1296d19c933eSdan ** Link the SubProgram object passed as the second argument into the linked
1297d19c933eSdan ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
1298d19c933eSdan ** objects when the VM is no longer required.
129965a7cd16Sdan */
sqlite3VdbeLinkSubProgram(Vdbe * pVdbe,SubProgram * p)1300d19c933eSdan void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
1301d19c933eSdan p->pNext = pVdbe->pProgram;
1302d19c933eSdan pVdbe->pProgram = p;
1303165921a7Sdan }
1304b38ad999Sdrh
13059a32464bSdrh /*
130606baba54Sdrh ** Return true if the given Vdbe has any SubPrograms.
130706baba54Sdrh */
sqlite3VdbeHasSubProgram(Vdbe * pVdbe)130806baba54Sdrh int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
130906baba54Sdrh return pVdbe->pProgram!=0;
131006baba54Sdrh }
131106baba54Sdrh
131206baba54Sdrh /*
131348f2d3b1Sdrh ** Change the opcode at addr into OP_Noop
1314f8875400Sdrh */
sqlite3VdbeChangeToNoop(Vdbe * p,int addr)13152ce1865dSdrh int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
13162ce1865dSdrh VdbeOp *pOp;
13172ce1865dSdrh if( p->db->mallocFailed ) return 0;
13182ce1865dSdrh assert( addr>=0 && addr<p->nOp );
13192ce1865dSdrh pOp = &p->aOp[addr];
13202ce1865dSdrh freeP4(p->db, pOp->p4type, pOp->p4.p);
13214b31bda2Sdrh pOp->p4type = P4_NOTUSED;
1322939e778bSdrh pOp->p4.z = 0;
1323f8875400Sdrh pOp->opcode = OP_Noop;
13242ce1865dSdrh return 1;
132592d4d7a9Sdanielk1977 }
1326f8875400Sdrh
1327f8875400Sdrh /*
132839c4b82bSdrh ** If the last opcode is "op" and it is not a jump destination,
132939c4b82bSdrh ** then remove it. Return true if and only if an opcode was removed.
1330762c1c40Sdrh */
sqlite3VdbeDeletePriorOpcode(Vdbe * p,u8 op)133161019c78Sdrh int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
13322831c4d1Sdrh if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
13332ce1865dSdrh return sqlite3VdbeChangeToNoop(p, p->nOp-1);
133461019c78Sdrh }else{
133561019c78Sdrh return 0;
133661019c78Sdrh }
1337762c1c40Sdrh }
1338762c1c40Sdrh
133913d79502Sdrh #ifdef SQLITE_DEBUG
134013d79502Sdrh /*
134113d79502Sdrh ** Generate an OP_ReleaseReg opcode to indicate that a range of
134213d79502Sdrh ** registers, except any identified by mask, are no longer in use.
134313d79502Sdrh */
sqlite3VdbeReleaseRegisters(Parse * pParse,int iFirst,int N,u32 mask,int bUndefine)13443aef2fb1Sdrh void sqlite3VdbeReleaseRegisters(
13453aef2fb1Sdrh Parse *pParse, /* Parsing context */
13463aef2fb1Sdrh int iFirst, /* Index of first register to be released */
13473aef2fb1Sdrh int N, /* Number of registers to release */
13483aef2fb1Sdrh u32 mask, /* Mask of registers to NOT release */
13493aef2fb1Sdrh int bUndefine /* If true, mark registers as undefined */
13503aef2fb1Sdrh ){
1351da4c7cccSdrh if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
135213d79502Sdrh assert( pParse->pVdbe );
13533aef2fb1Sdrh assert( iFirst>=1 );
13543aef2fb1Sdrh assert( iFirst+N-1<=pParse->nMem );
1355b2fe5a7cSdrh if( N<=31 && mask!=0 ){
135613d79502Sdrh while( N>0 && (mask&1)!=0 ){
135713d79502Sdrh mask >>= 1;
135813d79502Sdrh iFirst++;
135913d79502Sdrh N--;
136013d79502Sdrh }
136113d79502Sdrh while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
136213d79502Sdrh mask &= ~MASKBIT32(N-1);
136313d79502Sdrh N--;
136413d79502Sdrh }
1365b2fe5a7cSdrh }
136613d79502Sdrh if( N>0 ){
136713d79502Sdrh sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
13683aef2fb1Sdrh if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
136913d79502Sdrh }
137013d79502Sdrh }
137113d79502Sdrh #endif /* SQLITE_DEBUG */
137213d79502Sdrh
137313d79502Sdrh
1374762c1c40Sdrh /*
137566a5167bSdrh ** Change the value of the P4 operand for a specific instruction.
13769a32464bSdrh ** This routine is useful when a large program is loaded from a
13774adee20fSdanielk1977 ** static array using sqlite3VdbeAddOpList but we want to make a
13789a32464bSdrh ** few minor changes to the program.
13799a32464bSdrh **
138066a5167bSdrh ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
138117435752Sdrh ** the string is made into memory obtained from sqlite3_malloc().
138266a5167bSdrh ** A value of n==0 means copy bytes of zP4 up to and including the
138366a5167bSdrh ** first null byte. If n>0 then copy n+1 bytes of zP4.
13849a32464bSdrh **
138566a5167bSdrh ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
13861f55c056Sdanielk1977 ** to a string or structure that is guaranteed to exist for the lifetime of
13871f55c056Sdanielk1977 ** the Vdbe. In these cases we can just copy the pointer.
13889a32464bSdrh **
138966a5167bSdrh ** If addr<0 then change P4 on the most recently inserted instruction.
13909a32464bSdrh */
vdbeChangeP4Full(Vdbe * p,Op * pOp,const char * zP4,int n)139100dcecabSdrh static void SQLITE_NOINLINE vdbeChangeP4Full(
139200dcecabSdrh Vdbe *p,
139300dcecabSdrh Op *pOp,
139400dcecabSdrh const char *zP4,
139500dcecabSdrh int n
139600dcecabSdrh ){
139700dcecabSdrh if( pOp->p4type ){
139800dcecabSdrh freeP4(p->db, pOp->p4type, pOp->p4.p);
139900dcecabSdrh pOp->p4type = 0;
140000dcecabSdrh pOp->p4.p = 0;
140100dcecabSdrh }
140200dcecabSdrh if( n<0 ){
140300dcecabSdrh sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
140400dcecabSdrh }else{
140500dcecabSdrh if( n==0 ) n = sqlite3Strlen30(zP4);
140600dcecabSdrh pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
140700dcecabSdrh pOp->p4type = P4_DYNAMIC;
140800dcecabSdrh }
140900dcecabSdrh }
sqlite3VdbeChangeP4(Vdbe * p,int addr,const char * zP4,int n)141066a5167bSdrh void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
14119a32464bSdrh Op *pOp;
1412633e6d57Sdrh sqlite3 *db;
141391fd4d46Sdrh assert( p!=0 );
1414633e6d57Sdrh db = p->db;
141566181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
141600dcecabSdrh assert( p->aOp!=0 || db->mallocFailed );
141700dcecabSdrh if( db->mallocFailed ){
141800dcecabSdrh if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
1419d5d56523Sdanielk1977 return;
1420d5d56523Sdanielk1977 }
14217b746030Sdrh assert( p->nOp>0 );
142291fd4d46Sdrh assert( addr<p->nOp );
142391fd4d46Sdrh if( addr<0 ){
14249a32464bSdrh addr = p->nOp - 1;
14259a32464bSdrh }
14269a32464bSdrh pOp = &p->aOp[addr];
142700dcecabSdrh if( n>=0 || pOp->p4type ){
142800dcecabSdrh vdbeChangeP4Full(p, pOp, zP4, n);
142900dcecabSdrh return;
143000dcecabSdrh }
143198757157Sdrh if( n==P4_INT32 ){
143212d4082fSmlcreech /* Note: this cast is safe, because the origin data point was an int
143312d4082fSmlcreech ** that was cast to a (const char *). */
14341fc4129dSshane pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
14358df32841Sdrh pOp->p4type = P4_INT32;
143600dcecabSdrh }else if( zP4!=0 ){
143700dcecabSdrh assert( n<0 );
14382dca4ac1Sdanielk1977 pOp->p4.p = (void*)zP4;
14398df32841Sdrh pOp->p4type = (signed char)n;
144000dcecabSdrh if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
14419a32464bSdrh }
14429a32464bSdrh }
14439a32464bSdrh
14442ec2fb22Sdrh /*
1445f14b7fb7Sdrh ** Change the P4 operand of the most recently coded instruction
1446f14b7fb7Sdrh ** to the value defined by the arguments. This is a high-speed
1447f14b7fb7Sdrh ** version of sqlite3VdbeChangeP4().
1448f14b7fb7Sdrh **
1449f14b7fb7Sdrh ** The P4 operand must not have been previously defined. And the new
1450f14b7fb7Sdrh ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
1451f14b7fb7Sdrh ** those cases.
1452f14b7fb7Sdrh */
sqlite3VdbeAppendP4(Vdbe * p,void * pP4,int n)1453f14b7fb7Sdrh void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
1454f14b7fb7Sdrh VdbeOp *pOp;
1455f14b7fb7Sdrh assert( n!=P4_INT32 && n!=P4_VTAB );
1456f14b7fb7Sdrh assert( n<=0 );
1457f14b7fb7Sdrh if( p->db->mallocFailed ){
1458f14b7fb7Sdrh freeP4(p->db, n, pP4);
1459f14b7fb7Sdrh }else{
1460f14b7fb7Sdrh assert( pP4!=0 );
1461f14b7fb7Sdrh assert( p->nOp>0 );
1462f14b7fb7Sdrh pOp = &p->aOp[p->nOp-1];
1463f14b7fb7Sdrh assert( pOp->p4type==P4_NOTUSED );
1464f14b7fb7Sdrh pOp->p4type = n;
1465f14b7fb7Sdrh pOp->p4.p = pP4;
1466f14b7fb7Sdrh }
1467f14b7fb7Sdrh }
1468f14b7fb7Sdrh
1469f14b7fb7Sdrh /*
14702ec2fb22Sdrh ** Set the P4 on the most recently added opcode to the KeyInfo for the
14712ec2fb22Sdrh ** index given.
14722ec2fb22Sdrh */
sqlite3VdbeSetP4KeyInfo(Parse * pParse,Index * pIdx)14732ec2fb22Sdrh void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
14742ec2fb22Sdrh Vdbe *v = pParse->pVdbe;
1475f14b7fb7Sdrh KeyInfo *pKeyInfo;
14762ec2fb22Sdrh assert( v!=0 );
14772ec2fb22Sdrh assert( pIdx!=0 );
1478f14b7fb7Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
1479f14b7fb7Sdrh if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
14802ec2fb22Sdrh }
14812ec2fb22Sdrh
1482c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
1483ad6d9460Sdrh /*
1484d5578433Smistachkin ** Change the comment on the most recently coded instruction. Or
148516ee60ffSdrh ** insert a No-op and add the comment to that new instruction. This
148616ee60ffSdrh ** makes the code easier to read during debugging. None of this happens
148716ee60ffSdrh ** in a production build.
1488ad6d9460Sdrh */
vdbeVComment(Vdbe * p,const char * zFormat,va_list ap)1489b07028f7Sdrh static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
149001256832Sdanielk1977 assert( p->nOp>0 || p->aOp==0 );
14910c7d3d39Sdrh assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
1492dba0137eSdanielk1977 if( p->nOp ){
1493b07028f7Sdrh assert( p->aOp );
1494b07028f7Sdrh sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
1495b07028f7Sdrh p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
1496b07028f7Sdrh }
1497b07028f7Sdrh }
sqlite3VdbeComment(Vdbe * p,const char * zFormat,...)1498b07028f7Sdrh void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
1499b07028f7Sdrh va_list ap;
1500b07028f7Sdrh if( p ){
1501ad6d9460Sdrh va_start(ap, zFormat);
1502b07028f7Sdrh vdbeVComment(p, zFormat, ap);
1503ad6d9460Sdrh va_end(ap);
1504ad6d9460Sdrh }
1505dba0137eSdanielk1977 }
sqlite3VdbeNoopComment(Vdbe * p,const char * zFormat,...)150616ee60ffSdrh void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
150716ee60ffSdrh va_list ap;
1508b07028f7Sdrh if( p ){
150916ee60ffSdrh sqlite3VdbeAddOp0(p, OP_Noop);
151016ee60ffSdrh va_start(ap, zFormat);
1511b07028f7Sdrh vdbeVComment(p, zFormat, ap);
151216ee60ffSdrh va_end(ap);
151316ee60ffSdrh }
151416ee60ffSdrh }
151516ee60ffSdrh #endif /* NDEBUG */
1516ad6d9460Sdrh
1517688852abSdrh #ifdef SQLITE_VDBE_COVERAGE
1518688852abSdrh /*
1519688852abSdrh ** Set the value if the iSrcLine field for the previously coded instruction.
1520688852abSdrh */
sqlite3VdbeSetLineNumber(Vdbe * v,int iLine)1521688852abSdrh void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
1522058e9950Sdrh sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
1523688852abSdrh }
1524688852abSdrh #endif /* SQLITE_VDBE_COVERAGE */
1525688852abSdrh
15269a32464bSdrh /*
1527058e9950Sdrh ** Return the opcode for a given address. The address must be non-negative.
1528058e9950Sdrh ** See sqlite3VdbeGetLastOp() to get the most recently added opcode.
152920411ea7Sdrh **
153020411ea7Sdrh ** If a memory allocation error has occurred prior to the calling of this
153120411ea7Sdrh ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
1532f83dc1efSdrh ** is readable but not writable, though it is cast to a writable value.
1533f83dc1efSdrh ** The return of a dummy opcode allows the call to continue functioning
153460ec914cSpeter.d.reid ** after an OOM fault without having to check to see if the return from
1535f83dc1efSdrh ** this routine is a valid pointer. But because the dummy.opcode is 0,
1536f83dc1efSdrh ** dummy will never be written to. This is verified by code inspection and
1537f83dc1efSdrh ** by running with Valgrind.
15389a32464bSdrh */
sqlite3VdbeGetOp(Vdbe * p,int addr)15394adee20fSdanielk1977 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
1540a0b75da1Sdrh /* C89 specifies that the constant "dummy" will be initialized to all
1541a0b75da1Sdrh ** zeros, which is correct. MSVC generates a warning, nevertheless. */
15420fe5f95cSmistachkin static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
154366181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
154417435752Sdrh assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
154520411ea7Sdrh if( p->db->mallocFailed ){
1546f83dc1efSdrh return (VdbeOp*)&dummy;
154720411ea7Sdrh }else{
154820411ea7Sdrh return &p->aOp[addr];
154920411ea7Sdrh }
15509a32464bSdrh }
15519a32464bSdrh
1552058e9950Sdrh /* Return the most recently added opcode
1553058e9950Sdrh */
sqlite3VdbeGetLastOp(Vdbe * p)1554058e9950Sdrh VdbeOp * sqlite3VdbeGetLastOp(Vdbe *p){
1555058e9950Sdrh return sqlite3VdbeGetOp(p, p->nOp - 1);
1556058e9950Sdrh }
1557058e9950Sdrh
1558c7379ce4Sdrh #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
155981316f89Sdrh /*
1560f63552b2Sdrh ** Return an integer value for one of the parameters to the opcode pOp
1561f63552b2Sdrh ** determined by character c.
1562f63552b2Sdrh */
translateP(char c,const Op * pOp)1563f63552b2Sdrh static int translateP(char c, const Op *pOp){
1564f63552b2Sdrh if( c=='1' ) return pOp->p1;
1565f63552b2Sdrh if( c=='2' ) return pOp->p2;
1566f63552b2Sdrh if( c=='3' ) return pOp->p3;
1567f63552b2Sdrh if( c=='4' ) return pOp->p4.i;
1568f63552b2Sdrh return pOp->p5;
1569f63552b2Sdrh }
1570f63552b2Sdrh
157181316f89Sdrh /*
15724eded604Sdrh ** Compute a string for the "comment" field of a VDBE opcode listing.
15734eded604Sdrh **
15744eded604Sdrh ** The Synopsis: field in comments in the vdbe.c source file gets converted
15754eded604Sdrh ** to an extra string that is appended to the sqlite3OpcodeName(). In the
15764eded604Sdrh ** absence of other comments, this synopsis becomes the comment on the opcode.
15774eded604Sdrh ** Some translation occurs:
15784eded604Sdrh **
15794eded604Sdrh ** "PX" -> "r[X]"
15804eded604Sdrh ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
15814eded604Sdrh ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
15824eded604Sdrh ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
158381316f89Sdrh */
sqlite3VdbeDisplayComment(sqlite3 * db,const Op * pOp,const char * zP4)15848c5163a6Sdrh char *sqlite3VdbeDisplayComment(
1585cb49f546Sdrh sqlite3 *db, /* Optional - Oom error reporting only */
1586f63552b2Sdrh const Op *pOp, /* The opcode to be commented */
1587cb49f546Sdrh const char *zP4 /* Previously obtained value for P4 */
1588f63552b2Sdrh ){
158981316f89Sdrh const char *zOpName;
159081316f89Sdrh const char *zSynopsis;
159181316f89Sdrh int nOpName;
1592d7b10d74Sdrh int ii;
15931ad78c57Sdrh char zAlt[50];
1594d7b10d74Sdrh StrAccum x;
1595d7b10d74Sdrh
1596cb49f546Sdrh sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
159781316f89Sdrh zOpName = sqlite3OpcodeName(pOp->opcode);
159881316f89Sdrh nOpName = sqlite3Strlen30(zOpName);
159981316f89Sdrh if( zOpName[nOpName+1] ){
160081316f89Sdrh int seenCom = 0;
1601f63552b2Sdrh char c;
16027d4c94bcSdrh zSynopsis = zOpName + nOpName + 1;
16031ad78c57Sdrh if( strncmp(zSynopsis,"IF ",3)==0 ){
16041ad78c57Sdrh sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
16051ad78c57Sdrh zSynopsis = zAlt;
16061ad78c57Sdrh }
1607d7b10d74Sdrh for(ii=0; (c = zSynopsis[ii])!=0; ii++){
1608f63552b2Sdrh if( c=='P' ){
1609f63552b2Sdrh c = zSynopsis[++ii];
1610f63552b2Sdrh if( c=='4' ){
1611d7b10d74Sdrh sqlite3_str_appendall(&x, zP4);
1612f63552b2Sdrh }else if( c=='X' ){
1613088b615aSdrh if( pOp->zComment && pOp->zComment[0] ){
1614d7b10d74Sdrh sqlite3_str_appendall(&x, pOp->zComment);
1615f63552b2Sdrh seenCom = 1;
1616088b615aSdrh break;
1617d83997baSdrh }
161881316f89Sdrh }else{
1619f63552b2Sdrh int v1 = translateP(c, pOp);
1620f63552b2Sdrh int v2;
1621f63552b2Sdrh if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
1622f63552b2Sdrh ii += 3;
1623f63552b2Sdrh v2 = translateP(zSynopsis[ii], pOp);
16244eded604Sdrh if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
16254eded604Sdrh ii += 2;
16264eded604Sdrh v2++;
16274eded604Sdrh }
1628d7b10d74Sdrh if( v2<2 ){
1629d7b10d74Sdrh sqlite3_str_appendf(&x, "%d", v1);
1630d7b10d74Sdrh }else{
1631d7b10d74Sdrh sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
16324eded604Sdrh }
1633d7b10d74Sdrh }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
1634d7b10d74Sdrh sqlite3_context *pCtx = pOp->p4.pCtx;
163540d1db8dSdrh if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
1636d7b10d74Sdrh sqlite3_str_appendf(&x, "%d", v1);
1637d7b10d74Sdrh }else if( pCtx->argc>1 ){
1638d7b10d74Sdrh sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
16391a56fce6Sdrh }else if( x.accError==0 ){
1640d7b10d74Sdrh assert( x.nChar>2 );
1641d7b10d74Sdrh x.nChar -= 2;
1642d7b10d74Sdrh ii++;
1643d7b10d74Sdrh }
1644d7b10d74Sdrh ii += 3;
1645d7b10d74Sdrh }else{
1646d7b10d74Sdrh sqlite3_str_appendf(&x, "%d", v1);
1647d7b10d74Sdrh if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
1648f63552b2Sdrh ii += 4;
1649f63552b2Sdrh }
165081316f89Sdrh }
1651d7b10d74Sdrh }
165281316f89Sdrh }else{
1653d7b10d74Sdrh sqlite3_str_appendchar(&x, 1, c);
165481316f89Sdrh }
165581316f89Sdrh }
1656d7b10d74Sdrh if( !seenCom && pOp->zComment ){
1657d7b10d74Sdrh sqlite3_str_appendf(&x, "; %s", pOp->zComment);
165881316f89Sdrh }
165981316f89Sdrh }else if( pOp->zComment ){
1660d7b10d74Sdrh sqlite3_str_appendall(&x, pOp->zComment);
166181316f89Sdrh }
1662cb49f546Sdrh if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
1663cb49f546Sdrh sqlite3OomFault(db);
1664cb49f546Sdrh }
1665cb49f546Sdrh return sqlite3StrAccumFinish(&x);
166681316f89Sdrh }
1667e0ef4e2bSdrh #endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
166881316f89Sdrh
1669f7e36907Sdrh #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
1670f7e36907Sdrh /*
1671f7e36907Sdrh ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
1672f7e36907Sdrh ** that can be displayed in the P4 column of EXPLAIN output.
1673f7e36907Sdrh */
displayP4Expr(StrAccum * p,Expr * pExpr)16745f4a686fSdrh static void displayP4Expr(StrAccum *p, Expr *pExpr){
1675a67a3162Sdrh const char *zOp = 0;
1676f7e36907Sdrh switch( pExpr->op ){
1677f7e36907Sdrh case TK_STRING:
1678f9751074Sdrh assert( !ExprHasProperty(pExpr, EP_IntValue) );
16790cdbe1aeSdrh sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
1680f7e36907Sdrh break;
1681f7e36907Sdrh case TK_INTEGER:
16820cdbe1aeSdrh sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
1683f7e36907Sdrh break;
1684f7e36907Sdrh case TK_NULL:
16850cdbe1aeSdrh sqlite3_str_appendf(p, "NULL");
1686f7e36907Sdrh break;
1687f7e36907Sdrh case TK_REGISTER: {
16880cdbe1aeSdrh sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
1689f7e36907Sdrh break;
1690f7e36907Sdrh }
1691f7e36907Sdrh case TK_COLUMN: {
1692fe66352dSdrh if( pExpr->iColumn<0 ){
16930cdbe1aeSdrh sqlite3_str_appendf(p, "rowid");
1694fe66352dSdrh }else{
16950cdbe1aeSdrh sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
1696fe66352dSdrh }
1697f7e36907Sdrh break;
1698f7e36907Sdrh }
1699a67a3162Sdrh case TK_LT: zOp = "LT"; break;
1700a67a3162Sdrh case TK_LE: zOp = "LE"; break;
1701a67a3162Sdrh case TK_GT: zOp = "GT"; break;
1702a67a3162Sdrh case TK_GE: zOp = "GE"; break;
1703a67a3162Sdrh case TK_NE: zOp = "NE"; break;
1704a67a3162Sdrh case TK_EQ: zOp = "EQ"; break;
1705a67a3162Sdrh case TK_IS: zOp = "IS"; break;
1706a67a3162Sdrh case TK_ISNOT: zOp = "ISNOT"; break;
1707a67a3162Sdrh case TK_AND: zOp = "AND"; break;
1708a67a3162Sdrh case TK_OR: zOp = "OR"; break;
1709a67a3162Sdrh case TK_PLUS: zOp = "ADD"; break;
1710a67a3162Sdrh case TK_STAR: zOp = "MUL"; break;
1711a67a3162Sdrh case TK_MINUS: zOp = "SUB"; break;
1712a67a3162Sdrh case TK_REM: zOp = "REM"; break;
1713a67a3162Sdrh case TK_BITAND: zOp = "BITAND"; break;
1714a67a3162Sdrh case TK_BITOR: zOp = "BITOR"; break;
1715a67a3162Sdrh case TK_SLASH: zOp = "DIV"; break;
1716a67a3162Sdrh case TK_LSHIFT: zOp = "LSHIFT"; break;
1717a67a3162Sdrh case TK_RSHIFT: zOp = "RSHIFT"; break;
1718a67a3162Sdrh case TK_CONCAT: zOp = "CONCAT"; break;
1719a67a3162Sdrh case TK_UMINUS: zOp = "MINUS"; break;
1720a67a3162Sdrh case TK_UPLUS: zOp = "PLUS"; break;
1721a67a3162Sdrh case TK_BITNOT: zOp = "BITNOT"; break;
1722a67a3162Sdrh case TK_NOT: zOp = "NOT"; break;
1723a67a3162Sdrh case TK_ISNULL: zOp = "ISNULL"; break;
1724a67a3162Sdrh case TK_NOTNULL: zOp = "NOTNULL"; break;
172581316f89Sdrh
1726f7e36907Sdrh default:
17270cdbe1aeSdrh sqlite3_str_appendf(p, "%s", "expr");
1728f7e36907Sdrh break;
1729f7e36907Sdrh }
1730f7e36907Sdrh
1731a67a3162Sdrh if( zOp ){
17320cdbe1aeSdrh sqlite3_str_appendf(p, "%s(", zOp);
17335f4a686fSdrh displayP4Expr(p, pExpr->pLeft);
17345f4a686fSdrh if( pExpr->pRight ){
17350cdbe1aeSdrh sqlite3_str_append(p, ",", 1);
17365f4a686fSdrh displayP4Expr(p, pExpr->pRight);
1737a67a3162Sdrh }
17380cdbe1aeSdrh sqlite3_str_append(p, ")", 1);
1739f7e36907Sdrh }
1740f7e36907Sdrh }
1741f7e36907Sdrh #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
1742f7e36907Sdrh
1743f7e36907Sdrh
1744f7e36907Sdrh #if VDBE_DISPLAY_P4
17459a32464bSdrh /*
174666a5167bSdrh ** Compute a string that describes the P4 parameter for an opcode.
1747d3d39e93Sdrh ** Use zTemp for any required temporary buffer space.
1748d3d39e93Sdrh */
sqlite3VdbeDisplayP4(sqlite3 * db,Op * pOp)17498c5163a6Sdrh char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
1750cb49f546Sdrh char *zP4 = 0;
17515f4a686fSdrh StrAccum x;
1752cb49f546Sdrh
1753cb49f546Sdrh sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
175466a5167bSdrh switch( pOp->p4type ){
175566a5167bSdrh case P4_KEYINFO: {
17565f4a686fSdrh int j;
17572dca4ac1Sdanielk1977 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
17586e11892dSdan assert( pKeyInfo->aSortFlags!=0 );
17590cdbe1aeSdrh sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
1760a485ad19Sdrh for(j=0; j<pKeyInfo->nKeyField; j++){
1761d3d39e93Sdrh CollSeq *pColl = pKeyInfo->aColl[j];
17625f4a686fSdrh const char *zColl = pColl ? pColl->zName : "";
17635f4a686fSdrh if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
17646e11892dSdan sqlite3_str_appendf(&x, ",%s%s%s",
17656e11892dSdan (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
17666e11892dSdan (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
17676e11892dSdan zColl);
17685b843aa0Sdrh }
17690cdbe1aeSdrh sqlite3_str_append(&x, ")", 1);
1770d3d39e93Sdrh break;
1771d3d39e93Sdrh }
177228935364Sdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
177328935364Sdrh case P4_EXPR: {
17745f4a686fSdrh displayP4Expr(&x, pOp->p4.pExpr);
177528935364Sdrh break;
177628935364Sdrh }
177728935364Sdrh #endif
177866a5167bSdrh case P4_COLLSEQ: {
17794cf2121eSdrh static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
17802dca4ac1Sdanielk1977 CollSeq *pColl = pOp->p4.pColl;
17815025cb58Sdrh assert( pColl->enc<4 );
17824cf2121eSdrh sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
17834cf2121eSdrh encnames[pColl->enc]);
1784d3d39e93Sdrh break;
1785d3d39e93Sdrh }
178666a5167bSdrh case P4_FUNCDEF: {
17872dca4ac1Sdanielk1977 FuncDef *pDef = pOp->p4.pFunc;
17880cdbe1aeSdrh sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
1789f9b596ebSdrh break;
1790f9b596ebSdrh }
17919c7c913cSdrh case P4_FUNCCTX: {
17929c7c913cSdrh FuncDef *pDef = pOp->p4.pCtx->pFunc;
17930cdbe1aeSdrh sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
17949c7c913cSdrh break;
17959c7c913cSdrh }
179666a5167bSdrh case P4_INT64: {
17970cdbe1aeSdrh sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
1798d4e70ebdSdrh break;
1799d4e70ebdSdrh }
180066a5167bSdrh case P4_INT32: {
18010cdbe1aeSdrh sqlite3_str_appendf(&x, "%d", pOp->p4.i);
1802598f1340Sdrh break;
1803598f1340Sdrh }
180466a5167bSdrh case P4_REAL: {
18050cdbe1aeSdrh sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
1806d4e70ebdSdrh break;
1807d4e70ebdSdrh }
180866a5167bSdrh case P4_MEM: {
18092dca4ac1Sdanielk1977 Mem *pMem = pOp->p4.pMem;
1810d4e70ebdSdrh if( pMem->flags & MEM_Str ){
181166a5167bSdrh zP4 = pMem->z;
1812169f077eSdrh }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
18130cdbe1aeSdrh sqlite3_str_appendf(&x, "%lld", pMem->u.i);
1814d4e70ebdSdrh }else if( pMem->flags & MEM_Real ){
18150cdbe1aeSdrh sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
1816b8475df8Sdrh }else if( pMem->flags & MEM_Null ){
18175f4a686fSdrh zP4 = "NULL";
181856016893Sdrh }else{
181956016893Sdrh assert( pMem->flags & MEM_Blob );
182056016893Sdrh zP4 = "(blob)";
1821d4e70ebdSdrh }
1822598f1340Sdrh break;
1823598f1340Sdrh }
1824a967e886Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
182566a5167bSdrh case P4_VTAB: {
1826595a523aSdanielk1977 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
18270cdbe1aeSdrh sqlite3_str_appendf(&x, "vtab:%p", pVtab);
1828a967e886Sdrh break;
1829a967e886Sdrh }
1830a967e886Sdrh #endif
18310acb7e48Sdrh case P4_INTARRAY: {
1832abc38158Sdrh u32 i;
1833abc38158Sdrh u32 *ai = pOp->p4.ai;
1834abc38158Sdrh u32 n = ai[0]; /* The first element of an INTARRAY is always the
1835b1702026Sdrh ** count of the number of elements to follow */
1836b5c1063aSdrh for(i=1; i<=n; i++){
1837abc38158Sdrh sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
18385f4a686fSdrh }
18390cdbe1aeSdrh sqlite3_str_append(&x, "]", 1);
18400acb7e48Sdrh break;
18410acb7e48Sdrh }
1842165921a7Sdan case P4_SUBPROGRAM: {
1843cb49f546Sdrh zP4 = "program";
1844165921a7Sdan break;
1845165921a7Sdan }
184674c3302fSdrh case P4_TABLE: {
1847cb49f546Sdrh zP4 = pOp->p4.pTab->zName;
184874c3302fSdrh break;
184974c3302fSdrh }
1850d3d39e93Sdrh default: {
18512dca4ac1Sdanielk1977 zP4 = pOp->p4.z;
1852d3d39e93Sdrh }
1853d3d39e93Sdrh }
1854cb49f546Sdrh if( zP4 ) sqlite3_str_appendall(&x, zP4);
1855e1cd73f6Sdrh if( (x.accError & SQLITE_NOMEM)!=0 ){
1856cb49f546Sdrh sqlite3OomFault(db);
1857d3d39e93Sdrh }
1858cb49f546Sdrh return sqlite3StrAccumFinish(&x);
1859d3d39e93Sdrh }
1860f7e36907Sdrh #endif /* VDBE_DISPLAY_P4 */
1861d3d39e93Sdrh
1862900b31efSdrh /*
1863d0679edcSdrh ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
18643ebaee96Sdrh **
1865bdaec52cSdrh ** The prepared statements need to know in advance the complete set of
1866e4c88c0cSdrh ** attached databases that will be use. A mask of these databases
1867e4c88c0cSdrh ** is maintained in p->btreeMask. The p->lockMask value is the subset of
1868e4c88c0cSdrh ** p->btreeMask of databases that will require a lock.
1869900b31efSdrh */
sqlite3VdbeUsesBtree(Vdbe * p,int i)1870fb98264aSdrh void sqlite3VdbeUsesBtree(Vdbe *p, int i){
1871fcd71b60Sdrh assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
187200e13613Sdanielk1977 assert( i<(int)sizeof(p->btreeMask)*8 );
1873a7ab6d81Sdrh DbMaskSet(p->btreeMask, i);
1874dc5b047eSdrh if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
1875a7ab6d81Sdrh DbMaskSet(p->lockMask, i);
1876dc5b047eSdrh }
1877900b31efSdrh }
1878900b31efSdrh
187920d876faSdan #if !defined(SQLITE_OMIT_SHARED_CACHE)
1880bdaec52cSdrh /*
1881bdaec52cSdrh ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
1882bdaec52cSdrh ** this routine obtains the mutex associated with each BtShared structure
1883bdaec52cSdrh ** that may be accessed by the VM passed as an argument. In doing so it also
1884bdaec52cSdrh ** sets the BtShared.db member of each of the BtShared structures, ensuring
1885bdaec52cSdrh ** that the correct busy-handler callback is invoked if required.
1886bdaec52cSdrh **
1887bdaec52cSdrh ** If SQLite is not threadsafe but does support shared-cache mode, then
1888bdaec52cSdrh ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
1889bdaec52cSdrh ** of all of BtShared structures accessible via the database handle
1890bdaec52cSdrh ** associated with the VM.
1891bdaec52cSdrh **
1892bdaec52cSdrh ** If SQLite is not threadsafe and does not support shared-cache mode, this
1893bdaec52cSdrh ** function is a no-op.
1894bdaec52cSdrh **
1895bdaec52cSdrh ** The p->btreeMask field is a bitmask of all btrees that the prepared
1896bdaec52cSdrh ** statement p will ever use. Let N be the number of bits in p->btreeMask
1897bdaec52cSdrh ** corresponding to btrees that use shared cache. Then the runtime of
1898bdaec52cSdrh ** this routine is N*N. But as N is rarely more than 1, this should not
1899bdaec52cSdrh ** be a problem.
1900bdaec52cSdrh */
sqlite3VdbeEnter(Vdbe * p)1901bdaec52cSdrh void sqlite3VdbeEnter(Vdbe *p){
1902bdaec52cSdrh int i;
1903dc5b047eSdrh sqlite3 *db;
1904dc5b047eSdrh Db *aDb;
1905dc5b047eSdrh int nDb;
1906a7ab6d81Sdrh if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
1907dc5b047eSdrh db = p->db;
1908dc5b047eSdrh aDb = db->aDb;
1909dc5b047eSdrh nDb = db->nDb;
1910a7ab6d81Sdrh for(i=0; i<nDb; i++){
1911a7ab6d81Sdrh if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1912bdaec52cSdrh sqlite3BtreeEnter(aDb[i].pBt);
1913bdaec52cSdrh }
1914bdaec52cSdrh }
1915bdaec52cSdrh }
1916e54e0518Sdrh #endif
1917bdaec52cSdrh
1918e54e0518Sdrh #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
1919bdaec52cSdrh /*
1920bdaec52cSdrh ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
1921bdaec52cSdrh */
vdbeLeave(Vdbe * p)1922f1aabd6bSdrh static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
1923bdaec52cSdrh int i;
1924dc5b047eSdrh sqlite3 *db;
1925dc5b047eSdrh Db *aDb;
1926dc5b047eSdrh int nDb;
1927dc5b047eSdrh db = p->db;
1928dc5b047eSdrh aDb = db->aDb;
1929dc5b047eSdrh nDb = db->nDb;
1930a7ab6d81Sdrh for(i=0; i<nDb; i++){
1931a7ab6d81Sdrh if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
1932bdaec52cSdrh sqlite3BtreeLeave(aDb[i].pBt);
1933bdaec52cSdrh }
1934bdaec52cSdrh }
1935bdaec52cSdrh }
sqlite3VdbeLeave(Vdbe * p)1936f1aabd6bSdrh void sqlite3VdbeLeave(Vdbe *p){
1937f1aabd6bSdrh if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
1938f1aabd6bSdrh vdbeLeave(p);
1939f1aabd6bSdrh }
1940bdaec52cSdrh #endif
1941d3d39e93Sdrh
19428b60e0f1Sdanielk1977 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19439a32464bSdrh /*
19449a32464bSdrh ** Print a single opcode. This routine is used for debugging only.
19459a32464bSdrh */
sqlite3VdbePrintOp(FILE * pOut,int pc,VdbeOp * pOp)1946299bf7c2Sdrh void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
194766a5167bSdrh char *zP4;
1948cb49f546Sdrh char *zCom;
1949e1cd73f6Sdrh sqlite3 dummyDb;
195026198bb4Sdrh static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
19519a32464bSdrh if( pOut==0 ) pOut = stdout;
195262c94d0aSdan sqlite3BeginBenignMalloc();
1953e1cd73f6Sdrh dummyDb.mallocFailed = 1;
1954e1cd73f6Sdrh zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
1955c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
19568c5163a6Sdrh zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
195781316f89Sdrh #else
1958cb49f546Sdrh zCom = 0;
195981316f89Sdrh #endif
19604eded604Sdrh /* NB: The sqlite3OpcodeName() function is implemented by code created
19614eded604Sdrh ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
19624eded604Sdrh ** information from the vdbe.c source text */
196311641c11Sdanielk1977 fprintf(pOut, zFormat1, pc,
19647e088a6cSdrh sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
19657e088a6cSdrh zP4 ? zP4 : "", pOp->p5,
1966cb49f546Sdrh zCom ? zCom : ""
19671db639ceSdrh );
19689a32464bSdrh fflush(pOut);
1969cb49f546Sdrh sqlite3_free(zP4);
1970cb49f546Sdrh sqlite3_free(zCom);
197162c94d0aSdan sqlite3EndBenignMalloc();
19729a32464bSdrh }
19739a32464bSdrh #endif
19749a32464bSdrh
19759a32464bSdrh /*
19762a1df937Sdrh ** Initialize an array of N Mem element.
1977c9373e86Sdrh **
19784296357cSdrh ** This is a high-runner, so only those fields that really do need to
19794296357cSdrh ** be initialized are set. The Mem structure is organized so that
19804296357cSdrh ** the fields that get initialized are nearby and hopefully on the same
19814296357cSdrh ** cache line.
1982c9373e86Sdrh **
1983c9373e86Sdrh ** Mem.flags = flags
1984c9373e86Sdrh ** Mem.db = db
1985c9373e86Sdrh ** Mem.szMalloc = 0
1986c9373e86Sdrh **
1987c9373e86Sdrh ** All other fields of Mem can safely remain uninitialized for now. They
19884296357cSdrh ** will be initialized before use.
19892a1df937Sdrh */
initMemArray(Mem * p,int N,sqlite3 * db,u16 flags)19902a1df937Sdrh static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
1991c9373e86Sdrh if( N>0 ){
1992c9373e86Sdrh do{
19934296357cSdrh p->flags = flags;
19944296357cSdrh p->db = db;
19954296357cSdrh p->szMalloc = 0;
19962a1df937Sdrh #ifdef SQLITE_DEBUG
19972a1df937Sdrh p->pScopyFrom = 0;
19982a1df937Sdrh #endif
19992a1df937Sdrh p++;
2000c9373e86Sdrh }while( (--N)>0 );
20012a1df937Sdrh }
20022a1df937Sdrh }
20032a1df937Sdrh
20042a1df937Sdrh /*
20055308d393Sdrh ** Release auxiliary memory held in an array of N Mem elements.
20065308d393Sdrh **
20075308d393Sdrh ** After this routine returns, all Mem elements in the array will still
20085308d393Sdrh ** be valid. Those Mem elements that were not holding auxiliary resources
20095308d393Sdrh ** will be unchanged. Mem elements which had something freed will be
20105308d393Sdrh ** set to MEM_Undefined.
201176ff3a0eSdrh */
releaseMemArray(Mem * p,int N)2012c890fec3Sdrh static void releaseMemArray(Mem *p, int N){
2013a7a8e14bSdanielk1977 if( p && N ){
2014069c23c9Sdrh Mem *pEnd = &p[N];
2015a7a8e14bSdanielk1977 sqlite3 *db = p->db;
2016d46def77Sdan if( db->pnBytesFreed ){
2017069c23c9Sdrh do{
201817bcb102Sdrh if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
2019069c23c9Sdrh }while( (++p)<pEnd );
2020c176c27cSdrh return;
2021c176c27cSdrh }
2022069c23c9Sdrh do{
2023e972e031Sdanielk1977 assert( (&p[1])==pEnd || p[0].db==p[1].db );
202475fd0542Sdrh assert( sqlite3VdbeCheckMemInvariants(p) );
2025e972e031Sdanielk1977
2026e972e031Sdanielk1977 /* This block is really an inlined version of sqlite3VdbeMemRelease()
2027e972e031Sdanielk1977 ** that takes advantage of the fact that the memory cell value is
2028e972e031Sdanielk1977 ** being set to NULL after releasing any dynamic resources.
2029e972e031Sdanielk1977 **
2030e972e031Sdanielk1977 ** The justification for duplicating code is that according to
2031e972e031Sdanielk1977 ** callgrind, this causes a certain test case to hit the CPU 4.7
2032e972e031Sdanielk1977 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
2033e972e031Sdanielk1977 ** sqlite3MemRelease() were called from here. With -O2, this jumps
2034e972e031Sdanielk1977 ** to 6.6 percent. The test case is inserting 1000 rows into a table
2035e972e031Sdanielk1977 ** with no indexes using a single prepared INSERT statement, bind()
2036e972e031Sdanielk1977 ** and reset(). Inserts are grouped into a transaction.
2037e972e031Sdanielk1977 */
2038b6e8fd10Sdrh testcase( p->flags & MEM_Agg );
2039b6e8fd10Sdrh testcase( p->flags & MEM_Dyn );
20409d67afc4Sdrh if( p->flags&(MEM_Agg|MEM_Dyn) ){
20419fdd66e3Sdrh testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
2042a7a8e14bSdanielk1977 sqlite3VdbeMemRelease(p);
20435308d393Sdrh p->flags = MEM_Undefined;
204417bcb102Sdrh }else if( p->szMalloc ){
204541ce47c4Sdrh sqlite3DbNNFreeNN(db, p->zMalloc);
204617bcb102Sdrh p->szMalloc = 0;
2047a5750cfeSdrh p->flags = MEM_Undefined;
20485308d393Sdrh }
20495308d393Sdrh #ifdef SQLITE_DEBUG
20505308d393Sdrh else{
20515308d393Sdrh p->flags = MEM_Undefined;
20525308d393Sdrh }
20535308d393Sdrh #endif
2054069c23c9Sdrh }while( (++p)<pEnd );
205576ff3a0eSdrh }
205676ff3a0eSdrh }
205776ff3a0eSdrh
205872f56ef9Sdrh #ifdef SQLITE_DEBUG
205972f56ef9Sdrh /*
206072f56ef9Sdrh ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
206172f56ef9Sdrh ** and false if something is wrong.
206272f56ef9Sdrh **
206372f56ef9Sdrh ** This routine is intended for use inside of assert() statements only.
206472f56ef9Sdrh */
sqlite3VdbeFrameIsValid(VdbeFrame * pFrame)206572f56ef9Sdrh int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
206672f56ef9Sdrh if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
206772f56ef9Sdrh return 1;
206872f56ef9Sdrh }
206972f56ef9Sdrh #endif
207072f56ef9Sdrh
207172f56ef9Sdrh
207272f56ef9Sdrh /*
207372f56ef9Sdrh ** This is a destructor on a Mem object (which is really an sqlite3_value)
207472f56ef9Sdrh ** that deletes the Frame object that is attached to it as a blob.
207572f56ef9Sdrh **
207672f56ef9Sdrh ** This routine does not delete the Frame right away. It merely adds the
207772f56ef9Sdrh ** frame to a list of frames to be deleted when the Vdbe halts.
207872f56ef9Sdrh */
sqlite3VdbeFrameMemDel(void * pArg)207972f56ef9Sdrh void sqlite3VdbeFrameMemDel(void *pArg){
208072f56ef9Sdrh VdbeFrame *pFrame = (VdbeFrame*)pArg;
208172f56ef9Sdrh assert( sqlite3VdbeFrameIsValid(pFrame) );
208272f56ef9Sdrh pFrame->pParent = pFrame->v->pDelFrame;
208372f56ef9Sdrh pFrame->v->pDelFrame = pFrame;
208472f56ef9Sdrh }
208572f56ef9Sdrh
20868c5163a6Sdrh #if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
2087356cd76aSdrh /*
2088356cd76aSdrh ** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
2089356cd76aSdrh ** QUERY PLAN output.
2090356cd76aSdrh **
2091356cd76aSdrh ** Return SQLITE_ROW on success. Return SQLITE_DONE if there are no
2092356cd76aSdrh ** more opcodes to be displayed.
2093356cd76aSdrh */
sqlite3VdbeNextOpcode(Vdbe * p,Mem * pSub,int eMode,int * piPc,int * piAddr,Op ** paOp)2094356cd76aSdrh int sqlite3VdbeNextOpcode(
2095356cd76aSdrh Vdbe *p, /* The statement being explained */
2096356cd76aSdrh Mem *pSub, /* Storage for keeping track of subprogram nesting */
20978f78a528Sdrh int eMode, /* 0: normal. 1: EQP. 2: TablesUsed */
2098356cd76aSdrh int *piPc, /* IN/OUT: Current rowid. Overwritten with next rowid */
2099356cd76aSdrh int *piAddr, /* OUT: Write index into (*paOp)[] here */
2100356cd76aSdrh Op **paOp /* OUT: Write the opcode array here */
2101356cd76aSdrh ){
2102356cd76aSdrh int nRow; /* Stop when row count reaches this */
2103356cd76aSdrh int nSub = 0; /* Number of sub-vdbes seen so far */
2104356cd76aSdrh SubProgram **apSub = 0; /* Array of sub-vdbes */
2105356cd76aSdrh int i; /* Next instruction address */
2106356cd76aSdrh int rc = SQLITE_OK; /* Result code */
2107c004bd54Sdrh Op *aOp = 0; /* Opcode array */
2108356cd76aSdrh int iPc; /* Rowid. Copy of value in *piPc */
2109356cd76aSdrh
2110356cd76aSdrh /* When the number of output rows reaches nRow, that means the
2111356cd76aSdrh ** listing has finished and sqlite3_step() should return SQLITE_DONE.
2112356cd76aSdrh ** nRow is the sum of the number of rows in the main program, plus
2113356cd76aSdrh ** the sum of the number of rows in all trigger subprograms encountered
2114356cd76aSdrh ** so far. The nRow value will increase as new trigger subprograms are
2115356cd76aSdrh ** encountered, but p->pc will eventually catch up to nRow.
2116356cd76aSdrh */
2117356cd76aSdrh nRow = p->nOp;
2118356cd76aSdrh if( pSub!=0 ){
2119356cd76aSdrh if( pSub->flags&MEM_Blob ){
2120356cd76aSdrh /* pSub is initiallly NULL. It is initialized to a BLOB by
2121356cd76aSdrh ** the P4_SUBPROGRAM processing logic below */
2122356cd76aSdrh nSub = pSub->n/sizeof(Vdbe*);
2123356cd76aSdrh apSub = (SubProgram **)pSub->z;
2124356cd76aSdrh }
2125356cd76aSdrh for(i=0; i<nSub; i++){
2126356cd76aSdrh nRow += apSub[i]->nOp;
2127356cd76aSdrh }
2128356cd76aSdrh }
2129356cd76aSdrh iPc = *piPc;
2130356cd76aSdrh while(1){ /* Loop exits via break */
2131356cd76aSdrh i = iPc++;
2132356cd76aSdrh if( i>=nRow ){
2133356cd76aSdrh p->rc = SQLITE_OK;
2134356cd76aSdrh rc = SQLITE_DONE;
2135356cd76aSdrh break;
2136356cd76aSdrh }
2137356cd76aSdrh if( i<p->nOp ){
2138356cd76aSdrh /* The rowid is small enough that we are still in the
2139356cd76aSdrh ** main program. */
2140356cd76aSdrh aOp = p->aOp;
2141356cd76aSdrh }else{
2142356cd76aSdrh /* We are currently listing subprograms. Figure out which one and
2143356cd76aSdrh ** pick up the appropriate opcode. */
2144356cd76aSdrh int j;
2145356cd76aSdrh i -= p->nOp;
2146356cd76aSdrh assert( apSub!=0 );
2147356cd76aSdrh assert( nSub>0 );
2148356cd76aSdrh for(j=0; i>=apSub[j]->nOp; j++){
2149356cd76aSdrh i -= apSub[j]->nOp;
2150356cd76aSdrh assert( i<apSub[j]->nOp || j+1<nSub );
2151356cd76aSdrh }
2152356cd76aSdrh aOp = apSub[j]->aOp;
2153356cd76aSdrh }
2154356cd76aSdrh
2155356cd76aSdrh /* When an OP_Program opcode is encounter (the only opcode that has
2156356cd76aSdrh ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
2157356cd76aSdrh ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
2158356cd76aSdrh ** has not already been seen.
2159356cd76aSdrh */
2160356cd76aSdrh if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
2161356cd76aSdrh int nByte = (nSub+1)*sizeof(SubProgram*);
2162356cd76aSdrh int j;
2163356cd76aSdrh for(j=0; j<nSub; j++){
2164356cd76aSdrh if( apSub[j]==aOp[i].p4.pProgram ) break;
2165356cd76aSdrh }
2166356cd76aSdrh if( j==nSub ){
2167356cd76aSdrh p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
2168356cd76aSdrh if( p->rc!=SQLITE_OK ){
2169356cd76aSdrh rc = SQLITE_ERROR;
2170356cd76aSdrh break;
2171356cd76aSdrh }
2172356cd76aSdrh apSub = (SubProgram **)pSub->z;
2173356cd76aSdrh apSub[nSub++] = aOp[i].p4.pProgram;
21740518d061Sdrh MemSetTypeFlag(pSub, MEM_Blob);
2175356cd76aSdrh pSub->n = nSub*sizeof(SubProgram*);
2176356cd76aSdrh nRow += aOp[i].p4.pProgram->nOp;
2177356cd76aSdrh }
2178356cd76aSdrh }
21798f78a528Sdrh if( eMode==0 ) break;
21808f78a528Sdrh #ifdef SQLITE_ENABLE_BYTECODE_VTAB
21818f78a528Sdrh if( eMode==2 ){
21828f78a528Sdrh Op *pOp = aOp + i;
21838f78a528Sdrh if( pOp->opcode==OP_OpenRead ) break;
21848f78a528Sdrh if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
21858f78a528Sdrh if( pOp->opcode==OP_ReopenIdx ) break;
21868f78a528Sdrh }else
21878f78a528Sdrh #endif
21888f78a528Sdrh {
21898f78a528Sdrh assert( eMode==1 );
2190356cd76aSdrh if( aOp[i].opcode==OP_Explain ) break;
219149d01abaSdrh if( aOp[i].opcode==OP_Init && iPc>1 ) break;
2192356cd76aSdrh }
21938f78a528Sdrh }
2194356cd76aSdrh *piPc = iPc;
2195356cd76aSdrh *piAddr = i;
2196356cd76aSdrh *paOp = aOp;
2197356cd76aSdrh return rc;
2198356cd76aSdrh }
21998c5163a6Sdrh #endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
2200356cd76aSdrh
220172f56ef9Sdrh
220265a7cd16Sdan /*
220365a7cd16Sdan ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
220465a7cd16Sdan ** allocated by the OP_Program opcode in sqlite3VdbeExec().
220565a7cd16Sdan */
sqlite3VdbeFrameDelete(VdbeFrame * p)2206165921a7Sdan void sqlite3VdbeFrameDelete(VdbeFrame *p){
2207165921a7Sdan int i;
2208165921a7Sdan Mem *aMem = VdbeFrameMem(p);
2209165921a7Sdan VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
221072f56ef9Sdrh assert( sqlite3VdbeFrameIsValid(p) );
2211165921a7Sdan for(i=0; i<p->nChildCsr; i++){
2212473571b0Sdrh if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
2213165921a7Sdan }
2214165921a7Sdan releaseMemArray(aMem, p->nChildMem);
2215b9626cfaSdrh sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
2216165921a7Sdan sqlite3DbFree(p->v->db, p);
2217165921a7Sdan }
2218165921a7Sdan
2219b7f9164eSdrh #ifndef SQLITE_OMIT_EXPLAIN
222076ff3a0eSdrh /*
22219a32464bSdrh ** Give a listing of the program in the virtual machine.
22229a32464bSdrh **
22234adee20fSdanielk1977 ** The interface is the same as sqlite3VdbeExec(). But instead of
22249a32464bSdrh ** running the code, it invokes the callback once for each instruction.
22259a32464bSdrh ** This feature is used to implement "EXPLAIN".
22269cbf3425Sdrh **
22279cbf3425Sdrh ** When p->explain==1, each instruction is listed. When
22289cbf3425Sdrh ** p->explain==2, only OP_Explain instructions are listed and these
22299cbf3425Sdrh ** are shown in a different format. p->explain==2 is used to implement
22309cbf3425Sdrh ** EXPLAIN QUERY PLAN.
22314b5345ccSdrh ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
22324b5345ccSdrh ** are also shown, so that the boundaries between the main program and
22334b5345ccSdrh ** each trigger are clear.
22345cfa5848Sdrh **
22355cfa5848Sdrh ** When p->explain==1, first the main program is listed, then each of
22365cfa5848Sdrh ** the trigger subprograms are listed one by one.
22379a32464bSdrh */
sqlite3VdbeList(Vdbe * p)22384adee20fSdanielk1977 int sqlite3VdbeList(
22399a32464bSdrh Vdbe *p /* The VDBE */
22409a32464bSdrh ){
22415cfa5848Sdrh Mem *pSub = 0; /* Memory cell hold array of subprogs */
22425cfa5848Sdrh sqlite3 *db = p->db; /* The database connection */
22435cfa5848Sdrh int i; /* Loop counter */
22445cfa5848Sdrh int rc = SQLITE_OK; /* Return code */
22459734e6e1Sdrh Mem *pMem = &p->aMem[1]; /* First Mem of result set */
224636e31c69Sdrh int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
2247356cd76aSdrh Op *aOp; /* Array of opcodes */
2248356cd76aSdrh Op *pOp; /* Current opcode */
22499a32464bSdrh
22509a32464bSdrh assert( p->explain );
225166181ce2Sdrh assert( p->eVdbeState==VDBE_RUN_STATE );
22526c359f07Sdanielk1977 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
225318f41890Sdanielk1977
22549cbf3425Sdrh /* Even though this opcode does not use dynamic strings for
22559cbf3425Sdrh ** the result, result columns may become dynamic if the user calls
22564f26d6c4Sdrh ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
225718f41890Sdanielk1977 */
2258165921a7Sdan releaseMemArray(pMem, 8);
22599734e6e1Sdrh p->pResultSet = 0;
226018f41890Sdanielk1977
226185b76a28Sdrh if( p->rc==SQLITE_NOMEM ){
22626c359f07Sdanielk1977 /* This happens if a malloc() inside a call to sqlite3_column_text() or
22636c359f07Sdanielk1977 ** sqlite3_column_text16() failed. */
22644a642b60Sdrh sqlite3OomFault(db);
22656c359f07Sdanielk1977 return SQLITE_ERROR;
22666c359f07Sdanielk1977 }
22676c359f07Sdanielk1977
226836e31c69Sdrh if( bListSubprogs ){
22695cfa5848Sdrh /* The first 8 memory cells are used for the result set. So we will
22705cfa5848Sdrh ** commandeer the 9th cell to use as storage for an array of pointers
22715cfa5848Sdrh ** to trigger subprograms. The VDBE is guaranteed to have at least 9
22725cfa5848Sdrh ** cells. */
22735cfa5848Sdrh assert( p->nMem>9 );
2274165921a7Sdan pSub = &p->aMem[9];
2275165921a7Sdan }else{
2276356cd76aSdrh pSub = 0;
2277165921a7Sdan }
2278280db65eSdan
2279356cd76aSdrh /* Figure out which opcode is next to display */
2280356cd76aSdrh rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
2281280db65eSdan
2282280db65eSdan if( rc==SQLITE_OK ){
2283356cd76aSdrh pOp = aOp + i;
2284892edb69Sdan if( AtomicLoad(&db->u1.isInterrupted) ){
2285280db65eSdan p->rc = SQLITE_INTERRUPT;
2286280db65eSdan rc = SQLITE_ERROR;
2287280db65eSdan sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
2288280db65eSdan }else{
22898c5163a6Sdrh char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
2290cb49f546Sdrh if( p->explain==2 ){
2291cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem, pOp->p1);
2292cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
2293cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
2294cb49f546Sdrh sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
2295cb49f546Sdrh p->nResColumn = 4;
2296a7a8e14bSdanielk1977 }else{
2297cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+0, i);
2298cb49f546Sdrh sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
2299cb49f546Sdrh -1, SQLITE_UTF8, SQLITE_STATIC);
2300cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
2301cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
2302cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
2303cb49f546Sdrh /* pMem+5 for p4 is done last */
2304cb49f546Sdrh sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
2305c7379ce4Sdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
2306cb49f546Sdrh {
23078c5163a6Sdrh char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
2308cb49f546Sdrh sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
230981316f89Sdrh }
231081316f89Sdrh #else
2311cb49f546Sdrh sqlite3VdbeMemSetNull(pMem+7);
231281316f89Sdrh #endif
2313cb49f546Sdrh sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
2314cb49f546Sdrh p->nResColumn = 8;
23150d78bae3Sdanielk1977 }
2316cb49f546Sdrh p->pResultSet = pMem;
2317cb49f546Sdrh if( db->mallocFailed ){
2318cb49f546Sdrh p->rc = SQLITE_NOMEM;
2319cb49f546Sdrh rc = SQLITE_ERROR;
2320cb49f546Sdrh }else{
2321826fb5a3Sdrh p->rc = SQLITE_OK;
2322826fb5a3Sdrh rc = SQLITE_ROW;
23239a32464bSdrh }
2324280db65eSdan }
2325cb49f546Sdrh }
2326826fb5a3Sdrh return rc;
23279a32464bSdrh }
2328b7f9164eSdrh #endif /* SQLITE_OMIT_EXPLAIN */
23299a32464bSdrh
23307c4ac0c5Sdrh #ifdef SQLITE_DEBUG
23319a32464bSdrh /*
23323f7d4e49Sdrh ** Print the SQL that was used to generate a VDBE program.
23333f7d4e49Sdrh */
sqlite3VdbePrintSql(Vdbe * p)23343f7d4e49Sdrh void sqlite3VdbePrintSql(Vdbe *p){
233584e55a80Sdrh const char *z = 0;
233684e55a80Sdrh if( p->zSql ){
233784e55a80Sdrh z = p->zSql;
233884e55a80Sdrh }else if( p->nOp>=1 ){
233984e55a80Sdrh const VdbeOp *pOp = &p->aOp[0];
2340aceb31b1Sdrh if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
234184e55a80Sdrh z = pOp->p4.z;
234278ca0e7eSdanielk1977 while( sqlite3Isspace(*z) ) z++;
23433f7d4e49Sdrh }
23443f7d4e49Sdrh }
234584e55a80Sdrh if( z ) printf("SQL: [%s]\n", z);
234684e55a80Sdrh }
23477c4ac0c5Sdrh #endif
23483f7d4e49Sdrh
2349602c2374Sdrh #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
2350602c2374Sdrh /*
2351602c2374Sdrh ** Print an IOTRACE message showing SQL content.
2352602c2374Sdrh */
sqlite3VdbeIOTraceSql(Vdbe * p)2353602c2374Sdrh void sqlite3VdbeIOTraceSql(Vdbe *p){
2354602c2374Sdrh int nOp = p->nOp;
2355602c2374Sdrh VdbeOp *pOp;
23563a00f907Smlcreech if( sqlite3IoTrace==0 ) return;
2357602c2374Sdrh if( nOp<1 ) return;
2358949f9cd5Sdrh pOp = &p->aOp[0];
2359aceb31b1Sdrh if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
2360602c2374Sdrh int i, j;
236100a18e47Sdrh char z[1000];
2362949f9cd5Sdrh sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
236378ca0e7eSdanielk1977 for(i=0; sqlite3Isspace(z[i]); i++){}
2364602c2374Sdrh for(j=0; z[i]; i++){
236578ca0e7eSdanielk1977 if( sqlite3Isspace(z[i]) ){
2366602c2374Sdrh if( z[i-1]!=' ' ){
2367602c2374Sdrh z[j++] = ' ';
2368602c2374Sdrh }
2369602c2374Sdrh }else{
2370602c2374Sdrh z[j++] = z[i];
2371602c2374Sdrh }
2372602c2374Sdrh }
2373602c2374Sdrh z[j] = 0;
23743a00f907Smlcreech sqlite3IoTrace("SQL %s\n", z);
2375602c2374Sdrh }
2376602c2374Sdrh }
2377602c2374Sdrh #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
2378602c2374Sdrh
2379a7dc4a32Sdrh /* An instance of this object describes bulk memory available for use
2380a7dc4a32Sdrh ** by subcomponents of a prepared statement. Space is allocated out
2381a7dc4a32Sdrh ** of a ReusableSpace object by the allocSpace() routine below.
2382a7dc4a32Sdrh */
2383a7dc4a32Sdrh struct ReusableSpace {
2384a7dc4a32Sdrh u8 *pSpace; /* Available memory */
2385f6ad201aSdrh sqlite3_int64 nFree; /* Bytes of available memory */
2386f6ad201aSdrh sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
2387a7dc4a32Sdrh };
2388a7dc4a32Sdrh
2389a7dc4a32Sdrh /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
2390a7dc4a32Sdrh ** from the ReusableSpace object. Return a pointer to the allocated
2391a7dc4a32Sdrh ** memory on success. If insufficient memory is available in the
2392a7dc4a32Sdrh ** ReusableSpace object, increase the ReusableSpace.nNeeded
2393a7dc4a32Sdrh ** value by the amount needed and return NULL.
23944800b2eeSdrh **
2395a7dc4a32Sdrh ** If pBuf is not initially NULL, that means that the memory has already
2396a7dc4a32Sdrh ** been allocated by a prior call to this routine, so just return a copy
2397a7dc4a32Sdrh ** of pBuf and leave ReusableSpace unchanged.
2398b2771ce2Sdrh **
2399a7dc4a32Sdrh ** This allocator is employed to repurpose unused slots at the end of the
2400a7dc4a32Sdrh ** opcode array of prepared state for other memory needs of the prepared
2401a7dc4a32Sdrh ** statement.
2402b2771ce2Sdrh */
allocSpace(struct ReusableSpace * p,void * pBuf,sqlite3_int64 nByte)24034800b2eeSdrh static void *allocSpace(
2404a7dc4a32Sdrh struct ReusableSpace *p, /* Bulk memory available for allocation */
2405a7dc4a32Sdrh void *pBuf, /* Pointer to a prior allocation */
2406cf6e3fd7Sdrh sqlite3_int64 nByte /* Bytes of memory needed. */
2407b2771ce2Sdrh ){
2408a7dc4a32Sdrh assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
2409d797a9b5Sdrh if( pBuf==0 ){
2410cf6e3fd7Sdrh nByte = ROUND8P(nByte);
2411a7dc4a32Sdrh if( nByte <= p->nFree ){
2412a7dc4a32Sdrh p->nFree -= nByte;
2413a7dc4a32Sdrh pBuf = &p->pSpace[p->nFree];
2414b2771ce2Sdrh }else{
2415a7dc4a32Sdrh p->nNeeded += nByte;
2416b2771ce2Sdrh }
2417d797a9b5Sdrh }
2418d797a9b5Sdrh assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
24194800b2eeSdrh return pBuf;
2420b2771ce2Sdrh }
2421602c2374Sdrh
24223f7d4e49Sdrh /*
2423124c0b49Sdrh ** Rewind the VDBE back to the beginning in preparation for
2424124c0b49Sdrh ** running it.
24259a32464bSdrh */
sqlite3VdbeRewind(Vdbe * p)2426124c0b49Sdrh void sqlite3VdbeRewind(Vdbe *p){
2427124c0b49Sdrh #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
2428124c0b49Sdrh int i;
2429124c0b49Sdrh #endif
24309a32464bSdrh assert( p!=0 );
243199a21828Sdrh assert( p->eVdbeState==VDBE_INIT_STATE
243299a21828Sdrh || p->eVdbeState==VDBE_READY_STATE
243399a21828Sdrh || p->eVdbeState==VDBE_HALT_STATE );
24349a32464bSdrh
2435c16a03b5Sdrh /* There should be at least one opcode.
24369a32464bSdrh */
2437c16a03b5Sdrh assert( p->nOp>0 );
24389a32464bSdrh
243999a21828Sdrh p->eVdbeState = VDBE_READY_STATE;
2440634f298cSdanielk1977
2441124c0b49Sdrh #ifdef SQLITE_DEBUG
24429f6168b6Sdrh for(i=0; i<p->nMem; i++){
2443124c0b49Sdrh assert( p->aMem[i].db==p->db );
2444124c0b49Sdrh }
2445124c0b49Sdrh #endif
2446124c0b49Sdrh p->pc = -1;
2447124c0b49Sdrh p->rc = SQLITE_OK;
2448124c0b49Sdrh p->errorAction = OE_Abort;
2449124c0b49Sdrh p->nChange = 0;
2450124c0b49Sdrh p->cacheCtr = 1;
2451124c0b49Sdrh p->minWriteFileFormat = 255;
2452124c0b49Sdrh p->iStatement = 0;
2453124c0b49Sdrh p->nFkConstraint = 0;
2454124c0b49Sdrh #ifdef VDBE_PROFILE
2455124c0b49Sdrh for(i=0; i<p->nOp; i++){
2456124c0b49Sdrh p->aOp[i].cnt = 0;
2457124c0b49Sdrh p->aOp[i].cycles = 0;
2458124c0b49Sdrh }
2459124c0b49Sdrh #endif
2460124c0b49Sdrh }
2461124c0b49Sdrh
2462124c0b49Sdrh /*
2463124c0b49Sdrh ** Prepare a virtual machine for execution for the first time after
2464124c0b49Sdrh ** creating the virtual machine. This involves things such
24657abda856Sdrh ** as allocating registers and initializing the program counter.
2466124c0b49Sdrh ** After the VDBE has be prepped, it can be executed by one or more
2467124c0b49Sdrh ** calls to sqlite3VdbeExec().
2468124c0b49Sdrh **
246960ec914cSpeter.d.reid ** This function may be called exactly once on each virtual machine.
2470124c0b49Sdrh ** After this routine is called the VM has been "packaged" and is ready
247160ec914cSpeter.d.reid ** to run. After this routine is called, further calls to
2472124c0b49Sdrh ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
2473124c0b49Sdrh ** the Vdbe from the Parse object that helped generate it so that the
2474124c0b49Sdrh ** the Vdbe becomes an independent entity and the Parse object can be
2475124c0b49Sdrh ** destroyed.
2476124c0b49Sdrh **
2477124c0b49Sdrh ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
2478124c0b49Sdrh ** to its initial state after it has been run.
2479124c0b49Sdrh */
sqlite3VdbeMakeReady(Vdbe * p,Parse * pParse)2480124c0b49Sdrh void sqlite3VdbeMakeReady(
2481124c0b49Sdrh Vdbe *p, /* The VDBE */
2482124c0b49Sdrh Parse *pParse /* Parsing context */
2483124c0b49Sdrh ){
2484124c0b49Sdrh sqlite3 *db; /* The database connection */
2485124c0b49Sdrh int nVar; /* Number of parameters */
2486124c0b49Sdrh int nMem; /* Number of VM memory registers */
2487124c0b49Sdrh int nCursor; /* Number of cursors required */
2488124c0b49Sdrh int nArg; /* Number of arguments in subprograms */
2489124c0b49Sdrh int n; /* Loop counter */
2490a7dc4a32Sdrh struct ReusableSpace x; /* Reusable bulk memory */
2491124c0b49Sdrh
2492124c0b49Sdrh assert( p!=0 );
2493124c0b49Sdrh assert( p->nOp>0 );
2494124c0b49Sdrh assert( pParse!=0 );
249566181ce2Sdrh assert( p->eVdbeState==VDBE_INIT_STATE );
249673d5b8f5Sdrh assert( pParse==p->pParse );
2497e2b0a12dSdrh p->pVList = pParse->pVList;
2498e2b0a12dSdrh pParse->pVList = 0;
2499124c0b49Sdrh db = p->db;
2500124c0b49Sdrh assert( db->mallocFailed==0 );
2501124c0b49Sdrh nVar = pParse->nVar;
2502124c0b49Sdrh nMem = pParse->nMem;
2503124c0b49Sdrh nCursor = pParse->nTab;
2504124c0b49Sdrh nArg = pParse->nMaxArg;
2505124c0b49Sdrh
25063cdce92cSdrh /* Each cursor uses a memory cell. The first cursor (cursor 0) can
25073cdce92cSdrh ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
25083cdce92cSdrh ** space at the end of aMem[] for cursors 1 and greater.
2509cd3e8f7cSdanielk1977 ** See also: allocateCursor().
2510cd3e8f7cSdanielk1977 */
2511cd3e8f7cSdanielk1977 nMem += nCursor;
25129f6168b6Sdrh if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
2513cd3e8f7cSdanielk1977
2514a7dc4a32Sdrh /* Figure out how much reusable memory is available at the end of the
2515a7dc4a32Sdrh ** opcode array. This extra memory will be reallocated for other elements
2516a7dc4a32Sdrh ** of the prepared statement.
25179a32464bSdrh */
2518cf6e3fd7Sdrh n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
2519a7dc4a32Sdrh x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
2520a7dc4a32Sdrh assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
2521a7dc4a32Sdrh x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
2522a7dc4a32Sdrh assert( x.nFree>=0 );
2523a7dc4a32Sdrh assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
252419875c82Sdrh
25259cbf3425Sdrh resolveP2Values(p, &nArg);
2526124c0b49Sdrh p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
2527f3ce2483Sdrh if( pParse->explain ){
2528f3ce2483Sdrh static const char * const azColName[] = {
2529f3ce2483Sdrh "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
2530f3ce2483Sdrh "id", "parent", "notused", "detail"
2531f3ce2483Sdrh };
2532f3ce2483Sdrh int iFirst, mx, i;
2533f3ce2483Sdrh if( nMem<10 ) nMem = 10;
253462b6e1d0Sdrh p->explain = pParse->explain;
2535f3ce2483Sdrh if( pParse->explain==2 ){
2536f3ce2483Sdrh sqlite3VdbeSetNumCols(p, 4);
2537f3ce2483Sdrh iFirst = 8;
2538f3ce2483Sdrh mx = 12;
2539f3ce2483Sdrh }else{
2540f3ce2483Sdrh sqlite3VdbeSetNumCols(p, 8);
2541f3ce2483Sdrh iFirst = 0;
2542f3ce2483Sdrh mx = 8;
2543f3ce2483Sdrh }
2544f3ce2483Sdrh for(i=iFirst; i<mx; i++){
2545f3ce2483Sdrh sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
2546f3ce2483Sdrh azColName[i], SQLITE_STATIC);
2547f3ce2483Sdrh }
25480f7eb611Sdrh }
2549aab910c4Sdrh p->expired = 0;
2550b2771ce2Sdrh
2551a7dc4a32Sdrh /* Memory for registers, parameters, cursor, etc, is allocated in one or two
2552a7dc4a32Sdrh ** passes. On the first pass, we try to reuse unused memory at the
255319875c82Sdrh ** end of the opcode array. If we are unable to satisfy all memory
255419875c82Sdrh ** requirements by reusing the opcode array tail, then the second
2555a7dc4a32Sdrh ** pass will fill in the remainder using a fresh memory allocation.
255619875c82Sdrh **
255719875c82Sdrh ** This two-pass approach that reuses as much memory as possible from
2558a7dc4a32Sdrh ** the leftover memory at the end of the opcode array. This can significantly
255919875c82Sdrh ** reduce the amount of memory held by a prepared statement.
256019875c82Sdrh */
2561a7dc4a32Sdrh x.nNeeded = 0;
256281f9159bSdrh p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
256381f9159bSdrh p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
256481f9159bSdrh p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
256581f9159bSdrh p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
256681f9159bSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
256781f9159bSdrh p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
256881f9159bSdrh #endif
256981f9159bSdrh if( x.nNeeded ){
257081f9159bSdrh x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
257181f9159bSdrh x.nFree = x.nNeeded;
257281f9159bSdrh if( !db->mallocFailed ){
2573a7dc4a32Sdrh p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
2574a7dc4a32Sdrh p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
2575a7dc4a32Sdrh p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
2576a7dc4a32Sdrh p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
2577e2f771b0Sdan #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2578a7dc4a32Sdrh p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
2579e2f771b0Sdan #endif
258081f9159bSdrh }
258181f9159bSdrh }
2582b2771ce2Sdrh
2583ab3182f7Sdrh if( db->mallocFailed ){
2584ab3182f7Sdrh p->nVar = 0;
2585ab3182f7Sdrh p->nCursor = 0;
2586ab3182f7Sdrh p->nMem = 0;
2587ab3182f7Sdrh }else{
25882a1df937Sdrh p->nCursor = nCursor;
25892a1df937Sdrh p->nVar = (ynVar)nVar;
25902a1df937Sdrh initMemArray(p->aVar, nVar, db, MEM_Null);
25912a1df937Sdrh p->nMem = nMem;
25922a1df937Sdrh initMemArray(p->aMem, nMem, db, MEM_Undefined);
25932a1df937Sdrh memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
25942a1df937Sdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
25952a1df937Sdrh memset(p->anExec, 0, p->nOp*sizeof(i64));
25962a1df937Sdrh #endif
25972a1df937Sdrh }
2598124c0b49Sdrh sqlite3VdbeRewind(p);
25999a32464bSdrh }
26009a32464bSdrh
26019a32464bSdrh /*
2602cd3e8f7cSdanielk1977 ** Close a VDBE cursor and release all the resources that cursor
2603cd3e8f7cSdanielk1977 ** happens to hold.
26049a32464bSdrh */
sqlite3VdbeFreeCursor(Vdbe * p,VdbeCursor * pCx)2605dfe88eceSdrh void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
2606473571b0Sdrh if( pCx ) sqlite3VdbeFreeCursorNN(p,pCx);
26074774b130Sdrh }
sqlite3VdbeFreeCursorNN(Vdbe * p,VdbeCursor * pCx)2608473571b0Sdrh void sqlite3VdbeFreeCursorNN(Vdbe *p, VdbeCursor *pCx){
2609c960dcbaSdrh switch( pCx->eCurType ){
2610c960dcbaSdrh case CURTYPE_SORTER: {
2611a20fde64Sdan sqlite3VdbeSorterClose(p->db, pCx);
2612c960dcbaSdrh break;
2613c960dcbaSdrh }
2614c960dcbaSdrh case CURTYPE_BTREE: {
2615c960dcbaSdrh assert( pCx->uc.pCursor!=0 );
2616c960dcbaSdrh sqlite3BtreeCloseCursor(pCx->uc.pCursor);
2617c960dcbaSdrh break;
26189a32464bSdrh }
26199eff6167Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2620c960dcbaSdrh case CURTYPE_VTAB: {
2621c960dcbaSdrh sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
2622c960dcbaSdrh const sqlite3_module *pModule = pVCur->pVtab->pModule;
2623c960dcbaSdrh assert( pVCur->pVtab->nRef>0 );
2624c960dcbaSdrh pVCur->pVtab->nRef--;
2625c960dcbaSdrh pModule->xClose(pVCur);
2626c960dcbaSdrh break;
26279eff6167Sdrh }
26289eff6167Sdrh #endif
26299a32464bSdrh }
2630c960dcbaSdrh }
26319a32464bSdrh
263265a7cd16Sdan /*
2633ab4e7f33Sdrh ** Close all cursors in the current frame.
2634ab4e7f33Sdrh */
closeCursorsInFrame(Vdbe * p)2635ab4e7f33Sdrh static void closeCursorsInFrame(Vdbe *p){
2636ab4e7f33Sdrh int i;
2637ab4e7f33Sdrh for(i=0; i<p->nCursor; i++){
2638ab4e7f33Sdrh VdbeCursor *pC = p->apCsr[i];
2639ab4e7f33Sdrh if( pC ){
2640473571b0Sdrh sqlite3VdbeFreeCursorNN(p, pC);
2641ab4e7f33Sdrh p->apCsr[i] = 0;
2642ab4e7f33Sdrh }
2643ab4e7f33Sdrh }
2644ab4e7f33Sdrh }
2645ab4e7f33Sdrh
2646ab4e7f33Sdrh /*
264765a7cd16Sdan ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
264865a7cd16Sdan ** is used, for example, when a trigger sub-program is halted to restore
264965a7cd16Sdan ** control to the main program.
265065a7cd16Sdan */
sqlite3VdbeFrameRestore(VdbeFrame * pFrame)2651165921a7Sdan int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
2652165921a7Sdan Vdbe *v = pFrame->v;
2653ab4e7f33Sdrh closeCursorsInFrame(v);
2654e2f771b0Sdan #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
265543764a8eSdan v->anExec = pFrame->anExec;
2656e2f771b0Sdan #endif
2657165921a7Sdan v->aOp = pFrame->aOp;
2658165921a7Sdan v->nOp = pFrame->nOp;
2659165921a7Sdan v->aMem = pFrame->aMem;
2660165921a7Sdan v->nMem = pFrame->nMem;
2661165921a7Sdan v->apCsr = pFrame->apCsr;
2662165921a7Sdan v->nCursor = pFrame->nCursor;
266376d462eeSdan v->db->lastRowid = pFrame->lastRowid;
266476d462eeSdan v->nChange = pFrame->nChange;
2665c3da667bSdan v->db->nChange = pFrame->nDbChange;
2666b9626cfaSdrh sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
26673200132aSdan v->pAuxData = pFrame->pAuxData;
26683200132aSdan pFrame->pAuxData = 0;
2669165921a7Sdan return pFrame->pc;
2670165921a7Sdan }
2671165921a7Sdan
26729a32464bSdrh /*
26735f82e3ccSdrh ** Close all cursors.
2674165921a7Sdan **
2675165921a7Sdan ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
2676165921a7Sdan ** cell array. This is necessary as the memory cell array may contain
2677165921a7Sdan ** pointers to VdbeFrame objects, which may in turn contain pointers to
2678165921a7Sdan ** open cursors.
26799a32464bSdrh */
closeAllCursors(Vdbe * p)26805f82e3ccSdrh static void closeAllCursors(Vdbe *p){
2681165921a7Sdan if( p->pFrame ){
26822327275bSdrh VdbeFrame *pFrame;
2683165921a7Sdan for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2684165921a7Sdan sqlite3VdbeFrameRestore(pFrame);
2685165921a7Sdan p->pFrame = 0;
2686165921a7Sdan p->nFrame = 0;
2687f526dcadSdrh }
2688f526dcadSdrh assert( p->nFrame==0 );
2689ab4e7f33Sdrh closeCursorsInFrame(p);
26909f6168b6Sdrh releaseMemArray(p->aMem, p->nMem);
269127106570Sdan while( p->pDelFrame ){
269227106570Sdan VdbeFrame *pDel = p->pDelFrame;
269327106570Sdan p->pDelFrame = pDel->pParent;
269427106570Sdan sqlite3VdbeFrameDelete(pDel);
269527106570Sdan }
26960c547799Sdan
26970c547799Sdan /* Delete any auxdata allocations made by the VM */
2698b9626cfaSdrh if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
26990c547799Sdan assert( p->pAuxData==0 );
2700523a087bSdan }
27019a32464bSdrh
27029a32464bSdrh /*
270322322fd4Sdanielk1977 ** Set the number of result columns that will be returned by this SQL
270422322fd4Sdanielk1977 ** statement. This is now set at compile time, rather than during
270522322fd4Sdanielk1977 ** execution of the vdbe program so that sqlite3_column_count() can
270622322fd4Sdanielk1977 ** be called on an SQL statement before sqlite3_step().
270722322fd4Sdanielk1977 */
sqlite3VdbeSetNumCols(Vdbe * p,int nResColumn)270822322fd4Sdanielk1977 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
270976ff3a0eSdrh int n;
2710633e6d57Sdrh sqlite3 *db = p->db;
27114a50aac5Sdrh
2712b8a1290aSdrh if( p->nResColumn ){
2713c890fec3Sdrh releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
2714633e6d57Sdrh sqlite3DbFree(db, p->aColName);
2715b8a1290aSdrh }
2716955de52cSdanielk1977 n = nResColumn*COLNAME_N;
271736840fddSshane p->nResColumn = (u16)nResColumn;
2718b8a1290aSdrh p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
271976ff3a0eSdrh if( p->aColName==0 ) return;
2720b8a1290aSdrh initMemArray(p->aColName, n, db, MEM_Null);
272122322fd4Sdanielk1977 }
272222322fd4Sdanielk1977
272322322fd4Sdanielk1977 /*
27243cf86063Sdanielk1977 ** Set the name of the idx'th column to be returned by the SQL statement.
27253cf86063Sdanielk1977 ** zName must be a pointer to a nul terminated string.
27263cf86063Sdanielk1977 **
27273cf86063Sdanielk1977 ** This call must be made after a call to sqlite3VdbeSetNumCols().
27283cf86063Sdanielk1977 **
272910fb749bSdanielk1977 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
273010fb749bSdanielk1977 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
273110fb749bSdanielk1977 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
27323cf86063Sdanielk1977 */
sqlite3VdbeSetColName(Vdbe * p,int idx,int var,const char * zName,void (* xDel)(void *))273310fb749bSdanielk1977 int sqlite3VdbeSetColName(
273410fb749bSdanielk1977 Vdbe *p, /* Vdbe being configured */
273510fb749bSdanielk1977 int idx, /* Index of column zName applies to */
273610fb749bSdanielk1977 int var, /* One of the COLNAME_* constants */
273710fb749bSdanielk1977 const char *zName, /* Pointer to buffer containing name */
273810fb749bSdanielk1977 void (*xDel)(void*) /* Memory management strategy for zName */
273910fb749bSdanielk1977 ){
27403cf86063Sdanielk1977 int rc;
27413cf86063Sdanielk1977 Mem *pColName;
2742955de52cSdanielk1977 assert( idx<p->nResColumn );
2743955de52cSdanielk1977 assert( var<COLNAME_N );
274410fb749bSdanielk1977 if( p->db->mallocFailed ){
274510fb749bSdanielk1977 assert( !zName || xDel!=SQLITE_DYNAMIC );
2746fad3039cSmistachkin return SQLITE_NOMEM_BKPT;
274710fb749bSdanielk1977 }
274876ff3a0eSdrh assert( p->aColName!=0 );
2749955de52cSdanielk1977 pColName = &(p->aColName[idx+var*p->nResColumn]);
275010fb749bSdanielk1977 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
27510793f1bdSdrh assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
27523cf86063Sdanielk1977 return rc;
27533cf86063Sdanielk1977 }
27543cf86063Sdanielk1977
27553cf86063Sdanielk1977 /*
275613adf8a0Sdanielk1977 ** A read or write transaction may or may not be active on database handle
275713adf8a0Sdanielk1977 ** db. If a transaction is active, commit it. If there is a
275813adf8a0Sdanielk1977 ** write-transaction spanning more than one database file, this routine
2759ccb2113aSdrh ** takes care of the super-journal trickery.
276013adf8a0Sdanielk1977 */
vdbeCommit(sqlite3 * db,Vdbe * p)27613e3a84d3Sdanielk1977 static int vdbeCommit(sqlite3 *db, Vdbe *p){
276213adf8a0Sdanielk1977 int i;
27638e6cf0a7Sdrh int nTrans = 0; /* Number of databases with an active write-transaction
27648e6cf0a7Sdrh ** that are candidates for a two-phase commit using a
2765ccb2113aSdrh ** super-journal */
276613adf8a0Sdanielk1977 int rc = SQLITE_OK;
276713adf8a0Sdanielk1977 int needXcommit = 0;
276813adf8a0Sdanielk1977
276936840fddSshane #ifdef SQLITE_OMIT_VIRTUALTABLE
277036840fddSshane /* With this option, sqlite3VtabSync() is defined to be simply
277136840fddSshane ** SQLITE_OK so p is not used.
277236840fddSshane */
277336840fddSshane UNUSED_PARAMETER(p);
277436840fddSshane #endif
277536840fddSshane
27765bd270b2Sdanielk1977 /* Before doing anything else, call the xSync() callback for any
27775bd270b2Sdanielk1977 ** virtual module tables written in this transaction. This has to
2778ccb2113aSdrh ** be done before determining whether a super-journal file is
27795bd270b2Sdanielk1977 ** required, as an xSync() callback may add an attached database
27805bd270b2Sdanielk1977 ** to the transaction.
27815bd270b2Sdanielk1977 */
2782016f7811Sdan rc = sqlite3VtabSync(db, p);
27835bd270b2Sdanielk1977
27845bd270b2Sdanielk1977 /* This loop determines (a) if the commit hook should be invoked and
27855bd270b2Sdanielk1977 ** (b) how many database files have open write transactions, not
27865bd270b2Sdanielk1977 ** including the temp database. (b) is important because if more than
2787ccb2113aSdrh ** one database file has an open write transaction, a super-journal
27885bd270b2Sdanielk1977 ** file is required for an atomic commit.
27895bd270b2Sdanielk1977 */
2790abfb62f9Sdrh for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
279113adf8a0Sdanielk1977 Btree *pBt = db->aDb[i].pBt;
279299744fa4Sdrh if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
2793ccb2113aSdrh /* Whether or not a database might need a super-journal depends upon
27948e6cf0a7Sdrh ** its journal mode (among other things). This matrix determines which
2795ccb2113aSdrh ** journal modes use a super-journal and which do not */
27968e6cf0a7Sdrh static const u8 aMJNeeded[] = {
27978e6cf0a7Sdrh /* DELETE */ 1,
27988e6cf0a7Sdrh /* PERSIST */ 1,
27998e6cf0a7Sdrh /* OFF */ 0,
28008e6cf0a7Sdrh /* TRUNCATE */ 1,
28018e6cf0a7Sdrh /* MEMORY */ 0,
28028e6cf0a7Sdrh /* WAL */ 0
28038e6cf0a7Sdrh };
28048e6cf0a7Sdrh Pager *pPager; /* Pager associated with pBt */
280513adf8a0Sdanielk1977 needXcommit = 1;
28066b9bb59fSdan sqlite3BtreeEnter(pBt);
28078e6cf0a7Sdrh pPager = sqlite3BtreePager(pBt);
28088e6cf0a7Sdrh if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
28098e6cf0a7Sdrh && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
28106cbc5074Sdan && sqlite3PagerIsMemdb(pPager)==0
28118e6cf0a7Sdrh ){
28128e6cf0a7Sdrh assert( i!=1 );
28138e6cf0a7Sdrh nTrans++;
28148e6cf0a7Sdrh }
28158e6cf0a7Sdrh rc = sqlite3PagerExclusiveLock(pPager);
28166b9bb59fSdan sqlite3BtreeLeave(pBt);
281713adf8a0Sdanielk1977 }
281813adf8a0Sdanielk1977 }
2819abfb62f9Sdrh if( rc!=SQLITE_OK ){
2820abfb62f9Sdrh return rc;
2821abfb62f9Sdrh }
282213adf8a0Sdanielk1977
282313adf8a0Sdanielk1977 /* If there are any write-transactions at all, invoke the commit hook */
282413adf8a0Sdanielk1977 if( needXcommit && db->xCommitCallback ){
282592f02c31Sdrh rc = db->xCommitCallback(db->pCommitArg);
282692f02c31Sdrh if( rc ){
2827d91c1a17Sdrh return SQLITE_CONSTRAINT_COMMITHOOK;
282813adf8a0Sdanielk1977 }
282913adf8a0Sdanielk1977 }
283013adf8a0Sdanielk1977
283140b38dcdSdanielk1977 /* The simple case - no more than one database file (not counting the
283240b38dcdSdanielk1977 ** TEMP database) has a transaction active. There is no need for the
2833ccb2113aSdrh ** super-journal.
2834c9e0686eSdrh **
283540b38dcdSdanielk1977 ** If the return value of sqlite3BtreeGetFilename() is a zero length
283617b90b53Sdanielk1977 ** string, it means the main database is :memory: or a temp file. In
283717b90b53Sdanielk1977 ** that case we do not support atomic multi-file commits, so use the
283817b90b53Sdanielk1977 ** simple case then too.
283913adf8a0Sdanielk1977 */
2840ea678832Sdrh if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
2841ea678832Sdrh || nTrans<=1
2842ea678832Sdrh ){
28432ac3ee97Sdrh for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
28442ac3ee97Sdrh Btree *pBt = db->aDb[i].pBt;
28452ac3ee97Sdrh if( pBt ){
284680e35f46Sdrh rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
28472ac3ee97Sdrh }
28482ac3ee97Sdrh }
28492ac3ee97Sdrh
285080e35f46Sdrh /* Do the commit only if all databases successfully complete phase 1.
285180e35f46Sdrh ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
285280e35f46Sdrh ** IO error while deleting or truncating a journal file. It is unlikely,
285380e35f46Sdrh ** but could happen. In this case abandon processing and return the error.
2854979f38e5Sdanielk1977 */
2855979f38e5Sdanielk1977 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
285613adf8a0Sdanielk1977 Btree *pBt = db->aDb[i].pBt;
285713adf8a0Sdanielk1977 if( pBt ){
285860939d0aSdan rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
28592ac3ee97Sdrh }
286013adf8a0Sdanielk1977 }
2861979f38e5Sdanielk1977 if( rc==SQLITE_OK ){
2862f9e7dda7Sdanielk1977 sqlite3VtabCommit(db);
286313adf8a0Sdanielk1977 }
286413adf8a0Sdanielk1977 }
286513adf8a0Sdanielk1977
286613adf8a0Sdanielk1977 /* The complex case - There is a multi-file write-transaction active.
2867ccb2113aSdrh ** This requires a super-journal file to ensure the transaction is
286860ec914cSpeter.d.reid ** committed atomically.
286913adf8a0Sdanielk1977 */
287044ee5bf7Sdanielk1977 #ifndef SQLITE_OMIT_DISKIO
287113adf8a0Sdanielk1977 else{
2872b4b47411Sdanielk1977 sqlite3_vfs *pVfs = db->pVfs;
2873ccb2113aSdrh char *zSuper = 0; /* File-name for the super-journal */
287413adf8a0Sdanielk1977 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
2875067b92baSdrh sqlite3_file *pSuperJrnl = 0;
287662079060Sdanielk1977 i64 offset = 0;
2877861f7456Sdanielk1977 int res;
2878f580860fSdrh int retryCount = 0;
28795c531a4aSdrh int nMainFile;
288013adf8a0Sdanielk1977
2881ccb2113aSdrh /* Select a super-journal file name */
28825c531a4aSdrh nMainFile = sqlite3Strlen30(zMainFile);
2883ccb2113aSdrh zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
2884ccb2113aSdrh if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
2885ccb2113aSdrh zSuper += 4;
288613adf8a0Sdanielk1977 do {
2887dc5ea5c7Sdrh u32 iRandom;
288884968c05Sdrh if( retryCount ){
288984968c05Sdrh if( retryCount>100 ){
2890ccb2113aSdrh sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
2891ccb2113aSdrh sqlite3OsDelete(pVfs, zSuper, 0);
2892f580860fSdrh break;
289384968c05Sdrh }else if( retryCount==1 ){
2894ccb2113aSdrh sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
289513adf8a0Sdanielk1977 }
289684968c05Sdrh }
289784968c05Sdrh retryCount++;
289813adf8a0Sdanielk1977 sqlite3_randomness(sizeof(iRandom), &iRandom);
2899ccb2113aSdrh sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
2900f580860fSdrh (iRandom>>8)&0xffffff, iRandom&0xff);
2901ccb2113aSdrh /* The antipenultimate character of the super-journal name must
2902f580860fSdrh ** be "9" to avoid name collisions when using 8+3 filenames. */
2903ccb2113aSdrh assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
2904ccb2113aSdrh sqlite3FileSuffix3(zMainFile, zSuper);
2905ccb2113aSdrh rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
2906861f7456Sdanielk1977 }while( rc==SQLITE_OK && res );
2907861f7456Sdanielk1977 if( rc==SQLITE_OK ){
2908ccb2113aSdrh /* Open the super-journal. */
2909067b92baSdrh rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
2910fee2d25aSdanielk1977 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
2911067b92baSdrh SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
2912fee2d25aSdanielk1977 );
291319db9352Sdrh }
291413adf8a0Sdanielk1977 if( rc!=SQLITE_OK ){
2915ccb2113aSdrh sqlite3DbFree(db, zSuper-4);
291613adf8a0Sdanielk1977 return rc;
291713adf8a0Sdanielk1977 }
291813adf8a0Sdanielk1977
291913adf8a0Sdanielk1977 /* Write the name of each database file in the transaction into the new
2920ccb2113aSdrh ** super-journal file. If an error occurs at this point close
2921ccb2113aSdrh ** and delete the super-journal file. All the individual journal files
2922ccb2113aSdrh ** still have 'null' as the super-journal pointer, so they will roll
2923aca790acSdanielk1977 ** back independently if a failure occurs.
292413adf8a0Sdanielk1977 */
292513adf8a0Sdanielk1977 for(i=0; i<db->nDb; i++){
292613adf8a0Sdanielk1977 Btree *pBt = db->aDb[i].pBt;
292799744fa4Sdrh if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
29285865e3d5Sdanielk1977 char const *zFile = sqlite3BtreeGetJournalname(pBt);
29298c96a6eaSdrh if( zFile==0 ){
2930b290e1c7Sdrh continue; /* Ignore TEMP and :memory: databases */
2931b290e1c7Sdrh }
29328c96a6eaSdrh assert( zFile[0]!=0 );
2933067b92baSdrh rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
2934ea678832Sdrh offset += sqlite3Strlen30(zFile)+1;
293513adf8a0Sdanielk1977 if( rc!=SQLITE_OK ){
2936067b92baSdrh sqlite3OsCloseFree(pSuperJrnl);
2937ccb2113aSdrh sqlite3OsDelete(pVfs, zSuper, 0);
2938ccb2113aSdrh sqlite3DbFree(db, zSuper-4);
293913adf8a0Sdanielk1977 return rc;
294013adf8a0Sdanielk1977 }
294113adf8a0Sdanielk1977 }
294213adf8a0Sdanielk1977 }
294313adf8a0Sdanielk1977
2944ccb2113aSdrh /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
29459663b8f9Sdanielk1977 ** flag is set this is not required.
29469663b8f9Sdanielk1977 */
2947067b92baSdrh if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
2948067b92baSdrh && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
2949bea2a948Sdanielk1977 ){
2950067b92baSdrh sqlite3OsCloseFree(pSuperJrnl);
2951ccb2113aSdrh sqlite3OsDelete(pVfs, zSuper, 0);
2952ccb2113aSdrh sqlite3DbFree(db, zSuper-4);
29535865e3d5Sdanielk1977 return rc;
29545865e3d5Sdanielk1977 }
2955c9e0686eSdrh
295613adf8a0Sdanielk1977 /* Sync all the db files involved in the transaction. The same call
2957ccb2113aSdrh ** sets the super-journal pointer in each individual journal. If
2958ccb2113aSdrh ** an error occurs here, do not delete the super-journal file.
295913adf8a0Sdanielk1977 **
296080e35f46Sdrh ** If the error occurs during the first call to
296180e35f46Sdrh ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
2962ccb2113aSdrh ** super-journal file will be orphaned. But we cannot delete it,
2963ccb2113aSdrh ** in case the super-journal file name was written into the journal
2964be217793Sshane ** file before the failure occurred.
296513adf8a0Sdanielk1977 */
29665bd270b2Sdanielk1977 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
296713adf8a0Sdanielk1977 Btree *pBt = db->aDb[i].pBt;
2968d0679edcSdrh if( pBt ){
2969ccb2113aSdrh rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
29705bd270b2Sdanielk1977 }
29715bd270b2Sdanielk1977 }
2972067b92baSdrh sqlite3OsCloseFree(pSuperJrnl);
2973abfb62f9Sdrh assert( rc!=SQLITE_BUSY );
29745bd270b2Sdanielk1977 if( rc!=SQLITE_OK ){
2975ccb2113aSdrh sqlite3DbFree(db, zSuper-4);
297613adf8a0Sdanielk1977 return rc;
297713adf8a0Sdanielk1977 }
297813adf8a0Sdanielk1977
2979ccb2113aSdrh /* Delete the super-journal file. This commits the transaction. After
2980962398d3Sdanielk1977 ** doing this the directory is synced again before any individual
2981962398d3Sdanielk1977 ** transaction files are deleted.
2982962398d3Sdanielk1977 */
2983ccb2113aSdrh rc = sqlite3OsDelete(pVfs, zSuper, 1);
2984ccb2113aSdrh sqlite3DbFree(db, zSuper-4);
2985ccb2113aSdrh zSuper = 0;
298629a0138cSdrh if( rc ){
298729a0138cSdrh return rc;
298829a0138cSdrh }
298913adf8a0Sdanielk1977
299013adf8a0Sdanielk1977 /* All files and directories have already been synced, so the following
299180e35f46Sdrh ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
299280e35f46Sdrh ** deleting or truncating journals. If something goes wrong while
299380e35f46Sdrh ** this is happening we don't really care. The integrity of the
299480e35f46Sdrh ** transaction is already guaranteed, but some stray 'cold' journals
299580e35f46Sdrh ** may be lying around. Returning an error code won't help matters.
299613adf8a0Sdanielk1977 */
2997979f38e5Sdanielk1977 disable_simulated_io_errors();
29982d1d86fbSdanielk1977 sqlite3BeginBenignMalloc();
299913adf8a0Sdanielk1977 for(i=0; i<db->nDb; i++){
300013adf8a0Sdanielk1977 Btree *pBt = db->aDb[i].pBt;
300113adf8a0Sdanielk1977 if( pBt ){
300260939d0aSdan sqlite3BtreeCommitPhaseTwo(pBt, 1);
300313adf8a0Sdanielk1977 }
300413adf8a0Sdanielk1977 }
30052d1d86fbSdanielk1977 sqlite3EndBenignMalloc();
3006979f38e5Sdanielk1977 enable_simulated_io_errors();
3007979f38e5Sdanielk1977
3008f9e7dda7Sdanielk1977 sqlite3VtabCommit(db);
300913adf8a0Sdanielk1977 }
301044ee5bf7Sdanielk1977 #endif
3011026d270cSdanielk1977
30122ac3ee97Sdrh return rc;
301313adf8a0Sdanielk1977 }
301413adf8a0Sdanielk1977
301513adf8a0Sdanielk1977 /*
30164f7d3a5fSdrh ** This routine checks that the sqlite3.nVdbeActive count variable
30171d850a72Sdanielk1977 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
30181d850a72Sdanielk1977 ** currently active. An assertion fails if the two counts do not match.
301992f02c31Sdrh ** This is an internal self-check only - it is not an essential processing
302092f02c31Sdrh ** step.
30211d850a72Sdanielk1977 **
30221d850a72Sdanielk1977 ** This is a no-op if NDEBUG is defined.
30231d850a72Sdanielk1977 */
30241d850a72Sdanielk1977 #ifndef NDEBUG
checkActiveVdbeCnt(sqlite3 * db)30259bb575fdSdrh static void checkActiveVdbeCnt(sqlite3 *db){
30261d850a72Sdanielk1977 Vdbe *p;
30271d850a72Sdanielk1977 int cnt = 0;
3028ad4a4b80Sdrh int nWrite = 0;
30294f7d3a5fSdrh int nRead = 0;
30301d850a72Sdanielk1977 p = db->pVdbe;
30311d850a72Sdanielk1977 while( p ){
3032857745c0Sdan if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
30331d850a72Sdanielk1977 cnt++;
3034ad4a4b80Sdrh if( p->readOnly==0 ) nWrite++;
30351713afb0Sdrh if( p->bIsReader ) nRead++;
30361d850a72Sdanielk1977 }
3037e5928b17Sdrh p = p->pVNext;
30381d850a72Sdanielk1977 }
30394f7d3a5fSdrh assert( cnt==db->nVdbeActive );
30404f7d3a5fSdrh assert( nWrite==db->nVdbeWrite );
30414f7d3a5fSdrh assert( nRead==db->nVdbeRead );
30421d850a72Sdanielk1977 }
30431d850a72Sdanielk1977 #else
30441d850a72Sdanielk1977 #define checkActiveVdbeCnt(x)
30451d850a72Sdanielk1977 #endif
30461d850a72Sdanielk1977
30471d850a72Sdanielk1977 /*
3048bd43455cSdanielk1977 ** If the Vdbe passed as the first argument opened a statement-transaction,
3049bd43455cSdanielk1977 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
3050bd43455cSdanielk1977 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
3051bd43455cSdanielk1977 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
3052f7b5496eSdrh ** statement transaction is committed.
3053bd43455cSdanielk1977 **
3054bd43455cSdanielk1977 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
3055bd43455cSdanielk1977 ** Otherwise SQLITE_OK.
3056bd43455cSdanielk1977 */
vdbeCloseStatement(Vdbe * p,int eOp)3057d0840647Sdrh static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
3058c926b6a6Sdanielk1977 sqlite3 *const db = p->db;
3059bd43455cSdanielk1977 int rc = SQLITE_OK;
3060bd43455cSdanielk1977 int i;
3061bd43455cSdanielk1977 const int iSavepoint = p->iStatement-1;
3062bd43455cSdanielk1977
3063bd43455cSdanielk1977 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
3064bd43455cSdanielk1977 assert( db->nStatement>0 );
3065bd43455cSdanielk1977 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
3066bd43455cSdanielk1977
3067bd43455cSdanielk1977 for(i=0; i<db->nDb; i++){
3068bd43455cSdanielk1977 int rc2 = SQLITE_OK;
3069bd43455cSdanielk1977 Btree *pBt = db->aDb[i].pBt;
3070bd43455cSdanielk1977 if( pBt ){
3071bd43455cSdanielk1977 if( eOp==SAVEPOINT_ROLLBACK ){
3072bd43455cSdanielk1977 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
3073bd43455cSdanielk1977 }
3074bd43455cSdanielk1977 if( rc2==SQLITE_OK ){
3075bd43455cSdanielk1977 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
3076bd43455cSdanielk1977 }
3077bd43455cSdanielk1977 if( rc==SQLITE_OK ){
3078bd43455cSdanielk1977 rc = rc2;
3079bd43455cSdanielk1977 }
3080bd43455cSdanielk1977 }
3081bd43455cSdanielk1977 }
3082bd43455cSdanielk1977 db->nStatement--;
3083bd43455cSdanielk1977 p->iStatement = 0;
30841da40a38Sdan
3085a311b803Sdan if( rc==SQLITE_OK ){
3086a311b803Sdan if( eOp==SAVEPOINT_ROLLBACK ){
3087a311b803Sdan rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
3088a311b803Sdan }
3089a311b803Sdan if( rc==SQLITE_OK ){
3090a311b803Sdan rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
3091a311b803Sdan }
3092a311b803Sdan }
3093a311b803Sdan
30941da40a38Sdan /* If the statement transaction is being rolled back, also restore the
30951da40a38Sdan ** database handles deferred constraint counter to the value it had when
30961da40a38Sdan ** the statement transaction was opened. */
30971da40a38Sdan if( eOp==SAVEPOINT_ROLLBACK ){
30981da40a38Sdan db->nDeferredCons = p->nStmtDefCons;
3099cb3e4b79Sdan db->nDeferredImmCons = p->nStmtDefImmCons;
31001da40a38Sdan }
3101bd43455cSdanielk1977 return rc;
3102bd43455cSdanielk1977 }
sqlite3VdbeCloseStatement(Vdbe * p,int eOp)3103d0840647Sdrh int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
3104d0840647Sdrh if( p->db->nStatement && p->iStatement ){
3105d0840647Sdrh return vdbeCloseStatement(p, eOp);
3106d0840647Sdrh }
3107d0840647Sdrh return SQLITE_OK;
3108d0840647Sdrh }
3109d0840647Sdrh
3110bd43455cSdanielk1977
3111bd43455cSdanielk1977 /*
31121da40a38Sdan ** This function is called when a transaction opened by the database
31131da40a38Sdan ** handle associated with the VM passed as an argument is about to be
31141da40a38Sdan ** committed. If there are outstanding deferred foreign key constraint
31151da40a38Sdan ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
31161da40a38Sdan **
31171da40a38Sdan ** If there are outstanding FK violations and this function returns
3118d91c1a17Sdrh ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
3119d91c1a17Sdrh ** and write an error message to it. Then return SQLITE_ERROR.
31201da40a38Sdan */
31211da40a38Sdan #ifndef SQLITE_OMIT_FOREIGN_KEY
sqlite3VdbeCheckFk(Vdbe * p,int deferred)312232b09f29Sdan int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
31231da40a38Sdan sqlite3 *db = p->db;
3124cb3e4b79Sdan if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
3125cb3e4b79Sdan || (!deferred && p->nFkConstraint>0)
3126cb3e4b79Sdan ){
3127d91c1a17Sdrh p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
312832b09f29Sdan p->errorAction = OE_Abort;
312922c17b8bSdrh sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
313089cf958cSdrh if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
313190402d4dSdrh return SQLITE_CONSTRAINT_FOREIGNKEY;
31321da40a38Sdan }
31331da40a38Sdan return SQLITE_OK;
31341da40a38Sdan }
31351da40a38Sdan #endif
31361da40a38Sdan
31371da40a38Sdan /*
313892f02c31Sdrh ** This routine is called the when a VDBE tries to halt. If the VDBE
313992f02c31Sdrh ** has made changes and is in autocommit mode, then commit those
314092f02c31Sdrh ** changes. If a rollback is needed, then do the rollback.
31419a32464bSdrh **
3142687d74dfSdrh ** This routine is the only way to move the sqlite3eOpenState of a VM from
3143687d74dfSdrh ** SQLITE_STATE_RUN to SQLITE_STATE_HALT. It is harmless to
3144687d74dfSdrh ** call this on a VM that is in the SQLITE_STATE_HALT state.
314592f02c31Sdrh **
314692f02c31Sdrh ** Return an error code. If the commit could not complete because of
314792f02c31Sdrh ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
314892f02c31Sdrh ** means the close did not happen and needs to be repeated.
31499a32464bSdrh */
sqlite3VdbeHalt(Vdbe * p)3150ff0587c6Sdrh int sqlite3VdbeHalt(Vdbe *p){
3151bd43455cSdanielk1977 int rc; /* Used to store transient return codes */
31529bb575fdSdrh sqlite3 *db = p->db;
315307cb560bSdanielk1977
315407cb560bSdanielk1977 /* This function contains the logic that determines if a statement or
315507cb560bSdanielk1977 ** transaction will be committed or rolled back as a result of the
315607cb560bSdanielk1977 ** execution of this virtual machine.
315707cb560bSdanielk1977 **
315871b890a3Sdrh ** If any of the following errors occur:
315907cb560bSdanielk1977 **
316071b890a3Sdrh ** SQLITE_NOMEM
316171b890a3Sdrh ** SQLITE_IOERR
316271b890a3Sdrh ** SQLITE_FULL
316371b890a3Sdrh ** SQLITE_INTERRUPT
316407cb560bSdanielk1977 **
316571b890a3Sdrh ** Then the internal cache might have been left in an inconsistent
316671b890a3Sdrh ** state. We need to rollback the statement transaction, if there is
316771b890a3Sdrh ** one, or the complete transaction if there is no statement transaction.
316807cb560bSdanielk1977 */
31699a32464bSdrh
31708703edd3Sdrh assert( p->eVdbeState==VDBE_RUN_STATE );
3171b84e574cSdrh if( db->mallocFailed ){
3172fad3039cSmistachkin p->rc = SQLITE_NOMEM_BKPT;
3173261919ccSdanielk1977 }
31745f82e3ccSdrh closeAllCursors(p);
31751d850a72Sdanielk1977 checkActiveVdbeCnt(db);
317607cb560bSdanielk1977
3177c0537fe5Sdan /* No commit or rollback needed if the program never started or if the
3178c0537fe5Sdan ** SQL statement does not read or write a database file. */
317999a21828Sdrh if( p->bIsReader ){
3180aac2f554Sdrh int mrc; /* Primary error code from p->rc */
3181bd43455cSdanielk1977 int eStatementOp = 0;
3182bd43455cSdanielk1977 int isSpecialError; /* Set to true if a 'special' error */
3183ff0587c6Sdrh
3184ff0587c6Sdrh /* Lock all btrees used by the statement */
3185bdaec52cSdrh sqlite3VdbeEnter(p);
3186ff0587c6Sdrh
318771b890a3Sdrh /* Check for one of the special errors */
31883ce76a0bSdrh if( p->rc ){
3189aac2f554Sdrh mrc = p->rc & 0xff;
31903ce76a0bSdrh isSpecialError = mrc==SQLITE_NOMEM
31913ce76a0bSdrh || mrc==SQLITE_IOERR
31923ce76a0bSdrh || mrc==SQLITE_INTERRUPT
31933ce76a0bSdrh || mrc==SQLITE_FULL;
31943ce76a0bSdrh }else{
31953ce76a0bSdrh mrc = isSpecialError = 0;
31963ce76a0bSdrh }
319707cb560bSdanielk1977 if( isSpecialError ){
31985653e4daSdan /* If the query was read-only and the error code is SQLITE_INTERRUPT,
31995653e4daSdan ** no rollback is necessary. Otherwise, at least a savepoint
32005653e4daSdan ** transaction must be rolled back to restore the database to a
32015653e4daSdan ** consistent state.
32025653e4daSdan **
32035653e4daSdan ** Even if the statement is read-only, it is important to perform
32045653e4daSdan ** a statement or transaction rollback operation. If the error
320548864df9Smistachkin ** occurred while writing to the journal, sub-journal or database
32065653e4daSdan ** file as part of an effort to free up cache space (see function
32075653e4daSdan ** pagerStress() in pager.c), the rollback is required to restore
32085653e4daSdan ** the pager to a consistent state.
320907cb560bSdanielk1977 */
3210ad4a4b80Sdrh if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
3211fa3be904Sdrh if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
3212bd43455cSdanielk1977 eStatementOp = SAVEPOINT_ROLLBACK;
3213261919ccSdanielk1977 }else{
321407cb560bSdanielk1977 /* We are forced to roll back the active transaction. Before doing
321507cb560bSdanielk1977 ** so, abort any other statements this handle currently has active.
321607cb560bSdanielk1977 */
321721021a5cSdrh sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3218fc158bf9Sdanielk1977 sqlite3CloseSavepoints(db);
321907cb560bSdanielk1977 db->autoCommit = 1;
3220c3da667bSdan p->nChange = 0;
322107cb560bSdanielk1977 }
3222261919ccSdanielk1977 }
3223261919ccSdanielk1977 }
3224261919ccSdanielk1977
322532b09f29Sdan /* Check for immediate foreign key violations. */
3226f116ad85Sdan if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
322732b09f29Sdan sqlite3VdbeCheckFk(p, 0);
322832b09f29Sdan }
322932b09f29Sdan
3230bd43455cSdanielk1977 /* If the auto-commit flag is set and this is the only active writer
3231bd43455cSdanielk1977 ** VM, then we do either a commit or rollback of the current transaction.
323207cb560bSdanielk1977 **
323307cb560bSdanielk1977 ** Note: This block also runs if one of the special errors handled
3234ad4a4b80Sdrh ** above has occurred.
323507cb560bSdanielk1977 */
3236093e0f6fSdanielk1977 if( !sqlite3VtabInSync(db)
3237093e0f6fSdanielk1977 && db->autoCommit
32384f7d3a5fSdrh && db->nVdbeWrite==(p->readOnly==0)
3239093e0f6fSdanielk1977 ){
324007cb560bSdanielk1977 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
324119611b1aSdan rc = sqlite3VdbeCheckFk(p, 1);
324219611b1aSdan if( rc!=SQLITE_OK ){
3243e9ce5857Sdrh if( NEVER(p->readOnly) ){
3244bdaec52cSdrh sqlite3VdbeLeave(p);
32451da40a38Sdan return SQLITE_ERROR;
32461da40a38Sdan }
3247d91c1a17Sdrh rc = SQLITE_CONSTRAINT_FOREIGNKEY;
32489dc71885Sdrh }else if( db->flags & SQLITE_CorruptRdOnly ){
32499dc71885Sdrh rc = SQLITE_CORRUPT;
32509dc71885Sdrh db->flags &= ~SQLITE_CorruptRdOnly;
325119611b1aSdan }else{
32521da40a38Sdan /* The auto-commit flag is true, the vdbe program was successful
32531da40a38Sdan ** or hit an 'OR FAIL' constraint and there are no deferred foreign
32541da40a38Sdan ** key constraints to hold up the transaction. This means a commit
32551da40a38Sdan ** is required. */
3256bd43455cSdanielk1977 rc = vdbeCommit(db, p);
325719611b1aSdan }
325819611b1aSdan if( rc==SQLITE_BUSY && p->readOnly ){
3259bdaec52cSdrh sqlite3VdbeLeave(p);
326007cb560bSdanielk1977 return SQLITE_BUSY;
326107cb560bSdanielk1977 }else if( rc!=SQLITE_OK ){
326207cb560bSdanielk1977 p->rc = rc;
32630f198a74Sdrh sqlite3RollbackAll(db, SQLITE_OK);
3264c3da667bSdan p->nChange = 0;
326507cb560bSdanielk1977 }else{
32661da40a38Sdan db->nDeferredCons = 0;
3267cb3e4b79Sdan db->nDeferredImmCons = 0;
3268d5b44d60Sdrh db->flags &= ~(u64)SQLITE_DeferFKs;
326907cb560bSdanielk1977 sqlite3CommitInternalChanges(db);
327007cb560bSdanielk1977 }
327107cb560bSdanielk1977 }else{
32720f198a74Sdrh sqlite3RollbackAll(db, SQLITE_OK);
3273c3da667bSdan p->nChange = 0;
327407cb560bSdanielk1977 }
3275bd43455cSdanielk1977 db->nStatement = 0;
3276bd43455cSdanielk1977 }else if( eStatementOp==0 ){
32771d850a72Sdanielk1977 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
3278bd43455cSdanielk1977 eStatementOp = SAVEPOINT_RELEASE;
32791d850a72Sdanielk1977 }else if( p->errorAction==OE_Abort ){
3280bd43455cSdanielk1977 eStatementOp = SAVEPOINT_ROLLBACK;
32811d850a72Sdanielk1977 }else{
328221021a5cSdrh sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3283fc158bf9Sdanielk1977 sqlite3CloseSavepoints(db);
3284f3f06bb3Sdanielk1977 db->autoCommit = 1;
3285c3da667bSdan p->nChange = 0;
32861d850a72Sdanielk1977 }
32871d850a72Sdanielk1977 }
32881d850a72Sdanielk1977
3289bd43455cSdanielk1977 /* If eStatementOp is non-zero, then a statement transaction needs to
3290bd43455cSdanielk1977 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
3291bd43455cSdanielk1977 ** do so. If this operation returns an error, and the current statement
32923517324dSdrh ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
32933517324dSdrh ** current statement error code.
329413adf8a0Sdanielk1977 */
3295bd43455cSdanielk1977 if( eStatementOp ){
3296bd43455cSdanielk1977 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
329740ad9d28Sdan if( rc ){
3298d91c1a17Sdrh if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
32998a7aea3bSdanielk1977 p->rc = rc;
3300633e6d57Sdrh sqlite3DbFree(db, p->zErrMsg);
3301f089aa45Sdrh p->zErrMsg = 0;
33028a7aea3bSdanielk1977 }
330321021a5cSdrh sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
330440ad9d28Sdan sqlite3CloseSavepoints(db);
330540ad9d28Sdan db->autoCommit = 1;
3306c3da667bSdan p->nChange = 0;
330740ad9d28Sdan }
33081d850a72Sdanielk1977 }
33091d850a72Sdanielk1977
3310bd43455cSdanielk1977 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
3311bd43455cSdanielk1977 ** has been rolled back, update the database connection change-counter.
331207cb560bSdanielk1977 */
33136be240e5Sdrh if( p->changeCntOn ){
3314bd43455cSdanielk1977 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
3315b28af71aSdanielk1977 sqlite3VdbeSetChanges(db, p->nChange);
3316b28af71aSdanielk1977 }else{
3317b28af71aSdanielk1977 sqlite3VdbeSetChanges(db, 0);
3318b28af71aSdanielk1977 }
3319b28af71aSdanielk1977 p->nChange = 0;
3320b28af71aSdanielk1977 }
33211d850a72Sdanielk1977
3322ff0587c6Sdrh /* Release the locks */
3323bdaec52cSdrh sqlite3VdbeLeave(p);
332407cb560bSdanielk1977 }
33251d850a72Sdanielk1977
332665fd59f7Sdanielk1977 /* We have successfully halted and closed the VM. Record this fact. */
33274f7d3a5fSdrh db->nVdbeActive--;
33284f7d3a5fSdrh if( !p->readOnly ) db->nVdbeWrite--;
33291713afb0Sdrh if( p->bIsReader ) db->nVdbeRead--;
33304f7d3a5fSdrh assert( db->nVdbeActive>=db->nVdbeRead );
33314f7d3a5fSdrh assert( db->nVdbeRead>=db->nVdbeWrite );
33324f7d3a5fSdrh assert( db->nVdbeWrite>=0 );
333366181ce2Sdrh p->eVdbeState = VDBE_HALT_STATE;
333492f02c31Sdrh checkActiveVdbeCnt(db);
3335b84e574cSdrh if( db->mallocFailed ){
3336fad3039cSmistachkin p->rc = SQLITE_NOMEM_BKPT;
3337ff0587c6Sdrh }
33381d850a72Sdanielk1977
3339404ca075Sdanielk1977 /* If the auto-commit flag is set to true, then any locks that were held
3340404ca075Sdanielk1977 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
3341404ca075Sdanielk1977 ** to invoke any required unlock-notify callbacks.
3342404ca075Sdanielk1977 */
3343404ca075Sdanielk1977 if( db->autoCommit ){
3344404ca075Sdanielk1977 sqlite3ConnectionUnlocked(db);
3345404ca075Sdanielk1977 }
3346404ca075Sdanielk1977
33474f7d3a5fSdrh assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
334819611b1aSdan return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
334992f02c31Sdrh }
33504cf7c7f7Sdrh
335192f02c31Sdrh
335292f02c31Sdrh /*
33533c23a885Sdrh ** Each VDBE holds the result of the most recent sqlite3_step() call
33543c23a885Sdrh ** in p->rc. This routine sets that result back to SQLITE_OK.
33553c23a885Sdrh */
sqlite3VdbeResetStepResult(Vdbe * p)33563c23a885Sdrh void sqlite3VdbeResetStepResult(Vdbe *p){
33573c23a885Sdrh p->rc = SQLITE_OK;
33583c23a885Sdrh }
33593c23a885Sdrh
33603c23a885Sdrh /*
3361029ead64Sdan ** Copy the error code and error message belonging to the VDBE passed
3362029ead64Sdan ** as the first argument to its database handle (so that they will be
3363029ead64Sdan ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
3364029ead64Sdan **
3365029ead64Sdan ** This function does not clear the VDBE error code or message, just
3366029ead64Sdan ** copies them to the database handle.
3367029ead64Sdan */
sqlite3VdbeTransferError(Vdbe * p)3368029ead64Sdan int sqlite3VdbeTransferError(Vdbe *p){
3369029ead64Sdan sqlite3 *db = p->db;
3370029ead64Sdan int rc = p->rc;
3371029ead64Sdan if( p->zErrMsg ){
33724a642b60Sdrh db->bBenignMalloc++;
3373029ead64Sdan sqlite3BeginBenignMalloc();
3374a3cc007dSdrh if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
3375029ead64Sdan sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
3376029ead64Sdan sqlite3EndBenignMalloc();
33774a642b60Sdrh db->bBenignMalloc--;
3378e70d01f1Sdrh }else if( db->pErr ){
3379e70d01f1Sdrh sqlite3ValueSetNull(db->pErr);
3380029ead64Sdan }
3381e70d01f1Sdrh db->errCode = rc;
3382e1c47431Sdrh db->errByteOffset = -1;
3383029ead64Sdan return rc;
3384029ead64Sdan }
3385029ead64Sdan
3386ac455939Sdan #ifdef SQLITE_ENABLE_SQLLOG
3387ac455939Sdan /*
3388ac455939Sdan ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
3389ac455939Sdan ** invoke it.
3390ac455939Sdan */
vdbeInvokeSqllog(Vdbe * v)3391ac455939Sdan static void vdbeInvokeSqllog(Vdbe *v){
3392ac455939Sdan if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
3393ac455939Sdan char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
3394ac455939Sdan assert( v->db->init.busy==0 );
3395ac455939Sdan if( zExpanded ){
3396ac455939Sdan sqlite3GlobalConfig.xSqllog(
3397ac455939Sdan sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
3398ac455939Sdan );
3399ac455939Sdan sqlite3DbFree(v->db, zExpanded);
3400ac455939Sdan }
3401ac455939Sdan }
3402ac455939Sdan }
3403ac455939Sdan #else
3404ac455939Sdan # define vdbeInvokeSqllog(x)
3405ac455939Sdan #endif
3406ac455939Sdan
3407029ead64Sdan /*
340892f02c31Sdrh ** Clean up a VDBE after execution but do not delete the VDBE just yet.
340992f02c31Sdrh ** Write any error messages into *pzErrMsg. Return the result code.
341092f02c31Sdrh **
341192f02c31Sdrh ** After this routine is run, the VDBE should be ready to be executed
341292f02c31Sdrh ** again.
341392f02c31Sdrh **
341492f02c31Sdrh ** To look at it another way, this routine resets the state of the
341566181ce2Sdrh ** virtual machine from VDBE_RUN_STATE or VDBE_HALT_STATE back to
341666181ce2Sdrh ** VDBE_READY_STATE.
341792f02c31Sdrh */
sqlite3VdbeReset(Vdbe * p)3418c890fec3Sdrh int sqlite3VdbeReset(Vdbe *p){
34194537f77aSmistachkin #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
3420b60424e4Smistachkin int i;
3421b60424e4Smistachkin #endif
3422b60424e4Smistachkin
34234ac285a1Sdrh sqlite3 *db;
34244ac285a1Sdrh db = p->db;
342592f02c31Sdrh
342692f02c31Sdrh /* If the VM did not run to completion or if it encountered an
342792f02c31Sdrh ** error, then it might not have been halted properly. So halt
342892f02c31Sdrh ** it now.
342992f02c31Sdrh */
34308703edd3Sdrh if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
343192f02c31Sdrh
34328741d0ddSdrh /* If the VDBE has been run even partially, then transfer the error code
3433fb7e7651Sdrh ** and error message from the VDBE into the main database structure. But
3434fb7e7651Sdrh ** if the VDBE has just been set to run but has not actually executed any
3435fb7e7651Sdrh ** instructions yet, leave the main database error information unchanged.
343692f02c31Sdrh */
3437fb7e7651Sdrh if( p->pc>=0 ){
3438ac455939Sdan vdbeInvokeSqllog(p);
3439ed505ce3Sdrh if( db->pErr || p->zErrMsg ){
3440029ead64Sdan sqlite3VdbeTransferError(p);
3441ed505ce3Sdrh }else{
3442ed505ce3Sdrh db->errCode = p->rc;
3443ed505ce3Sdrh }
3444fb7e7651Sdrh }
344592f02c31Sdrh
3446c2c6fd18Sdrh /* Reset register contents and reclaim error message memory.
344792f02c31Sdrh */
3448c2c6fd18Sdrh #ifdef SQLITE_DEBUG
3449c2c6fd18Sdrh /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
3450c2c6fd18Sdrh ** Vdbe.aMem[] arrays have already been cleaned up. */
3451c2c6fd18Sdrh if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
3452c2c6fd18Sdrh if( p->aMem ){
3453c2c6fd18Sdrh for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
3454c2c6fd18Sdrh }
3455c2c6fd18Sdrh #endif
3456ed505ce3Sdrh if( p->zErrMsg ){
3457c2c6fd18Sdrh sqlite3DbFree(db, p->zErrMsg);
3458c2c6fd18Sdrh p->zErrMsg = 0;
3459ed505ce3Sdrh }
3460c2c6fd18Sdrh p->pResultSet = 0;
34614031bafaSdrh #ifdef SQLITE_DEBUG
34624031bafaSdrh p->nWrite = 0;
34634031bafaSdrh #endif
346492f02c31Sdrh
346592f02c31Sdrh /* Save profiling information from this VDBE run.
346692f02c31Sdrh */
34679a32464bSdrh #ifdef VDBE_PROFILE
34689a32464bSdrh {
34699a32464bSdrh FILE *out = fopen("vdbe_profile.out", "a");
34709a32464bSdrh if( out ){
34719a32464bSdrh fprintf(out, "---- ");
34729a32464bSdrh for(i=0; i<p->nOp; i++){
34739a32464bSdrh fprintf(out, "%02x", p->aOp[i].opcode);
34749a32464bSdrh }
34759a32464bSdrh fprintf(out, "\n");
34762926f969Sdrh if( p->zSql ){
34772926f969Sdrh char c, pc = 0;
34782926f969Sdrh fprintf(out, "-- ");
34792926f969Sdrh for(i=0; (c = p->zSql[i])!=0; i++){
34802926f969Sdrh if( pc=='\n' ) fprintf(out, "-- ");
34812926f969Sdrh putc(c, out);
34822926f969Sdrh pc = c;
34832926f969Sdrh }
34842926f969Sdrh if( pc!='\n' ) fprintf(out, "\n");
34852926f969Sdrh }
34869a32464bSdrh for(i=0; i<p->nOp; i++){
348715ab9418Sdrh char zHdr[100];
348815ab9418Sdrh sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
34899a32464bSdrh p->aOp[i].cnt,
34909a32464bSdrh p->aOp[i].cycles,
34919a32464bSdrh p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
34929a32464bSdrh );
349315ab9418Sdrh fprintf(out, "%s", zHdr);
34944adee20fSdanielk1977 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
34959a32464bSdrh }
34969a32464bSdrh fclose(out);
34979a32464bSdrh }
34989a32464bSdrh }
34999a32464bSdrh #endif
35004ac285a1Sdrh return p->rc & db->errMask;
35019a32464bSdrh }
35029a32464bSdrh
35039a32464bSdrh /*
35049a32464bSdrh ** Clean up and delete a VDBE after execution. Return an integer which is
35059a32464bSdrh ** the result code. Write any error message text into *pzErrMsg.
35069a32464bSdrh */
sqlite3VdbeFinalize(Vdbe * p)35079e6db7d7Sdanielk1977 int sqlite3VdbeFinalize(Vdbe *p){
3508b5548a8bSdanielk1977 int rc = SQLITE_OK;
350999a21828Sdrh assert( VDBE_RUN_STATE>VDBE_READY_STATE );
351099a21828Sdrh assert( VDBE_HALT_STATE>VDBE_READY_STATE );
351199a21828Sdrh assert( VDBE_INIT_STATE<VDBE_READY_STATE );
351299a21828Sdrh if( p->eVdbeState>=VDBE_READY_STATE ){
3513c890fec3Sdrh rc = sqlite3VdbeReset(p);
35144ac285a1Sdrh assert( (rc & p->db->errMask)==rc );
35159a32464bSdrh }
35164adee20fSdanielk1977 sqlite3VdbeDelete(p);
35179a32464bSdrh return rc;
35189a32464bSdrh }
35199a32464bSdrh
35209a32464bSdrh /*
35210c547799Sdan ** If parameter iOp is less than zero, then invoke the destructor for
35220c547799Sdan ** all auxiliary data pointers currently cached by the VM passed as
35230c547799Sdan ** the first argument.
35240c547799Sdan **
35250c547799Sdan ** Or, if iOp is greater than or equal to zero, then the destructor is
35260c547799Sdan ** only invoked for those auxiliary data pointers created by the user
35270c547799Sdan ** function invoked by the OP_Function opcode at instruction iOp of
35280c547799Sdan ** VM pVdbe, and only then if:
35290c547799Sdan **
35300c547799Sdan ** * the associated function parameter is the 32nd or later (counting
35310c547799Sdan ** from left to right), or
35320c547799Sdan **
35330c547799Sdan ** * the corresponding bit in argument mask is clear (where the first
353460ec914cSpeter.d.reid ** function parameter corresponds to bit 0 etc.).
3535f92c7ff7Sdrh */
sqlite3VdbeDeleteAuxData(sqlite3 * db,AuxData ** pp,int iOp,int mask)3536b9626cfaSdrh void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
35370c547799Sdan while( *pp ){
35380c547799Sdan AuxData *pAux = *pp;
35390c547799Sdan if( (iOp<0)
3540e6941397Sdrh || (pAux->iAuxOp==iOp
3541f7fa4e71Sdrh && pAux->iAuxArg>=0
3542e6941397Sdrh && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
35430c547799Sdan ){
3544e6941397Sdrh testcase( pAux->iAuxArg==31 );
3545e6941397Sdrh if( pAux->xDeleteAux ){
3546e6941397Sdrh pAux->xDeleteAux(pAux->pAux);
3547f92c7ff7Sdrh }
3548e6941397Sdrh *pp = pAux->pNextAux;
3549b9626cfaSdrh sqlite3DbFree(db, pAux);
35500c547799Sdan }else{
3551e6941397Sdrh pp= &pAux->pNextAux;
3552f92c7ff7Sdrh }
3553f92c7ff7Sdrh }
3554f92c7ff7Sdrh }
3555f92c7ff7Sdrh
3556f92c7ff7Sdrh /*
3557cb103b92Sdrh ** Free all memory associated with the Vdbe passed as the second argument,
3558cb103b92Sdrh ** except for object itself, which is preserved.
3559cb103b92Sdrh **
3560d46def77Sdan ** The difference between this function and sqlite3VdbeDelete() is that
3561d46def77Sdan ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
3562cb103b92Sdrh ** the database connection and frees the object itself.
3563d46def77Sdan */
sqlite3VdbeClearObject(sqlite3 * db,Vdbe * p)35641c848630Sdrh static void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
3565d19c933eSdan SubProgram *pSub, *pNext;
356641ce47c4Sdrh assert( db!=0 );
3567d46def77Sdan assert( p->db==0 || p->db==db );
3568da3ec15fSdrh if( p->aColName ){
3569d46def77Sdan releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
357041ce47c4Sdrh sqlite3DbNNFreeNN(db, p->aColName);
3571da3ec15fSdrh }
3572d19c933eSdan for(pSub=p->pProgram; pSub; pSub=pNext){
3573d19c933eSdan pNext = pSub->pNext;
3574d19c933eSdan vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
3575d19c933eSdan sqlite3DbFree(db, pSub);
3576d19c933eSdan }
357766181ce2Sdrh if( p->eVdbeState!=VDBE_INIT_STATE ){
35788dfef117Sdrh releaseMemArray(p->aVar, p->nVar);
357941ce47c4Sdrh if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
358041ce47c4Sdrh if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
35818dfef117Sdrh }
3582d46def77Sdan vdbeFreeOpArray(db, p->aOp, p->nOp);
358341ce47c4Sdrh if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
35848bee11a4Smistachkin #ifdef SQLITE_ENABLE_NORMALIZE
35858bee11a4Smistachkin sqlite3DbFree(db, p->zNormSql);
3586893bd375Sdrh {
3587893bd375Sdrh DblquoteStr *pThis, *pNext;
3588893bd375Sdrh for(pThis=p->pDblStr; pThis; pThis=pNext){
3589893bd375Sdrh pNext = pThis->pNextStr;
3590893bd375Sdrh sqlite3DbFree(db, pThis);
3591893bd375Sdrh }
3592893bd375Sdrh }
35938bee11a4Smistachkin #endif
35946f9702edSdan #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3595f326d66dSdrh {
3596f326d66dSdrh int i;
35976f9702edSdan for(i=0; i<p->nScan; i++){
35986f9702edSdan sqlite3DbFree(db, p->aScan[i].zName);
35996f9702edSdan }
36006f9702edSdan sqlite3DbFree(db, p->aScan);
3601f326d66dSdrh }
36026f9702edSdan #endif
3603d46def77Sdan }
3604d46def77Sdan
3605d46def77Sdan /*
36069a32464bSdrh ** Delete an entire VDBE.
36079a32464bSdrh */
sqlite3VdbeDelete(Vdbe * p)36084adee20fSdanielk1977 void sqlite3VdbeDelete(Vdbe *p){
3609633e6d57Sdrh sqlite3 *db;
3610633e6d57Sdrh
36119d9c41e2Sdrh assert( p!=0 );
3612633e6d57Sdrh db = p->db;
361341ce47c4Sdrh assert( db!=0 );
36144245c405Sdrh assert( sqlite3_mutex_held(db->mutex) );
3615cb103b92Sdrh sqlite3VdbeClearObject(db, p);
36161c848630Sdrh if( db->pnBytesFreed==0 ){
3617e5928b17Sdrh assert( p->ppVPrev!=0 );
3618e5928b17Sdrh *p->ppVPrev = p->pVNext;
3619e5928b17Sdrh if( p->pVNext ){
3620e5928b17Sdrh p->pVNext->ppVPrev = p->ppVPrev;
36219a32464bSdrh }
36221c848630Sdrh }
362341ce47c4Sdrh sqlite3DbNNFreeNN(db, p);
36249a32464bSdrh }
3625a11846b7Sdrh
3626a11846b7Sdrh /*
36276848dad8Sdrh ** The cursor "p" has a pending seek operation that has not yet been
36286848dad8Sdrh ** carried out. Seek the cursor now. If an error occurs, return
36296848dad8Sdrh ** the appropriate error code.
36306848dad8Sdrh */
sqlite3VdbeFinishMoveto(VdbeCursor * p)3631be3da241Sdrh int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
36326848dad8Sdrh int res, rc;
36336848dad8Sdrh #ifdef SQLITE_TEST
36346848dad8Sdrh extern int sqlite3_search_count;
36356848dad8Sdrh #endif
36366848dad8Sdrh assert( p->deferredMoveto );
36376848dad8Sdrh assert( p->isTable );
3638c960dcbaSdrh assert( p->eCurType==CURTYPE_BTREE );
363942a410dcSdrh rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
36406848dad8Sdrh if( rc ) return rc;
36416848dad8Sdrh if( res!=0 ) return SQLITE_CORRUPT_BKPT;
36426848dad8Sdrh #ifdef SQLITE_TEST
36436848dad8Sdrh sqlite3_search_count++;
36446848dad8Sdrh #endif
36456848dad8Sdrh p->deferredMoveto = 0;
36466848dad8Sdrh p->cacheStatus = CACHE_STALE;
36476848dad8Sdrh return SQLITE_OK;
36486848dad8Sdrh }
36496848dad8Sdrh
36506848dad8Sdrh /*
36516848dad8Sdrh ** Something has moved cursor "p" out of place. Maybe the row it was
36526848dad8Sdrh ** pointed to was deleted out from under it. Or maybe the btree was
36536848dad8Sdrh ** rebalanced. Whatever the cause, try to restore "p" to the place it
365460ec914cSpeter.d.reid ** is supposed to be pointing. If the row was deleted out from under the
36556848dad8Sdrh ** cursor, set the cursor to point to a NULL row.
36566848dad8Sdrh */
sqlite3VdbeHandleMovedCursor(VdbeCursor * p)3657fc569503Sdrh int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p){
36586848dad8Sdrh int isDifferentRow, rc;
3659c960dcbaSdrh assert( p->eCurType==CURTYPE_BTREE );
3660c960dcbaSdrh assert( p->uc.pCursor!=0 );
3661c960dcbaSdrh assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
3662c960dcbaSdrh rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
36636848dad8Sdrh p->cacheStatus = CACHE_STALE;
36646848dad8Sdrh if( isDifferentRow ) p->nullRow = 1;
36656848dad8Sdrh return rc;
36666848dad8Sdrh }
36676848dad8Sdrh
36686848dad8Sdrh /*
3669c22284f4Sdrh ** Check to ensure that the cursor is valid. Restore the cursor
3670c22284f4Sdrh ** if need be. Return any I/O error from the restore operation.
3671c22284f4Sdrh */
sqlite3VdbeCursorRestore(VdbeCursor * p)3672c22284f4Sdrh int sqlite3VdbeCursorRestore(VdbeCursor *p){
3673eab6c125Sdrh assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
3674c960dcbaSdrh if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
3675fc569503Sdrh return sqlite3VdbeHandleMovedCursor(p);
3676a11846b7Sdrh }
3677a11846b7Sdrh return SQLITE_OK;
3678a11846b7Sdrh }
36794adee20fSdanielk1977
3680ab9f7f12Sdrh /*
3681cfcdaefeSdanielk1977 ** The following functions:
368290e4d95dSdanielk1977 **
3683cfcdaefeSdanielk1977 ** sqlite3VdbeSerialType()
3684cfcdaefeSdanielk1977 ** sqlite3VdbeSerialTypeLen()
368590e4d95dSdanielk1977 ** sqlite3VdbeSerialLen()
3686d859dc2bSdrh ** sqlite3VdbeSerialPut() <--- in-lined into OP_MakeRecord as of 2022-04-02
36879200309eSshane ** sqlite3VdbeSerialGet()
368890e4d95dSdanielk1977 **
368990e4d95dSdanielk1977 ** encapsulate the code that serializes values for storage in SQLite
3690cfcdaefeSdanielk1977 ** data and index records. Each serialized value consists of a
3691cfcdaefeSdanielk1977 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
3692cfcdaefeSdanielk1977 ** integer, stored as a varint.
369390e4d95dSdanielk1977 **
3694cfcdaefeSdanielk1977 ** In an SQLite index record, the serial type is stored directly before
3695cfcdaefeSdanielk1977 ** the blob of data that it corresponds to. In a table record, all serial
3696cfcdaefeSdanielk1977 ** types are stored at the start of the record, and the blobs of data at
3697cfcdaefeSdanielk1977 ** the end. Hence these functions allow the caller to handle the
369848864df9Smistachkin ** serial-type and data blob separately.
3699cfcdaefeSdanielk1977 **
3700cfcdaefeSdanielk1977 ** The following table describes the various storage classes for data:
3701cfcdaefeSdanielk1977 **
3702cfcdaefeSdanielk1977 ** serial type bytes of data type
370390e4d95dSdanielk1977 ** -------------- --------------- ---------------
3704a19b775dSdrh ** 0 0 NULL
370590e4d95dSdanielk1977 ** 1 1 signed integer
370690e4d95dSdanielk1977 ** 2 2 signed integer
3707a19b775dSdrh ** 3 3 signed integer
3708a19b775dSdrh ** 4 4 signed integer
3709a19b775dSdrh ** 5 6 signed integer
3710a19b775dSdrh ** 6 8 signed integer
3711a19b775dSdrh ** 7 8 IEEE float
3712d946db00Sdrh ** 8 0 Integer constant 0
3713d946db00Sdrh ** 9 0 Integer constant 1
3714d946db00Sdrh ** 10,11 reserved for expansion
371590e4d95dSdanielk1977 ** N>=12 and even (N-12)/2 BLOB
371690e4d95dSdanielk1977 ** N>=13 and odd (N-13)/2 text
371790e4d95dSdanielk1977 **
371835a5965aSdrh ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
371935a5965aSdrh ** of SQLite will not understand those serial types.
372090e4d95dSdanielk1977 */
372190e4d95dSdanielk1977
3722175b8f06Sdrh #if 0 /* Inlined into the OP_MakeRecord opcode */
372390e4d95dSdanielk1977 /*
3724cfcdaefeSdanielk1977 ** Return the serial-type for the value stored in pMem.
37256bab6f2bSdrh **
37266bab6f2bSdrh ** This routine might convert a large MEM_IntReal value into MEM_Real.
3727c1da4397Sdrh **
3728c1da4397Sdrh ** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
3729c1da4397Sdrh ** opcode in the byte-code engine. But by moving this routine in-line, we
3730c1da4397Sdrh ** can omit some redundant tests and make that opcode a lot faster. So
3731175b8f06Sdrh ** this routine is now only used by the STAT3 logic and STAT3 support has
3732175b8f06Sdrh ** ended. The code is kept here for historical reference only.
3733192ac1dcSdanielk1977 */
3734be37c124Sdrh u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
3735cfcdaefeSdanielk1977 int flags = pMem->flags;
3736eac5bd78Sdrh u32 n;
373790e4d95dSdanielk1977
3738be37c124Sdrh assert( pLen!=0 );
3739cfcdaefeSdanielk1977 if( flags&MEM_Null ){
3740be37c124Sdrh *pLen = 0;
3741a19b775dSdrh return 0;
374290e4d95dSdanielk1977 }
3743169f077eSdrh if( flags&(MEM_Int|MEM_IntReal) ){
3744fe2093d7Sdrh /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
37455284a053Sdrh # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
37463c024d69Sdrh i64 i = pMem->u.i;
3747d946db00Sdrh u64 u;
37483242c69cSdrh testcase( flags & MEM_Int );
37493242c69cSdrh testcase( flags & MEM_IntReal );
3750cfd654bfSdrh if( i<0 ){
37511b40e63fSdrh u = ~i;
3752cfd654bfSdrh }else{
3753cfd654bfSdrh u = i;
3754cfd654bfSdrh }
375556690b3dSdrh if( u<=127 ){
3756be37c124Sdrh if( (i&1)==i && file_format>=4 ){
3757be37c124Sdrh *pLen = 0;
3758be37c124Sdrh return 8+(u32)u;
3759be37c124Sdrh }else{
3760be37c124Sdrh *pLen = 1;
3761be37c124Sdrh return 1;
376256690b3dSdrh }
3763be37c124Sdrh }
3764be37c124Sdrh if( u<=32767 ){ *pLen = 2; return 2; }
3765be37c124Sdrh if( u<=8388607 ){ *pLen = 3; return 3; }
3766be37c124Sdrh if( u<=2147483647 ){ *pLen = 4; return 4; }
3767be37c124Sdrh if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
3768be37c124Sdrh *pLen = 8;
37696bab6f2bSdrh if( flags&MEM_IntReal ){
37706bab6f2bSdrh /* If the value is IntReal and is going to take up 8 bytes to store
37716bab6f2bSdrh ** as an integer, then we might as well make it an 8-byte floating
37726bab6f2bSdrh ** point value */
37736bab6f2bSdrh pMem->u.r = (double)pMem->u.i;
37746bab6f2bSdrh pMem->flags &= ~MEM_IntReal;
37756bab6f2bSdrh pMem->flags |= MEM_Real;
37766bab6f2bSdrh return 7;
37776bab6f2bSdrh }
3778a19b775dSdrh return 6;
377990e4d95dSdanielk1977 }
3780cfcdaefeSdanielk1977 if( flags&MEM_Real ){
3781be37c124Sdrh *pLen = 8;
3782a19b775dSdrh return 7;
378390e4d95dSdanielk1977 }
3784e4359750Sdanielk1977 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
3785eac5bd78Sdrh assert( pMem->n>=0 );
3786eac5bd78Sdrh n = (u32)pMem->n;
3787fdf972a9Sdrh if( flags & MEM_Zero ){
37888df32841Sdrh n += pMem->u.nZero;
378990e4d95dSdanielk1977 }
3790be37c124Sdrh *pLen = n;
3791fdf972a9Sdrh return ((n*2) + 12 + ((flags&MEM_Str)!=0));
379290e4d95dSdanielk1977 }
3793175b8f06Sdrh #endif /* inlined into OP_MakeRecord */
3794192ac1dcSdanielk1977
3795192ac1dcSdanielk1977 /*
3796faf37279Sdrh ** The sizes for serial types less than 128
3797c5ef7151Sdrh */
3798d859dc2bSdrh const u8 sqlite3SmallTypeSizes[128] = {
3799faf37279Sdrh /* 0 1 2 3 4 5 6 7 8 9 */
3800faf37279Sdrh /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
3801faf37279Sdrh /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
3802faf37279Sdrh /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
3803faf37279Sdrh /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
3804faf37279Sdrh /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
3805faf37279Sdrh /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
3806faf37279Sdrh /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
3807faf37279Sdrh /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
3808faf37279Sdrh /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
3809faf37279Sdrh /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
3810faf37279Sdrh /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
3811faf37279Sdrh /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
3812faf37279Sdrh /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
3813c5ef7151Sdrh };
3814c5ef7151Sdrh
3815c5ef7151Sdrh /*
3816cfcdaefeSdanielk1977 ** Return the length of the data corresponding to the supplied serial-type.
3817192ac1dcSdanielk1977 */
sqlite3VdbeSerialTypeLen(u32 serial_type)381835cd643cSdrh u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
3819faf37279Sdrh if( serial_type>=128 ){
382051846b56Sdrh return (serial_type-12)/2;
382151846b56Sdrh }else{
3822faf37279Sdrh assert( serial_type<12
3823faf37279Sdrh || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
3824c5ef7151Sdrh return sqlite3SmallTypeSizes[serial_type];
382551846b56Sdrh }
3826192ac1dcSdanielk1977 }
sqlite3VdbeOneByteSerialTypeLen(u8 serial_type)3827faf37279Sdrh u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
3828faf37279Sdrh assert( serial_type<128 );
3829faf37279Sdrh return sqlite3SmallTypeSizes[serial_type];
3830faf37279Sdrh }
3831192ac1dcSdanielk1977
3832192ac1dcSdanielk1977 /*
3833110daac9Sdrh ** If we are on an architecture with mixed-endian floating
38347a4f5023Sdrh ** points (ex: ARM7) then swap the lower 4 bytes with the
3835110daac9Sdrh ** upper 4 bytes. Return the result.
3836110daac9Sdrh **
38377a4f5023Sdrh ** For most architectures, this is a no-op.
38387a4f5023Sdrh **
38397a4f5023Sdrh ** (later): It is reported to me that the mixed-endian problem
38407a4f5023Sdrh ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
38417a4f5023Sdrh ** that early versions of GCC stored the two words of a 64-bit
38427a4f5023Sdrh ** float in the wrong order. And that error has been propagated
38437a4f5023Sdrh ** ever since. The blame is not necessarily with GCC, though.
38447a4f5023Sdrh ** GCC might have just copying the problem from a prior compiler.
38457a4f5023Sdrh ** I am also told that newer versions of GCC that follow a different
38467a4f5023Sdrh ** ABI get the byte order right.
38477a4f5023Sdrh **
38487a4f5023Sdrh ** Developers using SQLite on an ARM7 should compile and run their
38497a4f5023Sdrh ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
38507a4f5023Sdrh ** enabled, some asserts below will ensure that the byte order of
38517a4f5023Sdrh ** floating point values is correct.
385260d09a71Sdrh **
385360d09a71Sdrh ** (2007-08-30) Frank van Vugt has studied this problem closely
385460d09a71Sdrh ** and has send his findings to the SQLite developers. Frank
385560d09a71Sdrh ** writes that some Linux kernels offer floating point hardware
385660d09a71Sdrh ** emulation that uses only 32-bit mantissas instead of a full
385760d09a71Sdrh ** 48-bits as required by the IEEE standard. (This is the
385860d09a71Sdrh ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
385960d09a71Sdrh ** byte swapping becomes very complicated. To avoid problems,
386060d09a71Sdrh ** the necessary byte swapping is carried out using a 64-bit integer
386160d09a71Sdrh ** rather than a 64-bit float. Frank assures us that the code here
386260d09a71Sdrh ** works for him. We, the developers, have no way to independently
386360d09a71Sdrh ** verify this, but Frank seems to know what he is talking about
386460d09a71Sdrh ** so we trust him.
3865110daac9Sdrh */
3866110daac9Sdrh #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
sqlite3FloatSwap(u64 in)3867d859dc2bSdrh u64 sqlite3FloatSwap(u64 in){
3868110daac9Sdrh union {
386960d09a71Sdrh u64 r;
3870110daac9Sdrh u32 i[2];
3871110daac9Sdrh } u;
3872110daac9Sdrh u32 t;
3873110daac9Sdrh
3874110daac9Sdrh u.r = in;
3875110daac9Sdrh t = u.i[0];
3876110daac9Sdrh u.i[0] = u.i[1];
3877110daac9Sdrh u.i[1] = t;
3878110daac9Sdrh return u.r;
3879110daac9Sdrh }
3880d859dc2bSdrh #endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */
3881110daac9Sdrh
3882d946db00Sdrh
3883f926d1eaSdrh /* Input "x" is a sequence of unsigned characters that represent a
3884f926d1eaSdrh ** big-endian integer. Return the equivalent native integer
3885f926d1eaSdrh */
3886f926d1eaSdrh #define ONE_BYTE_INT(x) ((i8)(x)[0])
3887f926d1eaSdrh #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
3888f926d1eaSdrh #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
3889f926d1eaSdrh #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
38908932becbSdrh #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
3891f926d1eaSdrh
3892cfcdaefeSdanielk1977 /*
3893cfcdaefeSdanielk1977 ** Deserialize the data blob pointed to by buf as serial type serial_type
389406164b23Sdrh ** and store the result in pMem.
389514a924a5Sdrh **
389614a924a5Sdrh ** This function is implemented as two separate routines for performance.
389714a924a5Sdrh ** The few cases that require local variables are broken out into a separate
389814a924a5Sdrh ** routine so that in most cases the overhead of moving the stack pointer
389914a924a5Sdrh ** is avoided.
390090e4d95dSdanielk1977 */
serialGet(const unsigned char * buf,u32 serial_type,Mem * pMem)390106164b23Sdrh static void serialGet(
390293d4675dSdanielk1977 const unsigned char *buf, /* Buffer to deserialize from */
390325aa1b45Sdrh u32 serial_type, /* Serial type to deserialize */
390425aa1b45Sdrh Mem *pMem /* Memory cell to write value into */
3905b1bc9531Sdanielk1977 ){
39068932becbSdrh u64 x = FOUR_BYTE_UINT(buf);
39078932becbSdrh u32 y = FOUR_BYTE_UINT(buf+4);
39088932becbSdrh x = (x<<32) + y;
390914a924a5Sdrh if( serial_type==6 ){
3910654858d7Sdrh /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
3911654858d7Sdrh ** twos-complement integer. */
391214a924a5Sdrh pMem->u.i = *(i64*)&x;
391314a924a5Sdrh pMem->flags = MEM_Int;
391414a924a5Sdrh testcase( pMem->u.i<0 );
391514a924a5Sdrh }else{
3916654858d7Sdrh /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
3917654858d7Sdrh ** floating point number. */
391814a924a5Sdrh #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
391914a924a5Sdrh /* Verify that integers and floating point values use the same
392014a924a5Sdrh ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
392114a924a5Sdrh ** defined that 64-bit floating point values really are mixed
392214a924a5Sdrh ** endian.
392314a924a5Sdrh */
392414a924a5Sdrh static const u64 t1 = ((u64)0x3ff00000)<<32;
392514a924a5Sdrh static const double r1 = 1.0;
392614a924a5Sdrh u64 t2 = t1;
392714a924a5Sdrh swapMixedEndianFloat(t2);
392814a924a5Sdrh assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
392914a924a5Sdrh #endif
393074eaba4dSdrh assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
393114a924a5Sdrh swapMixedEndianFloat(x);
393274eaba4dSdrh memcpy(&pMem->u.r, &x, sizeof(x));
393305921223Sdrh pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
393414a924a5Sdrh }
393514a924a5Sdrh }
sqlite3VdbeSerialGet(const unsigned char * buf,u32 serial_type,Mem * pMem)393606164b23Sdrh void sqlite3VdbeSerialGet(
3937b1bc9531Sdanielk1977 const unsigned char *buf, /* Buffer to deserialize from */
3938b1bc9531Sdanielk1977 u32 serial_type, /* Serial type to deserialize */
3939b1bc9531Sdanielk1977 Mem *pMem /* Memory cell to write value into */
3940b1bc9531Sdanielk1977 ){
39413c685821Sdrh switch( serial_type ){
3942ce2fbd1bSdrh case 10: { /* Internal use only: NULL with virtual table
3943ce2fbd1bSdrh ** UPDATE no-change flag set */
3944ce2fbd1bSdrh pMem->flags = MEM_Null|MEM_Zero;
3945cdb60978Sdrh pMem->n = 0;
3946cdb60978Sdrh pMem->u.nZero = 0;
394706164b23Sdrh return;
3948ce2fbd1bSdrh }
39493c685821Sdrh case 11: /* Reserved for future use */
3950654858d7Sdrh case 0: { /* Null */
3951654858d7Sdrh /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
3952a19b775dSdrh pMem->flags = MEM_Null;
395306164b23Sdrh return;
3954a19b775dSdrh }
3955654858d7Sdrh case 1: {
3956654858d7Sdrh /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
3957654858d7Sdrh ** integer. */
3958f926d1eaSdrh pMem->u.i = ONE_BYTE_INT(buf);
3959e51c44f4Sdrh pMem->flags = MEM_Int;
3960b6e8fd10Sdrh testcase( pMem->u.i<0 );
396106164b23Sdrh return;
39623c685821Sdrh }
39633c685821Sdrh case 2: { /* 2-byte signed integer */
3964654858d7Sdrh /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
3965654858d7Sdrh ** twos-complement integer. */
3966f926d1eaSdrh pMem->u.i = TWO_BYTE_INT(buf);
39673c685821Sdrh pMem->flags = MEM_Int;
3968b6e8fd10Sdrh testcase( pMem->u.i<0 );
396906164b23Sdrh return;
39703c685821Sdrh }
39713c685821Sdrh case 3: { /* 3-byte signed integer */
3972654858d7Sdrh /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
3973654858d7Sdrh ** twos-complement integer. */
3974f926d1eaSdrh pMem->u.i = THREE_BYTE_INT(buf);
39753c685821Sdrh pMem->flags = MEM_Int;
3976b6e8fd10Sdrh testcase( pMem->u.i<0 );
397706164b23Sdrh return;
39783c685821Sdrh }
39793c685821Sdrh case 4: { /* 4-byte signed integer */
3980654858d7Sdrh /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
3981654858d7Sdrh ** twos-complement integer. */
39828932becbSdrh pMem->u.i = FOUR_BYTE_INT(buf);
3983c8bb430dSdrh #ifdef __HP_cc
3984c8bb430dSdrh /* Work around a sign-extension bug in the HP compiler for HP/UX */
3985c8bb430dSdrh if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
3986c8bb430dSdrh #endif
39873c685821Sdrh pMem->flags = MEM_Int;
3988b6e8fd10Sdrh testcase( pMem->u.i<0 );
398906164b23Sdrh return;
39903c685821Sdrh }
39913c685821Sdrh case 5: { /* 6-byte signed integer */
3992654858d7Sdrh /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
3993654858d7Sdrh ** twos-complement integer. */
3994f926d1eaSdrh pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
39953c685821Sdrh pMem->flags = MEM_Int;
3996b6e8fd10Sdrh testcase( pMem->u.i<0 );
399706164b23Sdrh return;
39983c685821Sdrh }
399991124b35Sdrh case 6: /* 8-byte signed integer */
40003c685821Sdrh case 7: { /* IEEE floating point */
40018932becbSdrh /* These use local variables, so do them in a separate routine
40028932becbSdrh ** to avoid having to move the frame pointer in the common case */
400306164b23Sdrh serialGet(buf,serial_type,pMem);
400406164b23Sdrh return;
4005e51c44f4Sdrh }
4006d946db00Sdrh case 8: /* Integer 0 */
4007d946db00Sdrh case 9: { /* Integer 1 */
4008654858d7Sdrh /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
4009654858d7Sdrh /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
40103c024d69Sdrh pMem->u.i = serial_type-8;
4011d946db00Sdrh pMem->flags = MEM_Int;
401206164b23Sdrh return;
4013d946db00Sdrh }
40143c685821Sdrh default: {
4015654858d7Sdrh /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
4016654858d7Sdrh ** length.
4017654858d7Sdrh ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
4018654858d7Sdrh ** (N-13)/2 bytes in length. */
4019c138dafeSdrh static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
402061de0d1bSdanielk1977 pMem->z = (char *)buf;
402114a924a5Sdrh pMem->n = (serial_type-12)/2;
4022c138dafeSdrh pMem->flags = aFlag[serial_type&1];
402306164b23Sdrh return;
4024192ac1dcSdanielk1977 }
40253c685821Sdrh }
402606164b23Sdrh return;
40273c685821Sdrh }
40281e968a0cSdrh /*
402903e9cfc2Sdan ** This routine is used to allocate sufficient space for an UnpackedRecord
403003e9cfc2Sdan ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
403103e9cfc2Sdan ** the first argument is a pointer to KeyInfo structure pKeyInfo.
40321e968a0cSdrh **
403303e9cfc2Sdan ** The space is either allocated using sqlite3DbMallocRaw() or from within
403403e9cfc2Sdan ** the unaligned buffer passed via the second and third arguments (presumably
403503e9cfc2Sdan ** stack space). If the former, then *ppFree is set to a pointer that should
403603e9cfc2Sdan ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
403703e9cfc2Sdan ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
403803e9cfc2Sdan ** before returning.
40391e968a0cSdrh **
404003e9cfc2Sdan ** If an OOM error occurs, NULL is returned.
40411e968a0cSdrh */
sqlite3VdbeAllocUnpackedRecord(KeyInfo * pKeyInfo)404203e9cfc2Sdan UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
4043a582b016Sdrh KeyInfo *pKeyInfo /* Description of the record */
40441e968a0cSdrh ){
404503e9cfc2Sdan UnpackedRecord *p; /* Unpacked record to return */
404603e9cfc2Sdan int nByte; /* Number of bytes required for *p */
4047cf6e3fd7Sdrh nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
404803e9cfc2Sdan p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
404942acb3e5Sdan if( !p ) return 0;
4050cf6e3fd7Sdrh p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
40516e11892dSdan assert( pKeyInfo->aSortFlags!=0 );
40521e968a0cSdrh p->pKeyInfo = pKeyInfo;
4053a485ad19Sdrh p->nField = pKeyInfo->nKeyField + 1;
405403e9cfc2Sdan return p;
405503e9cfc2Sdan }
405603e9cfc2Sdan
405703e9cfc2Sdan /*
405803e9cfc2Sdan ** Given the nKey-byte encoding of a record in pKey[], populate the
405903e9cfc2Sdan ** UnpackedRecord structure indicated by the fourth argument with the
406003e9cfc2Sdan ** contents of the decoded record.
406103e9cfc2Sdan */
sqlite3VdbeRecordUnpack(KeyInfo * pKeyInfo,int nKey,const void * pKey,UnpackedRecord * p)406203e9cfc2Sdan void sqlite3VdbeRecordUnpack(
406303e9cfc2Sdan KeyInfo *pKeyInfo, /* Information about the record format */
406403e9cfc2Sdan int nKey, /* Size of the binary record */
406503e9cfc2Sdan const void *pKey, /* The binary record */
406603e9cfc2Sdan UnpackedRecord *p /* Populate this structure before returning. */
406703e9cfc2Sdan ){
406803e9cfc2Sdan const unsigned char *aKey = (const unsigned char *)pKey;
4069936ade4dSdrh u32 d;
407003e9cfc2Sdan u32 idx; /* Offset in aKey[] to read from */
407103e9cfc2Sdan u16 u; /* Unsigned loop counter */
407203e9cfc2Sdan u32 szHdr;
407342acb3e5Sdan Mem *pMem = p->aMem;
407403e9cfc2Sdan
40751fed5dabSdan p->default_rc = 0;
40768c5d152bSdrh assert( EIGHT_BYTE_ALIGNMENT(pMem) );
40773f8d5cfcSshane idx = getVarint32(aKey, szHdr);
40781e968a0cSdrh d = szHdr;
40790b8d2766Sshane u = 0;
4080f69af053Sdrh while( idx<szHdr && d<=(u32)nKey ){
40811e968a0cSdrh u32 serial_type;
40821e968a0cSdrh
408300e13613Sdanielk1977 idx += getVarint32(&aKey[idx], serial_type);
40841e968a0cSdrh pMem->enc = pKeyInfo->enc;
40851e968a0cSdrh pMem->db = pKeyInfo->db;
4086c3f1d5f0Sdrh /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
408717bcb102Sdrh pMem->szMalloc = 0;
4088304637c0Sdrh pMem->z = 0;
408906164b23Sdrh sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
409006164b23Sdrh d += sqlite3VdbeSerialTypeLen(serial_type);
4091e14006d0Sdrh pMem++;
40927f4b19f1Sdrh if( (++u)>=p->nField ) break;
40931e968a0cSdrh }
4094f69af053Sdrh if( d>(u32)nKey && u ){
40954067ce7dSdrh assert( CORRUPT_DB );
40964067ce7dSdrh /* In a corrupt record entry, the last pMem might have been set up using
40974067ce7dSdrh ** uninitialized memory. Overwrite its value with NULL, to prevent
40984067ce7dSdrh ** warnings from MSAN. */
40994067ce7dSdrh sqlite3VdbeMemSetNull(pMem-1);
41004067ce7dSdrh }
4101a485ad19Sdrh assert( u<=pKeyInfo->nKeyField + 1 );
41020b8d2766Sshane p->nField = u;
41031e968a0cSdrh }
41041e968a0cSdrh
4105d879e3ebSdrh #ifdef SQLITE_DEBUG
41061e968a0cSdrh /*
41073833e934Sdan ** This function compares two index or table record keys in the same way
41083833e934Sdan ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
41093833e934Sdan ** this function deserializes and compares values using the
41103833e934Sdan ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
41113833e934Sdan ** in assert() statements to ensure that the optimized code in
41123833e934Sdan ** sqlite3VdbeRecordCompare() returns results with these two primitives.
411379211e19Sdrh **
411479211e19Sdrh ** Return true if the result of comparison is equivalent to desiredResult.
411579211e19Sdrh ** Return false if there is a disagreement.
41161e968a0cSdrh */
vdbeRecordCompareDebug(int nKey1,const void * pKey1,const UnpackedRecord * pPKey2,int desiredResult)41173833e934Sdan static int vdbeRecordCompareDebug(
4118ec1fc80cSdrh int nKey1, const void *pKey1, /* Left key */
411979211e19Sdrh const UnpackedRecord *pPKey2, /* Right key */
412079211e19Sdrh int desiredResult /* Correct answer */
41211e968a0cSdrh ){
4122df003d61Sdrh u32 d1; /* Offset into aKey[] of next data element */
41231e968a0cSdrh u32 idx1; /* Offset into aKey[] of next header element */
41241e968a0cSdrh u32 szHdr1; /* Number of bytes in header */
41251e968a0cSdrh int i = 0;
41261e968a0cSdrh int rc = 0;
41271e968a0cSdrh const unsigned char *aKey1 = (const unsigned char *)pKey1;
41281e968a0cSdrh KeyInfo *pKeyInfo;
41291e968a0cSdrh Mem mem1;
41301e968a0cSdrh
41311e968a0cSdrh pKeyInfo = pPKey2->pKeyInfo;
413284de690bSdrh if( pKeyInfo->db==0 ) return 1;
41331e968a0cSdrh mem1.enc = pKeyInfo->enc;
413437272633Sdrh mem1.db = pKeyInfo->db;
4135d93a8b27Sdrh /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
413617bcb102Sdrh VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
41378b249a88Sdrh
41388b249a88Sdrh /* Compilers may complain that mem1.u.i is potentially uninitialized.
41398b249a88Sdrh ** We could initialize it, as shown here, to silence those complaints.
41405275d2eeSdrh ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
41418b249a88Sdrh ** the unnecessary initialization has a measurable negative performance
41428b249a88Sdrh ** impact, since this routine is a very high runner. And so, we choose
41438b249a88Sdrh ** to ignore the compiler warnings and leave this variable uninitialized.
41448b249a88Sdrh */
41458b249a88Sdrh /* mem1.u.i = 0; // not needed, here to silence compiler warning */
41461e968a0cSdrh
41473f8d5cfcSshane idx1 = getVarint32(aKey1, szHdr1);
414846981365Sdrh if( szHdr1>98307 ) return SQLITE_CORRUPT;
41491e968a0cSdrh d1 = szHdr1;
4150a485ad19Sdrh assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
41516e11892dSdan assert( pKeyInfo->aSortFlags!=0 );
4152a485ad19Sdrh assert( pKeyInfo->nKeyField>0 );
415389bc0218Sdan assert( idx1<=szHdr1 || CORRUPT_DB );
41540b9dadacSdrh do{
41551e968a0cSdrh u32 serial_type1;
41561e968a0cSdrh
41571e968a0cSdrh /* Read the serial types for the next element in each key. */
41583f8d5cfcSshane idx1 += getVarint32( aKey1+idx1, serial_type1 );
4159af5b2af7Sdrh
4160af5b2af7Sdrh /* Verify that there is enough key space remaining to avoid
4161af5b2af7Sdrh ** a buffer overread. The "d1+serial_type1+2" subexpression will
4162af5b2af7Sdrh ** always be greater than or equal to the amount of required key space.
4163af5b2af7Sdrh ** Use that approximation to avoid the more expensive call to
4164af5b2af7Sdrh ** sqlite3VdbeSerialTypeLen() in the common case.
4165af5b2af7Sdrh */
4166a79bcf35Sdrh if( d1+(u64)serial_type1+2>(u64)nKey1
4167a79bcf35Sdrh && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
4168af5b2af7Sdrh ){
4169af5b2af7Sdrh break;
4170af5b2af7Sdrh }
41711e968a0cSdrh
41721e968a0cSdrh /* Extract the values to be compared.
41731e968a0cSdrh */
417406164b23Sdrh sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
417506164b23Sdrh d1 += sqlite3VdbeSerialTypeLen(serial_type1);
41761e968a0cSdrh
41771e968a0cSdrh /* Do the comparison
41781e968a0cSdrh */
41799b13365bSdrh rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
41809b13365bSdrh pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
41811e968a0cSdrh if( rc!=0 ){
418217bcb102Sdrh assert( mem1.szMalloc==0 ); /* See comment below */
41836e11892dSdan if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
41846e11892dSdan && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
41856e11892dSdan ){
41866e11892dSdan rc = -rc;
41876e11892dSdan }
41886e11892dSdan if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
41896f225d0dSdrh rc = -rc; /* Invert the result for DESC sort order. */
41908b249a88Sdrh }
419179211e19Sdrh goto debugCompareEnd;
41928b249a88Sdrh }
41938b249a88Sdrh i++;
41940b9dadacSdrh }while( idx1<szHdr1 && i<pPKey2->nField );
41958b249a88Sdrh
41968b249a88Sdrh /* No memory allocation is ever used on mem1. Prove this using
41978b249a88Sdrh ** the following assert(). If the assert() fails, it indicates a
41988b249a88Sdrh ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
41998b249a88Sdrh */
420017bcb102Sdrh assert( mem1.szMalloc==0 );
42018b249a88Sdrh
4202ec1fc80cSdrh /* rc==0 here means that one of the keys ran out of fields and
420360ec914cSpeter.d.reid ** all the fields up to that point were equal. Return the default_rc
42043b9330f8Sdan ** value. */
420579211e19Sdrh rc = pPKey2->default_rc;
420679211e19Sdrh
420779211e19Sdrh debugCompareEnd:
420879211e19Sdrh if( desiredResult==0 && rc==0 ) return 1;
420979211e19Sdrh if( desiredResult<0 && rc<0 ) return 1;
421079211e19Sdrh if( desiredResult>0 && rc>0 ) return 1;
421179211e19Sdrh if( CORRUPT_DB ) return 1;
421279211e19Sdrh if( pKeyInfo->db->mallocFailed ) return 1;
421379211e19Sdrh return 0;
42141fed5dabSdan }
42153833e934Sdan #endif
42161fed5dabSdan
4217d879e3ebSdrh #ifdef SQLITE_DEBUG
4218e1bb802cSdrh /*
4219e1bb802cSdrh ** Count the number of fields (a.k.a. columns) in the record given by
4220e1bb802cSdrh ** pKey,nKey. The verify that this count is less than or equal to the
4221a485ad19Sdrh ** limit given by pKeyInfo->nAllField.
4222e1bb802cSdrh **
4223e1bb802cSdrh ** If this constraint is not satisfied, it means that the high-speed
4224e1bb802cSdrh ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
4225e1bb802cSdrh ** not work correctly. If this assert() ever fires, it probably means
4226a485ad19Sdrh ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
4227e1bb802cSdrh ** incorrectly.
4228e1bb802cSdrh */
vdbeAssertFieldCountWithinLimits(int nKey,const void * pKey,const KeyInfo * pKeyInfo)4229e1bb802cSdrh static void vdbeAssertFieldCountWithinLimits(
4230e1bb802cSdrh int nKey, const void *pKey, /* The record to verify */
4231e1bb802cSdrh const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
4232e1bb802cSdrh ){
4233e1bb802cSdrh int nField = 0;
4234e1bb802cSdrh u32 szHdr;
4235e1bb802cSdrh u32 idx;
4236e1bb802cSdrh u32 notUsed;
4237e1bb802cSdrh const unsigned char *aKey = (const unsigned char*)pKey;
4238e1bb802cSdrh
4239e1bb802cSdrh if( CORRUPT_DB ) return;
4240e1bb802cSdrh idx = getVarint32(aKey, szHdr);
42411b3ee492Smistachkin assert( nKey>=0 );
42421b3ee492Smistachkin assert( szHdr<=(u32)nKey );
4243e1bb802cSdrh while( idx<szHdr ){
4244e1bb802cSdrh idx += getVarint32(aKey+idx, notUsed);
4245e1bb802cSdrh nField++;
4246e1bb802cSdrh }
4247a485ad19Sdrh assert( nField <= pKeyInfo->nAllField );
4248e1bb802cSdrh }
42491af3c64dSdrh #else
42501af3c64dSdrh # define vdbeAssertFieldCountWithinLimits(A,B,C)
4251e1bb802cSdrh #endif
4252e1bb802cSdrh
42533833e934Sdan /*
42543833e934Sdan ** Both *pMem1 and *pMem2 contain string values. Compare the two values
42553833e934Sdan ** using the collation sequence pColl. As usual, return a negative , zero
42563833e934Sdan ** or positive value if *pMem1 is less than, equal to or greater than
42573833e934Sdan ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
4258ec1fc80cSdrh */
vdbeCompareMemString(const Mem * pMem1,const Mem * pMem2,const CollSeq * pColl,u8 * prcErr)42591fed5dabSdan static int vdbeCompareMemString(
42601fed5dabSdan const Mem *pMem1,
42611fed5dabSdan const Mem *pMem2,
426238fdead8Sdan const CollSeq *pColl,
426338fdead8Sdan u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
42641fed5dabSdan ){
42651fed5dabSdan if( pMem1->enc==pColl->enc ){
42661fed5dabSdan /* The strings are already in the correct encoding. Call the
42671fed5dabSdan ** comparison function directly */
42681fed5dabSdan return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
42691fed5dabSdan }else{
42701fed5dabSdan int rc;
42711fed5dabSdan const void *v1, *v2;
42721fed5dabSdan Mem c1;
42731fed5dabSdan Mem c2;
427417bcb102Sdrh sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
427517bcb102Sdrh sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
42761fed5dabSdan sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
42771fed5dabSdan sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
42781fed5dabSdan v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
42791fed5dabSdan v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
428021766c0cSdan if( (v1==0 || v2==0) ){
428121766c0cSdan if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
428221766c0cSdan rc = 0;
428321766c0cSdan }else{
428421766c0cSdan rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
428521766c0cSdan }
4286fc854505Sdrh sqlite3VdbeMemReleaseMalloc(&c1);
4287fc854505Sdrh sqlite3VdbeMemReleaseMalloc(&c2);
42881fed5dabSdan return rc;
42891fed5dabSdan }
42901fed5dabSdan }
42911fed5dabSdan
42921fed5dabSdan /*
429364caee40Sdrh ** The input pBlob is guaranteed to be a Blob that is not marked
429464caee40Sdrh ** with MEM_Zero. Return true if it could be a zero-blob.
429564caee40Sdrh */
isAllZero(const char * z,int n)42968aaf7bccSdrh static int isAllZero(const char *z, int n){
429764caee40Sdrh int i;
42988aaf7bccSdrh for(i=0; i<n; i++){
42998aaf7bccSdrh if( z[i] ) return 0;
43008aaf7bccSdrh }
43018aaf7bccSdrh return 1;
430264caee40Sdrh }
430364caee40Sdrh
430464caee40Sdrh /*
4305982ff72fSdrh ** Compare two blobs. Return negative, zero, or positive if the first
4306982ff72fSdrh ** is less than, equal to, or greater than the second, respectively.
4307982ff72fSdrh ** If one blob is a prefix of the other, then the shorter is the lessor.
4308982ff72fSdrh */
sqlite3BlobCompare(const Mem * pB1,const Mem * pB2)43098d7b212cSdrh SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
431064caee40Sdrh int c;
431164caee40Sdrh int n1 = pB1->n;
431264caee40Sdrh int n2 = pB2->n;
431364caee40Sdrh
431464caee40Sdrh /* It is possible to have a Blob value that has some non-zero content
431564caee40Sdrh ** followed by zero content. But that only comes up for Blobs formed
431664caee40Sdrh ** by the OP_MakeRecord opcode, and such Blobs never get passed into
431764caee40Sdrh ** sqlite3MemCompare(). */
431864caee40Sdrh assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
431964caee40Sdrh assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
432064caee40Sdrh
432164caee40Sdrh if( (pB1->flags|pB2->flags) & MEM_Zero ){
432264caee40Sdrh if( pB1->flags & pB2->flags & MEM_Zero ){
432364caee40Sdrh return pB1->u.nZero - pB2->u.nZero;
432464caee40Sdrh }else if( pB1->flags & MEM_Zero ){
43258aaf7bccSdrh if( !isAllZero(pB2->z, pB2->n) ) return -1;
432664caee40Sdrh return pB1->u.nZero - n2;
432764caee40Sdrh }else{
43288aaf7bccSdrh if( !isAllZero(pB1->z, pB1->n) ) return +1;
432964caee40Sdrh return n1 - pB2->u.nZero;
433064caee40Sdrh }
433164caee40Sdrh }
433264caee40Sdrh c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
4333982ff72fSdrh if( c ) return c;
433464caee40Sdrh return n1 - n2;
4335982ff72fSdrh }
4336982ff72fSdrh
43372ab410aaSdrh /*
43382ab410aaSdrh ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
43392ab410aaSdrh ** number. Return negative, zero, or positive if the first (i64) is less than,
43402ab410aaSdrh ** equal to, or greater than the second (double).
43412ab410aaSdrh */
sqlite3IntFloatCompare(i64 i,double r)4342de324617Sdrh int sqlite3IntFloatCompare(i64 i, double r){
43432ab410aaSdrh if( sizeof(LONGDOUBLE_TYPE)>8 ){
43442ab410aaSdrh LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
4345de9873bbSdrh testcase( x<r );
4346de9873bbSdrh testcase( x>r );
4347de9873bbSdrh testcase( x==r );
43482ab410aaSdrh if( x<r ) return -1;
4349de9873bbSdrh if( x>r ) return +1; /*NO_TEST*/ /* work around bugs in gcov */
4350de9873bbSdrh return 0; /*NO_TEST*/ /* work around bugs in gcov */
43512ab410aaSdrh }else{
43522ab410aaSdrh i64 y;
43532ab410aaSdrh double s;
43542ab410aaSdrh if( r<-9223372036854775808.0 ) return +1;
43556c319e12Sdrh if( r>=9223372036854775808.0 ) return -1;
43562ab410aaSdrh y = (i64)r;
43572ab410aaSdrh if( i<y ) return -1;
43586c319e12Sdrh if( i>y ) return +1;
43592ab410aaSdrh s = (double)i;
43602ab410aaSdrh if( s<r ) return -1;
43618d1751b6Sdrh if( s>r ) return +1;
43622ab410aaSdrh return 0;
43632ab410aaSdrh }
43642ab410aaSdrh }
4365982ff72fSdrh
4366982ff72fSdrh /*
43671fed5dabSdan ** Compare the values contained by the two memory cells, returning
43681fed5dabSdan ** negative, zero or positive if pMem1 is less than, equal to, or greater
43691fed5dabSdan ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
43701fed5dabSdan ** and reals) sorted numerically, followed by text ordered by the collating
43711fed5dabSdan ** sequence pColl and finally blob's ordered by memcmp().
43721fed5dabSdan **
43731fed5dabSdan ** Two NULL values are considered equal by this function.
43741fed5dabSdan */
sqlite3MemCompare(const Mem * pMem1,const Mem * pMem2,const CollSeq * pColl)43751fed5dabSdan int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
43761fed5dabSdan int f1, f2;
43771fed5dabSdan int combined_flags;
43781fed5dabSdan
43791fed5dabSdan f1 = pMem1->flags;
43801fed5dabSdan f2 = pMem2->flags;
43811fed5dabSdan combined_flags = f1|f2;
43829d67afc4Sdrh assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
43831fed5dabSdan
43841fed5dabSdan /* If one value is NULL, it is less than the other. If both values
43851fed5dabSdan ** are NULL, return 0.
43861fed5dabSdan */
43871fed5dabSdan if( combined_flags&MEM_Null ){
43881fed5dabSdan return (f2&MEM_Null) - (f1&MEM_Null);
43891fed5dabSdan }
43901fed5dabSdan
43912ab410aaSdrh /* At least one of the two values is a number
43921fed5dabSdan */
4393169f077eSdrh if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
43943242c69cSdrh testcase( combined_flags & MEM_Int );
43953242c69cSdrh testcase( combined_flags & MEM_Real );
43963242c69cSdrh testcase( combined_flags & MEM_IntReal );
4397169f077eSdrh if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
43983242c69cSdrh testcase( f1 & f2 & MEM_Int );
43993242c69cSdrh testcase( f1 & f2 & MEM_IntReal );
44001fed5dabSdan if( pMem1->u.i < pMem2->u.i ) return -1;
44012ab410aaSdrh if( pMem1->u.i > pMem2->u.i ) return +1;
44021fed5dabSdan return 0;
44031fed5dabSdan }
44042ab410aaSdrh if( (f1 & f2 & MEM_Real)!=0 ){
44052ab410aaSdrh if( pMem1->u.r < pMem2->u.r ) return -1;
44062ab410aaSdrh if( pMem1->u.r > pMem2->u.r ) return +1;
44072ab410aaSdrh return 0;
44081fed5dabSdan }
4409169f077eSdrh if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
44103242c69cSdrh testcase( f1 & MEM_Int );
44113242c69cSdrh testcase( f1 & MEM_IntReal );
44121fed5dabSdan if( (f2&MEM_Real)!=0 ){
44132ab410aaSdrh return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
4414169f077eSdrh }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
4415169f077eSdrh if( pMem1->u.i < pMem2->u.i ) return -1;
4416169f077eSdrh if( pMem1->u.i > pMem2->u.i ) return +1;
4417169f077eSdrh return 0;
44181fed5dabSdan }else{
44191fed5dabSdan return -1;
44201fed5dabSdan }
44212ab410aaSdrh }
44222ab410aaSdrh if( (f1&MEM_Real)!=0 ){
4423169f077eSdrh if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
44243242c69cSdrh testcase( f2 & MEM_Int );
44253242c69cSdrh testcase( f2 & MEM_IntReal );
44262ab410aaSdrh return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
44272ab410aaSdrh }else{
44282ab410aaSdrh return -1;
44292ab410aaSdrh }
44302ab410aaSdrh }
44312ab410aaSdrh return +1;
44321fed5dabSdan }
44331fed5dabSdan
44341fed5dabSdan /* If one value is a string and the other is a blob, the string is less.
44351fed5dabSdan ** If both are strings, compare using the collating functions.
44361fed5dabSdan */
44371fed5dabSdan if( combined_flags&MEM_Str ){
44381fed5dabSdan if( (f1 & MEM_Str)==0 ){
44391fed5dabSdan return 1;
44401fed5dabSdan }
44411fed5dabSdan if( (f2 & MEM_Str)==0 ){
44421fed5dabSdan return -1;
44431fed5dabSdan }
44441fed5dabSdan
4445e5520e2fSdrh assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
44461fed5dabSdan assert( pMem1->enc==SQLITE_UTF8 ||
44471fed5dabSdan pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
44481fed5dabSdan
44491fed5dabSdan /* The collation sequence must be defined at this point, even if
44501fed5dabSdan ** the user deletes the collation sequence after the vdbe program is
44511fed5dabSdan ** compiled (this was not always the case).
44521fed5dabSdan */
44531fed5dabSdan assert( !pColl || pColl->xCmp );
44541fed5dabSdan
44551fed5dabSdan if( pColl ){
445638fdead8Sdan return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
44571fed5dabSdan }
44581fed5dabSdan /* If a NULL pointer was passed as the collate function, fall through
44591fed5dabSdan ** to the blob case and use memcmp(). */
44601fed5dabSdan }
44611fed5dabSdan
44621fed5dabSdan /* Both values must be blobs. Compare using memcmp(). */
4463982ff72fSdrh return sqlite3BlobCompare(pMem1, pMem2);
44641e968a0cSdrh }
4465eb015e03Sdanielk1977
4466eb015e03Sdanielk1977
4467eb015e03Sdanielk1977 /*
44683833e934Sdan ** The first argument passed to this function is a serial-type that
44693833e934Sdan ** corresponds to an integer - all values between 1 and 9 inclusive
44703833e934Sdan ** except 7. The second points to a buffer containing an integer value
44713833e934Sdan ** serialized according to serial_type. This function deserializes
44723833e934Sdan ** and returns the value.
44733833e934Sdan */
vdbeRecordDecodeInt(u32 serial_type,const u8 * aKey)44743b9330f8Sdan static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
4475f926d1eaSdrh u32 y;
44763833e934Sdan assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
44773b9330f8Sdan switch( serial_type ){
44783833e934Sdan case 0:
44793b9330f8Sdan case 1:
4480b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4481f926d1eaSdrh return ONE_BYTE_INT(aKey);
44823b9330f8Sdan case 2:
4483b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4484f926d1eaSdrh return TWO_BYTE_INT(aKey);
44853b9330f8Sdan case 3:
4486b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4487f926d1eaSdrh return THREE_BYTE_INT(aKey);
4488f926d1eaSdrh case 4: {
4489b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4490f926d1eaSdrh y = FOUR_BYTE_UINT(aKey);
4491f926d1eaSdrh return (i64)*(int*)&y;
4492f926d1eaSdrh }
44933b9330f8Sdan case 5: {
4494b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4495f926d1eaSdrh return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
44963b9330f8Sdan }
44973b9330f8Sdan case 6: {
4498f926d1eaSdrh u64 x = FOUR_BYTE_UINT(aKey);
4499b6e8fd10Sdrh testcase( aKey[0]&0x80 );
4500f926d1eaSdrh x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4501f926d1eaSdrh return (i64)*(i64*)&x;
45023b9330f8Sdan }
45033b9330f8Sdan }
45043b9330f8Sdan
45053b9330f8Sdan return (serial_type - 8);
45063b9330f8Sdan }
45073b9330f8Sdan
45083833e934Sdan /*
45093833e934Sdan ** This function compares the two table rows or index records
45103833e934Sdan ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
45113833e934Sdan ** or positive integer if key1 is less than, equal to or
45123833e934Sdan ** greater than key2. The {nKey1, pKey1} key must be a blob
451360ec914cSpeter.d.reid ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
45143833e934Sdan ** key must be a parsed key such as obtained from
45153833e934Sdan ** sqlite3VdbeParseRecord.
45163833e934Sdan **
45173833e934Sdan ** If argument bSkip is non-zero, it is assumed that the caller has already
45183833e934Sdan ** determined that the first fields of the keys are equal.
45193833e934Sdan **
45203833e934Sdan ** Key1 and Key2 do not have to contain the same number of fields. If all
45213833e934Sdan ** fields that appear in both keys are equal, then pPKey2->default_rc is
45223833e934Sdan ** returned.
4523a1f7c0a2Sdrh **
452438fdead8Sdan ** If database corruption is discovered, set pPKey2->errCode to
452538fdead8Sdan ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
452638fdead8Sdan ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
452738fdead8Sdan ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
45283833e934Sdan */
sqlite3VdbeRecordCompareWithSkip(int nKey1,const void * pKey1,UnpackedRecord * pPKey2,int bSkip)45297004f3f6Sdan int sqlite3VdbeRecordCompareWithSkip(
4530183f9f73Sdanielk1977 int nKey1, const void *pKey1, /* Left key */
4531a1f7c0a2Sdrh UnpackedRecord *pPKey2, /* Right key */
45323833e934Sdan int bSkip /* If true, skip the first field */
4533183f9f73Sdanielk1977 ){
45343833e934Sdan u32 d1; /* Offset into aKey[] of next data element */
45353833e934Sdan int i; /* Index of next field to compare */
4536ffe6bc2bSmistachkin u32 szHdr1; /* Size of record header in bytes */
45373833e934Sdan u32 idx1; /* Offset of first type in header */
45383833e934Sdan int rc = 0; /* Return value */
45393833e934Sdan Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
45406eb3480bSdrh KeyInfo *pKeyInfo;
45411fed5dabSdan const unsigned char *aKey1 = (const unsigned char *)pKey1;
45421fed5dabSdan Mem mem1;
45431fed5dabSdan
45443833e934Sdan /* If bSkip is true, then the caller has already determined that the first
45453833e934Sdan ** two elements in the keys are equal. Fix the various stack variables so
45463b9330f8Sdan ** that this routine begins comparing at the second field. */
45473833e934Sdan if( bSkip ){
4548c2808f39Sdrh u32 s1 = aKey1[1];
4549c2808f39Sdrh if( s1<0x80 ){
4550c2808f39Sdrh idx1 = 2;
4551c2808f39Sdrh }else{
4552c2808f39Sdrh idx1 = 1 + sqlite3GetVarint32(&aKey1[1], &s1);
4553c2808f39Sdrh }
45543833e934Sdan szHdr1 = aKey1[0];
45553833e934Sdan d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
45563b9330f8Sdan i = 1;
45573b9330f8Sdan pRhs++;
45583833e934Sdan }else{
4559c2808f39Sdrh if( (szHdr1 = aKey1[0])<0x80 ){
4560c2808f39Sdrh idx1 = 1;
4561c2808f39Sdrh }else{
4562c2808f39Sdrh idx1 = sqlite3GetVarint32(aKey1, &szHdr1);
4563c2808f39Sdrh }
45643833e934Sdan d1 = szHdr1;
45652a58dbdeSdrh i = 0;
45662a58dbdeSdrh }
4567a1f7c0a2Sdrh if( d1>(unsigned)nKey1 ){
456838fdead8Sdan pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4569a1f7c0a2Sdrh return 0; /* Corruption */
4570a1f7c0a2Sdrh }
45711fed5dabSdan
457217bcb102Sdrh VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
4573a485ad19Sdrh assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
45741fed5dabSdan || CORRUPT_DB );
45756e11892dSdan assert( pPKey2->pKeyInfo->aSortFlags!=0 );
4576a485ad19Sdrh assert( pPKey2->pKeyInfo->nKeyField>0 );
45771fed5dabSdan assert( idx1<=szHdr1 || CORRUPT_DB );
4578*093677adSdrh while( 1 /*exit-by-break*/ ){
45791fed5dabSdan u32 serial_type;
45801fed5dabSdan
45811fed5dabSdan /* RHS is an integer */
4582169f077eSdrh if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
45833242c69cSdrh testcase( pRhs->flags & MEM_Int );
45843242c69cSdrh testcase( pRhs->flags & MEM_IntReal );
45851fed5dabSdan serial_type = aKey1[idx1];
4586b6e8fd10Sdrh testcase( serial_type==12 );
4587b95e1193Sdan if( serial_type>=10 ){
45880e522c06Sdrh rc = serial_type==10 ? -1 : +1;
45891fed5dabSdan }else if( serial_type==0 ){
45901fed5dabSdan rc = -1;
45913b9330f8Sdan }else if( serial_type==7 ){
45923b9330f8Sdan sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
45932ab410aaSdrh rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
45941fed5dabSdan }else{
45953b9330f8Sdan i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
45961fed5dabSdan i64 rhs = pRhs->u.i;
45973b9330f8Sdan if( lhs<rhs ){
45981fed5dabSdan rc = -1;
45993b9330f8Sdan }else if( lhs>rhs ){
46001fed5dabSdan rc = +1;
46011fed5dabSdan }
46021fed5dabSdan }
46031fed5dabSdan }
46041fed5dabSdan
46051fed5dabSdan /* RHS is real */
46061fed5dabSdan else if( pRhs->flags & MEM_Real ){
46071fed5dabSdan serial_type = aKey1[idx1];
4608cc7aa1f6Sdan if( serial_type>=10 ){
4609cc7aa1f6Sdan /* Serial types 12 or greater are strings and blobs (greater than
4610cc7aa1f6Sdan ** numbers). Types 10 and 11 are currently "reserved for future
4611cc7aa1f6Sdan ** use", so it doesn't really matter what the results of comparing
4612cc7aa1f6Sdan ** them to numberic values are. */
46130e522c06Sdrh rc = serial_type==10 ? -1 : +1;
46141fed5dabSdan }else if( serial_type==0 ){
46151fed5dabSdan rc = -1;
46161fed5dabSdan }else{
46171fed5dabSdan sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
46181fed5dabSdan if( serial_type==7 ){
46192ab410aaSdrh if( mem1.u.r<pRhs->u.r ){
46201fed5dabSdan rc = -1;
46212ab410aaSdrh }else if( mem1.u.r>pRhs->u.r ){
46221fed5dabSdan rc = +1;
46231fed5dabSdan }
46242ab410aaSdrh }else{
46252ab410aaSdrh rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
46262ab410aaSdrh }
46271fed5dabSdan }
46281fed5dabSdan }
46291fed5dabSdan
46301fed5dabSdan /* RHS is a string */
46311fed5dabSdan else if( pRhs->flags & MEM_Str ){
463202a95eb9Sdrh getVarint32NR(&aKey1[idx1], serial_type);
4633b6e8fd10Sdrh testcase( serial_type==12 );
46341fed5dabSdan if( serial_type<12 ){
46351fed5dabSdan rc = -1;
46361fed5dabSdan }else if( !(serial_type & 0x01) ){
46371fed5dabSdan rc = +1;
46381fed5dabSdan }else{
46391fed5dabSdan mem1.n = (serial_type - 12) / 2;
4640b6e8fd10Sdrh testcase( (d1+mem1.n)==(unsigned)nKey1 );
4641b6e8fd10Sdrh testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
46429b13365bSdrh if( (d1+mem1.n) > (unsigned)nKey1
46439b13365bSdrh || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
46449b13365bSdrh ){
464538fdead8Sdan pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4646a1f7c0a2Sdrh return 0; /* Corruption */
46479b13365bSdrh }else if( pKeyInfo->aColl[i] ){
46481fed5dabSdan mem1.enc = pKeyInfo->enc;
46491fed5dabSdan mem1.db = pKeyInfo->db;
46501fed5dabSdan mem1.flags = MEM_Str;
4651fcb44a89Sdrh mem1.z = (char*)&aKey1[d1];
465238fdead8Sdan rc = vdbeCompareMemString(
465338fdead8Sdan &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
465438fdead8Sdan );
46551fed5dabSdan }else{
46561fed5dabSdan int nCmp = MIN(mem1.n, pRhs->n);
46571fed5dabSdan rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
46581fed5dabSdan if( rc==0 ) rc = mem1.n - pRhs->n;
46591fed5dabSdan }
46601fed5dabSdan }
46611fed5dabSdan }
46621fed5dabSdan
46631fed5dabSdan /* RHS is a blob */
46641fed5dabSdan else if( pRhs->flags & MEM_Blob ){
46658aaf7bccSdrh assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
466602a95eb9Sdrh getVarint32NR(&aKey1[idx1], serial_type);
4667b6e8fd10Sdrh testcase( serial_type==12 );
46681fed5dabSdan if( serial_type<12 || (serial_type & 0x01) ){
46691fed5dabSdan rc = -1;
46701fed5dabSdan }else{
46711fed5dabSdan int nStr = (serial_type - 12) / 2;
4672b6e8fd10Sdrh testcase( (d1+nStr)==(unsigned)nKey1 );
4673b6e8fd10Sdrh testcase( (d1+nStr+1)==(unsigned)nKey1 );
4674295aedf0Sdrh if( (d1+nStr) > (unsigned)nKey1 ){
467538fdead8Sdan pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4676a1f7c0a2Sdrh return 0; /* Corruption */
46778aaf7bccSdrh }else if( pRhs->flags & MEM_Zero ){
46788aaf7bccSdrh if( !isAllZero((const char*)&aKey1[d1],nStr) ){
46798aaf7bccSdrh rc = 1;
46808aaf7bccSdrh }else{
46818aaf7bccSdrh rc = nStr - pRhs->u.nZero;
46828aaf7bccSdrh }
46831fed5dabSdan }else{
46841fed5dabSdan int nCmp = MIN(nStr, pRhs->n);
46851fed5dabSdan rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
46861fed5dabSdan if( rc==0 ) rc = nStr - pRhs->n;
46871fed5dabSdan }
46881fed5dabSdan }
46891fed5dabSdan }
46901fed5dabSdan
46911fed5dabSdan /* RHS is null */
46921fed5dabSdan else{
46931fed5dabSdan serial_type = aKey1[idx1];
469443fce6bbSdrh rc = (serial_type!=0 && serial_type!=10);
46951fed5dabSdan }
46961fed5dabSdan
46971fed5dabSdan if( rc!=0 ){
46986e11892dSdan int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
46996e11892dSdan if( sortFlags ){
47006e11892dSdan if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
47016e11892dSdan || ((sortFlags & KEYINFO_ORDER_DESC)
47026e11892dSdan !=(serial_type==0 || (pRhs->flags&MEM_Null)))
47036e11892dSdan ){
47041fed5dabSdan rc = -rc;
47051fed5dabSdan }
47066e11892dSdan }
470779211e19Sdrh assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
470817bcb102Sdrh assert( mem1.szMalloc==0 ); /* See comment below */
4709183f9f73Sdanielk1977 return rc;
4710183f9f73Sdanielk1977 }
4711183f9f73Sdanielk1977
47121fed5dabSdan i++;
4713d882108aSdrh if( i==pPKey2->nField ) break;
47143b9330f8Sdan pRhs++;
47151fed5dabSdan d1 += sqlite3VdbeSerialTypeLen(serial_type);
4716*093677adSdrh if( d1>(unsigned)nKey1 ) break;
47171fed5dabSdan idx1 += sqlite3VarintLen(serial_type);
4718*093677adSdrh if( idx1>=(unsigned)szHdr1 ){
4719*093677adSdrh pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4720*093677adSdrh return 0; /* Corrupt index */
4721*093677adSdrh }
4722*093677adSdrh }
47231fed5dabSdan
47241fed5dabSdan /* No memory allocation is ever used on mem1. Prove this using
47251fed5dabSdan ** the following assert(). If the assert() fails, it indicates a
47263833e934Sdan ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
472717bcb102Sdrh assert( mem1.szMalloc==0 );
47281fed5dabSdan
47291fed5dabSdan /* rc==0 here means that one or both of the keys ran out of fields and
473060ec914cSpeter.d.reid ** all the fields up to that point were equal. Return the default_rc
47311fed5dabSdan ** value. */
47323833e934Sdan assert( CORRUPT_DB
473366141816Sdrh || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
47346eb3480bSdrh || pPKey2->pKeyInfo->db->mallocFailed
47353833e934Sdan );
473670528d78Sdrh pPKey2->eqSeen = 1;
47371fed5dabSdan return pPKey2->default_rc;
47381fed5dabSdan }
sqlite3VdbeRecordCompare(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)473975179dedSdrh int sqlite3VdbeRecordCompare(
474075179dedSdrh int nKey1, const void *pKey1, /* Left key */
474175179dedSdrh UnpackedRecord *pPKey2 /* Right key */
474275179dedSdrh ){
47437004f3f6Sdan return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
474475179dedSdrh }
474575179dedSdrh
47461fed5dabSdan
47473833e934Sdan /*
47483833e934Sdan ** This function is an optimized version of sqlite3VdbeRecordCompare()
47493833e934Sdan ** that (a) the first field of pPKey2 is an integer, and (b) the
47503833e934Sdan ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
47513833e934Sdan ** byte (i.e. is less than 128).
4752e2ac5067Sdrh **
4753e2ac5067Sdrh ** To avoid concerns about buffer overreads, this routine is only used
4754e2ac5067Sdrh ** on schemas where the maximum valid header size is 63 bytes or less.
47553833e934Sdan */
vdbeRecordCompareInt(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)47563b9330f8Sdan static int vdbeRecordCompareInt(
47573b9330f8Sdan int nKey1, const void *pKey1, /* Left key */
475875179dedSdrh UnpackedRecord *pPKey2 /* Right key */
47593b9330f8Sdan ){
47609b8afef2Sdan const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
47613b9330f8Sdan int serial_type = ((const u8*)pKey1)[1];
47623b9330f8Sdan int res;
4763f926d1eaSdrh u32 y;
4764f926d1eaSdrh u64 x;
47655f6eb1a0Sdrh i64 v;
47663b9330f8Sdan i64 lhs;
47673b9330f8Sdan
4768e1bb802cSdrh vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4769e2ac5067Sdrh assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
47703833e934Sdan switch( serial_type ){
4771f926d1eaSdrh case 1: { /* 1-byte signed integer */
4772f926d1eaSdrh lhs = ONE_BYTE_INT(aKey);
4773b6e8fd10Sdrh testcase( lhs<0 );
47743b9330f8Sdan break;
47753b9330f8Sdan }
4776f926d1eaSdrh case 2: { /* 2-byte signed integer */
4777f926d1eaSdrh lhs = TWO_BYTE_INT(aKey);
4778b6e8fd10Sdrh testcase( lhs<0 );
4779f926d1eaSdrh break;
4780f926d1eaSdrh }
4781f926d1eaSdrh case 3: { /* 3-byte signed integer */
4782f926d1eaSdrh lhs = THREE_BYTE_INT(aKey);
4783b6e8fd10Sdrh testcase( lhs<0 );
4784f926d1eaSdrh break;
4785f926d1eaSdrh }
4786f926d1eaSdrh case 4: { /* 4-byte signed integer */
4787f926d1eaSdrh y = FOUR_BYTE_UINT(aKey);
4788f926d1eaSdrh lhs = (i64)*(int*)&y;
4789b6e8fd10Sdrh testcase( lhs<0 );
4790f926d1eaSdrh break;
4791f926d1eaSdrh }
4792f926d1eaSdrh case 5: { /* 6-byte signed integer */
4793f926d1eaSdrh lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
4794b6e8fd10Sdrh testcase( lhs<0 );
4795f926d1eaSdrh break;
4796f926d1eaSdrh }
4797f926d1eaSdrh case 6: { /* 8-byte signed integer */
4798f926d1eaSdrh x = FOUR_BYTE_UINT(aKey);
4799f926d1eaSdrh x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
4800f926d1eaSdrh lhs = *(i64*)&x;
4801b6e8fd10Sdrh testcase( lhs<0 );
48023b9330f8Sdan break;
48033b9330f8Sdan }
48043b9330f8Sdan case 8:
48053b9330f8Sdan lhs = 0;
48063b9330f8Sdan break;
48073b9330f8Sdan case 9:
48083b9330f8Sdan lhs = 1;
48093b9330f8Sdan break;
48103b9330f8Sdan
4811063d4a04Sdan /* This case could be removed without changing the results of running
4812063d4a04Sdan ** this code. Including it causes gcc to generate a faster switch
4813063d4a04Sdan ** statement (since the range of switch targets now starts at zero and
4814597515d7Sdan ** is contiguous) but does not cause any duplicate code to be generated
4815063d4a04Sdan ** (as gcc is clever enough to combine the two like cases). Other
4816063d4a04Sdan ** compilers might be similar. */
4817063d4a04Sdan case 0: case 7:
481875179dedSdrh return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
4819063d4a04Sdan
48203b9330f8Sdan default:
482175179dedSdrh return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
48223b9330f8Sdan }
48233b9330f8Sdan
4824f357cafaSdrh assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
4825f357cafaSdrh v = pPKey2->u.i;
48263b9330f8Sdan if( v>lhs ){
48273b9330f8Sdan res = pPKey2->r1;
48283b9330f8Sdan }else if( v<lhs ){
48293b9330f8Sdan res = pPKey2->r2;
48303b9330f8Sdan }else if( pPKey2->nField>1 ){
4831063d4a04Sdan /* The first fields of the two keys are equal. Compare the trailing
4832063d4a04Sdan ** fields. */
48337004f3f6Sdan res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
48343b9330f8Sdan }else{
4835063d4a04Sdan /* The first fields of the two keys are equal and there are no trailing
4836063d4a04Sdan ** fields. Return pPKey2->default_rc in this case. */
48373b9330f8Sdan res = pPKey2->default_rc;
483870528d78Sdrh pPKey2->eqSeen = 1;
48393b9330f8Sdan }
48403b9330f8Sdan
484179211e19Sdrh assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
48423b9330f8Sdan return res;
48433b9330f8Sdan }
48443b9330f8Sdan
48453833e934Sdan /*
48463833e934Sdan ** This function is an optimized version of sqlite3VdbeRecordCompare()
48473833e934Sdan ** that (a) the first field of pPKey2 is a string, that (b) the first field
48483833e934Sdan ** uses the collation sequence BINARY and (c) that the size-of-header varint
48493833e934Sdan ** at the start of (pKey1/nKey1) fits in a single byte.
48503833e934Sdan */
vdbeRecordCompareString(int nKey1,const void * pKey1,UnpackedRecord * pPKey2)48513b9330f8Sdan static int vdbeRecordCompareString(
48523b9330f8Sdan int nKey1, const void *pKey1, /* Left key */
485375179dedSdrh UnpackedRecord *pPKey2 /* Right key */
48543b9330f8Sdan ){
48553b9330f8Sdan const u8 *aKey1 = (const u8*)pKey1;
48563b9330f8Sdan int serial_type;
48573b9330f8Sdan int res;
48583b9330f8Sdan
48592ab410aaSdrh assert( pPKey2->aMem[0].flags & MEM_Str );
4860f357cafaSdrh assert( pPKey2->aMem[0].n == pPKey2->n );
4861f357cafaSdrh assert( pPKey2->aMem[0].z == pPKey2->u.z );
4862e1bb802cSdrh vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
4863a1e951faSdrh serial_type = (signed char)(aKey1[1]);
4864a1e951faSdrh
4865a1e951faSdrh vrcs_restart:
48663b9330f8Sdan if( serial_type<12 ){
4867a1e951faSdrh if( serial_type<0 ){
4868a1e951faSdrh sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
4869a1e951faSdrh if( serial_type>=12 ) goto vrcs_restart;
4870a1e951faSdrh assert( CORRUPT_DB );
4871a1e951faSdrh }
48723b9330f8Sdan res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
48733b9330f8Sdan }else if( !(serial_type & 0x01) ){
48743b9330f8Sdan res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
48753b9330f8Sdan }else{
48763b9330f8Sdan int nCmp;
48773b9330f8Sdan int nStr;
48783833e934Sdan int szHdr = aKey1[0];
48793b9330f8Sdan
48803b9330f8Sdan nStr = (serial_type-12) / 2;
4881a1f7c0a2Sdrh if( (szHdr + nStr) > nKey1 ){
488238fdead8Sdan pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
4883a1f7c0a2Sdrh return 0; /* Corruption */
4884a1f7c0a2Sdrh }
4885f357cafaSdrh nCmp = MIN( pPKey2->n, nStr );
4886f357cafaSdrh res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
48873b9330f8Sdan
488852d9a3c2Sdan if( res>0 ){
488952d9a3c2Sdan res = pPKey2->r2;
489052d9a3c2Sdan }else if( res<0 ){
489152d9a3c2Sdan res = pPKey2->r1;
489252d9a3c2Sdan }else{
4893f357cafaSdrh res = nStr - pPKey2->n;
48943b9330f8Sdan if( res==0 ){
48953b9330f8Sdan if( pPKey2->nField>1 ){
48967004f3f6Sdan res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
48973b9330f8Sdan }else{
48983b9330f8Sdan res = pPKey2->default_rc;
489970528d78Sdrh pPKey2->eqSeen = 1;
49003b9330f8Sdan }
49013b9330f8Sdan }else if( res>0 ){
49023b9330f8Sdan res = pPKey2->r2;
49033b9330f8Sdan }else{
49043b9330f8Sdan res = pPKey2->r1;
49053b9330f8Sdan }
49063b9330f8Sdan }
49073b9330f8Sdan }
49083b9330f8Sdan
490966141816Sdrh assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
49103b9330f8Sdan || CORRUPT_DB
49116696ba3eSdan || pPKey2->pKeyInfo->db->mallocFailed
49123b9330f8Sdan );
49133b9330f8Sdan return res;
49143b9330f8Sdan }
49153b9330f8Sdan
49163833e934Sdan /*
49173833e934Sdan ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
49183833e934Sdan ** suitable for comparing serialized records to the unpacked record passed
49193833e934Sdan ** as the only argument.
49203833e934Sdan */
sqlite3VdbeFindCompare(UnpackedRecord * p)49211fed5dabSdan RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
49229b8afef2Sdan /* varintRecordCompareInt() and varintRecordCompareString() both assume
49239b8afef2Sdan ** that the size-of-header varint that occurs at the start of each record
49249b8afef2Sdan ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
49259b8afef2Sdan ** also assumes that it is safe to overread a buffer by at least the
49269b8afef2Sdan ** maximum possible legal header size plus 8 bytes. Because there is
49279b8afef2Sdan ** guaranteed to be at least 74 (but not 136) bytes of padding following each
49289b8afef2Sdan ** buffer passed to varintRecordCompareInt() this makes it convenient to
49299b8afef2Sdan ** limit the size of the header to 64 bytes in cases where the first field
49309b8afef2Sdan ** is an integer.
49319b8afef2Sdan **
49329b8afef2Sdan ** The easiest way to enforce this limit is to consider only records with
49339b8afef2Sdan ** 13 fields or less. If the first field is an integer, the maximum legal
49349b8afef2Sdan ** header size is (12*5 + 1 + 1) bytes. */
4935a485ad19Sdrh if( p->pKeyInfo->nAllField<=13 ){
49361fed5dabSdan int flags = p->aMem[0].flags;
49376e11892dSdan if( p->pKeyInfo->aSortFlags[0] ){
49386e11892dSdan if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
49396e11892dSdan return sqlite3VdbeRecordCompare;
49406e11892dSdan }
49413b9330f8Sdan p->r1 = 1;
49423b9330f8Sdan p->r2 = -1;
49433b9330f8Sdan }else{
49443b9330f8Sdan p->r1 = -1;
49453b9330f8Sdan p->r2 = 1;
49463b9330f8Sdan }
49471fed5dabSdan if( (flags & MEM_Int) ){
4948f357cafaSdrh p->u.i = p->aMem[0].u.i;
49491fed5dabSdan return vdbeRecordCompareInt;
49503b9330f8Sdan }
4951b6e8fd10Sdrh testcase( flags & MEM_Real );
4952b6e8fd10Sdrh testcase( flags & MEM_Null );
4953b6e8fd10Sdrh testcase( flags & MEM_Blob );
4954169f077eSdrh if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
4955169f077eSdrh && p->pKeyInfo->aColl[0]==0
4956169f077eSdrh ){
4957b6e8fd10Sdrh assert( flags & MEM_Str );
4958f357cafaSdrh p->u.z = p->aMem[0].z;
4959f357cafaSdrh p->n = p->aMem[0].n;
49601fed5dabSdan return vdbeRecordCompareString;
49611fed5dabSdan }
49621fed5dabSdan }
49633b9330f8Sdan
49643833e934Sdan return sqlite3VdbeRecordCompare;
49653b9330f8Sdan }
4966183f9f73Sdanielk1977
4967183f9f73Sdanielk1977 /*
49687a224debSdrh ** pCur points at an index entry created using the OP_MakeRecord opcode.
49697a224debSdrh ** Read the rowid (the last field in the record) and store it in *rowid.
49707a224debSdrh ** Return SQLITE_OK if everything works, or an error code otherwise.
497188a003e2Sdrh **
497288a003e2Sdrh ** pCur might be pointing to text obtained from a corrupt database file.
497388a003e2Sdrh ** So the content cannot be trusted. Do appropriate checks on the content.
49748d059845Sdanielk1977 */
sqlite3VdbeIdxRowid(sqlite3 * db,BtCursor * pCur,i64 * rowid)497535f6b936Sdrh int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
497661fc595fSdrh i64 nCellKey = 0;
49778d059845Sdanielk1977 int rc;
4978d5788201Sdrh u32 szHdr; /* Size of the header */
4979d5788201Sdrh u32 typeRowid; /* Serial type of the rowid */
4980d5788201Sdrh u32 lenRowid; /* Size of the rowid */
4981d5788201Sdrh Mem m, v;
4982183f9f73Sdanielk1977
498388a003e2Sdrh /* Get the size of the index entry. Only indices entries of less
49847b746030Sdrh ** than 2GiB are support - anything large must be database corruption.
49857b746030Sdrh ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
4986c27ae614Sdrh ** this code can safely assume that nCellKey is 32-bits
4987c27ae614Sdrh */
4988ea8ffdfeSdrh assert( sqlite3BtreeCursorIsValid(pCur) );
4989a7c90c42Sdrh nCellKey = sqlite3BtreePayloadSize(pCur);
49907b746030Sdrh assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
499188a003e2Sdrh
499288a003e2Sdrh /* Read in the complete content of the index entry */
4993d3b74200Sdrh sqlite3VdbeMemInit(&m, db, 0);
49942a740060Sdrh rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
4995d5788201Sdrh if( rc ){
4996183f9f73Sdanielk1977 return rc;
4997183f9f73Sdanielk1977 }
499888a003e2Sdrh
499988a003e2Sdrh /* The index entry must begin with a header size */
500002a95eb9Sdrh getVarint32NR((u8*)m.z, szHdr);
50017b746030Sdrh testcase( szHdr==3 );
50022b5fbb28Smistachkin testcase( szHdr==(u32)m.n );
500344d06853Sdrh testcase( szHdr>0x7fffffff );
500444d06853Sdrh assert( m.n>=0 );
500544d06853Sdrh if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
500688a003e2Sdrh goto idx_rowid_corruption;
500788a003e2Sdrh }
500888a003e2Sdrh
500988a003e2Sdrh /* The last field of the index should be an integer - the ROWID.
501088a003e2Sdrh ** Verify that the last entry really is an integer. */
501102a95eb9Sdrh getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
501288a003e2Sdrh testcase( typeRowid==1 );
501388a003e2Sdrh testcase( typeRowid==2 );
501488a003e2Sdrh testcase( typeRowid==3 );
501588a003e2Sdrh testcase( typeRowid==4 );
501688a003e2Sdrh testcase( typeRowid==5 );
501788a003e2Sdrh testcase( typeRowid==6 );
501888a003e2Sdrh testcase( typeRowid==8 );
501988a003e2Sdrh testcase( typeRowid==9 );
502088a003e2Sdrh if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
502188a003e2Sdrh goto idx_rowid_corruption;
502288a003e2Sdrh }
5023c5ef7151Sdrh lenRowid = sqlite3SmallTypeSizes[typeRowid];
5024eeb844a7Sdrh testcase( (u32)m.n==szHdr+lenRowid );
5025eeb844a7Sdrh if( unlikely((u32)m.n<szHdr+lenRowid) ){
502688a003e2Sdrh goto idx_rowid_corruption;
502788a003e2Sdrh }
502888a003e2Sdrh
502988a003e2Sdrh /* Fetch the integer off the end of the index record */
50302646da7eSdrh sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50313c024d69Sdrh *rowid = v.u.i;
5032fc854505Sdrh sqlite3VdbeMemReleaseMalloc(&m);
5033183f9f73Sdanielk1977 return SQLITE_OK;
503488a003e2Sdrh
503588a003e2Sdrh /* Jump here if database corruption is detected after m has been
503688a003e2Sdrh ** allocated. Free the m object and return SQLITE_CORRUPT. */
503788a003e2Sdrh idx_rowid_corruption:
503817bcb102Sdrh testcase( m.szMalloc!=0 );
5039fc854505Sdrh sqlite3VdbeMemReleaseMalloc(&m);
504088a003e2Sdrh return SQLITE_CORRUPT_BKPT;
5041183f9f73Sdanielk1977 }
5042183f9f73Sdanielk1977
50437cf6e4deSdrh /*
50445f82e3ccSdrh ** Compare the key of the index entry that cursor pC is pointing to against
50455f82e3ccSdrh ** the key string in pUnpacked. Write into *pRes a number
50467cf6e4deSdrh ** that is negative, zero, or positive if pC is less than, equal to,
50475f82e3ccSdrh ** or greater than pUnpacked. Return SQLITE_OK on success.
5048d3d39e93Sdrh **
50495f82e3ccSdrh ** pUnpacked is either created without a rowid or is truncated so that it
5050d5788201Sdrh ** omits the rowid at the end. The rowid at the end of the index entry
5051ec1fc80cSdrh ** is ignored as well. Hence, this routine only compares the prefixes
5052ec1fc80cSdrh ** of the keys prior to the final rowid, not the entire key.
50537cf6e4deSdrh */
sqlite3VdbeIdxKeyCompare(sqlite3 * db,VdbeCursor * pC,UnpackedRecord * pUnpacked,int * res)5054183f9f73Sdanielk1977 int sqlite3VdbeIdxKeyCompare(
5055d3b74200Sdrh sqlite3 *db, /* Database connection */
5056dfe88eceSdrh VdbeCursor *pC, /* The cursor to compare against */
5057a1f7c0a2Sdrh UnpackedRecord *pUnpacked, /* Unpacked version of key */
50587cf6e4deSdrh int *res /* Write the comparison result here */
5059183f9f73Sdanielk1977 ){
506061fc595fSdrh i64 nCellKey = 0;
5061183f9f73Sdanielk1977 int rc;
5062c960dcbaSdrh BtCursor *pCur;
5063d5788201Sdrh Mem m;
5064183f9f73Sdanielk1977
5065c960dcbaSdrh assert( pC->eCurType==CURTYPE_BTREE );
5066c960dcbaSdrh pCur = pC->uc.pCursor;
5067ea8ffdfeSdrh assert( sqlite3BtreeCursorIsValid(pCur) );
5068a7c90c42Sdrh nCellKey = sqlite3BtreePayloadSize(pCur);
50695668969aSdrh /* nCellKey will always be between 0 and 0xffffffff because of the way
5070407414c2Sdrh ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
5071c27ae614Sdrh if( nCellKey<=0 || nCellKey>0x7fffffff ){
5072183f9f73Sdanielk1977 *res = 0;
50739978c97eSdrh return SQLITE_CORRUPT_BKPT;
5074183f9f73Sdanielk1977 }
5075d3b74200Sdrh sqlite3VdbeMemInit(&m, db, 0);
50762a740060Sdrh rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
5077ec1fc80cSdrh if( rc ){
5078183f9f73Sdanielk1977 return rc;
5079183f9f73Sdanielk1977 }
50806eb3480bSdrh *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
5081fc854505Sdrh sqlite3VdbeMemReleaseMalloc(&m);
5082183f9f73Sdanielk1977 return SQLITE_OK;
5083183f9f73Sdanielk1977 }
5084b28af71aSdanielk1977
5085b28af71aSdanielk1977 /*
5086b28af71aSdanielk1977 ** This routine sets the value to be returned by subsequent calls to
5087b28af71aSdanielk1977 ** sqlite3_changes() on the database handle 'db'.
5088b28af71aSdanielk1977 */
sqlite3VdbeSetChanges(sqlite3 * db,i64 nChange)50892c718873Sdan void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
5090b21c8cd4Sdrh assert( sqlite3_mutex_held(db->mutex) );
5091b28af71aSdanielk1977 db->nChange = nChange;
5092b28af71aSdanielk1977 db->nTotalChange += nChange;
5093b28af71aSdanielk1977 }
5094b28af71aSdanielk1977
5095b28af71aSdanielk1977 /*
5096b28af71aSdanielk1977 ** Set a flag in the vdbe to update the change counter when it is finalised
5097b28af71aSdanielk1977 ** or reset.
5098b28af71aSdanielk1977 */
sqlite3VdbeCountChanges(Vdbe * v)50994794f735Sdrh void sqlite3VdbeCountChanges(Vdbe *v){
51004794f735Sdrh v->changeCntOn = 1;
5101b28af71aSdanielk1977 }
5102d89bd007Sdrh
5103d89bd007Sdrh /*
5104d89bd007Sdrh ** Mark every prepared statement associated with a database connection
5105d89bd007Sdrh ** as expired.
5106d89bd007Sdrh **
5107d89bd007Sdrh ** An expired statement means that recompilation of the statement is
5108d89bd007Sdrh ** recommend. Statements expire when things happen that make their
5109d89bd007Sdrh ** programs obsolete. Removing user-defined functions or collating
5110d89bd007Sdrh ** sequences, or changing an authorization function are the types of
5111d89bd007Sdrh ** things that make prepared statements obsolete.
5112ba968dbfSdrh **
5113ba968dbfSdrh ** If iCode is 1, then expiration is advisory. The statement should
5114ba968dbfSdrh ** be reprepared before being restarted, but if it is already running
5115ba968dbfSdrh ** it is allowed to run to completion.
5116ba968dbfSdrh **
5117ba968dbfSdrh ** Internally, this function just sets the Vdbe.expired flag on all
5118ba968dbfSdrh ** prepared statements. The flag is set to 1 for an immediate expiration
5119ba968dbfSdrh ** and set to 2 for an advisory expiration.
5120d89bd007Sdrh */
sqlite3ExpirePreparedStatements(sqlite3 * db,int iCode)5121ba968dbfSdrh void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
5122d89bd007Sdrh Vdbe *p;
5123e5928b17Sdrh for(p = db->pVdbe; p; p=p->pVNext){
5124ba968dbfSdrh p->expired = iCode+1;
5125d89bd007Sdrh }
5126d89bd007Sdrh }
5127aee18ef8Sdanielk1977
5128aee18ef8Sdanielk1977 /*
5129aee18ef8Sdanielk1977 ** Return the database associated with the Vdbe.
5130aee18ef8Sdanielk1977 */
sqlite3VdbeDb(Vdbe * v)5131aee18ef8Sdanielk1977 sqlite3 *sqlite3VdbeDb(Vdbe *v){
5132aee18ef8Sdanielk1977 return v->db;
5133aee18ef8Sdanielk1977 }
5134937d0deaSdan
5135937d0deaSdan /*
51362c2f392dSdrh ** Return the SQLITE_PREPARE flags for a Vdbe.
51372c2f392dSdrh */
sqlite3VdbePrepareFlags(Vdbe * v)51382c2f392dSdrh u8 sqlite3VdbePrepareFlags(Vdbe *v){
51392c2f392dSdrh return v->prepFlags;
51402c2f392dSdrh }
51412c2f392dSdrh
51422c2f392dSdrh /*
5143937d0deaSdan ** Return a pointer to an sqlite3_value structure containing the value bound
5144937d0deaSdan ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
5145937d0deaSdan ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
5146937d0deaSdan ** constants) to the value before returning it.
5147937d0deaSdan **
5148937d0deaSdan ** The returned value must be freed by the caller using sqlite3ValueFree().
5149937d0deaSdan */
sqlite3VdbeGetBoundValue(Vdbe * v,int iVar,u8 aff)5150cf0fd4a5Sdrh sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
5151937d0deaSdan assert( iVar>0 );
5152937d0deaSdan if( v ){
5153937d0deaSdan Mem *pMem = &v->aVar[iVar-1];
51547df7475dSdrh assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
5155937d0deaSdan if( 0==(pMem->flags & MEM_Null) ){
5156937d0deaSdan sqlite3_value *pRet = sqlite3ValueNew(v->db);
5157937d0deaSdan if( pRet ){
5158937d0deaSdan sqlite3VdbeMemCopy((Mem *)pRet, pMem);
5159937d0deaSdan sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
5160937d0deaSdan }
5161937d0deaSdan return pRet;
5162937d0deaSdan }
5163937d0deaSdan }
5164937d0deaSdan return 0;
5165937d0deaSdan }
5166937d0deaSdan
5167937d0deaSdan /*
5168937d0deaSdan ** Configure SQL variable iVar so that binding a new value to it signals
5169937d0deaSdan ** to sqlite3_reoptimize() that re-preparing the statement may result
5170937d0deaSdan ** in a better query plan.
5171937d0deaSdan */
sqlite3VdbeSetVarmask(Vdbe * v,int iVar)51721d2ce4f8Sdan void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
5173937d0deaSdan assert( iVar>0 );
51747df7475dSdrh assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
51752996796dSdrh if( iVar>=32 ){
51762996796dSdrh v->expmask |= 0x80000000;
5177937d0deaSdan }else{
51781d2ce4f8Sdan v->expmask |= ((u32)1 << (iVar-1));
5179937d0deaSdan }
5180937d0deaSdan }
518146c47d46Sdan
51823e34eabcSdrh /*
51833e34eabcSdrh ** Cause a function to throw an error if it was call from OP_PureFunc
51843e34eabcSdrh ** rather than OP_Function.
51853e34eabcSdrh **
51863e34eabcSdrh ** OP_PureFunc means that the function must be deterministic, and should
51873e34eabcSdrh ** throw an error if it is given inputs that would make it non-deterministic.
51883e34eabcSdrh ** This routine is invoked by date/time functions that use non-deterministic
51893e34eabcSdrh ** features such as 'now'.
51903e34eabcSdrh */
sqlite3NotPureFunc(sqlite3_context * pCtx)51916e97f8ecSdrh int sqlite3NotPureFunc(sqlite3_context *pCtx){
519220cee7d0Sdrh const VdbeOp *pOp;
5193175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
5194e8cf1ab9Sdrh if( pCtx->pVdbe==0 ) return 1;
5195e8cf1ab9Sdrh #endif
519620cee7d0Sdrh pOp = pCtx->pVdbe->aOp + pCtx->iOp;
519720cee7d0Sdrh if( pOp->opcode==OP_PureFunc ){
519820cee7d0Sdrh const char *zContext;
519920cee7d0Sdrh char *zMsg;
520020cee7d0Sdrh if( pOp->p5 & NC_IsCheck ){
520120cee7d0Sdrh zContext = "a CHECK constraint";
520220cee7d0Sdrh }else if( pOp->p5 & NC_GenCol ){
520320cee7d0Sdrh zContext = "a generated column";
520420cee7d0Sdrh }else{
520520cee7d0Sdrh zContext = "an index";
520620cee7d0Sdrh }
520720cee7d0Sdrh zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
520820cee7d0Sdrh pCtx->pFunc->zName, zContext);
5209920cf596Sdrh sqlite3_result_error(pCtx, zMsg, -1);
5210920cf596Sdrh sqlite3_free(zMsg);
52116e97f8ecSdrh return 0;
52123e34eabcSdrh }
52136e97f8ecSdrh return 1;
52143e34eabcSdrh }
52153e34eabcSdrh
5216016f7811Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE
5217016f7811Sdan /*
5218016f7811Sdan ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
5219016f7811Sdan ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
5220016f7811Sdan ** in memory obtained from sqlite3DbMalloc).
5221016f7811Sdan */
sqlite3VtabImportErrmsg(Vdbe * p,sqlite3_vtab * pVtab)5222016f7811Sdan void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
52235c3aa051Sdan if( pVtab->zErrMsg ){
5224016f7811Sdan sqlite3 *db = p->db;
5225016f7811Sdan sqlite3DbFree(db, p->zErrMsg);
5226016f7811Sdan p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
5227016f7811Sdan sqlite3_free(pVtab->zErrMsg);
5228016f7811Sdan pVtab->zErrMsg = 0;
5229016f7811Sdan }
52305c3aa051Sdan }
5231016f7811Sdan #endif /* SQLITE_OMIT_VIRTUALTABLE */
523232683532Sdrh
52339b1c62d4Sdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
523493bca695Sdan
523593bca695Sdan /*
523693bca695Sdan ** If the second argument is not NULL, release any allocations associated
523793bca695Sdan ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
523893bca695Sdan ** structure itself, using sqlite3DbFree().
523993bca695Sdan **
524093bca695Sdan ** This function is used to free UnpackedRecord structures allocated by
524193bca695Sdan ** the vdbeUnpackRecord() function found in vdbeapi.c.
524293bca695Sdan */
vdbeFreeUnpacked(sqlite3 * db,int nField,UnpackedRecord * p)52432a86c196Sdan static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
524441ce47c4Sdrh assert( db!=0 );
524593bca695Sdan if( p ){
524693bca695Sdan int i;
52472a86c196Sdan for(i=0; i<nField; i++){
524893bca695Sdan Mem *pMem = &p->aMem[i];
5249fc854505Sdrh if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
525093bca695Sdan }
525141ce47c4Sdrh sqlite3DbNNFreeNN(db, p);
525293bca695Sdan }
525393bca695Sdan }
525474c3302fSdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
525593bca695Sdan
525674c3302fSdrh #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
525746c47d46Sdan /*
525846c47d46Sdan ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
525946c47d46Sdan ** then cursor passed as the second argument should point to the row about
526046c47d46Sdan ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
526146c47d46Sdan ** the required value will be read from the row the cursor points to.
526246c47d46Sdan */
sqlite3VdbePreUpdateHook(Vdbe * v,VdbeCursor * pCsr,int op,const char * zDb,Table * pTab,i64 iKey1,int iReg,int iBlobWrite)526346c47d46Sdan void sqlite3VdbePreUpdateHook(
526446c47d46Sdan Vdbe *v, /* Vdbe pre-update hook is invoked by */
526546c47d46Sdan VdbeCursor *pCsr, /* Cursor to grab old.* values from */
526646c47d46Sdan int op, /* SQLITE_INSERT, UPDATE or DELETE */
526746c47d46Sdan const char *zDb, /* Database name */
5268319eeb7bSdan Table *pTab, /* Modified table */
526946c47d46Sdan i64 iKey1, /* Initial key value */
5270a23a873fSdan int iReg, /* Register for new.* record */
5271a23a873fSdan int iBlobWrite
527246c47d46Sdan ){
527346c47d46Sdan sqlite3 *db = v->db;
527437db03bfSdan i64 iKey2;
527546c47d46Sdan PreUpdate preupdate;
5276319eeb7bSdan const char *zTbl = pTab->zName;
5277c4645dacSdrh static const u8 fakeSortOrder = 0;
527846c47d46Sdan
5279304637c0Sdrh assert( db->pPreUpdate==0 );
5280304637c0Sdrh memset(&preupdate, 0, sizeof(PreUpdate));
5281cb9a3643Sdan if( HasRowid(pTab)==0 ){
5282cb9a3643Sdan iKey1 = iKey2 = 0;
5283cb9a3643Sdan preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
5284cb9a3643Sdan }else{
528537db03bfSdan if( op==SQLITE_UPDATE ){
528637db03bfSdan iKey2 = v->aMem[iReg].u.i;
528737db03bfSdan }else{
528837db03bfSdan iKey2 = iKey1;
528937db03bfSdan }
5290cb9a3643Sdan }
529137db03bfSdan
52923ab4ffceSdrh assert( pCsr!=0 );
52933ab4ffceSdrh assert( pCsr->eCurType==CURTYPE_BTREE );
5294e437ca5eSdan assert( pCsr->nField==pTab->nCol
5295e437ca5eSdan || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
5296e437ca5eSdan );
5297e437ca5eSdan
529837db03bfSdan preupdate.v = v;
529946c47d46Sdan preupdate.pCsr = pCsr;
530046c47d46Sdan preupdate.op = op;
530137db03bfSdan preupdate.iNewReg = iReg;
53024fccf43aSdan preupdate.keyinfo.db = db;
53034fccf43aSdan preupdate.keyinfo.enc = ENC(db);
5304a485ad19Sdrh preupdate.keyinfo.nKeyField = pTab->nCol;
5305a677eecaSdrh preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
5306319eeb7bSdan preupdate.iKey1 = iKey1;
5307319eeb7bSdan preupdate.iKey2 = iKey2;
5308e43635aaSdan preupdate.pTab = pTab;
5309a23a873fSdan preupdate.iBlobWrite = iBlobWrite;
5310319eeb7bSdan
531146c47d46Sdan db->pPreUpdate = &preupdate;
531246c47d46Sdan db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
531346c47d46Sdan db->pPreUpdate = 0;
531446c47d46Sdan sqlite3DbFree(db, preupdate.aRecord);
5315a485ad19Sdrh vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
5316a485ad19Sdrh vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
531737db03bfSdan if( preupdate.aNew ){
531837db03bfSdan int i;
531937db03bfSdan for(i=0; i<pCsr->nField; i++){
532037db03bfSdan sqlite3VdbeMemRelease(&preupdate.aNew[i]);
532137db03bfSdan }
532241ce47c4Sdrh sqlite3DbNNFreeNN(db, preupdate.aNew);
532337db03bfSdan }
532446c47d46Sdan }
53259b1c62d4Sdrh #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
5326