Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1849)

Side by Side Diff: third_party/sqlite/sqlite-src-3080704/src/vdbe.c

Issue 883353008: [sql] Import reference version of SQLite 3.8.7.4. (Closed) Base URL: http://chromium.googlesource.com/chromium/src.git@master
Patch Set: Hold back encoding change which is messing up patch. Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 ** 2001 September 15 2 ** 2001 September 15
3 ** 3 **
4 ** The author disclaims copyright to this source code. In place of 4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing: 5 ** a legal notice, here is a blessing:
6 ** 6 **
7 ** May you do good and not evil. 7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others. 8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give. 9 ** May you share freely, never taking more than you give.
10 ** 10 **
11 ************************************************************************* 11 *************************************************************************
12 ** The code in this file implements execution method of the 12 ** The code in this file implements the function that runs the
13 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c") 13 ** bytecode of a prepared statement.
14 ** handles housekeeping details such as creating and deleting
15 ** VDBE instances. This file is solely interested in executing
16 ** the VDBE program.
17 **
18 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
19 ** to a VDBE.
20 **
21 ** The SQL parser generates a program which is then executed by
22 ** the VDBE to do the work of the SQL statement. VDBE programs are
23 ** similar in form to assembly language. The program consists of
24 ** a linear sequence of operations. Each operation has an opcode
25 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
26 ** is a null-terminated string. Operand P5 is an unsigned character.
27 ** Few opcodes use all 5 operands.
28 **
29 ** Computation results are stored on a set of registers numbered beginning
30 ** with 1 and going up to Vdbe.nMem. Each register can store
31 ** either an integer, a null-terminated string, a floating point
32 ** number, or the SQL "NULL" value. An implicit conversion from one
33 ** type to the other occurs as necessary.
34 **
35 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
36 ** function which does the work of interpreting a VDBE program.
37 ** But other routines are also provided to help in building up
38 ** a program instruction by instruction.
39 ** 14 **
40 ** Various scripts scan this source file in order to generate HTML 15 ** Various scripts scan this source file in order to generate HTML
41 ** documentation, headers files, or other derived files. The formatting 16 ** documentation, headers files, or other derived files. The formatting
42 ** of the code in this file is, therefore, important. See other comments 17 ** of the code in this file is, therefore, important. See other comments
43 ** in this file for details. If in doubt, do not deviate from existing 18 ** in this file for details. If in doubt, do not deviate from existing
44 ** commenting and indentation practices when changing or adding code. 19 ** commenting and indentation practices when changing or adding code.
45 */ 20 */
46 #include "sqliteInt.h" 21 #include "sqliteInt.h"
47 #include "vdbeInt.h" 22 #include "vdbeInt.h"
48 23
49 /* 24 /*
50 ** Invoke this macro on memory cells just prior to changing the 25 ** Invoke this macro on memory cells just prior to changing the
51 ** value of the cell. This macro verifies that shallow copies are 26 ** value of the cell. This macro verifies that shallow copies are
52 ** not misused. 27 ** not misused. A shallow copy of a string or blob just copies a
28 ** pointer to the string or blob, not the content. If the original
29 ** is changed while the copy is still in use, the string or blob might
30 ** be changed out from under the copy. This macro verifies that nothing
31 ** like that ever happens.
53 */ 32 */
54 #ifdef SQLITE_DEBUG 33 #ifdef SQLITE_DEBUG
55 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M) 34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
56 #else 35 #else
57 # define memAboutToChange(P,M) 36 # define memAboutToChange(P,M)
58 #endif 37 #endif
59 38
60 /* 39 /*
61 ** The following global variable is incremented every time a cursor 40 ** The following global variable is incremented every time a cursor
62 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test 41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
63 ** procedures use this information to make sure that indices are 42 ** procedures use this information to make sure that indices are
64 ** working correctly. This variable has no function other than to 43 ** working correctly. This variable has no function other than to
65 ** help verify the correct operation of the library. 44 ** help verify the correct operation of the library.
66 */ 45 */
67 #ifdef SQLITE_TEST 46 #ifdef SQLITE_TEST
68 int sqlite3_search_count = 0; 47 int sqlite3_search_count = 0;
69 #endif 48 #endif
70 49
71 /* 50 /*
72 ** When this global variable is positive, it gets decremented once before 51 ** When this global variable is positive, it gets decremented once before
73 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted 52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
74 ** field of the sqlite3 structure is set in order to simulate and interrupt. 53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
75 ** 54 **
76 ** This facility is used for testing purposes only. It does not function 55 ** This facility is used for testing purposes only. It does not function
77 ** in an ordinary build. 56 ** in an ordinary build.
78 */ 57 */
79 #ifdef SQLITE_TEST 58 #ifdef SQLITE_TEST
80 int sqlite3_interrupt_count = 0; 59 int sqlite3_interrupt_count = 0;
81 #endif 60 #endif
82 61
83 /* 62 /*
84 ** The next global variable is incremented each type the OP_Sort opcode 63 ** The next global variable is incremented each type the OP_Sort opcode
(...skipping 16 matching lines...) Expand all
101 #ifdef SQLITE_TEST 80 #ifdef SQLITE_TEST
102 int sqlite3_max_blobsize = 0; 81 int sqlite3_max_blobsize = 0;
103 static void updateMaxBlobsize(Mem *p){ 82 static void updateMaxBlobsize(Mem *p){
104 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ 83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
105 sqlite3_max_blobsize = p->n; 84 sqlite3_max_blobsize = p->n;
106 } 85 }
107 } 86 }
108 #endif 87 #endif
109 88
110 /* 89 /*
111 ** The next global variable is incremented each type the OP_Found opcode 90 ** The next global variable is incremented each time the OP_Found opcode
112 ** is executed. This is used to test whether or not the foreign key 91 ** is executed. This is used to test whether or not the foreign key
113 ** operation implemented using OP_FkIsZero is working. This variable 92 ** operation implemented using OP_FkIsZero is working. This variable
114 ** has no function other than to help verify the correct operation of the 93 ** has no function other than to help verify the correct operation of the
115 ** library. 94 ** library.
116 */ 95 */
117 #ifdef SQLITE_TEST 96 #ifdef SQLITE_TEST
118 int sqlite3_found_count = 0; 97 int sqlite3_found_count = 0;
119 #endif 98 #endif
120 99
121 /* 100 /*
122 ** Test a register to see if it exceeds the current maximum blob size. 101 ** Test a register to see if it exceeds the current maximum blob size.
123 ** If it does, record the new maximum blob size. 102 ** If it does, record the new maximum blob size.
124 */ 103 */
125 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST) 104 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
126 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) 105 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
127 #else 106 #else
128 # define UPDATE_MAX_BLOBSIZE(P) 107 # define UPDATE_MAX_BLOBSIZE(P)
129 #endif 108 #endif
130 109
131 /* 110 /*
111 ** Invoke the VDBE coverage callback, if that callback is defined. This
112 ** feature is used for test suite validation only and does not appear an
113 ** production builds.
114 **
115 ** M is an integer, 2 or 3, that indices how many different ways the
116 ** branch can go. It is usually 2. "I" is the direction the branch
117 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
118 ** second alternative branch is taken.
119 **
120 ** iSrcLine is the source code line (from the __LINE__ macro) that
121 ** generated the VDBE instruction. This instrumentation assumes that all
122 ** source code is in a single file (the amalgamation). Special values 1
123 ** and 2 for the iSrcLine parameter mean that this particular branch is
124 ** always taken or never taken, respectively.
125 */
126 #if !defined(SQLITE_VDBE_COVERAGE)
127 # define VdbeBranchTaken(I,M)
128 #else
129 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
130 static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
131 if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
132 M = iSrcLine;
133 /* Assert the truth of VdbeCoverageAlwaysTaken() and
134 ** VdbeCoverageNeverTaken() */
135 assert( (M & I)==I );
136 }else{
137 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
138 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
139 iSrcLine,I,M);
140 }
141 }
142 #endif
143
144 /*
132 ** Convert the given register into a string if it isn't one 145 ** Convert the given register into a string if it isn't one
133 ** already. Return non-zero if a malloc() fails. 146 ** already. Return non-zero if a malloc() fails.
134 */ 147 */
135 #define Stringify(P, enc) \ 148 #define Stringify(P, enc) \
136 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \ 149 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
137 { goto no_mem; } 150 { goto no_mem; }
138 151
139 /* 152 /*
140 ** An ephemeral string value (signified by the MEM_Ephem flag) contains 153 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
141 ** a pointer to a dynamically allocated string where some other entity 154 ** a pointer to a dynamically allocated string where some other entity
142 ** is responsible for deallocating that string. Because the register 155 ** is responsible for deallocating that string. Because the register
143 ** does not control the string, it might be deleted without the register 156 ** does not control the string, it might be deleted without the register
144 ** knowing it. 157 ** knowing it.
145 ** 158 **
146 ** This routine converts an ephemeral string into a dynamically allocated 159 ** This routine converts an ephemeral string into a dynamically allocated
147 ** string that the register itself controls. In other words, it 160 ** string that the register itself controls. In other words, it
148 ** converts an MEM_Ephem string into an MEM_Dyn string. 161 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
149 */ 162 */
150 #define Deephemeralize(P) \ 163 #define Deephemeralize(P) \
151 if( ((P)->flags&MEM_Ephem)!=0 \ 164 if( ((P)->flags&MEM_Ephem)!=0 \
152 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} 165 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
153 166
154 /* 167 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
155 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*) 168 #define isSorter(x) ((x)->pSorter!=0)
156 ** P if required.
157 */
158 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
159
160 /*
161 ** Argument pMem points at a register that will be passed to a
162 ** user-defined function or returned to the user as the result of a query.
163 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
164 ** routines.
165 */
166 void sqlite3VdbeMemStoreType(Mem *pMem){
167 int flags = pMem->flags;
168 if( flags & MEM_Null ){
169 pMem->type = SQLITE_NULL;
170 }
171 else if( flags & MEM_Int ){
172 pMem->type = SQLITE_INTEGER;
173 }
174 else if( flags & MEM_Real ){
175 pMem->type = SQLITE_FLOAT;
176 }
177 else if( flags & MEM_Str ){
178 pMem->type = SQLITE_TEXT;
179 }else{
180 pMem->type = SQLITE_BLOB;
181 }
182 }
183 169
184 /* 170 /*
185 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL 171 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
186 ** if we run out of memory. 172 ** if we run out of memory.
187 */ 173 */
188 static VdbeCursor *allocateCursor( 174 static VdbeCursor *allocateCursor(
189 Vdbe *p, /* The virtual machine */ 175 Vdbe *p, /* The virtual machine */
190 int iCur, /* Index of the new VdbeCursor */ 176 int iCur, /* Index of the new VdbeCursor */
191 int nField, /* Number of fields in the table or index */ 177 int nField, /* Number of fields in the table or index */
192 int iDb, /* When database the cursor belongs to, or -1 */ 178 int iDb, /* Database the cursor belongs to, or -1 */
193 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */ 179 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
194 ){ 180 ){
195 /* Find the memory cell that will be used to store the blob of memory 181 /* Find the memory cell that will be used to store the blob of memory
196 ** required for this VdbeCursor structure. It is convenient to use a 182 ** required for this VdbeCursor structure. It is convenient to use a
197 ** vdbe memory cell to manage the memory allocation required for a 183 ** vdbe memory cell to manage the memory allocation required for a
198 ** VdbeCursor structure for the following reasons: 184 ** VdbeCursor structure for the following reasons:
199 ** 185 **
200 ** * Sometimes cursor numbers are used for a couple of different 186 ** * Sometimes cursor numbers are used for a couple of different
201 ** purposes in a vdbe program. The different uses might require 187 ** purposes in a vdbe program. The different uses might require
202 ** different sized allocations. Memory cells provide growable 188 ** different sized allocations. Memory cells provide growable
203 ** allocations. 189 ** allocations.
204 ** 190 **
205 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can 191 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
206 ** be freed lazily via the sqlite3_release_memory() API. This 192 ** be freed lazily via the sqlite3_release_memory() API. This
207 ** minimizes the number of malloc calls made by the system. 193 ** minimizes the number of malloc calls made by the system.
208 ** 194 **
209 ** Memory cells for cursors are allocated at the top of the address 195 ** Memory cells for cursors are allocated at the top of the address
210 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for 196 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
211 ** cursor 1 is managed by memory cell (p->nMem-1), etc. 197 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
212 */ 198 */
213 Mem *pMem = &p->aMem[p->nMem-iCur]; 199 Mem *pMem = &p->aMem[p->nMem-iCur];
214 200
215 int nByte; 201 int nByte;
216 VdbeCursor *pCx = 0; 202 VdbeCursor *pCx = 0;
217 nByte = 203 nByte =
218 ROUND8(sizeof(VdbeCursor)) + 204 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
219 (isBtreeCursor?sqlite3BtreeCursorSize():0) + 205 (isBtreeCursor?sqlite3BtreeCursorSize():0);
220 2*nField*sizeof(u32);
221 206
222 assert( iCur<p->nCursor ); 207 assert( iCur<p->nCursor );
223 if( p->apCsr[iCur] ){ 208 if( p->apCsr[iCur] ){
224 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); 209 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
225 p->apCsr[iCur] = 0; 210 p->apCsr[iCur] = 0;
226 } 211 }
227 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){ 212 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
228 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; 213 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
229 memset(pCx, 0, sizeof(VdbeCursor)); 214 memset(pCx, 0, sizeof(VdbeCursor));
230 pCx->iDb = iDb; 215 pCx->iDb = iDb;
231 pCx->nField = nField; 216 pCx->nField = nField;
232 if( nField ){ 217 pCx->aOffset = &pCx->aType[nField];
233 pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
234 }
235 if( isBtreeCursor ){ 218 if( isBtreeCursor ){
236 pCx->pCursor = (BtCursor*) 219 pCx->pCursor = (BtCursor*)
237 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)]; 220 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
238 sqlite3BtreeCursorZero(pCx->pCursor); 221 sqlite3BtreeCursorZero(pCx->pCursor);
239 } 222 }
240 } 223 }
241 return pCx; 224 return pCx;
242 } 225 }
243 226
244 /* 227 /*
245 ** Try to convert a value into a numeric representation if we can 228 ** Try to convert a value into a numeric representation if we can
246 ** do so without loss of information. In other words, if the string 229 ** do so without loss of information. In other words, if the string
247 ** looks like a number, convert it into a number. If it does not 230 ** looks like a number, convert it into a number. If it does not
248 ** look like a number, leave it alone. 231 ** look like a number, leave it alone.
232 **
233 ** If the bTryForInt flag is true, then extra effort is made to give
234 ** an integer representation. Strings that look like floating point
235 ** values but which have no fractional component (example: '48.00')
236 ** will have a MEM_Int representation when bTryForInt is true.
237 **
238 ** If bTryForInt is false, then if the input string contains a decimal
239 ** point or exponential notation, the result is only MEM_Real, even
240 ** if there is an exact integer representation of the quantity.
249 */ 241 */
250 static void applyNumericAffinity(Mem *pRec){ 242 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
251 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){ 243 double rValue;
252 double rValue; 244 i64 iValue;
253 i64 iValue; 245 u8 enc = pRec->enc;
254 u8 enc = pRec->enc; 246 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
255 if( (pRec->flags&MEM_Str)==0 ) return; 247 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
256 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; 248 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
257 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ 249 pRec->u.i = iValue;
258 pRec->u.i = iValue; 250 pRec->flags |= MEM_Int;
259 pRec->flags |= MEM_Int; 251 }else{
260 }else{ 252 pRec->u.r = rValue;
261 pRec->r = rValue; 253 pRec->flags |= MEM_Real;
262 pRec->flags |= MEM_Real; 254 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
263 }
264 } 255 }
265 } 256 }
266 257
267 /* 258 /*
268 ** Processing is determine by the affinity parameter: 259 ** Processing is determine by the affinity parameter:
269 ** 260 **
270 ** SQLITE_AFF_INTEGER: 261 ** SQLITE_AFF_INTEGER:
271 ** SQLITE_AFF_REAL: 262 ** SQLITE_AFF_REAL:
272 ** SQLITE_AFF_NUMERIC: 263 ** SQLITE_AFF_NUMERIC:
273 ** Try to convert pRec to an integer representation or a 264 ** Try to convert pRec to an integer representation or a
274 ** floating-point representation if an integer representation 265 ** floating-point representation if an integer representation
275 ** is not possible. Note that the integer representation is 266 ** is not possible. Note that the integer representation is
276 ** always preferred, even if the affinity is REAL, because 267 ** always preferred, even if the affinity is REAL, because
277 ** an integer representation is more space efficient on disk. 268 ** an integer representation is more space efficient on disk.
278 ** 269 **
279 ** SQLITE_AFF_TEXT: 270 ** SQLITE_AFF_TEXT:
280 ** Convert pRec to a text representation. 271 ** Convert pRec to a text representation.
281 ** 272 **
282 ** SQLITE_AFF_NONE: 273 ** SQLITE_AFF_NONE:
283 ** No-op. pRec is unchanged. 274 ** No-op. pRec is unchanged.
284 */ 275 */
285 static void applyAffinity( 276 static void applyAffinity(
286 Mem *pRec, /* The value to apply affinity to */ 277 Mem *pRec, /* The value to apply affinity to */
287 char affinity, /* The affinity to be applied */ 278 char affinity, /* The affinity to be applied */
288 u8 enc /* Use this text encoding */ 279 u8 enc /* Use this text encoding */
289 ){ 280 ){
290 if( affinity==SQLITE_AFF_TEXT ){ 281 if( affinity>=SQLITE_AFF_NUMERIC ){
282 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
283 || affinity==SQLITE_AFF_NUMERIC );
284 if( (pRec->flags & MEM_Int)==0 ){
285 if( (pRec->flags & MEM_Real)==0 ){
286 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
287 }else{
288 sqlite3VdbeIntegerAffinity(pRec);
289 }
290 }
291 }else if( affinity==SQLITE_AFF_TEXT ){
291 /* Only attempt the conversion to TEXT if there is an integer or real 292 /* Only attempt the conversion to TEXT if there is an integer or real
292 ** representation (blob and NULL do not get converted) but no string 293 ** representation (blob and NULL do not get converted) but no string
293 ** representation. 294 ** representation.
294 */ 295 */
295 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){ 296 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
296 sqlite3VdbeMemStringify(pRec, enc); 297 sqlite3VdbeMemStringify(pRec, enc, 1);
297 }
298 pRec->flags &= ~(MEM_Real|MEM_Int);
299 }else if( affinity!=SQLITE_AFF_NONE ){
300 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
301 || affinity==SQLITE_AFF_NUMERIC );
302 applyNumericAffinity(pRec);
303 if( pRec->flags & MEM_Real ){
304 sqlite3VdbeIntegerAffinity(pRec);
305 } 298 }
306 } 299 }
307 } 300 }
308 301
309 /* 302 /*
310 ** Try to convert the type of a function argument or a result column 303 ** Try to convert the type of a function argument or a result column
311 ** into a numeric representation. Use either INTEGER or REAL whichever 304 ** into a numeric representation. Use either INTEGER or REAL whichever
312 ** is appropriate. But only do the conversion if it is possible without 305 ** is appropriate. But only do the conversion if it is possible without
313 ** loss of information and return the revised type of the argument. 306 ** loss of information and return the revised type of the argument.
314 */ 307 */
315 int sqlite3_value_numeric_type(sqlite3_value *pVal){ 308 int sqlite3_value_numeric_type(sqlite3_value *pVal){
316 Mem *pMem = (Mem*)pVal; 309 int eType = sqlite3_value_type(pVal);
317 if( pMem->type==SQLITE_TEXT ){ 310 if( eType==SQLITE_TEXT ){
318 applyNumericAffinity(pMem); 311 Mem *pMem = (Mem*)pVal;
319 sqlite3VdbeMemStoreType(pMem); 312 applyNumericAffinity(pMem, 0);
313 eType = sqlite3_value_type(pVal);
320 } 314 }
321 return pMem->type; 315 return eType;
322 } 316 }
323 317
324 /* 318 /*
325 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 319 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
326 ** not the internal Mem* type. 320 ** not the internal Mem* type.
327 */ 321 */
328 void sqlite3ValueApplyAffinity( 322 void sqlite3ValueApplyAffinity(
329 sqlite3_value *pVal, 323 sqlite3_value *pVal,
330 u8 affinity, 324 u8 affinity,
331 u8 enc 325 u8 enc
332 ){ 326 ){
333 applyAffinity((Mem *)pVal, affinity, enc); 327 applyAffinity((Mem *)pVal, affinity, enc);
334 } 328 }
335 329
330 /*
331 ** pMem currently only holds a string type (or maybe a BLOB that we can
332 ** interpret as a string if we want to). Compute its corresponding
333 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
334 ** accordingly.
335 */
336 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
337 assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
338 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
339 if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
340 return 0;
341 }
342 if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
343 return MEM_Int;
344 }
345 return MEM_Real;
346 }
347
348 /*
349 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
350 ** none.
351 **
352 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
353 ** But it does set pMem->u.r and pMem->u.i appropriately.
354 */
355 static u16 numericType(Mem *pMem){
356 if( pMem->flags & (MEM_Int|MEM_Real) ){
357 return pMem->flags & (MEM_Int|MEM_Real);
358 }
359 if( pMem->flags & (MEM_Str|MEM_Blob) ){
360 return computeNumericType(pMem);
361 }
362 return 0;
363 }
364
336 #ifdef SQLITE_DEBUG 365 #ifdef SQLITE_DEBUG
337 /* 366 /*
338 ** Write a nice string representation of the contents of cell pMem 367 ** Write a nice string representation of the contents of cell pMem
339 ** into buffer zBuf, length nBuf. 368 ** into buffer zBuf, length nBuf.
340 */ 369 */
341 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ 370 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
342 char *zCsr = zBuf; 371 char *zCsr = zBuf;
343 int f = pMem->flags; 372 int f = pMem->flags;
344 373
345 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; 374 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
413 k += sqlite3Strlen30(&zBuf[k]); 442 k += sqlite3Strlen30(&zBuf[k]);
414 zBuf[k++] = 0; 443 zBuf[k++] = 0;
415 } 444 }
416 } 445 }
417 #endif 446 #endif
418 447
419 #ifdef SQLITE_DEBUG 448 #ifdef SQLITE_DEBUG
420 /* 449 /*
421 ** Print the value of a register for tracing purposes: 450 ** Print the value of a register for tracing purposes:
422 */ 451 */
423 static void memTracePrint(FILE *out, Mem *p){ 452 static void memTracePrint(Mem *p){
424 if( p->flags & MEM_Null ){ 453 if( p->flags & MEM_Undefined ){
425 fprintf(out, " NULL"); 454 printf(" undefined");
455 }else if( p->flags & MEM_Null ){
456 printf(" NULL");
426 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ 457 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
427 fprintf(out, " si:%lld", p->u.i); 458 printf(" si:%lld", p->u.i);
428 }else if( p->flags & MEM_Int ){ 459 }else if( p->flags & MEM_Int ){
429 fprintf(out, " i:%lld", p->u.i); 460 printf(" i:%lld", p->u.i);
430 #ifndef SQLITE_OMIT_FLOATING_POINT 461 #ifndef SQLITE_OMIT_FLOATING_POINT
431 }else if( p->flags & MEM_Real ){ 462 }else if( p->flags & MEM_Real ){
432 fprintf(out, " r:%g", p->r); 463 printf(" r:%g", p->u.r);
433 #endif 464 #endif
434 }else if( p->flags & MEM_RowSet ){ 465 }else if( p->flags & MEM_RowSet ){
435 fprintf(out, " (rowset)"); 466 printf(" (rowset)");
436 }else{ 467 }else{
437 char zBuf[200]; 468 char zBuf[200];
438 sqlite3VdbeMemPrettyPrint(p, zBuf); 469 sqlite3VdbeMemPrettyPrint(p, zBuf);
439 fprintf(out, " "); 470 printf(" %s", zBuf);
440 fprintf(out, "%s", zBuf);
441 } 471 }
442 } 472 }
443 static void registerTrace(FILE *out, int iReg, Mem *p){ 473 static void registerTrace(int iReg, Mem *p){
444 fprintf(out, "REG[%d] = ", iReg); 474 printf("REG[%d] = ", iReg);
445 memTracePrint(out, p); 475 memTracePrint(p);
446 fprintf(out, "\n"); 476 printf("\n");
447 } 477 }
448 #endif 478 #endif
449 479
450 #ifdef SQLITE_DEBUG 480 #ifdef SQLITE_DEBUG
451 # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M) 481 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
452 #else 482 #else
453 # define REGISTER_TRACE(R,M) 483 # define REGISTER_TRACE(R,M)
454 #endif 484 #endif
455 485
456 486
457 #ifdef VDBE_PROFILE 487 #ifdef VDBE_PROFILE
458 488
459 /* 489 /*
460 ** hwtime.h contains inline assembler code for implementing 490 ** hwtime.h contains inline assembler code for implementing
461 ** high-performance timing routines. 491 ** high-performance timing routines.
462 */ 492 */
463 #include "hwtime.h" 493 #include "hwtime.h"
464 494
465 #endif 495 #endif
466 496
467 /*
468 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
469 ** sqlite3_interrupt() routine has been called. If it has been, then
470 ** processing of the VDBE program is interrupted.
471 **
472 ** This macro added to every instruction that does a jump in order to
473 ** implement a loop. This test used to be on every single instruction,
474 ** but that meant we more testing that we needed. By only testing the
475 ** flag on jump instructions, we get a (small) speed improvement.
476 */
477 #define CHECK_FOR_INTERRUPT \
478 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
479
480
481 #ifndef NDEBUG 497 #ifndef NDEBUG
482 /* 498 /*
483 ** This function is only called from within an assert() expression. It 499 ** This function is only called from within an assert() expression. It
484 ** checks that the sqlite3.nTransaction variable is correctly set to 500 ** checks that the sqlite3.nTransaction variable is correctly set to
485 ** the number of non-transaction savepoints currently in the 501 ** the number of non-transaction savepoints currently in the
486 ** linked list starting at sqlite3.pSavepoint. 502 ** linked list starting at sqlite3.pSavepoint.
487 ** 503 **
488 ** Usage: 504 ** Usage:
489 ** 505 **
490 ** assert( checkSavepointCount(db) ); 506 ** assert( checkSavepointCount(db) );
491 */ 507 */
492 static int checkSavepointCount(sqlite3 *db){ 508 static int checkSavepointCount(sqlite3 *db){
493 int n = 0; 509 int n = 0;
494 Savepoint *p; 510 Savepoint *p;
495 for(p=db->pSavepoint; p; p=p->pNext) n++; 511 for(p=db->pSavepoint; p; p=p->pNext) n++;
496 assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); 512 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
497 return 1; 513 return 1;
498 } 514 }
499 #endif 515 #endif
500 516
501 /*
502 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
503 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
504 ** in memory obtained from sqlite3DbMalloc).
505 */
506 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
507 sqlite3 *db = p->db;
508 sqlite3DbFree(db, p->zErrMsg);
509 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
510 sqlite3_free(pVtab->zErrMsg);
511 pVtab->zErrMsg = 0;
512 }
513
514 517
515 /* 518 /*
516 ** Execute as much of a VDBE program as we can then return. 519 ** Execute as much of a VDBE program as we can.
517 ** 520 ** This is the core of sqlite3_step().
518 ** sqlite3VdbeMakeReady() must be called before this routine in order to
519 ** close the program with a final OP_Halt and to set up the callbacks
520 ** and the error message pointer.
521 **
522 ** Whenever a row or result data is available, this routine will either
523 ** invoke the result callback (if there is one) or return with
524 ** SQLITE_ROW.
525 **
526 ** If an attempt is made to open a locked database, then this routine
527 ** will either invoke the busy callback (if there is one) or it will
528 ** return SQLITE_BUSY.
529 **
530 ** If an error occurs, an error message is written to memory obtained
531 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
532 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
533 **
534 ** If the callback ever returns non-zero, then the program exits
535 ** immediately. There will be no error message but the p->rc field is
536 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
537 **
538 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
539 ** routine to return SQLITE_ERROR.
540 **
541 ** Other fatal errors return SQLITE_ERROR.
542 **
543 ** After this routine has finished, sqlite3VdbeFinalize() should be
544 ** used to clean up the mess that was left behind.
545 */ 521 */
546 int sqlite3VdbeExec( 522 int sqlite3VdbeExec(
547 Vdbe *p /* The VDBE */ 523 Vdbe *p /* The VDBE */
548 ){ 524 ){
549 int pc=0; /* The program counter */ 525 int pc=0; /* The program counter */
550 Op *aOp = p->aOp; /* Copy of p->aOp */ 526 Op *aOp = p->aOp; /* Copy of p->aOp */
551 Op *pOp; /* Current operation */ 527 Op *pOp; /* Current operation */
552 int rc = SQLITE_OK; /* Value to return */ 528 int rc = SQLITE_OK; /* Value to return */
553 sqlite3 *db = p->db; /* The database */ 529 sqlite3 *db = p->db; /* The database */
554 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ 530 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
555 u8 encoding = ENC(db); /* The database encoding */ 531 u8 encoding = ENC(db); /* The database encoding */
532 int iCompare = 0; /* Result of last OP_Compare operation */
533 unsigned nVmStep = 0; /* Number of virtual machine steps */
556 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 534 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
557 int checkProgress; /* True if progress callbacks are enabled */ 535 unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
558 int nProgressOps = 0; /* Opcodes executed since progress callback. */
559 #endif 536 #endif
560 Mem *aMem = p->aMem; /* Copy of p->aMem */ 537 Mem *aMem = p->aMem; /* Copy of p->aMem */
561 Mem *pIn1 = 0; /* 1st input operand */ 538 Mem *pIn1 = 0; /* 1st input operand */
562 Mem *pIn2 = 0; /* 2nd input operand */ 539 Mem *pIn2 = 0; /* 2nd input operand */
563 Mem *pIn3 = 0; /* 3rd input operand */ 540 Mem *pIn3 = 0; /* 3rd input operand */
564 Mem *pOut = 0; /* Output operand */ 541 Mem *pOut = 0; /* Output operand */
565 int iCompare = 0; /* Result of last OP_Compare operation */
566 int *aPermute = 0; /* Permutation of columns for OP_Compare */ 542 int *aPermute = 0; /* Permutation of columns for OP_Compare */
543 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
567 #ifdef VDBE_PROFILE 544 #ifdef VDBE_PROFILE
568 u64 start; /* CPU clock count at start of opcode */ 545 u64 start; /* CPU clock count at start of opcode */
569 int origPc; /* Program counter at start of opcode */
570 #endif 546 #endif
571 /*** INSERT STACK UNION HERE ***/ 547 /*** INSERT STACK UNION HERE ***/
572 548
573 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ 549 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
574 sqlite3VdbeEnter(p); 550 sqlite3VdbeEnter(p);
575 if( p->rc==SQLITE_NOMEM ){ 551 if( p->rc==SQLITE_NOMEM ){
576 /* This happens if a malloc() inside a call to sqlite3_column_text() or 552 /* This happens if a malloc() inside a call to sqlite3_column_text() or
577 ** sqlite3_column_text16() failed. */ 553 ** sqlite3_column_text16() failed. */
578 goto no_mem; 554 goto no_mem;
579 } 555 }
580 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); 556 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
557 assert( p->bIsReader || p->readOnly!=0 );
581 p->rc = SQLITE_OK; 558 p->rc = SQLITE_OK;
559 p->iCurrentTime = 0;
582 assert( p->explain==0 ); 560 assert( p->explain==0 );
583 p->pResultSet = 0; 561 p->pResultSet = 0;
584 db->busyHandler.nBusy = 0; 562 db->busyHandler.nBusy = 0;
585 CHECK_FOR_INTERRUPT; 563 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
586 sqlite3VdbeIOTraceSql(p); 564 sqlite3VdbeIOTraceSql(p);
587 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 565 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
588 checkProgress = db->xProgress!=0; 566 if( db->xProgress ){
567 assert( 0 < db->nProgressOps );
568 nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
569 if( nProgressLimit==0 ){
570 nProgressLimit = db->nProgressOps;
571 }else{
572 nProgressLimit %= (unsigned)db->nProgressOps;
573 }
574 }
589 #endif 575 #endif
590 #ifdef SQLITE_DEBUG 576 #ifdef SQLITE_DEBUG
591 sqlite3BeginBenignMalloc(); 577 sqlite3BeginBenignMalloc();
592 if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){ 578 if( p->pc==0
579 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
580 ){
593 int i; 581 int i;
594 printf("VDBE Program Listing:\n"); 582 int once = 1;
595 sqlite3VdbePrintSql(p); 583 sqlite3VdbePrintSql(p);
596 for(i=0; i<p->nOp; i++){ 584 if( p->db->flags & SQLITE_VdbeListing ){
597 sqlite3VdbePrintOp(stdout, i, &aOp[i]); 585 printf("VDBE Program Listing:\n");
586 for(i=0; i<p->nOp; i++){
587 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
588 }
598 } 589 }
590 if( p->db->flags & SQLITE_VdbeEQP ){
591 for(i=0; i<p->nOp; i++){
592 if( aOp[i].opcode==OP_Explain ){
593 if( once ) printf("VDBE Query Plan:\n");
594 printf("%s\n", aOp[i].p4.z);
595 once = 0;
596 }
597 }
598 }
599 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
599 } 600 }
600 sqlite3EndBenignMalloc(); 601 sqlite3EndBenignMalloc();
601 #endif 602 #endif
602 for(pc=p->pc; rc==SQLITE_OK; pc++){ 603 for(pc=p->pc; rc==SQLITE_OK; pc++){
603 assert( pc>=0 && pc<p->nOp ); 604 assert( pc>=0 && pc<p->nOp );
604 if( db->mallocFailed ) goto no_mem; 605 if( db->mallocFailed ) goto no_mem;
605 #ifdef VDBE_PROFILE 606 #ifdef VDBE_PROFILE
606 origPc = pc;
607 start = sqlite3Hwtime(); 607 start = sqlite3Hwtime();
608 #endif 608 #endif
609 nVmStep++;
609 pOp = &aOp[pc]; 610 pOp = &aOp[pc];
610 611
611 /* Only allow tracing if SQLITE_DEBUG is defined. 612 /* Only allow tracing if SQLITE_DEBUG is defined.
612 */ 613 */
613 #ifdef SQLITE_DEBUG 614 #ifdef SQLITE_DEBUG
614 if( p->trace ){ 615 if( db->flags & SQLITE_VdbeTrace ){
615 if( pc==0 ){ 616 sqlite3VdbePrintOp(stdout, pc, pOp);
616 printf("VDBE Execution Trace:\n");
617 sqlite3VdbePrintSql(p);
618 }
619 sqlite3VdbePrintOp(p->trace, pc, pOp);
620 } 617 }
621 #endif 618 #endif
622 619
623 620
624 /* Check to see if we need to simulate an interrupt. This only happens 621 /* Check to see if we need to simulate an interrupt. This only happens
625 ** if we have a special test build. 622 ** if we have a special test build.
626 */ 623 */
627 #ifdef SQLITE_TEST 624 #ifdef SQLITE_TEST
628 if( sqlite3_interrupt_count>0 ){ 625 if( sqlite3_interrupt_count>0 ){
629 sqlite3_interrupt_count--; 626 sqlite3_interrupt_count--;
630 if( sqlite3_interrupt_count==0 ){ 627 if( sqlite3_interrupt_count==0 ){
631 sqlite3_interrupt(db); 628 sqlite3_interrupt(db);
632 } 629 }
633 } 630 }
634 #endif 631 #endif
635 632
636 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 633 /* On any opcode with the "out2-prerelease" tag, free any
637 /* Call the progress callback if it is configured and the required number
638 ** of VDBE ops have been executed (either since this invocation of
639 ** sqlite3VdbeExec() or since last time the progress callback was called).
640 ** If the progress callback returns non-zero, exit the virtual machine with
641 ** a return code SQLITE_ABORT.
642 */
643 if( checkProgress ){
644 if( db->nProgressOps==nProgressOps ){
645 int prc;
646 prc = db->xProgress(db->pProgressArg);
647 if( prc!=0 ){
648 rc = SQLITE_INTERRUPT;
649 goto vdbe_error_halt;
650 }
651 nProgressOps = 0;
652 }
653 nProgressOps++;
654 }
655 #endif
656
657 /* On any opcode with the "out2-prerelase" tag, free any
658 ** external allocations out of mem[p2] and set mem[p2] to be 634 ** external allocations out of mem[p2] and set mem[p2] to be
659 ** an undefined integer. Opcodes will either fill in the integer 635 ** an undefined integer. Opcodes will either fill in the integer
660 ** value or convert mem[p2] to a different type. 636 ** value or convert mem[p2] to a different type.
661 */ 637 */
662 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] ); 638 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
663 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){ 639 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
664 assert( pOp->p2>0 ); 640 assert( pOp->p2>0 );
665 assert( pOp->p2<=p->nMem ); 641 assert( pOp->p2<=(p->nMem-p->nCursor) );
666 pOut = &aMem[pOp->p2]; 642 pOut = &aMem[pOp->p2];
667 memAboutToChange(p, pOut); 643 memAboutToChange(p, pOut);
668 sqlite3VdbeMemReleaseExternal(pOut); 644 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
669 pOut->flags = MEM_Int; 645 pOut->flags = MEM_Int;
670 } 646 }
671 647
672 /* Sanity checking on other operands */ 648 /* Sanity checking on other operands */
673 #ifdef SQLITE_DEBUG 649 #ifdef SQLITE_DEBUG
674 if( (pOp->opflags & OPFLG_IN1)!=0 ){ 650 if( (pOp->opflags & OPFLG_IN1)!=0 ){
675 assert( pOp->p1>0 ); 651 assert( pOp->p1>0 );
676 assert( pOp->p1<=p->nMem ); 652 assert( pOp->p1<=(p->nMem-p->nCursor) );
677 assert( memIsValid(&aMem[pOp->p1]) ); 653 assert( memIsValid(&aMem[pOp->p1]) );
654 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
678 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); 655 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
679 } 656 }
680 if( (pOp->opflags & OPFLG_IN2)!=0 ){ 657 if( (pOp->opflags & OPFLG_IN2)!=0 ){
681 assert( pOp->p2>0 ); 658 assert( pOp->p2>0 );
682 assert( pOp->p2<=p->nMem ); 659 assert( pOp->p2<=(p->nMem-p->nCursor) );
683 assert( memIsValid(&aMem[pOp->p2]) ); 660 assert( memIsValid(&aMem[pOp->p2]) );
661 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
684 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); 662 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
685 } 663 }
686 if( (pOp->opflags & OPFLG_IN3)!=0 ){ 664 if( (pOp->opflags & OPFLG_IN3)!=0 ){
687 assert( pOp->p3>0 ); 665 assert( pOp->p3>0 );
688 assert( pOp->p3<=p->nMem ); 666 assert( pOp->p3<=(p->nMem-p->nCursor) );
689 assert( memIsValid(&aMem[pOp->p3]) ); 667 assert( memIsValid(&aMem[pOp->p3]) );
668 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
690 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); 669 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
691 } 670 }
692 if( (pOp->opflags & OPFLG_OUT2)!=0 ){ 671 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
693 assert( pOp->p2>0 ); 672 assert( pOp->p2>0 );
694 assert( pOp->p2<=p->nMem ); 673 assert( pOp->p2<=(p->nMem-p->nCursor) );
695 memAboutToChange(p, &aMem[pOp->p2]); 674 memAboutToChange(p, &aMem[pOp->p2]);
696 } 675 }
697 if( (pOp->opflags & OPFLG_OUT3)!=0 ){ 676 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
698 assert( pOp->p3>0 ); 677 assert( pOp->p3>0 );
699 assert( pOp->p3<=p->nMem ); 678 assert( pOp->p3<=(p->nMem-p->nCursor) );
700 memAboutToChange(p, &aMem[pOp->p3]); 679 memAboutToChange(p, &aMem[pOp->p3]);
701 } 680 }
702 #endif 681 #endif
703 682
704 switch( pOp->opcode ){ 683 switch( pOp->opcode ){
705 684
706 /***************************************************************************** 685 /*****************************************************************************
707 ** What follows is a massive switch statement where each case implements a 686 ** What follows is a massive switch statement where each case implements a
708 ** separate instruction in the virtual machine. If we follow the usual 687 ** separate instruction in the virtual machine. If we follow the usual
709 ** indentation conventions, each case should be indented by 6 spaces. But 688 ** indentation conventions, each case should be indented by 6 spaces. But
(...skipping 27 matching lines...) Expand all
737 ** Do not deviate from the formatting style currently in use. 716 ** Do not deviate from the formatting style currently in use.
738 ** 717 **
739 *****************************************************************************/ 718 *****************************************************************************/
740 719
741 /* Opcode: Goto * P2 * * * 720 /* Opcode: Goto * P2 * * *
742 ** 721 **
743 ** An unconditional jump to address P2. 722 ** An unconditional jump to address P2.
744 ** The next instruction executed will be 723 ** The next instruction executed will be
745 ** the one at index P2 from the beginning of 724 ** the one at index P2 from the beginning of
746 ** the program. 725 ** the program.
726 **
727 ** The P1 parameter is not actually used by this opcode. However, it
728 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
729 ** that this Goto is the bottom of a loop and that the lines from P2 down
730 ** to the current line should be indented for EXPLAIN output.
747 */ 731 */
748 case OP_Goto: { /* jump */ 732 case OP_Goto: { /* jump */
749 CHECK_FOR_INTERRUPT;
750 pc = pOp->p2 - 1; 733 pc = pOp->p2 - 1;
734
735 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
736 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
737 ** completion. Check to see if sqlite3_interrupt() has been called
738 ** or if the progress callback needs to be invoked.
739 **
740 ** This code uses unstructured "goto" statements and does not look clean.
741 ** But that is not due to sloppy coding habits. The code is written this
742 ** way for performance, to avoid having to run the interrupt and progress
743 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
744 ** faster according to "valgrind --tool=cachegrind" */
745 check_for_interrupt:
746 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
747 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
748 /* Call the progress callback if it is configured and the required number
749 ** of VDBE ops have been executed (either since this invocation of
750 ** sqlite3VdbeExec() or since last time the progress callback was called).
751 ** If the progress callback returns non-zero, exit the virtual machine with
752 ** a return code SQLITE_ABORT.
753 */
754 if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
755 assert( db->nProgressOps!=0 );
756 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
757 if( db->xProgress(db->pProgressArg) ){
758 rc = SQLITE_INTERRUPT;
759 goto vdbe_error_halt;
760 }
761 }
762 #endif
763
751 break; 764 break;
752 } 765 }
753 766
754 /* Opcode: Gosub P1 P2 * * * 767 /* Opcode: Gosub P1 P2 * * *
755 ** 768 **
756 ** Write the current address onto register P1 769 ** Write the current address onto register P1
757 ** and then jump to address P2. 770 ** and then jump to address P2.
758 */ 771 */
759 case OP_Gosub: { /* jump, in1 */ 772 case OP_Gosub: { /* jump */
773 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
760 pIn1 = &aMem[pOp->p1]; 774 pIn1 = &aMem[pOp->p1];
761 assert( (pIn1->flags & MEM_Dyn)==0 ); 775 assert( VdbeMemDynamic(pIn1)==0 );
762 memAboutToChange(p, pIn1); 776 memAboutToChange(p, pIn1);
763 pIn1->flags = MEM_Int; 777 pIn1->flags = MEM_Int;
764 pIn1->u.i = pc; 778 pIn1->u.i = pc;
765 REGISTER_TRACE(pOp->p1, pIn1); 779 REGISTER_TRACE(pOp->p1, pIn1);
766 pc = pOp->p2 - 1; 780 pc = pOp->p2 - 1;
767 break; 781 break;
768 } 782 }
769 783
770 /* Opcode: Return P1 * * * * 784 /* Opcode: Return P1 * * * *
771 ** 785 **
772 ** Jump to the next instruction after the address in register P1. 786 ** Jump to the next instruction after the address in register P1. After
787 ** the jump, register P1 becomes undefined.
773 */ 788 */
774 case OP_Return: { /* in1 */ 789 case OP_Return: { /* in1 */
775 pIn1 = &aMem[pOp->p1]; 790 pIn1 = &aMem[pOp->p1];
776 assert( pIn1->flags & MEM_Int ); 791 assert( pIn1->flags==MEM_Int );
777 pc = (int)pIn1->u.i; 792 pc = (int)pIn1->u.i;
793 pIn1->flags = MEM_Undefined;
778 break; 794 break;
779 } 795 }
780 796
781 /* Opcode: Yield P1 * * * * 797 /* Opcode: InitCoroutine P1 P2 P3 * *
782 ** 798 **
783 ** Swap the program counter with the value in register P1. 799 ** Set up register P1 so that it will Yield to the coroutine
800 ** located at address P3.
801 **
802 ** If P2!=0 then the coroutine implementation immediately follows
803 ** this opcode. So jump over the coroutine implementation to
804 ** address P2.
805 **
806 ** See also: EndCoroutine
784 */ 807 */
785 case OP_Yield: { /* in1 */ 808 case OP_InitCoroutine: { /* jump */
809 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
810 assert( pOp->p2>=0 && pOp->p2<p->nOp );
811 assert( pOp->p3>=0 && pOp->p3<p->nOp );
812 pOut = &aMem[pOp->p1];
813 assert( !VdbeMemDynamic(pOut) );
814 pOut->u.i = pOp->p3 - 1;
815 pOut->flags = MEM_Int;
816 if( pOp->p2 ) pc = pOp->p2 - 1;
817 break;
818 }
819
820 /* Opcode: EndCoroutine P1 * * * *
821 **
822 ** The instruction at the address in register P1 is a Yield.
823 ** Jump to the P2 parameter of that Yield.
824 ** After the jump, register P1 becomes undefined.
825 **
826 ** See also: InitCoroutine
827 */
828 case OP_EndCoroutine: { /* in1 */
829 VdbeOp *pCaller;
830 pIn1 = &aMem[pOp->p1];
831 assert( pIn1->flags==MEM_Int );
832 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
833 pCaller = &aOp[pIn1->u.i];
834 assert( pCaller->opcode==OP_Yield );
835 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
836 pc = pCaller->p2 - 1;
837 pIn1->flags = MEM_Undefined;
838 break;
839 }
840
841 /* Opcode: Yield P1 P2 * * *
842 **
843 ** Swap the program counter with the value in register P1. This
844 ** has the effect of yielding to a coroutine.
845 **
846 ** If the coroutine that is launched by this instruction ends with
847 ** Yield or Return then continue to the next instruction. But if
848 ** the coroutine launched by this instruction ends with
849 ** EndCoroutine, then jump to P2 rather than continuing with the
850 ** next instruction.
851 **
852 ** See also: InitCoroutine
853 */
854 case OP_Yield: { /* in1, jump */
786 int pcDest; 855 int pcDest;
787 pIn1 = &aMem[pOp->p1]; 856 pIn1 = &aMem[pOp->p1];
788 assert( (pIn1->flags & MEM_Dyn)==0 ); 857 assert( VdbeMemDynamic(pIn1)==0 );
789 pIn1->flags = MEM_Int; 858 pIn1->flags = MEM_Int;
790 pcDest = (int)pIn1->u.i; 859 pcDest = (int)pIn1->u.i;
791 pIn1->u.i = pc; 860 pIn1->u.i = pc;
792 REGISTER_TRACE(pOp->p1, pIn1); 861 REGISTER_TRACE(pOp->p1, pIn1);
793 pc = pcDest; 862 pc = pcDest;
794 break; 863 break;
795 } 864 }
796 865
797 /* Opcode: HaltIfNull P1 P2 P3 P4 * 866 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
867 ** Synopsis: if r[P3]=null halt
798 ** 868 **
799 ** Check the value in register P3. If is is NULL then Halt using 869 ** Check the value in register P3. If it is NULL then Halt using
800 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the 870 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
801 ** value in register P3 is not NULL, then this routine is a no-op. 871 ** value in register P3 is not NULL, then this routine is a no-op.
872 ** The P5 parameter should be 1.
802 */ 873 */
803 case OP_HaltIfNull: { /* in3 */ 874 case OP_HaltIfNull: { /* in3 */
804 pIn3 = &aMem[pOp->p3]; 875 pIn3 = &aMem[pOp->p3];
805 if( (pIn3->flags & MEM_Null)==0 ) break; 876 if( (pIn3->flags & MEM_Null)==0 ) break;
806 /* Fall through into OP_Halt */ 877 /* Fall through into OP_Halt */
807 } 878 }
808 879
809 /* Opcode: Halt P1 P2 * P4 * 880 /* Opcode: Halt P1 P2 * P4 P5
810 ** 881 **
811 ** Exit immediately. All open cursors, etc are closed 882 ** Exit immediately. All open cursors, etc are closed
812 ** automatically. 883 ** automatically.
813 ** 884 **
814 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), 885 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
815 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). 886 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
816 ** For errors, it can be some other value. If P1!=0 then P2 will determine 887 ** For errors, it can be some other value. If P1!=0 then P2 will determine
817 ** whether or not to rollback the current transaction. Do not rollback 888 ** whether or not to rollback the current transaction. Do not rollback
818 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, 889 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
819 ** then back out all changes that have occurred during this execution of the 890 ** then back out all changes that have occurred during this execution of the
820 ** VDBE, but do not rollback the transaction. 891 ** VDBE, but do not rollback the transaction.
821 ** 892 **
822 ** If P4 is not null then it is an error message string. 893 ** If P4 is not null then it is an error message string.
823 ** 894 **
895 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
896 **
897 ** 0: (no change)
898 ** 1: NOT NULL contraint failed: P4
899 ** 2: UNIQUE constraint failed: P4
900 ** 3: CHECK constraint failed: P4
901 ** 4: FOREIGN KEY constraint failed: P4
902 **
903 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
904 ** omitted.
905 **
824 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of 906 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
825 ** every program. So a jump past the last instruction of the program 907 ** every program. So a jump past the last instruction of the program
826 ** is the same as executing Halt. 908 ** is the same as executing Halt.
827 */ 909 */
828 case OP_Halt: { 910 case OP_Halt: {
911 const char *zType;
912 const char *zLogFmt;
913
829 if( pOp->p1==SQLITE_OK && p->pFrame ){ 914 if( pOp->p1==SQLITE_OK && p->pFrame ){
830 /* Halt the sub-program. Return control to the parent frame. */ 915 /* Halt the sub-program. Return control to the parent frame. */
831 VdbeFrame *pFrame = p->pFrame; 916 VdbeFrame *pFrame = p->pFrame;
832 p->pFrame = pFrame->pParent; 917 p->pFrame = pFrame->pParent;
833 p->nFrame--; 918 p->nFrame--;
834 sqlite3VdbeSetChanges(db, p->nChange); 919 sqlite3VdbeSetChanges(db, p->nChange);
835 pc = sqlite3VdbeFrameRestore(pFrame); 920 pc = sqlite3VdbeFrameRestore(pFrame);
921 lastRowid = db->lastRowid;
836 if( pOp->p2==OE_Ignore ){ 922 if( pOp->p2==OE_Ignore ){
837 /* Instruction pc is the OP_Program that invoked the sub-program 923 /* Instruction pc is the OP_Program that invoked the sub-program
838 ** currently being halted. If the p2 instruction of this OP_Halt 924 ** currently being halted. If the p2 instruction of this OP_Halt
839 ** instruction is set to OE_Ignore, then the sub-program is throwing 925 ** instruction is set to OE_Ignore, then the sub-program is throwing
840 ** an IGNORE exception. In this case jump to the address specified 926 ** an IGNORE exception. In this case jump to the address specified
841 ** as the p2 of the calling OP_Program. */ 927 ** as the p2 of the calling OP_Program. */
842 pc = p->aOp[pc].p2-1; 928 pc = p->aOp[pc].p2-1;
843 } 929 }
844 aOp = p->aOp; 930 aOp = p->aOp;
845 aMem = p->aMem; 931 aMem = p->aMem;
846 break; 932 break;
847 } 933 }
848
849 p->rc = pOp->p1; 934 p->rc = pOp->p1;
850 p->errorAction = (u8)pOp->p2; 935 p->errorAction = (u8)pOp->p2;
851 p->pc = pc; 936 p->pc = pc;
852 if( pOp->p4.z ){ 937 if( p->rc ){
853 assert( p->rc!=SQLITE_OK ); 938 if( pOp->p5 ){
854 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); 939 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
855 testcase( sqlite3GlobalConfig.xLog!=0 ); 940 "FOREIGN KEY" };
856 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z); 941 assert( pOp->p5>=1 && pOp->p5<=4 );
857 }else if( p->rc ){ 942 testcase( pOp->p5==1 );
858 testcase( sqlite3GlobalConfig.xLog!=0 ); 943 testcase( pOp->p5==2 );
859 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql); 944 testcase( pOp->p5==3 );
945 testcase( pOp->p5==4 );
946 zType = azType[pOp->p5-1];
947 }else{
948 zType = 0;
949 }
950 assert( zType!=0 || pOp->p4.z!=0 );
951 zLogFmt = "abort at %d in [%s]: %s";
952 if( zType && pOp->p4.z ){
953 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
954 zType, pOp->p4.z);
955 }else if( pOp->p4.z ){
956 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
957 }else{
958 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
959 }
960 sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
860 } 961 }
861 rc = sqlite3VdbeHalt(p); 962 rc = sqlite3VdbeHalt(p);
862 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); 963 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
863 if( rc==SQLITE_BUSY ){ 964 if( rc==SQLITE_BUSY ){
864 p->rc = rc = SQLITE_BUSY; 965 p->rc = rc = SQLITE_BUSY;
865 }else{ 966 }else{
866 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ); 967 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
867 assert( rc==SQLITE_OK || db->nDeferredCons>0 ); 968 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
868 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; 969 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
869 } 970 }
870 goto vdbe_return; 971 goto vdbe_return;
871 } 972 }
872 973
873 /* Opcode: Integer P1 P2 * * * 974 /* Opcode: Integer P1 P2 * * *
975 ** Synopsis: r[P2]=P1
874 ** 976 **
875 ** The 32-bit integer value P1 is written into register P2. 977 ** The 32-bit integer value P1 is written into register P2.
876 */ 978 */
877 case OP_Integer: { /* out2-prerelease */ 979 case OP_Integer: { /* out2-prerelease */
878 pOut->u.i = pOp->p1; 980 pOut->u.i = pOp->p1;
879 break; 981 break;
880 } 982 }
881 983
882 /* Opcode: Int64 * P2 * P4 * 984 /* Opcode: Int64 * P2 * P4 *
985 ** Synopsis: r[P2]=P4
883 ** 986 **
884 ** P4 is a pointer to a 64-bit integer value. 987 ** P4 is a pointer to a 64-bit integer value.
885 ** Write that value into register P2. 988 ** Write that value into register P2.
886 */ 989 */
887 case OP_Int64: { /* out2-prerelease */ 990 case OP_Int64: { /* out2-prerelease */
888 assert( pOp->p4.pI64!=0 ); 991 assert( pOp->p4.pI64!=0 );
889 pOut->u.i = *pOp->p4.pI64; 992 pOut->u.i = *pOp->p4.pI64;
890 break; 993 break;
891 } 994 }
892 995
893 #ifndef SQLITE_OMIT_FLOATING_POINT 996 #ifndef SQLITE_OMIT_FLOATING_POINT
894 /* Opcode: Real * P2 * P4 * 997 /* Opcode: Real * P2 * P4 *
998 ** Synopsis: r[P2]=P4
895 ** 999 **
896 ** P4 is a pointer to a 64-bit floating point value. 1000 ** P4 is a pointer to a 64-bit floating point value.
897 ** Write that value into register P2. 1001 ** Write that value into register P2.
898 */ 1002 */
899 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ 1003 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
900 pOut->flags = MEM_Real; 1004 pOut->flags = MEM_Real;
901 assert( !sqlite3IsNaN(*pOp->p4.pReal) ); 1005 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
902 pOut->r = *pOp->p4.pReal; 1006 pOut->u.r = *pOp->p4.pReal;
903 break; 1007 break;
904 } 1008 }
905 #endif 1009 #endif
906 1010
907 /* Opcode: String8 * P2 * P4 * 1011 /* Opcode: String8 * P2 * P4 *
1012 ** Synopsis: r[P2]='P4'
908 ** 1013 **
909 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 1014 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
910 ** into an OP_String before it is executed for the first time. 1015 ** into a String before it is executed for the first time. During
1016 ** this transformation, the length of string P4 is computed and stored
1017 ** as the P1 parameter.
911 */ 1018 */
912 case OP_String8: { /* same as TK_STRING, out2-prerelease */ 1019 case OP_String8: { /* same as TK_STRING, out2-prerelease */
913 assert( pOp->p4.z!=0 ); 1020 assert( pOp->p4.z!=0 );
914 pOp->opcode = OP_String; 1021 pOp->opcode = OP_String;
915 pOp->p1 = sqlite3Strlen30(pOp->p4.z); 1022 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
916 1023
917 #ifndef SQLITE_OMIT_UTF16 1024 #ifndef SQLITE_OMIT_UTF16
918 if( encoding!=SQLITE_UTF8 ){ 1025 if( encoding!=SQLITE_UTF8 ){
919 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); 1026 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
920 if( rc==SQLITE_TOOBIG ) goto too_big; 1027 if( rc==SQLITE_TOOBIG ) goto too_big;
921 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; 1028 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
922 assert( pOut->zMalloc==pOut->z ); 1029 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
923 assert( pOut->flags & MEM_Dyn ); 1030 assert( VdbeMemDynamic(pOut)==0 );
924 pOut->zMalloc = 0; 1031 pOut->szMalloc = 0;
925 pOut->flags |= MEM_Static; 1032 pOut->flags |= MEM_Static;
926 pOut->flags &= ~MEM_Dyn;
927 if( pOp->p4type==P4_DYNAMIC ){ 1033 if( pOp->p4type==P4_DYNAMIC ){
928 sqlite3DbFree(db, pOp->p4.z); 1034 sqlite3DbFree(db, pOp->p4.z);
929 } 1035 }
930 pOp->p4type = P4_DYNAMIC; 1036 pOp->p4type = P4_DYNAMIC;
931 pOp->p4.z = pOut->z; 1037 pOp->p4.z = pOut->z;
932 pOp->p1 = pOut->n; 1038 pOp->p1 = pOut->n;
933 } 1039 }
934 #endif 1040 #endif
935 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1041 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
936 goto too_big; 1042 goto too_big;
937 } 1043 }
938 /* Fall through to the next case, OP_String */ 1044 /* Fall through to the next case, OP_String */
939 } 1045 }
940 1046
941 /* Opcode: String P1 P2 * P4 * 1047 /* Opcode: String P1 P2 * P4 *
1048 ** Synopsis: r[P2]='P4' (len=P1)
942 ** 1049 **
943 ** The string value P4 of length P1 (bytes) is stored in register P2. 1050 ** The string value P4 of length P1 (bytes) is stored in register P2.
944 */ 1051 */
945 case OP_String: { /* out2-prerelease */ 1052 case OP_String: { /* out2-prerelease */
946 assert( pOp->p4.z!=0 ); 1053 assert( pOp->p4.z!=0 );
947 pOut->flags = MEM_Str|MEM_Static|MEM_Term; 1054 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
948 pOut->z = pOp->p4.z; 1055 pOut->z = pOp->p4.z;
949 pOut->n = pOp->p1; 1056 pOut->n = pOp->p1;
950 pOut->enc = encoding; 1057 pOut->enc = encoding;
951 UPDATE_MAX_BLOBSIZE(pOut); 1058 UPDATE_MAX_BLOBSIZE(pOut);
952 break; 1059 break;
953 } 1060 }
954 1061
955 /* Opcode: Null * P2 * * * 1062 /* Opcode: Null P1 P2 P3 * *
1063 ** Synopsis: r[P2..P3]=NULL
956 ** 1064 **
957 ** Write a NULL into register P2. 1065 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1066 ** NULL into register P3 and every register in between P2 and P3. If P3
1067 ** is less than P2 (typically P3 is zero) then only register P2 is
1068 ** set to NULL.
1069 **
1070 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1071 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1072 ** OP_Ne or OP_Eq.
958 */ 1073 */
959 case OP_Null: { /* out2-prerelease */ 1074 case OP_Null: { /* out2-prerelease */
960 pOut->flags = MEM_Null; 1075 int cnt;
1076 u16 nullFlag;
1077 cnt = pOp->p3-pOp->p2;
1078 assert( pOp->p3<=(p->nMem-p->nCursor) );
1079 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1080 while( cnt>0 ){
1081 pOut++;
1082 memAboutToChange(p, pOut);
1083 sqlite3VdbeMemSetNull(pOut);
1084 pOut->flags = nullFlag;
1085 cnt--;
1086 }
961 break; 1087 break;
962 } 1088 }
963 1089
1090 /* Opcode: SoftNull P1 * * * *
1091 ** Synopsis: r[P1]=NULL
1092 **
1093 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1094 ** instruction, but do not free any string or blob memory associated with
1095 ** the register, so that if the value was a string or blob that was
1096 ** previously copied using OP_SCopy, the copies will continue to be valid.
1097 */
1098 case OP_SoftNull: {
1099 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
1100 pOut = &aMem[pOp->p1];
1101 pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
1102 break;
1103 }
964 1104
965 /* Opcode: Blob P1 P2 * P4 1105 /* Opcode: Blob P1 P2 * P4 *
1106 ** Synopsis: r[P2]=P4 (len=P1)
966 ** 1107 **
967 ** P4 points to a blob of data P1 bytes long. Store this 1108 ** P4 points to a blob of data P1 bytes long. Store this
968 ** blob in register P2. 1109 ** blob in register P2.
969 */ 1110 */
970 case OP_Blob: { /* out2-prerelease */ 1111 case OP_Blob: { /* out2-prerelease */
971 assert( pOp->p1 <= SQLITE_MAX_LENGTH ); 1112 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
972 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); 1113 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
973 pOut->enc = encoding; 1114 pOut->enc = encoding;
974 UPDATE_MAX_BLOBSIZE(pOut); 1115 UPDATE_MAX_BLOBSIZE(pOut);
975 break; 1116 break;
976 } 1117 }
977 1118
978 /* Opcode: Variable P1 P2 * P4 * 1119 /* Opcode: Variable P1 P2 * P4 *
1120 ** Synopsis: r[P2]=parameter(P1,P4)
979 ** 1121 **
980 ** Transfer the values of bound parameter P1 into register P2 1122 ** Transfer the values of bound parameter P1 into register P2
981 ** 1123 **
982 ** If the parameter is named, then its name appears in P4 and P3==1. 1124 ** If the parameter is named, then its name appears in P4.
983 ** The P4 value is used by sqlite3_bind_parameter_name(). 1125 ** The P4 value is used by sqlite3_bind_parameter_name().
984 */ 1126 */
985 case OP_Variable: { /* out2-prerelease */ 1127 case OP_Variable: { /* out2-prerelease */
986 Mem *pVar; /* Value being transferred */ 1128 Mem *pVar; /* Value being transferred */
987 1129
988 assert( pOp->p1>0 && pOp->p1<=p->nVar ); 1130 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1131 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
989 pVar = &p->aVar[pOp->p1 - 1]; 1132 pVar = &p->aVar[pOp->p1 - 1];
990 if( sqlite3VdbeMemTooBig(pVar) ){ 1133 if( sqlite3VdbeMemTooBig(pVar) ){
991 goto too_big; 1134 goto too_big;
992 } 1135 }
993 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); 1136 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
994 UPDATE_MAX_BLOBSIZE(pOut); 1137 UPDATE_MAX_BLOBSIZE(pOut);
995 break; 1138 break;
996 } 1139 }
997 1140
998 /* Opcode: Move P1 P2 P3 * * 1141 /* Opcode: Move P1 P2 P3 * *
1142 ** Synopsis: r[P2@P3]=r[P1@P3]
999 ** 1143 **
1000 ** Move the values in register P1..P1+P3-1 over into 1144 ** Move the P3 values in register P1..P1+P3-1 over into
1001 ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are 1145 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1002 ** left holding a NULL. It is an error for register ranges 1146 ** left holding a NULL. It is an error for register ranges
1003 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. 1147 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1148 ** for P3 to be less than 1.
1004 */ 1149 */
1005 case OP_Move: { 1150 case OP_Move: {
1006 char *zMalloc; /* Holding variable for allocated memory */
1007 int n; /* Number of registers left to copy */ 1151 int n; /* Number of registers left to copy */
1008 int p1; /* Register to copy from */ 1152 int p1; /* Register to copy from */
1009 int p2; /* Register to copy to */ 1153 int p2; /* Register to copy to */
1010 1154
1011 n = pOp->p3; 1155 n = pOp->p3;
1012 p1 = pOp->p1; 1156 p1 = pOp->p1;
1013 p2 = pOp->p2; 1157 p2 = pOp->p2;
1014 assert( n>0 && p1>0 && p2>0 ); 1158 assert( n>0 && p1>0 && p2>0 );
1015 assert( p1+n<=p2 || p2+n<=p1 ); 1159 assert( p1+n<=p2 || p2+n<=p1 );
1016 1160
1017 pIn1 = &aMem[p1]; 1161 pIn1 = &aMem[p1];
1018 pOut = &aMem[p2]; 1162 pOut = &aMem[p2];
1019 while( n-- ){ 1163 do{
1020 assert( pOut<=&aMem[p->nMem] ); 1164 assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
1021 assert( pIn1<=&aMem[p->nMem] ); 1165 assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
1022 assert( memIsValid(pIn1) ); 1166 assert( memIsValid(pIn1) );
1023 memAboutToChange(p, pOut); 1167 memAboutToChange(p, pOut);
1024 zMalloc = pOut->zMalloc;
1025 pOut->zMalloc = 0;
1026 sqlite3VdbeMemMove(pOut, pIn1); 1168 sqlite3VdbeMemMove(pOut, pIn1);
1027 pIn1->zMalloc = zMalloc; 1169 #ifdef SQLITE_DEBUG
1170 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
1171 pOut->pScopyFrom += p1 - pOp->p2;
1172 }
1173 #endif
1028 REGISTER_TRACE(p2++, pOut); 1174 REGISTER_TRACE(p2++, pOut);
1029 pIn1++; 1175 pIn1++;
1030 pOut++; 1176 pOut++;
1177 }while( --n );
1178 break;
1179 }
1180
1181 /* Opcode: Copy P1 P2 P3 * *
1182 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1183 **
1184 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1185 **
1186 ** This instruction makes a deep copy of the value. A duplicate
1187 ** is made of any string or blob constant. See also OP_SCopy.
1188 */
1189 case OP_Copy: {
1190 int n;
1191
1192 n = pOp->p3;
1193 pIn1 = &aMem[pOp->p1];
1194 pOut = &aMem[pOp->p2];
1195 assert( pOut!=pIn1 );
1196 while( 1 ){
1197 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1198 Deephemeralize(pOut);
1199 #ifdef SQLITE_DEBUG
1200 pOut->pScopyFrom = 0;
1201 #endif
1202 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1203 if( (n--)==0 ) break;
1204 pOut++;
1205 pIn1++;
1031 } 1206 }
1032 break; 1207 break;
1033 } 1208 }
1034 1209
1035 /* Opcode: Copy P1 P2 * * *
1036 **
1037 ** Make a copy of register P1 into register P2.
1038 **
1039 ** This instruction makes a deep copy of the value. A duplicate
1040 ** is made of any string or blob constant. See also OP_SCopy.
1041 */
1042 case OP_Copy: { /* in1, out2 */
1043 pIn1 = &aMem[pOp->p1];
1044 pOut = &aMem[pOp->p2];
1045 assert( pOut!=pIn1 );
1046 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1047 Deephemeralize(pOut);
1048 REGISTER_TRACE(pOp->p2, pOut);
1049 break;
1050 }
1051
1052 /* Opcode: SCopy P1 P2 * * * 1210 /* Opcode: SCopy P1 P2 * * *
1211 ** Synopsis: r[P2]=r[P1]
1053 ** 1212 **
1054 ** Make a shallow copy of register P1 into register P2. 1213 ** Make a shallow copy of register P1 into register P2.
1055 ** 1214 **
1056 ** This instruction makes a shallow copy of the value. If the value 1215 ** This instruction makes a shallow copy of the value. If the value
1057 ** is a string or blob, then the copy is only a pointer to the 1216 ** is a string or blob, then the copy is only a pointer to the
1058 ** original and hence if the original changes so will the copy. 1217 ** original and hence if the original changes so will the copy.
1059 ** Worse, if the original is deallocated, the copy becomes invalid. 1218 ** Worse, if the original is deallocated, the copy becomes invalid.
1060 ** Thus the program must guarantee that the original will not change 1219 ** Thus the program must guarantee that the original will not change
1061 ** during the lifetime of the copy. Use OP_Copy to make a complete 1220 ** during the lifetime of the copy. Use OP_Copy to make a complete
1062 ** copy. 1221 ** copy.
1063 */ 1222 */
1064 case OP_SCopy: { /* in1, out2 */ 1223 case OP_SCopy: { /* out2 */
1065 pIn1 = &aMem[pOp->p1]; 1224 pIn1 = &aMem[pOp->p1];
1066 pOut = &aMem[pOp->p2]; 1225 pOut = &aMem[pOp->p2];
1067 assert( pOut!=pIn1 ); 1226 assert( pOut!=pIn1 );
1068 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); 1227 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1069 #ifdef SQLITE_DEBUG 1228 #ifdef SQLITE_DEBUG
1070 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; 1229 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
1071 #endif 1230 #endif
1072 REGISTER_TRACE(pOp->p2, pOut);
1073 break; 1231 break;
1074 } 1232 }
1075 1233
1076 /* Opcode: ResultRow P1 P2 * * * 1234 /* Opcode: ResultRow P1 P2 * * *
1235 ** Synopsis: output=r[P1@P2]
1077 ** 1236 **
1078 ** The registers P1 through P1+P2-1 contain a single row of 1237 ** The registers P1 through P1+P2-1 contain a single row of
1079 ** results. This opcode causes the sqlite3_step() call to terminate 1238 ** results. This opcode causes the sqlite3_step() call to terminate
1080 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt 1239 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1081 ** structure to provide access to the top P1 values as the result 1240 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1082 ** row. 1241 ** the result row.
1083 */ 1242 */
1084 case OP_ResultRow: { 1243 case OP_ResultRow: {
1085 Mem *pMem; 1244 Mem *pMem;
1086 int i; 1245 int i;
1087 assert( p->nResColumn==pOp->p2 ); 1246 assert( p->nResColumn==pOp->p2 );
1088 assert( pOp->p1>0 ); 1247 assert( pOp->p1>0 );
1089 assert( pOp->p1+pOp->p2<=p->nMem+1 ); 1248 assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
1249
1250 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1251 /* Run the progress counter just before returning.
1252 */
1253 if( db->xProgress!=0
1254 && nVmStep>=nProgressLimit
1255 && db->xProgress(db->pProgressArg)!=0
1256 ){
1257 rc = SQLITE_INTERRUPT;
1258 goto vdbe_error_halt;
1259 }
1260 #endif
1090 1261
1091 /* If this statement has violated immediate foreign key constraints, do 1262 /* If this statement has violated immediate foreign key constraints, do
1092 ** not return the number of rows modified. And do not RELEASE the statement 1263 ** not return the number of rows modified. And do not RELEASE the statement
1093 ** transaction. It needs to be rolled back. */ 1264 ** transaction. It needs to be rolled back. */
1094 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ 1265 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
1095 assert( db->flags&SQLITE_CountRows ); 1266 assert( db->flags&SQLITE_CountRows );
1096 assert( p->usesStmtJournal ); 1267 assert( p->usesStmtJournal );
1097 break; 1268 break;
1098 } 1269 }
1099 1270
(...skipping 16 matching lines...) Expand all
1116 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); 1287 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
1117 if( NEVER(rc!=SQLITE_OK) ){ 1288 if( NEVER(rc!=SQLITE_OK) ){
1118 break; 1289 break;
1119 } 1290 }
1120 1291
1121 /* Invalidate all ephemeral cursor row caches */ 1292 /* Invalidate all ephemeral cursor row caches */
1122 p->cacheCtr = (p->cacheCtr + 2)|1; 1293 p->cacheCtr = (p->cacheCtr + 2)|1;
1123 1294
1124 /* Make sure the results of the current row are \000 terminated 1295 /* Make sure the results of the current row are \000 terminated
1125 ** and have an assigned type. The results are de-ephemeralized as 1296 ** and have an assigned type. The results are de-ephemeralized as
1126 ** as side effect. 1297 ** a side effect.
1127 */ 1298 */
1128 pMem = p->pResultSet = &aMem[pOp->p1]; 1299 pMem = p->pResultSet = &aMem[pOp->p1];
1129 for(i=0; i<pOp->p2; i++){ 1300 for(i=0; i<pOp->p2; i++){
1130 assert( memIsValid(&pMem[i]) ); 1301 assert( memIsValid(&pMem[i]) );
1131 Deephemeralize(&pMem[i]); 1302 Deephemeralize(&pMem[i]);
1132 assert( (pMem[i].flags & MEM_Ephem)==0 1303 assert( (pMem[i].flags & MEM_Ephem)==0
1133 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); 1304 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1134 sqlite3VdbeMemNulTerminate(&pMem[i]); 1305 sqlite3VdbeMemNulTerminate(&pMem[i]);
1135 sqlite3VdbeMemStoreType(&pMem[i]);
1136 REGISTER_TRACE(pOp->p1+i, &pMem[i]); 1306 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1137 } 1307 }
1138 if( db->mallocFailed ) goto no_mem; 1308 if( db->mallocFailed ) goto no_mem;
1139 1309
1140 /* Return SQLITE_ROW 1310 /* Return SQLITE_ROW
1141 */ 1311 */
1142 p->pc = pc + 1; 1312 p->pc = pc + 1;
1143 rc = SQLITE_ROW; 1313 rc = SQLITE_ROW;
1144 goto vdbe_return; 1314 goto vdbe_return;
1145 } 1315 }
1146 1316
1147 /* Opcode: Concat P1 P2 P3 * * 1317 /* Opcode: Concat P1 P2 P3 * *
1318 ** Synopsis: r[P3]=r[P2]+r[P1]
1148 ** 1319 **
1149 ** Add the text in register P1 onto the end of the text in 1320 ** Add the text in register P1 onto the end of the text in
1150 ** register P2 and store the result in register P3. 1321 ** register P2 and store the result in register P3.
1151 ** If either the P1 or P2 text are NULL then store NULL in P3. 1322 ** If either the P1 or P2 text are NULL then store NULL in P3.
1152 ** 1323 **
1153 ** P3 = P2 || P1 1324 ** P3 = P2 || P1
1154 ** 1325 **
1155 ** It is illegal for P1 and P3 to be the same register. Sometimes, 1326 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1156 ** if P3 is the same register as P2, the implementation is able 1327 ** if P3 is the same register as P2, the implementation is able
1157 ** to avoid a memcpy(). 1328 ** to avoid a memcpy().
1158 */ 1329 */
1159 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ 1330 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1160 i64 nByte; 1331 i64 nByte;
1161 1332
1162 pIn1 = &aMem[pOp->p1]; 1333 pIn1 = &aMem[pOp->p1];
1163 pIn2 = &aMem[pOp->p2]; 1334 pIn2 = &aMem[pOp->p2];
1164 pOut = &aMem[pOp->p3]; 1335 pOut = &aMem[pOp->p3];
1165 assert( pIn1!=pOut ); 1336 assert( pIn1!=pOut );
1166 if( (pIn1->flags | pIn2->flags) & MEM_Null ){ 1337 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1167 sqlite3VdbeMemSetNull(pOut); 1338 sqlite3VdbeMemSetNull(pOut);
1168 break; 1339 break;
1169 } 1340 }
1170 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; 1341 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
1171 Stringify(pIn1, encoding); 1342 Stringify(pIn1, encoding);
1172 Stringify(pIn2, encoding); 1343 Stringify(pIn2, encoding);
1173 nByte = pIn1->n + pIn2->n; 1344 nByte = pIn1->n + pIn2->n;
1174 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1345 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1175 goto too_big; 1346 goto too_big;
1176 } 1347 }
1177 MemSetTypeFlag(pOut, MEM_Str);
1178 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ 1348 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
1179 goto no_mem; 1349 goto no_mem;
1180 } 1350 }
1351 MemSetTypeFlag(pOut, MEM_Str);
1181 if( pOut!=pIn2 ){ 1352 if( pOut!=pIn2 ){
1182 memcpy(pOut->z, pIn2->z, pIn2->n); 1353 memcpy(pOut->z, pIn2->z, pIn2->n);
1183 } 1354 }
1184 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); 1355 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1185 pOut->z[nByte] = 0; 1356 pOut->z[nByte]=0;
1186 pOut->z[nByte+1] = 0; 1357 pOut->z[nByte+1] = 0;
1187 pOut->flags |= MEM_Term; 1358 pOut->flags |= MEM_Term;
1188 pOut->n = (int)nByte; 1359 pOut->n = (int)nByte;
1189 pOut->enc = encoding; 1360 pOut->enc = encoding;
1190 UPDATE_MAX_BLOBSIZE(pOut); 1361 UPDATE_MAX_BLOBSIZE(pOut);
1191 break; 1362 break;
1192 } 1363 }
1193 1364
1194 /* Opcode: Add P1 P2 P3 * * 1365 /* Opcode: Add P1 P2 P3 * *
1366 ** Synopsis: r[P3]=r[P1]+r[P2]
1195 ** 1367 **
1196 ** Add the value in register P1 to the value in register P2 1368 ** Add the value in register P1 to the value in register P2
1197 ** and store the result in register P3. 1369 ** and store the result in register P3.
1198 ** If either input is NULL, the result is NULL. 1370 ** If either input is NULL, the result is NULL.
1199 */ 1371 */
1200 /* Opcode: Multiply P1 P2 P3 * * 1372 /* Opcode: Multiply P1 P2 P3 * *
1373 ** Synopsis: r[P3]=r[P1]*r[P2]
1201 ** 1374 **
1202 ** 1375 **
1203 ** Multiply the value in register P1 by the value in register P2 1376 ** Multiply the value in register P1 by the value in register P2
1204 ** and store the result in register P3. 1377 ** and store the result in register P3.
1205 ** If either input is NULL, the result is NULL. 1378 ** If either input is NULL, the result is NULL.
1206 */ 1379 */
1207 /* Opcode: Subtract P1 P2 P3 * * 1380 /* Opcode: Subtract P1 P2 P3 * *
1381 ** Synopsis: r[P3]=r[P2]-r[P1]
1208 ** 1382 **
1209 ** Subtract the value in register P1 from the value in register P2 1383 ** Subtract the value in register P1 from the value in register P2
1210 ** and store the result in register P3. 1384 ** and store the result in register P3.
1211 ** If either input is NULL, the result is NULL. 1385 ** If either input is NULL, the result is NULL.
1212 */ 1386 */
1213 /* Opcode: Divide P1 P2 P3 * * 1387 /* Opcode: Divide P1 P2 P3 * *
1388 ** Synopsis: r[P3]=r[P2]/r[P1]
1214 ** 1389 **
1215 ** Divide the value in register P1 by the value in register P2 1390 ** Divide the value in register P1 by the value in register P2
1216 ** and store the result in register P3 (P3=P2/P1). If the value in 1391 ** and store the result in register P3 (P3=P2/P1). If the value in
1217 ** register P1 is zero, then the result is NULL. If either input is 1392 ** register P1 is zero, then the result is NULL. If either input is
1218 ** NULL, the result is NULL. 1393 ** NULL, the result is NULL.
1219 */ 1394 */
1220 /* Opcode: Remainder P1 P2 P3 * * 1395 /* Opcode: Remainder P1 P2 P3 * *
1396 ** Synopsis: r[P3]=r[P2]%r[P1]
1221 ** 1397 **
1222 ** Compute the remainder after integer division of the value in 1398 ** Compute the remainder after integer register P2 is divided by
1223 ** register P1 by the value in register P2 and store the result in P3. 1399 ** register P1 and store the result in register P3.
1224 ** If the value in register P2 is zero the result is NULL. 1400 ** If the value in register P1 is zero the result is NULL.
1225 ** If either operand is NULL, the result is NULL. 1401 ** If either operand is NULL, the result is NULL.
1226 */ 1402 */
1227 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ 1403 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1228 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ 1404 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1229 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ 1405 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1230 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ 1406 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1231 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ 1407 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1232 int flags; /* Combined MEM_* flags from both inputs */ 1408 char bIntint; /* Started out as two integer operands */
1409 u16 flags; /* Combined MEM_* flags from both inputs */
1410 u16 type1; /* Numeric type of left operand */
1411 u16 type2; /* Numeric type of right operand */
1233 i64 iA; /* Integer value of left operand */ 1412 i64 iA; /* Integer value of left operand */
1234 i64 iB; /* Integer value of right operand */ 1413 i64 iB; /* Integer value of right operand */
1235 double rA; /* Real value of left operand */ 1414 double rA; /* Real value of left operand */
1236 double rB; /* Real value of right operand */ 1415 double rB; /* Real value of right operand */
1237 1416
1238 pIn1 = &aMem[pOp->p1]; 1417 pIn1 = &aMem[pOp->p1];
1239 applyNumericAffinity(pIn1); 1418 type1 = numericType(pIn1);
1240 pIn2 = &aMem[pOp->p2]; 1419 pIn2 = &aMem[pOp->p2];
1241 applyNumericAffinity(pIn2); 1420 type2 = numericType(pIn2);
1242 pOut = &aMem[pOp->p3]; 1421 pOut = &aMem[pOp->p3];
1243 flags = pIn1->flags | pIn2->flags; 1422 flags = pIn1->flags | pIn2->flags;
1244 if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; 1423 if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
1245 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){ 1424 if( (type1 & type2 & MEM_Int)!=0 ){
1246 iA = pIn1->u.i; 1425 iA = pIn1->u.i;
1247 iB = pIn2->u.i; 1426 iB = pIn2->u.i;
1427 bIntint = 1;
1248 switch( pOp->opcode ){ 1428 switch( pOp->opcode ){
1249 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; 1429 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1250 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; 1430 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1251 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; 1431 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1252 case OP_Divide: { 1432 case OP_Divide: {
1253 if( iA==0 ) goto arithmetic_result_is_null; 1433 if( iA==0 ) goto arithmetic_result_is_null;
1254 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; 1434 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1255 iB /= iA; 1435 iB /= iA;
1256 break; 1436 break;
1257 } 1437 }
1258 default: { 1438 default: {
1259 if( iA==0 ) goto arithmetic_result_is_null; 1439 if( iA==0 ) goto arithmetic_result_is_null;
1260 if( iA==-1 ) iA = 1; 1440 if( iA==-1 ) iA = 1;
1261 iB %= iA; 1441 iB %= iA;
1262 break; 1442 break;
1263 } 1443 }
1264 } 1444 }
1265 pOut->u.i = iB; 1445 pOut->u.i = iB;
1266 MemSetTypeFlag(pOut, MEM_Int); 1446 MemSetTypeFlag(pOut, MEM_Int);
1267 }else{ 1447 }else{
1448 bIntint = 0;
1268 fp_math: 1449 fp_math:
1269 rA = sqlite3VdbeRealValue(pIn1); 1450 rA = sqlite3VdbeRealValue(pIn1);
1270 rB = sqlite3VdbeRealValue(pIn2); 1451 rB = sqlite3VdbeRealValue(pIn2);
1271 switch( pOp->opcode ){ 1452 switch( pOp->opcode ){
1272 case OP_Add: rB += rA; break; 1453 case OP_Add: rB += rA; break;
1273 case OP_Subtract: rB -= rA; break; 1454 case OP_Subtract: rB -= rA; break;
1274 case OP_Multiply: rB *= rA; break; 1455 case OP_Multiply: rB *= rA; break;
1275 case OP_Divide: { 1456 case OP_Divide: {
1276 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ 1457 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1277 if( rA==(double)0 ) goto arithmetic_result_is_null; 1458 if( rA==(double)0 ) goto arithmetic_result_is_null;
1278 rB /= rA; 1459 rB /= rA;
1279 break; 1460 break;
1280 } 1461 }
1281 default: { 1462 default: {
1282 iA = (i64)rA; 1463 iA = (i64)rA;
1283 iB = (i64)rB; 1464 iB = (i64)rB;
1284 if( iA==0 ) goto arithmetic_result_is_null; 1465 if( iA==0 ) goto arithmetic_result_is_null;
1285 if( iA==-1 ) iA = 1; 1466 if( iA==-1 ) iA = 1;
1286 rB = (double)(iB % iA); 1467 rB = (double)(iB % iA);
1287 break; 1468 break;
1288 } 1469 }
1289 } 1470 }
1290 #ifdef SQLITE_OMIT_FLOATING_POINT 1471 #ifdef SQLITE_OMIT_FLOATING_POINT
1291 pOut->u.i = rB; 1472 pOut->u.i = rB;
1292 MemSetTypeFlag(pOut, MEM_Int); 1473 MemSetTypeFlag(pOut, MEM_Int);
1293 #else 1474 #else
1294 if( sqlite3IsNaN(rB) ){ 1475 if( sqlite3IsNaN(rB) ){
1295 goto arithmetic_result_is_null; 1476 goto arithmetic_result_is_null;
1296 } 1477 }
1297 pOut->r = rB; 1478 pOut->u.r = rB;
1298 MemSetTypeFlag(pOut, MEM_Real); 1479 MemSetTypeFlag(pOut, MEM_Real);
1299 if( (flags & MEM_Real)==0 ){ 1480 if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
1300 sqlite3VdbeIntegerAffinity(pOut); 1481 sqlite3VdbeIntegerAffinity(pOut);
1301 } 1482 }
1302 #endif 1483 #endif
1303 } 1484 }
1304 break; 1485 break;
1305 1486
1306 arithmetic_result_is_null: 1487 arithmetic_result_is_null:
1307 sqlite3VdbeMemSetNull(pOut); 1488 sqlite3VdbeMemSetNull(pOut);
1308 break; 1489 break;
1309 } 1490 }
1310 1491
1311 /* Opcode: CollSeq * * P4 1492 /* Opcode: CollSeq P1 * * P4
1312 ** 1493 **
1313 ** P4 is a pointer to a CollSeq struct. If the next call to a user function 1494 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
1314 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will 1495 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1315 ** be returned. This is used by the built-in min(), max() and nullif() 1496 ** be returned. This is used by the built-in min(), max() and nullif()
1316 ** functions. 1497 ** functions.
1317 ** 1498 **
1499 ** If P1 is not zero, then it is a register that a subsequent min() or
1500 ** max() aggregate will set to 1 if the current row is not the minimum or
1501 ** maximum. The P1 register is initialized to 0 by this instruction.
1502 **
1318 ** The interface used by the implementation of the aforementioned functions 1503 ** The interface used by the implementation of the aforementioned functions
1319 ** to retrieve the collation sequence set by this opcode is not available 1504 ** to retrieve the collation sequence set by this opcode is not available
1320 ** publicly, only to user functions defined in func.c. 1505 ** publicly, only to user functions defined in func.c.
1321 */ 1506 */
1322 case OP_CollSeq: { 1507 case OP_CollSeq: {
1323 assert( pOp->p4type==P4_COLLSEQ ); 1508 assert( pOp->p4type==P4_COLLSEQ );
1509 if( pOp->p1 ){
1510 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1511 }
1324 break; 1512 break;
1325 } 1513 }
1326 1514
1327 /* Opcode: Function P1 P2 P3 P4 P5 1515 /* Opcode: Function P1 P2 P3 P4 P5
1516 ** Synopsis: r[P3]=func(r[P2@P5])
1328 ** 1517 **
1329 ** Invoke a user function (P4 is a pointer to a Function structure that 1518 ** Invoke a user function (P4 is a pointer to a Function structure that
1330 ** defines the function) with P5 arguments taken from register P2 and 1519 ** defines the function) with P5 arguments taken from register P2 and
1331 ** successors. The result of the function is stored in register P3. 1520 ** successors. The result of the function is stored in register P3.
1332 ** Register P3 must not be one of the function inputs. 1521 ** Register P3 must not be one of the function inputs.
1333 ** 1522 **
1334 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 1523 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1335 ** function was determined to be constant at compile time. If the first 1524 ** function was determined to be constant at compile time. If the first
1336 ** argument was constant then bit 0 of P1 is set. This is used to determine 1525 ** argument was constant then bit 0 of P1 is set. This is used to determine
1337 ** whether meta data associated with a user function argument using the 1526 ** whether meta data associated with a user function argument using the
1338 ** sqlite3_set_auxdata() API may be safely retained until the next 1527 ** sqlite3_set_auxdata() API may be safely retained until the next
1339 ** invocation of this opcode. 1528 ** invocation of this opcode.
1340 ** 1529 **
1341 ** See also: AggStep and AggFinal 1530 ** See also: AggStep and AggFinal
1342 */ 1531 */
1343 case OP_Function: { 1532 case OP_Function: {
1344 int i; 1533 int i;
1345 Mem *pArg; 1534 Mem *pArg;
1346 sqlite3_context ctx; 1535 sqlite3_context ctx;
1347 sqlite3_value **apVal; 1536 sqlite3_value **apVal;
1348 int n; 1537 int n;
1349 1538
1350 n = pOp->p5; 1539 n = pOp->p5;
1351 apVal = p->apArg; 1540 apVal = p->apArg;
1352 assert( apVal || n==0 ); 1541 assert( apVal || n==0 );
1353 assert( pOp->p3>0 && pOp->p3<=p->nMem ); 1542 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
1354 pOut = &aMem[pOp->p3]; 1543 ctx.pOut = &aMem[pOp->p3];
1355 memAboutToChange(p, pOut); 1544 memAboutToChange(p, ctx.pOut);
1356 1545
1357 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem+1) ); 1546 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
1358 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); 1547 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
1359 pArg = &aMem[pOp->p2]; 1548 pArg = &aMem[pOp->p2];
1360 for(i=0; i<n; i++, pArg++){ 1549 for(i=0; i<n; i++, pArg++){
1361 assert( memIsValid(pArg) ); 1550 assert( memIsValid(pArg) );
1362 apVal[i] = pArg; 1551 apVal[i] = pArg;
1363 Deephemeralize(pArg); 1552 Deephemeralize(pArg);
1364 sqlite3VdbeMemStoreType(pArg);
1365 REGISTER_TRACE(pOp->p2+i, pArg); 1553 REGISTER_TRACE(pOp->p2+i, pArg);
1366 } 1554 }
1367 1555
1368 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC ); 1556 assert( pOp->p4type==P4_FUNCDEF );
1369 if( pOp->p4type==P4_FUNCDEF ){ 1557 ctx.pFunc = pOp->p4.pFunc;
1370 ctx.pFunc = pOp->p4.pFunc; 1558 ctx.iOp = pc;
1371 ctx.pVdbeFunc = 0; 1559 ctx.pVdbe = p;
1372 }else{ 1560 MemSetTypeFlag(ctx.pOut, MEM_Null);
1373 ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc; 1561 ctx.fErrorOrAux = 0;
1374 ctx.pFunc = ctx.pVdbeFunc->pFunc; 1562 db->lastRowid = lastRowid;
1375 }
1376
1377 ctx.s.flags = MEM_Null;
1378 ctx.s.db = db;
1379 ctx.s.xDel = 0;
1380 ctx.s.zMalloc = 0;
1381
1382 /* The output cell may already have a buffer allocated. Move
1383 ** the pointer to ctx.s so in case the user-function can use
1384 ** the already allocated buffer instead of allocating a new one.
1385 */
1386 sqlite3VdbeMemMove(&ctx.s, pOut);
1387 MemSetTypeFlag(&ctx.s, MEM_Null);
1388
1389 ctx.isError = 0;
1390 if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
1391 assert( pOp>aOp );
1392 assert( pOp[-1].p4type==P4_COLLSEQ );
1393 assert( pOp[-1].opcode==OP_CollSeq );
1394 ctx.pColl = pOp[-1].p4.pColl;
1395 }
1396 (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */ 1563 (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
1397 if( db->mallocFailed ){ 1564 lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
1398 /* Even though a malloc() has failed, the implementation of the
1399 ** user function may have called an sqlite3_result_XXX() function
1400 ** to return a value. The following call releases any resources
1401 ** associated with such a value.
1402 */
1403 sqlite3VdbeMemRelease(&ctx.s);
1404 goto no_mem;
1405 }
1406
1407 /* If any auxiliary data functions have been called by this user function,
1408 ** immediately call the destructor for any non-static values.
1409 */
1410 if( ctx.pVdbeFunc ){
1411 sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1412 pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
1413 pOp->p4type = P4_VDBEFUNC;
1414 }
1415 1565
1416 /* If the function returned an error, throw an exception */ 1566 /* If the function returned an error, throw an exception */
1417 if( ctx.isError ){ 1567 if( ctx.fErrorOrAux ){
1418 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s)); 1568 if( ctx.isError ){
1419 rc = ctx.isError; 1569 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
1570 rc = ctx.isError;
1571 }
1572 sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
1420 } 1573 }
1421 1574
1422 /* Copy the result of the function into register P3 */ 1575 /* Copy the result of the function into register P3 */
1423 sqlite3VdbeChangeEncoding(&ctx.s, encoding); 1576 sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
1424 sqlite3VdbeMemMove(pOut, &ctx.s); 1577 if( sqlite3VdbeMemTooBig(ctx.pOut) ){
1425 if( sqlite3VdbeMemTooBig(pOut) ){
1426 goto too_big; 1578 goto too_big;
1427 } 1579 }
1428 1580
1429 #if 0 1581 REGISTER_TRACE(pOp->p3, ctx.pOut);
1430 /* The app-defined function has done something that as caused this 1582 UPDATE_MAX_BLOBSIZE(ctx.pOut);
1431 ** statement to expire. (Perhaps the function called sqlite3_exec()
1432 ** with a CREATE TABLE statement.)
1433 */
1434 if( p->expired ) rc = SQLITE_ABORT;
1435 #endif
1436
1437 REGISTER_TRACE(pOp->p3, pOut);
1438 UPDATE_MAX_BLOBSIZE(pOut);
1439 break; 1583 break;
1440 } 1584 }
1441 1585
1442 /* Opcode: BitAnd P1 P2 P3 * * 1586 /* Opcode: BitAnd P1 P2 P3 * *
1587 ** Synopsis: r[P3]=r[P1]&r[P2]
1443 ** 1588 **
1444 ** Take the bit-wise AND of the values in register P1 and P2 and 1589 ** Take the bit-wise AND of the values in register P1 and P2 and
1445 ** store the result in register P3. 1590 ** store the result in register P3.
1446 ** If either input is NULL, the result is NULL. 1591 ** If either input is NULL, the result is NULL.
1447 */ 1592 */
1448 /* Opcode: BitOr P1 P2 P3 * * 1593 /* Opcode: BitOr P1 P2 P3 * *
1594 ** Synopsis: r[P3]=r[P1]|r[P2]
1449 ** 1595 **
1450 ** Take the bit-wise OR of the values in register P1 and P2 and 1596 ** Take the bit-wise OR of the values in register P1 and P2 and
1451 ** store the result in register P3. 1597 ** store the result in register P3.
1452 ** If either input is NULL, the result is NULL. 1598 ** If either input is NULL, the result is NULL.
1453 */ 1599 */
1454 /* Opcode: ShiftLeft P1 P2 P3 * * 1600 /* Opcode: ShiftLeft P1 P2 P3 * *
1601 ** Synopsis: r[P3]=r[P2]<<r[P1]
1455 ** 1602 **
1456 ** Shift the integer value in register P2 to the left by the 1603 ** Shift the integer value in register P2 to the left by the
1457 ** number of bits specified by the integer in register P1. 1604 ** number of bits specified by the integer in register P1.
1458 ** Store the result in register P3. 1605 ** Store the result in register P3.
1459 ** If either input is NULL, the result is NULL. 1606 ** If either input is NULL, the result is NULL.
1460 */ 1607 */
1461 /* Opcode: ShiftRight P1 P2 P3 * * 1608 /* Opcode: ShiftRight P1 P2 P3 * *
1609 ** Synopsis: r[P3]=r[P2]>>r[P1]
1462 ** 1610 **
1463 ** Shift the integer value in register P2 to the right by the 1611 ** Shift the integer value in register P2 to the right by the
1464 ** number of bits specified by the integer in register P1. 1612 ** number of bits specified by the integer in register P1.
1465 ** Store the result in register P3. 1613 ** Store the result in register P3.
1466 ** If either input is NULL, the result is NULL. 1614 ** If either input is NULL, the result is NULL.
1467 */ 1615 */
1468 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ 1616 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1469 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ 1617 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1470 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ 1618 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1471 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ 1619 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
1511 } 1659 }
1512 memcpy(&iA, &uA, sizeof(iA)); 1660 memcpy(&iA, &uA, sizeof(iA));
1513 } 1661 }
1514 } 1662 }
1515 pOut->u.i = iA; 1663 pOut->u.i = iA;
1516 MemSetTypeFlag(pOut, MEM_Int); 1664 MemSetTypeFlag(pOut, MEM_Int);
1517 break; 1665 break;
1518 } 1666 }
1519 1667
1520 /* Opcode: AddImm P1 P2 * * * 1668 /* Opcode: AddImm P1 P2 * * *
1669 ** Synopsis: r[P1]=r[P1]+P2
1521 ** 1670 **
1522 ** Add the constant P2 to the value in register P1. 1671 ** Add the constant P2 to the value in register P1.
1523 ** The result is always an integer. 1672 ** The result is always an integer.
1524 ** 1673 **
1525 ** To force any register to be an integer, just add 0. 1674 ** To force any register to be an integer, just add 0.
1526 */ 1675 */
1527 case OP_AddImm: { /* in1 */ 1676 case OP_AddImm: { /* in1 */
1528 pIn1 = &aMem[pOp->p1]; 1677 pIn1 = &aMem[pOp->p1];
1529 memAboutToChange(p, pIn1); 1678 memAboutToChange(p, pIn1);
1530 sqlite3VdbeMemIntegerify(pIn1); 1679 sqlite3VdbeMemIntegerify(pIn1);
1531 pIn1->u.i += pOp->p2; 1680 pIn1->u.i += pOp->p2;
1532 break; 1681 break;
1533 } 1682 }
1534 1683
1535 /* Opcode: MustBeInt P1 P2 * * * 1684 /* Opcode: MustBeInt P1 P2 * * *
1536 ** 1685 **
1537 ** Force the value in register P1 to be an integer. If the value 1686 ** Force the value in register P1 to be an integer. If the value
1538 ** in P1 is not an integer and cannot be converted into an integer 1687 ** in P1 is not an integer and cannot be converted into an integer
1539 ** without data loss, then jump immediately to P2, or if P2==0 1688 ** without data loss, then jump immediately to P2, or if P2==0
1540 ** raise an SQLITE_MISMATCH exception. 1689 ** raise an SQLITE_MISMATCH exception.
1541 */ 1690 */
1542 case OP_MustBeInt: { /* jump, in1 */ 1691 case OP_MustBeInt: { /* jump, in1 */
1543 pIn1 = &aMem[pOp->p1]; 1692 pIn1 = &aMem[pOp->p1];
1544 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1545 if( (pIn1->flags & MEM_Int)==0 ){ 1693 if( (pIn1->flags & MEM_Int)==0 ){
1546 if( pOp->p2==0 ){ 1694 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1547 rc = SQLITE_MISMATCH; 1695 VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
1548 goto abort_due_to_error; 1696 if( (pIn1->flags & MEM_Int)==0 ){
1549 }else{ 1697 if( pOp->p2==0 ){
1550 pc = pOp->p2 - 1; 1698 rc = SQLITE_MISMATCH;
1699 goto abort_due_to_error;
1700 }else{
1701 pc = pOp->p2 - 1;
1702 break;
1703 }
1551 } 1704 }
1552 }else{
1553 MemSetTypeFlag(pIn1, MEM_Int);
1554 } 1705 }
1706 MemSetTypeFlag(pIn1, MEM_Int);
1555 break; 1707 break;
1556 } 1708 }
1557 1709
1558 #ifndef SQLITE_OMIT_FLOATING_POINT 1710 #ifndef SQLITE_OMIT_FLOATING_POINT
1559 /* Opcode: RealAffinity P1 * * * * 1711 /* Opcode: RealAffinity P1 * * * *
1560 ** 1712 **
1561 ** If register P1 holds an integer convert it to a real value. 1713 ** If register P1 holds an integer convert it to a real value.
1562 ** 1714 **
1563 ** This opcode is used when extracting information from a column that 1715 ** This opcode is used when extracting information from a column that
1564 ** has REAL affinity. Such column values may still be stored as 1716 ** has REAL affinity. Such column values may still be stored as
1565 ** integers, for space efficiency, but after extraction we want them 1717 ** integers, for space efficiency, but after extraction we want them
1566 ** to have only a real value. 1718 ** to have only a real value.
1567 */ 1719 */
1568 case OP_RealAffinity: { /* in1 */ 1720 case OP_RealAffinity: { /* in1 */
1569 pIn1 = &aMem[pOp->p1]; 1721 pIn1 = &aMem[pOp->p1];
1570 if( pIn1->flags & MEM_Int ){ 1722 if( pIn1->flags & MEM_Int ){
1571 sqlite3VdbeMemRealify(pIn1); 1723 sqlite3VdbeMemRealify(pIn1);
1572 } 1724 }
1573 break; 1725 break;
1574 } 1726 }
1575 #endif 1727 #endif
1576 1728
1577 #ifndef SQLITE_OMIT_CAST 1729 #ifndef SQLITE_OMIT_CAST
1578 /* Opcode: ToText P1 * * * * 1730 /* Opcode: Cast P1 P2 * * *
1731 ** Synopsis: affinity(r[P1])
1579 ** 1732 **
1580 ** Force the value in register P1 to be text. 1733 ** Force the value in register P1 to be the type defined by P2.
1581 ** If the value is numeric, convert it to a string using the 1734 **
1582 ** equivalent of printf(). Blob values are unchanged and 1735 ** <ul>
1583 ** are afterwards simply interpreted as text. 1736 ** <li value="97"> TEXT
1737 ** <li value="98"> BLOB
1738 ** <li value="99"> NUMERIC
1739 ** <li value="100"> INTEGER
1740 ** <li value="101"> REAL
1741 ** </ul>
1584 ** 1742 **
1585 ** A NULL value is not changed by this routine. It remains NULL. 1743 ** A NULL value is not changed by this routine. It remains NULL.
1586 */ 1744 */
1587 case OP_ToText: { /* same as TK_TO_TEXT, in1 */ 1745 case OP_Cast: { /* in1 */
1746 assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
1747 testcase( pOp->p2==SQLITE_AFF_TEXT );
1748 testcase( pOp->p2==SQLITE_AFF_NONE );
1749 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1750 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1751 testcase( pOp->p2==SQLITE_AFF_REAL );
1588 pIn1 = &aMem[pOp->p1]; 1752 pIn1 = &aMem[pOp->p1];
1589 memAboutToChange(p, pIn1); 1753 memAboutToChange(p, pIn1);
1590 if( pIn1->flags & MEM_Null ) break;
1591 assert( MEM_Str==(MEM_Blob>>3) );
1592 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
1593 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1594 rc = ExpandBlob(pIn1); 1754 rc = ExpandBlob(pIn1);
1595 assert( pIn1->flags & MEM_Str || db->mallocFailed ); 1755 sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1596 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
1597 UPDATE_MAX_BLOBSIZE(pIn1); 1756 UPDATE_MAX_BLOBSIZE(pIn1);
1598 break; 1757 break;
1599 } 1758 }
1600
1601 /* Opcode: ToBlob P1 * * * *
1602 **
1603 ** Force the value in register P1 to be a BLOB.
1604 ** If the value is numeric, convert it to a string first.
1605 ** Strings are simply reinterpreted as blobs with no change
1606 ** to the underlying data.
1607 **
1608 ** A NULL value is not changed by this routine. It remains NULL.
1609 */
1610 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
1611 pIn1 = &aMem[pOp->p1];
1612 if( pIn1->flags & MEM_Null ) break;
1613 if( (pIn1->flags & MEM_Blob)==0 ){
1614 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1615 assert( pIn1->flags & MEM_Str || db->mallocFailed );
1616 MemSetTypeFlag(pIn1, MEM_Blob);
1617 }else{
1618 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
1619 }
1620 UPDATE_MAX_BLOBSIZE(pIn1);
1621 break;
1622 }
1623
1624 /* Opcode: ToNumeric P1 * * * *
1625 **
1626 ** Force the value in register P1 to be numeric (either an
1627 ** integer or a floating-point number.)
1628 ** If the value is text or blob, try to convert it to an using the
1629 ** equivalent of atoi() or atof() and store 0 if no such conversion
1630 ** is possible.
1631 **
1632 ** A NULL value is not changed by this routine. It remains NULL.
1633 */
1634 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
1635 pIn1 = &aMem[pOp->p1];
1636 sqlite3VdbeMemNumerify(pIn1);
1637 break;
1638 }
1639 #endif /* SQLITE_OMIT_CAST */ 1759 #endif /* SQLITE_OMIT_CAST */
1640 1760
1641 /* Opcode: ToInt P1 * * * *
1642 **
1643 ** Force the value in register P1 to be an integer. If
1644 ** The value is currently a real number, drop its fractional part.
1645 ** If the value is text or blob, try to convert it to an integer using the
1646 ** equivalent of atoi() and store 0 if no such conversion is possible.
1647 **
1648 ** A NULL value is not changed by this routine. It remains NULL.
1649 */
1650 case OP_ToInt: { /* same as TK_TO_INT, in1 */
1651 pIn1 = &aMem[pOp->p1];
1652 if( (pIn1->flags & MEM_Null)==0 ){
1653 sqlite3VdbeMemIntegerify(pIn1);
1654 }
1655 break;
1656 }
1657
1658 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
1659 /* Opcode: ToReal P1 * * * *
1660 **
1661 ** Force the value in register P1 to be a floating point number.
1662 ** If The value is currently an integer, convert it.
1663 ** If the value is text or blob, try to convert it to an integer using the
1664 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
1665 **
1666 ** A NULL value is not changed by this routine. It remains NULL.
1667 */
1668 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
1669 pIn1 = &aMem[pOp->p1];
1670 memAboutToChange(p, pIn1);
1671 if( (pIn1->flags & MEM_Null)==0 ){
1672 sqlite3VdbeMemRealify(pIn1);
1673 }
1674 break;
1675 }
1676 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
1677
1678 /* Opcode: Lt P1 P2 P3 P4 P5 1761 /* Opcode: Lt P1 P2 P3 P4 P5
1762 ** Synopsis: if r[P1]<r[P3] goto P2
1679 ** 1763 **
1680 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then 1764 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1681 ** jump to address P2. 1765 ** jump to address P2.
1682 ** 1766 **
1683 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or 1767 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1684 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL 1768 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
1685 ** bit is clear then fall through if either operand is NULL. 1769 ** bit is clear then fall through if either operand is NULL.
1686 ** 1770 **
1687 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character - 1771 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1688 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 1772 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1689 ** to coerce both inputs according to this affinity before the 1773 ** to coerce both inputs according to this affinity before the
1690 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric 1774 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1691 ** affinity is used. Note that the affinity conversions are stored 1775 ** affinity is used. Note that the affinity conversions are stored
1692 ** back into the input registers P1 and P3. So this opcode can cause 1776 ** back into the input registers P1 and P3. So this opcode can cause
1693 ** persistent changes to registers P1 and P3. 1777 ** persistent changes to registers P1 and P3.
1694 ** 1778 **
1695 ** Once any conversions have taken place, and neither value is NULL, 1779 ** Once any conversions have taken place, and neither value is NULL,
1696 ** the values are compared. If both values are blobs then memcmp() is 1780 ** the values are compared. If both values are blobs then memcmp() is
1697 ** used to determine the results of the comparison. If both values 1781 ** used to determine the results of the comparison. If both values
1698 ** are text, then the appropriate collating function specified in 1782 ** are text, then the appropriate collating function specified in
1699 ** P4 is used to do the comparison. If P4 is not specified then 1783 ** P4 is used to do the comparison. If P4 is not specified then
1700 ** memcmp() is used to compare text string. If both values are 1784 ** memcmp() is used to compare text string. If both values are
1701 ** numeric, then a numeric comparison is used. If the two values 1785 ** numeric, then a numeric comparison is used. If the two values
1702 ** are of different types, then numbers are considered less than 1786 ** are of different types, then numbers are considered less than
1703 ** strings and strings are considered less than blobs. 1787 ** strings and strings are considered less than blobs.
1704 ** 1788 **
1705 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead, 1789 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
1706 ** store a boolean result (either 0, or 1, or NULL) in register P2. 1790 ** store a boolean result (either 0, or 1, or NULL) in register P2.
1791 **
1792 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
1793 ** equal to one another, provided that they do not have their MEM_Cleared
1794 ** bit set.
1707 */ 1795 */
1708 /* Opcode: Ne P1 P2 P3 P4 P5 1796 /* Opcode: Ne P1 P2 P3 P4 P5
1797 ** Synopsis: if r[P1]!=r[P3] goto P2
1709 ** 1798 **
1710 ** This works just like the Lt opcode except that the jump is taken if 1799 ** This works just like the Lt opcode except that the jump is taken if
1711 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for 1800 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
1712 ** additional information. 1801 ** additional information.
1713 ** 1802 **
1714 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either 1803 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1715 ** true or false and is never NULL. If both operands are NULL then the result 1804 ** true or false and is never NULL. If both operands are NULL then the result
1716 ** of comparison is false. If either operand is NULL then the result is true. 1805 ** of comparison is false. If either operand is NULL then the result is true.
1717 ** If neither operand is NULL the the result is the same as it would be if 1806 ** If neither operand is NULL the result is the same as it would be if
1718 ** the SQLITE_NULLEQ flag were omitted from P5. 1807 ** the SQLITE_NULLEQ flag were omitted from P5.
1719 */ 1808 */
1720 /* Opcode: Eq P1 P2 P3 P4 P5 1809 /* Opcode: Eq P1 P2 P3 P4 P5
1810 ** Synopsis: if r[P1]==r[P3] goto P2
1721 ** 1811 **
1722 ** This works just like the Lt opcode except that the jump is taken if 1812 ** This works just like the Lt opcode except that the jump is taken if
1723 ** the operands in registers P1 and P3 are equal. 1813 ** the operands in registers P1 and P3 are equal.
1724 ** See the Lt opcode for additional information. 1814 ** See the Lt opcode for additional information.
1725 ** 1815 **
1726 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either 1816 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1727 ** true or false and is never NULL. If both operands are NULL then the result 1817 ** true or false and is never NULL. If both operands are NULL then the result
1728 ** of comparison is true. If either operand is NULL then the result is false. 1818 ** of comparison is true. If either operand is NULL then the result is false.
1729 ** If neither operand is NULL the the result is the same as it would be if 1819 ** If neither operand is NULL the result is the same as it would be if
1730 ** the SQLITE_NULLEQ flag were omitted from P5. 1820 ** the SQLITE_NULLEQ flag were omitted from P5.
1731 */ 1821 */
1732 /* Opcode: Le P1 P2 P3 P4 P5 1822 /* Opcode: Le P1 P2 P3 P4 P5
1823 ** Synopsis: if r[P1]<=r[P3] goto P2
1733 ** 1824 **
1734 ** This works just like the Lt opcode except that the jump is taken if 1825 ** This works just like the Lt opcode except that the jump is taken if
1735 ** the content of register P3 is less than or equal to the content of 1826 ** the content of register P3 is less than or equal to the content of
1736 ** register P1. See the Lt opcode for additional information. 1827 ** register P1. See the Lt opcode for additional information.
1737 */ 1828 */
1738 /* Opcode: Gt P1 P2 P3 P4 P5 1829 /* Opcode: Gt P1 P2 P3 P4 P5
1830 ** Synopsis: if r[P1]>r[P3] goto P2
1739 ** 1831 **
1740 ** This works just like the Lt opcode except that the jump is taken if 1832 ** This works just like the Lt opcode except that the jump is taken if
1741 ** the content of register P3 is greater than the content of 1833 ** the content of register P3 is greater than the content of
1742 ** register P1. See the Lt opcode for additional information. 1834 ** register P1. See the Lt opcode for additional information.
1743 */ 1835 */
1744 /* Opcode: Ge P1 P2 P3 P4 P5 1836 /* Opcode: Ge P1 P2 P3 P4 P5
1837 ** Synopsis: if r[P1]>=r[P3] goto P2
1745 ** 1838 **
1746 ** This works just like the Lt opcode except that the jump is taken if 1839 ** This works just like the Lt opcode except that the jump is taken if
1747 ** the content of register P3 is greater than or equal to the content of 1840 ** the content of register P3 is greater than or equal to the content of
1748 ** register P1. See the Lt opcode for additional information. 1841 ** register P1. See the Lt opcode for additional information.
1749 */ 1842 */
1750 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ 1843 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1751 case OP_Ne: /* same as TK_NE, jump, in1, in3 */ 1844 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1752 case OP_Lt: /* same as TK_LT, jump, in1, in3 */ 1845 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1753 case OP_Le: /* same as TK_LE, jump, in1, in3 */ 1846 case OP_Le: /* same as TK_LE, jump, in1, in3 */
1754 case OP_Gt: /* same as TK_GT, jump, in1, in3 */ 1847 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1755 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ 1848 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1756 int res; /* Result of the comparison of pIn1 against pIn3 */ 1849 int res; /* Result of the comparison of pIn1 against pIn3 */
1757 char affinity; /* Affinity to use for comparison */ 1850 char affinity; /* Affinity to use for comparison */
1758 u16 flags1; /* Copy of initial value of pIn1->flags */ 1851 u16 flags1; /* Copy of initial value of pIn1->flags */
1759 u16 flags3; /* Copy of initial value of pIn3->flags */ 1852 u16 flags3; /* Copy of initial value of pIn3->flags */
1760 1853
1761 pIn1 = &aMem[pOp->p1]; 1854 pIn1 = &aMem[pOp->p1];
1762 pIn3 = &aMem[pOp->p3]; 1855 pIn3 = &aMem[pOp->p3];
1763 flags1 = pIn1->flags; 1856 flags1 = pIn1->flags;
1764 flags3 = pIn3->flags; 1857 flags3 = pIn3->flags;
1765 if( (pIn1->flags | pIn3->flags)&MEM_Null ){ 1858 if( (flags1 | flags3)&MEM_Null ){
1766 /* One or both operands are NULL */ 1859 /* One or both operands are NULL */
1767 if( pOp->p5 & SQLITE_NULLEQ ){ 1860 if( pOp->p5 & SQLITE_NULLEQ ){
1768 /* If SQLITE_NULLEQ is set (which will only happen if the operator is 1861 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
1769 ** OP_Eq or OP_Ne) then take the jump or not depending on whether 1862 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
1770 ** or not both operands are null. 1863 ** or not both operands are null.
1771 */ 1864 */
1772 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); 1865 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
1773 res = (pIn1->flags & pIn3->flags & MEM_Null)==0; 1866 assert( (flags1 & MEM_Cleared)==0 );
1867 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
1868 if( (flags1&MEM_Null)!=0
1869 && (flags3&MEM_Null)!=0
1870 && (flags3&MEM_Cleared)==0
1871 ){
1872 res = 0; /* Results are equal */
1873 }else{
1874 res = 1; /* Results are not equal */
1875 }
1774 }else{ 1876 }else{
1775 /* SQLITE_NULLEQ is clear and at least one operand is NULL, 1877 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
1776 ** then the result is always NULL. 1878 ** then the result is always NULL.
1777 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. 1879 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1778 */ 1880 */
1779 if( pOp->p5 & SQLITE_STOREP2 ){ 1881 if( pOp->p5 & SQLITE_STOREP2 ){
1780 pOut = &aMem[pOp->p2]; 1882 pOut = &aMem[pOp->p2];
1781 MemSetTypeFlag(pOut, MEM_Null); 1883 MemSetTypeFlag(pOut, MEM_Null);
1782 REGISTER_TRACE(pOp->p2, pOut); 1884 REGISTER_TRACE(pOp->p2, pOut);
1783 }else if( pOp->p5 & SQLITE_JUMPIFNULL ){ 1885 }else{
1784 pc = pOp->p2-1; 1886 VdbeBranchTaken(2,3);
1887 if( pOp->p5 & SQLITE_JUMPIFNULL ){
1888 pc = pOp->p2-1;
1889 }
1785 } 1890 }
1786 break; 1891 break;
1787 } 1892 }
1788 }else{ 1893 }else{
1789 /* Neither operand is NULL. Do a comparison. */ 1894 /* Neither operand is NULL. Do a comparison. */
1790 affinity = pOp->p5 & SQLITE_AFF_MASK; 1895 affinity = pOp->p5 & SQLITE_AFF_MASK;
1791 if( affinity ){ 1896 if( affinity>=SQLITE_AFF_NUMERIC ){
1792 applyAffinity(pIn1, affinity, encoding); 1897 if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1793 applyAffinity(pIn3, affinity, encoding); 1898 applyNumericAffinity(pIn1,0);
1794 if( db->mallocFailed ) goto no_mem; 1899 }
1900 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
1901 applyNumericAffinity(pIn3,0);
1902 }
1903 }else if( affinity==SQLITE_AFF_TEXT ){
1904 if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
1905 testcase( pIn1->flags & MEM_Int );
1906 testcase( pIn1->flags & MEM_Real );
1907 sqlite3VdbeMemStringify(pIn1, encoding, 1);
1908 }
1909 if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
1910 testcase( pIn3->flags & MEM_Int );
1911 testcase( pIn3->flags & MEM_Real );
1912 sqlite3VdbeMemStringify(pIn3, encoding, 1);
1913 }
1795 } 1914 }
1796
1797 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); 1915 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1798 ExpandBlob(pIn1); 1916 if( pIn1->flags & MEM_Zero ){
1799 ExpandBlob(pIn3); 1917 sqlite3VdbeMemExpandBlob(pIn1);
1918 flags1 &= ~MEM_Zero;
1919 }
1920 if( pIn3->flags & MEM_Zero ){
1921 sqlite3VdbeMemExpandBlob(pIn3);
1922 flags3 &= ~MEM_Zero;
1923 }
1924 if( db->mallocFailed ) goto no_mem;
1800 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); 1925 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1801 } 1926 }
1802 switch( pOp->opcode ){ 1927 switch( pOp->opcode ){
1803 case OP_Eq: res = res==0; break; 1928 case OP_Eq: res = res==0; break;
1804 case OP_Ne: res = res!=0; break; 1929 case OP_Ne: res = res!=0; break;
1805 case OP_Lt: res = res<0; break; 1930 case OP_Lt: res = res<0; break;
1806 case OP_Le: res = res<=0; break; 1931 case OP_Le: res = res<=0; break;
1807 case OP_Gt: res = res>0; break; 1932 case OP_Gt: res = res>0; break;
1808 default: res = res>=0; break; 1933 default: res = res>=0; break;
1809 } 1934 }
1810 1935
1811 if( pOp->p5 & SQLITE_STOREP2 ){ 1936 if( pOp->p5 & SQLITE_STOREP2 ){
1812 pOut = &aMem[pOp->p2]; 1937 pOut = &aMem[pOp->p2];
1813 memAboutToChange(p, pOut); 1938 memAboutToChange(p, pOut);
1814 MemSetTypeFlag(pOut, MEM_Int); 1939 MemSetTypeFlag(pOut, MEM_Int);
1815 pOut->u.i = res; 1940 pOut->u.i = res;
1816 REGISTER_TRACE(pOp->p2, pOut); 1941 REGISTER_TRACE(pOp->p2, pOut);
1817 }else if( res ){ 1942 }else{
1818 pc = pOp->p2-1; 1943 VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
1944 if( res ){
1945 pc = pOp->p2-1;
1946 }
1819 } 1947 }
1820
1821 /* Undo any changes made by applyAffinity() to the input registers. */ 1948 /* Undo any changes made by applyAffinity() to the input registers. */
1822 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask); 1949 pIn1->flags = flags1;
1823 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask); 1950 pIn3->flags = flags3;
1824 break; 1951 break;
1825 } 1952 }
1826 1953
1827 /* Opcode: Permutation * * * P4 * 1954 /* Opcode: Permutation * * * P4 *
1828 ** 1955 **
1829 ** Set the permutation used by the OP_Compare operator to be the array 1956 ** Set the permutation used by the OP_Compare operator to be the array
1830 ** of integers in P4. 1957 ** of integers in P4.
1831 ** 1958 **
1832 ** The permutation is only valid until the next OP_Permutation, OP_Compare, 1959 ** The permutation is only valid until the next OP_Compare that has
1833 ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur 1960 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
1834 ** immediately prior to the OP_Compare. 1961 ** occur immediately prior to the OP_Compare.
1835 */ 1962 */
1836 case OP_Permutation: { 1963 case OP_Permutation: {
1837 assert( pOp->p4type==P4_INTARRAY ); 1964 assert( pOp->p4type==P4_INTARRAY );
1838 assert( pOp->p4.ai ); 1965 assert( pOp->p4.ai );
1839 aPermute = pOp->p4.ai; 1966 aPermute = pOp->p4.ai;
1840 break; 1967 break;
1841 } 1968 }
1842 1969
1843 /* Opcode: Compare P1 P2 P3 P4 * 1970 /* Opcode: Compare P1 P2 P3 P4 P5
1971 ** Synopsis: r[P1@P3] <-> r[P2@P3]
1844 ** 1972 **
1845 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this 1973 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
1846 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of 1974 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
1847 ** the comparison for use by the next OP_Jump instruct. 1975 ** the comparison for use by the next OP_Jump instruct.
1848 ** 1976 **
1977 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
1978 ** determined by the most recent OP_Permutation operator. If the
1979 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
1980 ** order.
1981 **
1849 ** P4 is a KeyInfo structure that defines collating sequences and sort 1982 ** P4 is a KeyInfo structure that defines collating sequences and sort
1850 ** orders for the comparison. The permutation applies to registers 1983 ** orders for the comparison. The permutation applies to registers
1851 ** only. The KeyInfo elements are used sequentially. 1984 ** only. The KeyInfo elements are used sequentially.
1852 ** 1985 **
1853 ** The comparison is a sort comparison, so NULLs compare equal, 1986 ** The comparison is a sort comparison, so NULLs compare equal,
1854 ** NULLs are less than numbers, numbers are less than strings, 1987 ** NULLs are less than numbers, numbers are less than strings,
1855 ** and strings are less than blobs. 1988 ** and strings are less than blobs.
1856 */ 1989 */
1857 case OP_Compare: { 1990 case OP_Compare: {
1858 int n; 1991 int n;
1859 int i; 1992 int i;
1860 int p1; 1993 int p1;
1861 int p2; 1994 int p2;
1862 const KeyInfo *pKeyInfo; 1995 const KeyInfo *pKeyInfo;
1863 int idx; 1996 int idx;
1864 CollSeq *pColl; /* Collating sequence to use on this term */ 1997 CollSeq *pColl; /* Collating sequence to use on this term */
1865 int bRev; /* True for DESCENDING sort order */ 1998 int bRev; /* True for DESCENDING sort order */
1866 1999
2000 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
1867 n = pOp->p3; 2001 n = pOp->p3;
1868 pKeyInfo = pOp->p4.pKeyInfo; 2002 pKeyInfo = pOp->p4.pKeyInfo;
1869 assert( n>0 ); 2003 assert( n>0 );
1870 assert( pKeyInfo!=0 ); 2004 assert( pKeyInfo!=0 );
1871 p1 = pOp->p1; 2005 p1 = pOp->p1;
1872 p2 = pOp->p2; 2006 p2 = pOp->p2;
1873 #if SQLITE_DEBUG 2007 #if SQLITE_DEBUG
1874 if( aPermute ){ 2008 if( aPermute ){
1875 int k, mx = 0; 2009 int k, mx = 0;
1876 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k]; 2010 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
1877 assert( p1>0 && p1+mx<=p->nMem+1 ); 2011 assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
1878 assert( p2>0 && p2+mx<=p->nMem+1 ); 2012 assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
1879 }else{ 2013 }else{
1880 assert( p1>0 && p1+n<=p->nMem+1 ); 2014 assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
1881 assert( p2>0 && p2+n<=p->nMem+1 ); 2015 assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
1882 } 2016 }
1883 #endif /* SQLITE_DEBUG */ 2017 #endif /* SQLITE_DEBUG */
1884 for(i=0; i<n; i++){ 2018 for(i=0; i<n; i++){
1885 idx = aPermute ? aPermute[i] : i; 2019 idx = aPermute ? aPermute[i] : i;
1886 assert( memIsValid(&aMem[p1+idx]) ); 2020 assert( memIsValid(&aMem[p1+idx]) );
1887 assert( memIsValid(&aMem[p2+idx]) ); 2021 assert( memIsValid(&aMem[p2+idx]) );
1888 REGISTER_TRACE(p1+idx, &aMem[p1+idx]); 2022 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
1889 REGISTER_TRACE(p2+idx, &aMem[p2+idx]); 2023 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
1890 assert( i<pKeyInfo->nField ); 2024 assert( i<pKeyInfo->nField );
1891 pColl = pKeyInfo->aColl[i]; 2025 pColl = pKeyInfo->aColl[i];
1892 bRev = pKeyInfo->aSortOrder[i]; 2026 bRev = pKeyInfo->aSortOrder[i];
1893 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); 2027 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
1894 if( iCompare ){ 2028 if( iCompare ){
1895 if( bRev ) iCompare = -iCompare; 2029 if( bRev ) iCompare = -iCompare;
1896 break; 2030 break;
1897 } 2031 }
1898 } 2032 }
1899 aPermute = 0; 2033 aPermute = 0;
1900 break; 2034 break;
1901 } 2035 }
1902 2036
1903 /* Opcode: Jump P1 P2 P3 * * 2037 /* Opcode: Jump P1 P2 P3 * *
1904 ** 2038 **
1905 ** Jump to the instruction at address P1, P2, or P3 depending on whether 2039 ** Jump to the instruction at address P1, P2, or P3 depending on whether
1906 ** in the most recent OP_Compare instruction the P1 vector was less than 2040 ** in the most recent OP_Compare instruction the P1 vector was less than
1907 ** equal to, or greater than the P2 vector, respectively. 2041 ** equal to, or greater than the P2 vector, respectively.
1908 */ 2042 */
1909 case OP_Jump: { /* jump */ 2043 case OP_Jump: { /* jump */
1910 if( iCompare<0 ){ 2044 if( iCompare<0 ){
1911 pc = pOp->p1 - 1; 2045 pc = pOp->p1 - 1; VdbeBranchTaken(0,3);
1912 }else if( iCompare==0 ){ 2046 }else if( iCompare==0 ){
1913 pc = pOp->p2 - 1; 2047 pc = pOp->p2 - 1; VdbeBranchTaken(1,3);
1914 }else{ 2048 }else{
1915 pc = pOp->p3 - 1; 2049 pc = pOp->p3 - 1; VdbeBranchTaken(2,3);
1916 } 2050 }
1917 break; 2051 break;
1918 } 2052 }
1919 2053
1920 /* Opcode: And P1 P2 P3 * * 2054 /* Opcode: And P1 P2 P3 * *
2055 ** Synopsis: r[P3]=(r[P1] && r[P2])
1921 ** 2056 **
1922 ** Take the logical AND of the values in registers P1 and P2 and 2057 ** Take the logical AND of the values in registers P1 and P2 and
1923 ** write the result into register P3. 2058 ** write the result into register P3.
1924 ** 2059 **
1925 ** If either P1 or P2 is 0 (false) then the result is 0 even if 2060 ** If either P1 or P2 is 0 (false) then the result is 0 even if
1926 ** the other input is NULL. A NULL and true or two NULLs give 2061 ** the other input is NULL. A NULL and true or two NULLs give
1927 ** a NULL output. 2062 ** a NULL output.
1928 */ 2063 */
1929 /* Opcode: Or P1 P2 P3 * * 2064 /* Opcode: Or P1 P2 P3 * *
2065 ** Synopsis: r[P3]=(r[P1] || r[P2])
1930 ** 2066 **
1931 ** Take the logical OR of the values in register P1 and P2 and 2067 ** Take the logical OR of the values in register P1 and P2 and
1932 ** store the answer in register P3. 2068 ** store the answer in register P3.
1933 ** 2069 **
1934 ** If either P1 or P2 is nonzero (true) then the result is 1 (true) 2070 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
1935 ** even if the other input is NULL. A NULL and false or two NULLs 2071 ** even if the other input is NULL. A NULL and false or two NULLs
1936 ** give a NULL output. 2072 ** give a NULL output.
1937 */ 2073 */
1938 case OP_And: /* same as TK_AND, in1, in2, out3 */ 2074 case OP_And: /* same as TK_AND, in1, in2, out3 */
1939 case OP_Or: { /* same as TK_OR, in1, in2, out3 */ 2075 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
(...skipping 23 matching lines...) Expand all
1963 if( v1==2 ){ 2099 if( v1==2 ){
1964 MemSetTypeFlag(pOut, MEM_Null); 2100 MemSetTypeFlag(pOut, MEM_Null);
1965 }else{ 2101 }else{
1966 pOut->u.i = v1; 2102 pOut->u.i = v1;
1967 MemSetTypeFlag(pOut, MEM_Int); 2103 MemSetTypeFlag(pOut, MEM_Int);
1968 } 2104 }
1969 break; 2105 break;
1970 } 2106 }
1971 2107
1972 /* Opcode: Not P1 P2 * * * 2108 /* Opcode: Not P1 P2 * * *
2109 ** Synopsis: r[P2]= !r[P1]
1973 ** 2110 **
1974 ** Interpret the value in register P1 as a boolean value. Store the 2111 ** Interpret the value in register P1 as a boolean value. Store the
1975 ** boolean complement in register P2. If the value in register P1 is 2112 ** boolean complement in register P2. If the value in register P1 is
1976 ** NULL, then a NULL is stored in P2. 2113 ** NULL, then a NULL is stored in P2.
1977 */ 2114 */
1978 case OP_Not: { /* same as TK_NOT, in1, out2 */ 2115 case OP_Not: { /* same as TK_NOT, in1, out2 */
1979 pIn1 = &aMem[pOp->p1]; 2116 pIn1 = &aMem[pOp->p1];
1980 pOut = &aMem[pOp->p2]; 2117 pOut = &aMem[pOp->p2];
1981 if( pIn1->flags & MEM_Null ){ 2118 sqlite3VdbeMemSetNull(pOut);
1982 sqlite3VdbeMemSetNull(pOut); 2119 if( (pIn1->flags & MEM_Null)==0 ){
1983 }else{ 2120 pOut->flags = MEM_Int;
1984 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1)); 2121 pOut->u.i = !sqlite3VdbeIntValue(pIn1);
1985 } 2122 }
1986 break; 2123 break;
1987 } 2124 }
1988 2125
1989 /* Opcode: BitNot P1 P2 * * * 2126 /* Opcode: BitNot P1 P2 * * *
2127 ** Synopsis: r[P1]= ~r[P1]
1990 ** 2128 **
1991 ** Interpret the content of register P1 as an integer. Store the 2129 ** Interpret the content of register P1 as an integer. Store the
1992 ** ones-complement of the P1 value into register P2. If P1 holds 2130 ** ones-complement of the P1 value into register P2. If P1 holds
1993 ** a NULL then store a NULL in P2. 2131 ** a NULL then store a NULL in P2.
1994 */ 2132 */
1995 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ 2133 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
1996 pIn1 = &aMem[pOp->p1]; 2134 pIn1 = &aMem[pOp->p1];
1997 pOut = &aMem[pOp->p2]; 2135 pOut = &aMem[pOp->p2];
1998 if( pIn1->flags & MEM_Null ){ 2136 sqlite3VdbeMemSetNull(pOut);
1999 sqlite3VdbeMemSetNull(pOut); 2137 if( (pIn1->flags & MEM_Null)==0 ){
2138 pOut->flags = MEM_Int;
2139 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2140 }
2141 break;
2142 }
2143
2144 /* Opcode: Once P1 P2 * * *
2145 **
2146 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
2147 ** Otherwise, set the flag and fall through to the next instruction.
2148 ** In other words, this opcode causes all following opcodes up through P2
2149 ** (but not including P2) to run just once and to be skipped on subsequent
2150 ** times through the loop.
2151 **
2152 ** All "once" flags are initially cleared whenever a prepared statement
2153 ** first begins to run.
2154 */
2155 case OP_Once: { /* jump */
2156 assert( pOp->p1<p->nOnceFlag );
2157 VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
2158 if( p->aOnceFlag[pOp->p1] ){
2159 pc = pOp->p2-1;
2000 }else{ 2160 }else{
2001 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1)); 2161 p->aOnceFlag[pOp->p1] = 1;
2002 } 2162 }
2003 break; 2163 break;
2004 } 2164 }
2005 2165
2006 /* Opcode: If P1 P2 P3 * * 2166 /* Opcode: If P1 P2 P3 * *
2007 ** 2167 **
2008 ** Jump to P2 if the value in register P1 is true. The value is 2168 ** Jump to P2 if the value in register P1 is true. The value
2009 ** is considered true if it is numeric and non-zero. If the value 2169 ** is considered true if it is numeric and non-zero. If the value
2010 ** in P1 is NULL then take the jump if P3 is true. 2170 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2011 */ 2171 */
2012 /* Opcode: IfNot P1 P2 P3 * * 2172 /* Opcode: IfNot P1 P2 P3 * *
2013 ** 2173 **
2014 ** Jump to P2 if the value in register P1 is False. The value is 2174 ** Jump to P2 if the value in register P1 is False. The value
2015 ** is considered true if it has a numeric value of zero. If the value 2175 ** is considered false if it has a numeric value of zero. If the value
2016 ** in P1 is NULL then take the jump if P3 is true. 2176 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2017 */ 2177 */
2018 case OP_If: /* jump, in1 */ 2178 case OP_If: /* jump, in1 */
2019 case OP_IfNot: { /* jump, in1 */ 2179 case OP_IfNot: { /* jump, in1 */
2020 int c; 2180 int c;
2021 pIn1 = &aMem[pOp->p1]; 2181 pIn1 = &aMem[pOp->p1];
2022 if( pIn1->flags & MEM_Null ){ 2182 if( pIn1->flags & MEM_Null ){
2023 c = pOp->p3; 2183 c = pOp->p3;
2024 }else{ 2184 }else{
2025 #ifdef SQLITE_OMIT_FLOATING_POINT 2185 #ifdef SQLITE_OMIT_FLOATING_POINT
2026 c = sqlite3VdbeIntValue(pIn1)!=0; 2186 c = sqlite3VdbeIntValue(pIn1)!=0;
2027 #else 2187 #else
2028 c = sqlite3VdbeRealValue(pIn1)!=0.0; 2188 c = sqlite3VdbeRealValue(pIn1)!=0.0;
2029 #endif 2189 #endif
2030 if( pOp->opcode==OP_IfNot ) c = !c; 2190 if( pOp->opcode==OP_IfNot ) c = !c;
2031 } 2191 }
2192 VdbeBranchTaken(c!=0, 2);
2032 if( c ){ 2193 if( c ){
2033 pc = pOp->p2-1; 2194 pc = pOp->p2-1;
2034 } 2195 }
2035 break; 2196 break;
2036 } 2197 }
2037 2198
2038 /* Opcode: IsNull P1 P2 * * * 2199 /* Opcode: IsNull P1 P2 * * *
2200 ** Synopsis: if r[P1]==NULL goto P2
2039 ** 2201 **
2040 ** Jump to P2 if the value in register P1 is NULL. 2202 ** Jump to P2 if the value in register P1 is NULL.
2041 */ 2203 */
2042 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ 2204 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2043 pIn1 = &aMem[pOp->p1]; 2205 pIn1 = &aMem[pOp->p1];
2206 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2044 if( (pIn1->flags & MEM_Null)!=0 ){ 2207 if( (pIn1->flags & MEM_Null)!=0 ){
2045 pc = pOp->p2 - 1; 2208 pc = pOp->p2 - 1;
2046 } 2209 }
2047 break; 2210 break;
2048 } 2211 }
2049 2212
2050 /* Opcode: NotNull P1 P2 * * * 2213 /* Opcode: NotNull P1 P2 * * *
2214 ** Synopsis: if r[P1]!=NULL goto P2
2051 ** 2215 **
2052 ** Jump to P2 if the value in register P1 is not NULL. 2216 ** Jump to P2 if the value in register P1 is not NULL.
2053 */ 2217 */
2054 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ 2218 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2055 pIn1 = &aMem[pOp->p1]; 2219 pIn1 = &aMem[pOp->p1];
2220 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2056 if( (pIn1->flags & MEM_Null)==0 ){ 2221 if( (pIn1->flags & MEM_Null)==0 ){
2057 pc = pOp->p2 - 1; 2222 pc = pOp->p2 - 1;
2058 } 2223 }
2059 break; 2224 break;
2060 } 2225 }
2061 2226
2062 /* Opcode: Column P1 P2 P3 P4 P5 2227 /* Opcode: Column P1 P2 P3 P4 P5
2228 ** Synopsis: r[P3]=PX
2063 ** 2229 **
2064 ** Interpret the data that cursor P1 points to as a structure built using 2230 ** Interpret the data that cursor P1 points to as a structure built using
2065 ** the MakeRecord instruction. (See the MakeRecord opcode for additional 2231 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2066 ** information about the format of the data.) Extract the P2-th column 2232 ** information about the format of the data.) Extract the P2-th column
2067 ** from this record. If there are less that (P2+1) 2233 ** from this record. If there are less that (P2+1)
2068 ** values in the record, extract a NULL. 2234 ** values in the record, extract a NULL.
2069 ** 2235 **
2070 ** The value extracted is stored in register P3. 2236 ** The value extracted is stored in register P3.
2071 ** 2237 **
2072 ** If the column contains fewer than P2 fields, then extract a NULL. Or, 2238 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
2073 ** if the P4 argument is a P4_MEM use the value of the P4 argument as 2239 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2074 ** the result. 2240 ** the result.
2075 ** 2241 **
2076 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, 2242 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
2077 ** then the cache of the cursor is reset prior to extracting the column. 2243 ** then the cache of the cursor is reset prior to extracting the column.
2078 ** The first OP_Column against a pseudo-table after the value of the content 2244 ** The first OP_Column against a pseudo-table after the value of the content
2079 ** register has changed should have this bit set. 2245 ** register has changed should have this bit set.
2246 **
2247 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
2248 ** the result is guaranteed to only be used as the argument of a length()
2249 ** or typeof() function, respectively. The loading of large blobs can be
2250 ** skipped for length() and all content loading can be skipped for typeof().
2080 */ 2251 */
2081 case OP_Column: { 2252 case OP_Column: {
2082 u32 payloadSize; /* Number of bytes in the record */
2083 i64 payloadSize64; /* Number of bytes in the record */ 2253 i64 payloadSize64; /* Number of bytes in the record */
2084 int p1; /* P1 value of the opcode */
2085 int p2; /* column number to retrieve */ 2254 int p2; /* column number to retrieve */
2086 VdbeCursor *pC; /* The VDBE cursor */ 2255 VdbeCursor *pC; /* The VDBE cursor */
2087 char *zRec; /* Pointer to complete record-data */
2088 BtCursor *pCrsr; /* The BTree cursor */ 2256 BtCursor *pCrsr; /* The BTree cursor */
2089 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
2090 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ 2257 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2091 int nField; /* number of fields in the record */
2092 int len; /* The length of the serialized data for the column */ 2258 int len; /* The length of the serialized data for the column */
2093 int i; /* Loop counter */ 2259 int i; /* Loop counter */
2094 char *zData; /* Part of the record being decoded */
2095 Mem *pDest; /* Where to write the extracted value */ 2260 Mem *pDest; /* Where to write the extracted value */
2096 Mem sMem; /* For storing the record being decoded */ 2261 Mem sMem; /* For storing the record being decoded */
2097 u8 *zIdx; /* Index into header */ 2262 const u8 *zData; /* Part of the record being decoded */
2098 u8 *zEndHdr; /* Pointer to first byte after the header */ 2263 const u8 *zHdr; /* Next unparsed byte of the header */
2264 const u8 *zEndHdr; /* Pointer to first byte after the header */
2099 u32 offset; /* Offset into the data */ 2265 u32 offset; /* Offset into the data */
2100 u32 szField; /* Number of bytes in the content of a field */ 2266 u32 szField; /* Number of bytes in the content of a field */
2101 int szHdr; /* Size of the header size field at start of record */ 2267 u32 avail; /* Number of bytes of available data */
2102 int avail; /* Number of bytes of available data */ 2268 u32 t; /* A type code from the record header */
2269 u16 fx; /* pDest->flags value */
2103 Mem *pReg; /* PseudoTable input register */ 2270 Mem *pReg; /* PseudoTable input register */
2104 2271
2105
2106 p1 = pOp->p1;
2107 p2 = pOp->p2; 2272 p2 = pOp->p2;
2108 pC = 0; 2273 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
2109 memset(&sMem, 0, sizeof(sMem));
2110 assert( p1<p->nCursor );
2111 assert( pOp->p3>0 && pOp->p3<=p->nMem );
2112 pDest = &aMem[pOp->p3]; 2274 pDest = &aMem[pOp->p3];
2113 memAboutToChange(p, pDest); 2275 memAboutToChange(p, pDest);
2114 MemSetTypeFlag(pDest, MEM_Null); 2276 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2115 zRec = 0; 2277 pC = p->apCsr[pOp->p1];
2116
2117 /* This block sets the variable payloadSize to be the total number of
2118 ** bytes in the record.
2119 **
2120 ** zRec is set to be the complete text of the record if it is available.
2121 ** The complete record text is always available for pseudo-tables
2122 ** If the record is stored in a cursor, the complete record text
2123 ** might be available in the pC->aRow cache. Or it might not be.
2124 ** If the data is unavailable, zRec is set to NULL.
2125 **
2126 ** We also compute the number of columns in the record. For cursors,
2127 ** the number of columns is stored in the VdbeCursor.nField element.
2128 */
2129 pC = p->apCsr[p1];
2130 assert( pC!=0 ); 2278 assert( pC!=0 );
2279 assert( p2<pC->nField );
2280 aOffset = pC->aOffset;
2131 #ifndef SQLITE_OMIT_VIRTUALTABLE 2281 #ifndef SQLITE_OMIT_VIRTUALTABLE
2132 assert( pC->pVtabCursor==0 ); 2282 assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
2133 #endif 2283 #endif
2134 pCrsr = pC->pCursor; 2284 pCrsr = pC->pCursor;
2135 if( pCrsr!=0 ){ 2285 assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
2136 /* The record is stored in a B-Tree */ 2286 assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
2137 rc = sqlite3VdbeCursorMoveto(pC); 2287
2138 if( rc ) goto abort_due_to_error; 2288 /* If the cursor cache is stale, bring it up-to-date */
2289 rc = sqlite3VdbeCursorMoveto(pC);
2290 if( rc ) goto abort_due_to_error;
2291 if( pC->cacheStatus!=p->cacheCtr ){
2139 if( pC->nullRow ){ 2292 if( pC->nullRow ){
2140 payloadSize = 0; 2293 if( pCrsr==0 ){
2141 }else if( pC->cacheStatus==p->cacheCtr ){ 2294 assert( pC->pseudoTableReg>0 );
2142 payloadSize = pC->payloadSize; 2295 pReg = &aMem[pC->pseudoTableReg];
2143 zRec = (char*)pC->aRow; 2296 assert( pReg->flags & MEM_Blob );
2144 }else if( pC->isIndex ){ 2297 assert( memIsValid(pReg) );
2145 assert( sqlite3BtreeCursorIsValid(pCrsr) ); 2298 pC->payloadSize = pC->szRow = avail = pReg->n;
2146 rc = sqlite3BtreeKeySize(pCrsr, &payloadSize64); 2299 pC->aRow = (u8*)pReg->z;
2147 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ 2300 }else{
2148 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the 2301 sqlite3VdbeMemSetNull(pDest);
2149 ** payload size, so it is impossible for payloadSize64 to be 2302 goto op_column_out;
2150 ** larger than 32 bits. */ 2303 }
2151 assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
2152 payloadSize = (u32)payloadSize64;
2153 }else{ 2304 }else{
2154 assert( sqlite3BtreeCursorIsValid(pCrsr) ); 2305 assert( pCrsr );
2155 rc = sqlite3BtreeDataSize(pCrsr, &payloadSize); 2306 if( pC->isTable==0 ){
2156 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ 2307 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2157 } 2308 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2158 }else if( pC->pseudoTableReg>0 ){ 2309 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
2159 pReg = &aMem[pC->pseudoTableReg]; 2310 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
2160 assert( pReg->flags & MEM_Blob ); 2311 ** payload size, so it is impossible for payloadSize64 to be
2161 assert( memIsValid(pReg) ); 2312 ** larger than 32 bits. */
2162 payloadSize = pReg->n; 2313 assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
2163 zRec = pReg->z; 2314 pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
2164 pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr; 2315 pC->payloadSize = (u32)payloadSize64;
2165 assert( payloadSize==0 || zRec!=0 );
2166 }else{
2167 /* Consider the row to be NULL */
2168 payloadSize = 0;
2169 }
2170
2171 /* If payloadSize is 0, then just store a NULL */
2172 if( payloadSize==0 ){
2173 assert( pDest->flags&MEM_Null );
2174 goto op_column_out;
2175 }
2176 assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
2177 if( payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2178 goto too_big;
2179 }
2180
2181 nField = pC->nField;
2182 assert( p2<nField );
2183
2184 /* Read and parse the table header. Store the results of the parse
2185 ** into the record header cache fields of the cursor.
2186 */
2187 aType = pC->aType;
2188 if( pC->cacheStatus==p->cacheCtr ){
2189 aOffset = pC->aOffset;
2190 }else{
2191 assert(aType);
2192 avail = 0;
2193 pC->aOffset = aOffset = &aType[nField];
2194 pC->payloadSize = payloadSize;
2195 pC->cacheStatus = p->cacheCtr;
2196
2197 /* Figure out how many bytes are in the header */
2198 if( zRec ){
2199 zData = zRec;
2200 }else{
2201 if( pC->isIndex ){
2202 zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2203 }else{ 2316 }else{
2204 zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail); 2317 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2318 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
2319 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
2320 pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
2205 } 2321 }
2206 /* If KeyFetch()/DataFetch() managed to get the entire payload, 2322 assert( avail<=65536 ); /* Maximum page size is 64KiB */
2207 ** save the payload in the pC->aRow cache. That will save us from 2323 if( pC->payloadSize <= (u32)avail ){
2208 ** having to make additional calls to fetch the content portion of 2324 pC->szRow = pC->payloadSize;
2209 ** the record.
2210 */
2211 assert( avail>=0 );
2212 if( payloadSize <= (u32)avail ){
2213 zRec = zData;
2214 pC->aRow = (u8*)zData;
2215 }else{ 2325 }else{
2216 pC->aRow = 0; 2326 pC->szRow = avail;
2327 }
2328 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2329 goto too_big;
2217 } 2330 }
2218 } 2331 }
2219 /* The following assert is true in all cases accept when 2332 pC->cacheStatus = p->cacheCtr;
2220 ** the database file has been corrupted externally. 2333 pC->iHdrOffset = getVarint32(pC->aRow, offset);
2221 ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */ 2334 pC->nHdrParsed = 0;
2222 szHdr = getVarint32((u8*)zData, offset); 2335 aOffset[0] = offset;
2223 2336
2224 /* Make sure a corrupt database has not given us an oversize header. 2337 /* Make sure a corrupt database has not given us an oversize header.
2225 ** Do this now to avoid an oversize memory allocation. 2338 ** Do this now to avoid an oversize memory allocation.
2226 ** 2339 **
2227 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte 2340 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2228 ** types use so much data space that there can only be 4096 and 32 of 2341 ** types use so much data space that there can only be 4096 and 32 of
2229 ** them, respectively. So the maximum header length results from a 2342 ** them, respectively. So the maximum header length results from a
2230 ** 3-byte type for each of the maximum of 32768 columns plus three 2343 ** 3-byte type for each of the maximum of 32768 columns plus three
2231 ** extra bytes for the header length itself. 32768*3 + 3 = 98307. 2344 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2232 */ 2345 */
2233 if( offset > 98307 ){ 2346 if( offset > 98307 || offset > pC->payloadSize ){
2234 rc = SQLITE_CORRUPT_BKPT; 2347 rc = SQLITE_CORRUPT_BKPT;
2235 goto op_column_out; 2348 goto op_column_error;
2236 } 2349 }
2237 2350
2238 /* Compute in len the number of bytes of data we need to read in order 2351 if( avail<offset ){
2239 ** to get nField type values. offset is an upper bound on this. But 2352 /* pC->aRow does not have to hold the entire row, but it does at least
2240 ** nField might be significantly less than the true number of columns 2353 ** need to cover the header of the record. If pC->aRow does not contain
2241 ** in the table, and in that case, 5*nField+3 might be smaller than offset. 2354 ** the complete header, then set it to zero, forcing the header to be
2242 ** We want to minimize len in order to limit the size of the memory 2355 ** dynamically allocated. */
2243 ** allocation, especially if a corrupt database file has caused offset 2356 pC->aRow = 0;
2244 ** to be oversized. Offset is limited to 98307 above. But 98307 might 2357 pC->szRow = 0;
2245 ** still exceed Robson memory allocation limits on some configurations. 2358 }
2246 ** On systems that cannot tolerate large memory allocations, nField*5+3 2359
2247 ** will likely be much smaller since nField will likely be less than 2360 /* The following goto is an optimization. It can be omitted and
2248 ** 20 or so. This insures that Robson memory allocation limits are 2361 ** everything will still work. But OP_Column is measurably faster
2249 ** not exceeded even for corrupt database files. 2362 ** by skipping the subsequent conditional, which is always true.
2250 */ 2363 */
2251 len = nField*5 + 3; 2364 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2252 if( len > (int)offset ) len = (int)offset; 2365 goto op_column_read_header;
2366 }
2253 2367
2254 /* The KeyFetch() or DataFetch() above are fast and will get the entire 2368 /* Make sure at least the first p2+1 entries of the header have been
2255 ** record header in most cases. But they will fail to get the complete 2369 ** parsed and valid information is in aOffset[] and pC->aType[].
2256 ** record header if the record header does not fit on a single page 2370 */
2257 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to 2371 if( pC->nHdrParsed<=p2 ){
2258 ** acquire the complete header text. 2372 /* If there is more header available for parsing in the record, try
2373 ** to extract additional fields up through the p2+1-th field
2259 */ 2374 */
2260 if( !zRec && avail<len ){ 2375 op_column_read_header:
2261 sMem.flags = 0; 2376 if( pC->iHdrOffset<aOffset[0] ){
2262 sMem.db = 0; 2377 /* Make sure zData points to enough of the record to cover the header. */
2263 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, len, pC->isIndex, &sMem); 2378 if( pC->aRow==0 ){
2264 if( rc!=SQLITE_OK ){ 2379 memset(&sMem, 0, sizeof(sMem));
2265 goto op_column_out; 2380 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
2381 !pC->isTable, &sMem);
2382 if( rc!=SQLITE_OK ){
2383 goto op_column_error;
2384 }
2385 zData = (u8*)sMem.z;
2386 }else{
2387 zData = pC->aRow;
2266 } 2388 }
2267 zData = sMem.z; 2389
2268 } 2390 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2269 zEndHdr = (u8 *)&zData[len]; 2391 i = pC->nHdrParsed;
2270 zIdx = (u8 *)&zData[szHdr]; 2392 offset = aOffset[i];
2271 2393 zHdr = zData + pC->iHdrOffset;
2272 /* Scan the header and use it to fill in the aType[] and aOffset[] 2394 zEndHdr = zData + aOffset[0];
2273 ** arrays. aType[i] will contain the type integer for the i-th 2395 assert( i<=p2 && zHdr<zEndHdr );
2274 ** column and aOffset[i] will contain the offset from the beginning 2396 do{
2275 ** of the record to the start of the data for the i-th column 2397 if( zHdr[0]<0x80 ){
2276 */ 2398 t = zHdr[0];
2277 for(i=0; i<nField; i++){ 2399 zHdr++;
2278 if( zIdx<zEndHdr ){ 2400 }else{
2279 aOffset[i] = offset; 2401 zHdr += sqlite3GetVarint32(zHdr, &t);
2280 zIdx += getVarint32(zIdx, aType[i]); 2402 }
2281 szField = sqlite3VdbeSerialTypeLen(aType[i]); 2403 pC->aType[i] = t;
2404 szField = sqlite3VdbeSerialTypeLen(t);
2282 offset += szField; 2405 offset += szField;
2283 if( offset<szField ){ /* True if offset overflows */ 2406 if( offset<szField ){ /* True if offset overflows */
2284 zIdx = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */ 2407 zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
2285 break; 2408 break;
2286 } 2409 }
2287 }else{ 2410 i++;
2288 /* If i is less that nField, then there are less fields in this 2411 aOffset[i] = offset;
2289 ** record than SetNumColumns indicated there are columns in the 2412 }while( i<=p2 && zHdr<zEndHdr );
2290 ** table. Set the offset for any extra columns not present in 2413 pC->nHdrParsed = i;
2291 ** the record to 0. This tells code below to store a NULL 2414 pC->iHdrOffset = (u32)(zHdr - zData);
2292 ** instead of deserializing a value from the record. 2415 if( pC->aRow==0 ){
2293 */ 2416 sqlite3VdbeMemRelease(&sMem);
2294 aOffset[i] = 0; 2417 sMem.flags = MEM_Null;
2418 }
2419
2420 /* The record is corrupt if any of the following are true:
2421 ** (1) the bytes of the header extend past the declared header size
2422 ** (zHdr>zEndHdr)
2423 ** (2) the entire header was used but not all data was used
2424 ** (zHdr==zEndHdr && offset!=pC->payloadSize)
2425 ** (3) the end of the data extends beyond the end of the record.
2426 ** (offset > pC->payloadSize)
2427 */
2428 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
2429 || (offset > pC->payloadSize)
2430 ){
2431 rc = SQLITE_CORRUPT_BKPT;
2432 goto op_column_error;
2295 } 2433 }
2296 } 2434 }
2297 sqlite3VdbeMemRelease(&sMem);
2298 sMem.flags = MEM_Null;
2299 2435
2300 /* If we have read more header data than was contained in the header, 2436 /* If after trying to extra new entries from the header, nHdrParsed is
2301 ** or if the end of the last field appears to be past the end of the 2437 ** still not up to p2, that means that the record has fewer than p2
2302 ** record, or if the end of the last field appears to be before the end 2438 ** columns. So the result will be either the default value or a NULL.
2303 ** of the record (when all fields present), then we must be dealing
2304 ** with a corrupt database.
2305 */ 2439 */
2306 if( (zIdx > zEndHdr) || (offset > payloadSize) 2440 if( pC->nHdrParsed<=p2 ){
2307 || (zIdx==zEndHdr && offset!=payloadSize) ){ 2441 if( pOp->p4type==P4_MEM ){
2308 rc = SQLITE_CORRUPT_BKPT; 2442 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2443 }else{
2444 sqlite3VdbeMemSetNull(pDest);
2445 }
2309 goto op_column_out; 2446 goto op_column_out;
2310 } 2447 }
2311 } 2448 }
2312 2449
2313 /* Get the column information. If aOffset[p2] is non-zero, then 2450 /* Extract the content for the p2+1-th column. Control can only
2314 ** deserialize the value from the record. If aOffset[p2] is zero, 2451 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2315 ** then there are not enough fields in the record to satisfy the 2452 ** all valid.
2316 ** request. In this case, set the value NULL or to P4 if P4 is
2317 ** a pointer to a Mem object.
2318 */ 2453 */
2319 if( aOffset[p2] ){ 2454 assert( p2<pC->nHdrParsed );
2320 assert( rc==SQLITE_OK ); 2455 assert( rc==SQLITE_OK );
2321 if( zRec ){ 2456 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2322 sqlite3VdbeMemReleaseExternal(pDest); 2457 if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
2323 sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest); 2458 t = pC->aType[p2];
2459 if( pC->szRow>=aOffset[p2+1] ){
2460 /* This is the common case where the desired content fits on the original
2461 ** page - where the content is not on an overflow page */
2462 sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
2463 }else{
2464 /* This branch happens only when content is on overflow pages */
2465 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2466 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2467 || (len = sqlite3VdbeSerialTypeLen(t))==0
2468 ){
2469 /* Content is irrelevant for
2470 ** 1. the typeof() function,
2471 ** 2. the length(X) function if X is a blob, and
2472 ** 3. if the content length is zero.
2473 ** So we might as well use bogus content rather than reading
2474 ** content from disk. NULL will work for the value for strings
2475 ** and blobs and whatever is in the payloadSize64 variable
2476 ** will work for everything else. */
2477 sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
2324 }else{ 2478 }else{
2325 len = sqlite3VdbeSerialTypeLen(aType[p2]); 2479 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
2326 sqlite3VdbeMemMove(&sMem, pDest); 2480 pDest);
2327 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
2328 if( rc!=SQLITE_OK ){ 2481 if( rc!=SQLITE_OK ){
2329 goto op_column_out; 2482 goto op_column_error;
2330 } 2483 }
2331 zData = sMem.z; 2484 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2332 sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest); 2485 pDest->flags &= ~MEM_Ephem;
2333 }
2334 pDest->enc = encoding;
2335 }else{
2336 if( pOp->p4type==P4_MEM ){
2337 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2338 }else{
2339 assert( pDest->flags&MEM_Null );
2340 } 2486 }
2341 } 2487 }
2342 2488 pDest->enc = encoding;
2343 /* If we dynamically allocated space to hold the data (in the
2344 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2345 ** dynamically allocated space over to the pDest structure.
2346 ** This prevents a memory copy.
2347 */
2348 if( sMem.zMalloc ){
2349 assert( sMem.z==sMem.zMalloc );
2350 assert( !(pDest->flags & MEM_Dyn) );
2351 assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
2352 pDest->flags &= ~(MEM_Ephem|MEM_Static);
2353 pDest->flags |= MEM_Term;
2354 pDest->z = sMem.z;
2355 pDest->zMalloc = sMem.zMalloc;
2356 }
2357
2358 rc = sqlite3VdbeMemMakeWriteable(pDest);
2359 2489
2360 op_column_out: 2490 op_column_out:
2491 /* If the column value is an ephemeral string, go ahead and persist
2492 ** that string in case the cursor moves before the column value is
2493 ** used. The following code does the equivalent of Deephemeralize()
2494 ** but does it faster. */
2495 if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
2496 fx = pDest->flags & (MEM_Str|MEM_Blob);
2497 assert( fx!=0 );
2498 zData = (const u8*)pDest->z;
2499 len = pDest->n;
2500 if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
2501 memcpy(pDest->z, zData, len);
2502 pDest->z[len] = 0;
2503 pDest->z[len+1] = 0;
2504 pDest->flags = fx|MEM_Term;
2505 }
2506 op_column_error:
2361 UPDATE_MAX_BLOBSIZE(pDest); 2507 UPDATE_MAX_BLOBSIZE(pDest);
2362 REGISTER_TRACE(pOp->p3, pDest); 2508 REGISTER_TRACE(pOp->p3, pDest);
2363 break; 2509 break;
2364 } 2510 }
2365 2511
2366 /* Opcode: Affinity P1 P2 * P4 * 2512 /* Opcode: Affinity P1 P2 * P4 *
2513 ** Synopsis: affinity(r[P1@P2])
2367 ** 2514 **
2368 ** Apply affinities to a range of P2 registers starting with P1. 2515 ** Apply affinities to a range of P2 registers starting with P1.
2369 ** 2516 **
2370 ** P4 is a string that is P2 characters long. The nth character of the 2517 ** P4 is a string that is P2 characters long. The nth character of the
2371 ** string indicates the column affinity that should be used for the nth 2518 ** string indicates the column affinity that should be used for the nth
2372 ** memory cell in the range. 2519 ** memory cell in the range.
2373 */ 2520 */
2374 case OP_Affinity: { 2521 case OP_Affinity: {
2375 const char *zAffinity; /* The affinity to be applied */ 2522 const char *zAffinity; /* The affinity to be applied */
2376 char cAff; /* A single character of affinity */ 2523 char cAff; /* A single character of affinity */
2377 2524
2378 zAffinity = pOp->p4.z; 2525 zAffinity = pOp->p4.z;
2379 assert( zAffinity!=0 ); 2526 assert( zAffinity!=0 );
2380 assert( zAffinity[pOp->p2]==0 ); 2527 assert( zAffinity[pOp->p2]==0 );
2381 pIn1 = &aMem[pOp->p1]; 2528 pIn1 = &aMem[pOp->p1];
2382 while( (cAff = *(zAffinity++))!=0 ){ 2529 while( (cAff = *(zAffinity++))!=0 ){
2383 assert( pIn1 <= &p->aMem[p->nMem] ); 2530 assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
2384 assert( memIsValid(pIn1) ); 2531 assert( memIsValid(pIn1) );
2385 ExpandBlob(pIn1);
2386 applyAffinity(pIn1, cAff, encoding); 2532 applyAffinity(pIn1, cAff, encoding);
2387 pIn1++; 2533 pIn1++;
2388 } 2534 }
2389 break; 2535 break;
2390 } 2536 }
2391 2537
2392 /* Opcode: MakeRecord P1 P2 P3 P4 * 2538 /* Opcode: MakeRecord P1 P2 P3 P4 *
2539 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2393 ** 2540 **
2394 ** Convert P2 registers beginning with P1 into the [record format] 2541 ** Convert P2 registers beginning with P1 into the [record format]
2395 ** use as a data record in a database table or as a key 2542 ** use as a data record in a database table or as a key
2396 ** in an index. The OP_Column opcode can decode the record later. 2543 ** in an index. The OP_Column opcode can decode the record later.
2397 ** 2544 **
2398 ** P4 may be a string that is P2 characters long. The nth character of the 2545 ** P4 may be a string that is P2 characters long. The nth character of the
2399 ** string indicates the column affinity that should be used for the nth 2546 ** string indicates the column affinity that should be used for the nth
2400 ** field of the index key. 2547 ** field of the index key.
2401 ** 2548 **
2402 ** The mapping from character to affinity is given by the SQLITE_AFF_ 2549 ** The mapping from character to affinity is given by the SQLITE_AFF_
2403 ** macros defined in sqliteInt.h. 2550 ** macros defined in sqliteInt.h.
2404 ** 2551 **
2405 ** If P4 is NULL then all index fields have the affinity NONE. 2552 ** If P4 is NULL then all index fields have the affinity NONE.
2406 */ 2553 */
2407 case OP_MakeRecord: { 2554 case OP_MakeRecord: {
2408 u8 *zNewRecord; /* A buffer to hold the data for the new record */ 2555 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2409 Mem *pRec; /* The new record */ 2556 Mem *pRec; /* The new record */
2410 u64 nData; /* Number of bytes of data space */ 2557 u64 nData; /* Number of bytes of data space */
2411 int nHdr; /* Number of bytes of header space */ 2558 int nHdr; /* Number of bytes of header space */
2412 i64 nByte; /* Data space required for this record */ 2559 i64 nByte; /* Data space required for this record */
2413 int nZero; /* Number of zero bytes at the end of the record */ 2560 int nZero; /* Number of zero bytes at the end of the record */
2414 int nVarint; /* Number of bytes in a varint */ 2561 int nVarint; /* Number of bytes in a varint */
2415 u32 serial_type; /* Type field */ 2562 u32 serial_type; /* Type field */
2416 Mem *pData0; /* First field to be combined into the record */ 2563 Mem *pData0; /* First field to be combined into the record */
2417 Mem *pLast; /* Last field of the record */ 2564 Mem *pLast; /* Last field of the record */
2418 int nField; /* Number of fields in the record */ 2565 int nField; /* Number of fields in the record */
2419 char *zAffinity; /* The affinity string for the record */ 2566 char *zAffinity; /* The affinity string for the record */
2420 int file_format; /* File format to use for encoding */ 2567 int file_format; /* File format to use for encoding */
2421 int i; /* Space used in zNewRecord[] */ 2568 int i; /* Space used in zNewRecord[] header */
2569 int j; /* Space used in zNewRecord[] content */
2422 int len; /* Length of a field */ 2570 int len; /* Length of a field */
2423 2571
2424 /* Assuming the record contains N fields, the record format looks 2572 /* Assuming the record contains N fields, the record format looks
2425 ** like this: 2573 ** like this:
2426 ** 2574 **
2427 ** ------------------------------------------------------------------------ 2575 ** ------------------------------------------------------------------------
2428 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 2576 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2429 ** ------------------------------------------------------------------------ 2577 ** ------------------------------------------------------------------------
2430 ** 2578 **
2431 ** Data(0) is taken from register P1. Data(1) comes from register P1+1 2579 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2432 ** and so froth. 2580 ** and so forth.
2433 ** 2581 **
2434 ** Each type field is a varint representing the serial type of the 2582 ** Each type field is a varint representing the serial type of the
2435 ** corresponding data element (see sqlite3VdbeSerialType()). The 2583 ** corresponding data element (see sqlite3VdbeSerialType()). The
2436 ** hdr-size field is also a varint which is the offset from the beginning 2584 ** hdr-size field is also a varint which is the offset from the beginning
2437 ** of the record to data0. 2585 ** of the record to data0.
2438 */ 2586 */
2439 nData = 0; /* Number of bytes of data space */ 2587 nData = 0; /* Number of bytes of data space */
2440 nHdr = 0; /* Number of bytes of header space */ 2588 nHdr = 0; /* Number of bytes of header space */
2441 nZero = 0; /* Number of zero bytes at the end of the record */ 2589 nZero = 0; /* Number of zero bytes at the end of the record */
2442 nField = pOp->p1; 2590 nField = pOp->p1;
2443 zAffinity = pOp->p4.z; 2591 zAffinity = pOp->p4.z;
2444 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem+1 ); 2592 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
2445 pData0 = &aMem[nField]; 2593 pData0 = &aMem[nField];
2446 nField = pOp->p2; 2594 nField = pOp->p2;
2447 pLast = &pData0[nField-1]; 2595 pLast = &pData0[nField-1];
2448 file_format = p->minWriteFileFormat; 2596 file_format = p->minWriteFileFormat;
2449 2597
2450 /* Identify the output register */ 2598 /* Identify the output register */
2451 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 ); 2599 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2452 pOut = &aMem[pOp->p3]; 2600 pOut = &aMem[pOp->p3];
2453 memAboutToChange(p, pOut); 2601 memAboutToChange(p, pOut);
2454 2602
2603 /* Apply the requested affinity to all inputs
2604 */
2605 assert( pData0<=pLast );
2606 if( zAffinity ){
2607 pRec = pData0;
2608 do{
2609 applyAffinity(pRec++, *(zAffinity++), encoding);
2610 assert( zAffinity[0]==0 || pRec<=pLast );
2611 }while( zAffinity[0] );
2612 }
2613
2455 /* Loop through the elements that will make up the record to figure 2614 /* Loop through the elements that will make up the record to figure
2456 ** out how much space is required for the new record. 2615 ** out how much space is required for the new record.
2457 */ 2616 */
2458 for(pRec=pData0; pRec<=pLast; pRec++){ 2617 pRec = pLast;
2618 do{
2459 assert( memIsValid(pRec) ); 2619 assert( memIsValid(pRec) );
2460 if( zAffinity ){ 2620 pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
2461 applyAffinity(pRec, zAffinity[pRec-pData0], encoding); 2621 len = sqlite3VdbeSerialTypeLen(serial_type);
2622 if( pRec->flags & MEM_Zero ){
2623 if( nData ){
2624 sqlite3VdbeMemExpandBlob(pRec);
2625 }else{
2626 nZero += pRec->u.nZero;
2627 len -= pRec->u.nZero;
2628 }
2462 } 2629 }
2463 if( pRec->flags&MEM_Zero && pRec->n>0 ){
2464 sqlite3VdbeMemExpandBlob(pRec);
2465 }
2466 serial_type = sqlite3VdbeSerialType(pRec, file_format);
2467 len = sqlite3VdbeSerialTypeLen(serial_type);
2468 nData += len; 2630 nData += len;
2469 nHdr += sqlite3VarintLen(serial_type); 2631 testcase( serial_type==127 );
2470 if( pRec->flags & MEM_Zero ){ 2632 testcase( serial_type==128 );
2471 /* Only pure zero-filled BLOBs can be input to this Opcode. 2633 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
2472 ** We do not allow blobs with a prefix and a zero-filled tail. */ 2634 }while( (--pRec)>=pData0 );
2473 nZero += pRec->u.nZero;
2474 }else if( len ){
2475 nZero = 0;
2476 }
2477 }
2478 2635
2479 /* Add the initial header varint and total the size */ 2636 /* Add the initial header varint and total the size */
2480 nHdr += nVarint = sqlite3VarintLen(nHdr); 2637 testcase( nHdr==126 );
2481 if( nVarint<sqlite3VarintLen(nHdr) ){ 2638 testcase( nHdr==127 );
2482 nHdr++; 2639 if( nHdr<=126 ){
2640 /* The common case */
2641 nHdr += 1;
2642 }else{
2643 /* Rare case of a really large header */
2644 nVarint = sqlite3VarintLen(nHdr);
2645 nHdr += nVarint;
2646 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
2483 } 2647 }
2484 nByte = nHdr+nData-nZero; 2648 nByte = nHdr+nData;
2485 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 2649 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2486 goto too_big; 2650 goto too_big;
2487 } 2651 }
2488 2652
2489 /* Make sure the output register has a buffer large enough to store 2653 /* Make sure the output register has a buffer large enough to store
2490 ** the new record. The output register (pOp->p3) is not allowed to 2654 ** the new record. The output register (pOp->p3) is not allowed to
2491 ** be one of the input registers (because the following call to 2655 ** be one of the input registers (because the following call to
2492 ** sqlite3VdbeMemGrow() could clobber the value before it is used). 2656 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
2493 */ 2657 */
2494 if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){ 2658 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
2495 goto no_mem; 2659 goto no_mem;
2496 } 2660 }
2497 zNewRecord = (u8 *)pOut->z; 2661 zNewRecord = (u8 *)pOut->z;
2498 2662
2499 /* Write the record */ 2663 /* Write the record */
2500 i = putVarint32(zNewRecord, nHdr); 2664 i = putVarint32(zNewRecord, nHdr);
2501 for(pRec=pData0; pRec<=pLast; pRec++){ 2665 j = nHdr;
2502 serial_type = sqlite3VdbeSerialType(pRec, file_format); 2666 assert( pData0<=pLast );
2503 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ 2667 pRec = pData0;
2504 } 2668 do{
2505 for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */ 2669 serial_type = pRec->uTemp;
2506 i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format); 2670 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2507 } 2671 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
2508 assert( i==nByte ); 2672 }while( (++pRec)<=pLast );
2673 assert( i==nHdr );
2674 assert( j==nByte );
2509 2675
2510 assert( pOp->p3>0 && pOp->p3<=p->nMem ); 2676 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
2511 pOut->n = (int)nByte; 2677 pOut->n = (int)nByte;
2512 pOut->flags = MEM_Blob | MEM_Dyn; 2678 pOut->flags = MEM_Blob;
2513 pOut->xDel = 0;
2514 if( nZero ){ 2679 if( nZero ){
2515 pOut->u.nZero = nZero; 2680 pOut->u.nZero = nZero;
2516 pOut->flags |= MEM_Zero; 2681 pOut->flags |= MEM_Zero;
2517 } 2682 }
2518 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ 2683 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
2519 REGISTER_TRACE(pOp->p3, pOut); 2684 REGISTER_TRACE(pOp->p3, pOut);
2520 UPDATE_MAX_BLOBSIZE(pOut); 2685 UPDATE_MAX_BLOBSIZE(pOut);
2521 break; 2686 break;
2522 } 2687 }
2523 2688
2524 /* Opcode: Count P1 P2 * * * 2689 /* Opcode: Count P1 P2 * * *
2690 ** Synopsis: r[P2]=count()
2525 ** 2691 **
2526 ** Store the number of entries (an integer value) in the table or index 2692 ** Store the number of entries (an integer value) in the table or index
2527 ** opened by cursor P1 in register P2 2693 ** opened by cursor P1 in register P2
2528 */ 2694 */
2529 #ifndef SQLITE_OMIT_BTREECOUNT 2695 #ifndef SQLITE_OMIT_BTREECOUNT
2530 case OP_Count: { /* out2-prerelease */ 2696 case OP_Count: { /* out2-prerelease */
2531 i64 nEntry; 2697 i64 nEntry;
2532 BtCursor *pCrsr; 2698 BtCursor *pCrsr;
2533 2699
2534 pCrsr = p->apCsr[pOp->p1]->pCursor; 2700 pCrsr = p->apCsr[pOp->p1]->pCursor;
2535 if( pCrsr ){ 2701 assert( pCrsr );
2536 rc = sqlite3BtreeCount(pCrsr, &nEntry); 2702 nEntry = 0; /* Not needed. Only used to silence a warning. */
2537 }else{ 2703 rc = sqlite3BtreeCount(pCrsr, &nEntry);
2538 nEntry = 0;
2539 }
2540 pOut->u.i = nEntry; 2704 pOut->u.i = nEntry;
2541 break; 2705 break;
2542 } 2706 }
2543 #endif 2707 #endif
2544 2708
2545 /* Opcode: Savepoint P1 * * P4 * 2709 /* Opcode: Savepoint P1 * * P4 *
2546 ** 2710 **
2547 ** Open, release or rollback the savepoint named by parameter P4, depending 2711 ** Open, release or rollback the savepoint named by parameter P4, depending
2548 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an 2712 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
2549 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. 2713 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
(...skipping 11 matching lines...) Expand all
2561 p1 = pOp->p1; 2725 p1 = pOp->p1;
2562 zName = pOp->p4.z; 2726 zName = pOp->p4.z;
2563 2727
2564 /* Assert that the p1 parameter is valid. Also that if there is no open 2728 /* Assert that the p1 parameter is valid. Also that if there is no open
2565 ** transaction, then there cannot be any savepoints. 2729 ** transaction, then there cannot be any savepoints.
2566 */ 2730 */
2567 assert( db->pSavepoint==0 || db->autoCommit==0 ); 2731 assert( db->pSavepoint==0 || db->autoCommit==0 );
2568 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); 2732 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
2569 assert( db->pSavepoint || db->isTransactionSavepoint==0 ); 2733 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
2570 assert( checkSavepointCount(db) ); 2734 assert( checkSavepointCount(db) );
2735 assert( p->bIsReader );
2571 2736
2572 if( p1==SAVEPOINT_BEGIN ){ 2737 if( p1==SAVEPOINT_BEGIN ){
2573 if( db->writeVdbeCnt>0 ){ 2738 if( db->nVdbeWrite>0 ){
2574 /* A new savepoint cannot be created if there are active write 2739 /* A new savepoint cannot be created if there are active write
2575 ** statements (i.e. open read/write incremental blob handles). 2740 ** statements (i.e. open read/write incremental blob handles).
2576 */ 2741 */
2577 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - " 2742 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
2578 "SQL statements in progress"); 2743 "SQL statements in progress");
2579 rc = SQLITE_BUSY; 2744 rc = SQLITE_BUSY;
2580 }else{ 2745 }else{
2581 nName = sqlite3Strlen30(zName); 2746 nName = sqlite3Strlen30(zName);
2582 2747
2748 #ifndef SQLITE_OMIT_VIRTUALTABLE
2749 /* This call is Ok even if this savepoint is actually a transaction
2750 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
2751 ** If this is a transaction savepoint being opened, it is guaranteed
2752 ** that the db->aVTrans[] array is empty. */
2753 assert( db->autoCommit==0 || db->nVTrans==0 );
2754 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
2755 db->nStatement+db->nSavepoint);
2756 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2757 #endif
2758
2583 /* Create a new savepoint structure. */ 2759 /* Create a new savepoint structure. */
2584 pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1); 2760 pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
2585 if( pNew ){ 2761 if( pNew ){
2586 pNew->zName = (char *)&pNew[1]; 2762 pNew->zName = (char *)&pNew[1];
2587 memcpy(pNew->zName, zName, nName+1); 2763 memcpy(pNew->zName, zName, nName+1);
2588 2764
2589 /* If there is no open transaction, then mark this as a special 2765 /* If there is no open transaction, then mark this as a special
2590 ** "transaction savepoint". */ 2766 ** "transaction savepoint". */
2591 if( db->autoCommit ){ 2767 if( db->autoCommit ){
2592 db->autoCommit = 0; 2768 db->autoCommit = 0;
2593 db->isTransactionSavepoint = 1; 2769 db->isTransactionSavepoint = 1;
2594 }else{ 2770 }else{
2595 db->nSavepoint++; 2771 db->nSavepoint++;
2596 } 2772 }
2597 2773
2598 /* Link the new savepoint into the database handle's list. */ 2774 /* Link the new savepoint into the database handle's list. */
2599 pNew->pNext = db->pSavepoint; 2775 pNew->pNext = db->pSavepoint;
2600 db->pSavepoint = pNew; 2776 db->pSavepoint = pNew;
2601 pNew->nDeferredCons = db->nDeferredCons; 2777 pNew->nDeferredCons = db->nDeferredCons;
2778 pNew->nDeferredImmCons = db->nDeferredImmCons;
2602 } 2779 }
2603 } 2780 }
2604 }else{ 2781 }else{
2605 iSavepoint = 0; 2782 iSavepoint = 0;
2606 2783
2607 /* Find the named savepoint. If there is no such savepoint, then an 2784 /* Find the named savepoint. If there is no such savepoint, then an
2608 ** an error is returned to the user. */ 2785 ** an error is returned to the user. */
2609 for( 2786 for(
2610 pSavepoint = db->pSavepoint; 2787 pSavepoint = db->pSavepoint;
2611 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); 2788 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
2612 pSavepoint = pSavepoint->pNext 2789 pSavepoint = pSavepoint->pNext
2613 ){ 2790 ){
2614 iSavepoint++; 2791 iSavepoint++;
2615 } 2792 }
2616 if( !pSavepoint ){ 2793 if( !pSavepoint ){
2617 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName); 2794 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
2618 rc = SQLITE_ERROR; 2795 rc = SQLITE_ERROR;
2619 }else if( 2796 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
2620 db->writeVdbeCnt>0 || (p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
2621 ){
2622 /* It is not possible to release (commit) a savepoint if there are 2797 /* It is not possible to release (commit) a savepoint if there are
2623 ** active write statements. It is not possible to rollback a savepoint 2798 ** active write statements.
2624 ** if there are any active statements at all.
2625 */ 2799 */
2626 sqlite3SetString(&p->zErrMsg, db, 2800 sqlite3SetString(&p->zErrMsg, db,
2627 "cannot %s savepoint - SQL statements in progress", 2801 "cannot release savepoint - SQL statements in progress"
2628 (p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
2629 ); 2802 );
2630 rc = SQLITE_BUSY; 2803 rc = SQLITE_BUSY;
2631 }else{ 2804 }else{
2632 2805
2633 /* Determine whether or not this is a transaction savepoint. If so, 2806 /* Determine whether or not this is a transaction savepoint. If so,
2634 ** and this is a RELEASE command, then the current transaction 2807 ** and this is a RELEASE command, then the current transaction
2635 ** is committed. 2808 ** is committed.
2636 */ 2809 */
2637 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; 2810 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
2638 if( isTransaction && p1==SAVEPOINT_RELEASE ){ 2811 if( isTransaction && p1==SAVEPOINT_RELEASE ){
2639 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ 2812 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
2640 goto vdbe_return; 2813 goto vdbe_return;
2641 } 2814 }
2642 db->autoCommit = 1; 2815 db->autoCommit = 1;
2643 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ 2816 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2644 p->pc = pc; 2817 p->pc = pc;
2645 db->autoCommit = 0; 2818 db->autoCommit = 0;
2646 p->rc = rc = SQLITE_BUSY; 2819 p->rc = rc = SQLITE_BUSY;
2647 goto vdbe_return; 2820 goto vdbe_return;
2648 } 2821 }
2649 db->isTransactionSavepoint = 0; 2822 db->isTransactionSavepoint = 0;
2650 rc = p->rc; 2823 rc = p->rc;
2651 }else{ 2824 }else{
2825 int isSchemaChange;
2652 iSavepoint = db->nSavepoint - iSavepoint - 1; 2826 iSavepoint = db->nSavepoint - iSavepoint - 1;
2827 if( p1==SAVEPOINT_ROLLBACK ){
2828 isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
2829 for(ii=0; ii<db->nDb; ii++){
2830 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
2831 SQLITE_ABORT_ROLLBACK,
2832 isSchemaChange==0);
2833 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2834 }
2835 }else{
2836 isSchemaChange = 0;
2837 }
2653 for(ii=0; ii<db->nDb; ii++){ 2838 for(ii=0; ii<db->nDb; ii++){
2654 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); 2839 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
2655 if( rc!=SQLITE_OK ){ 2840 if( rc!=SQLITE_OK ){
2656 goto abort_due_to_error; 2841 goto abort_due_to_error;
2657 } 2842 }
2658 } 2843 }
2659 if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){ 2844 if( isSchemaChange ){
2660 sqlite3ExpirePreparedStatements(db); 2845 sqlite3ExpirePreparedStatements(db);
2661 sqlite3ResetInternalSchema(db, -1); 2846 sqlite3ResetAllSchemasOfConnection(db);
2662 db->flags = (db->flags | SQLITE_InternChanges); 2847 db->flags = (db->flags | SQLITE_InternChanges);
2663 } 2848 }
2664 } 2849 }
2665 2850
2666 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 2851 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
2667 ** savepoints nested inside of the savepoint being operated on. */ 2852 ** savepoints nested inside of the savepoint being operated on. */
2668 while( db->pSavepoint!=pSavepoint ){ 2853 while( db->pSavepoint!=pSavepoint ){
2669 pTmp = db->pSavepoint; 2854 pTmp = db->pSavepoint;
2670 db->pSavepoint = pTmp->pNext; 2855 db->pSavepoint = pTmp->pNext;
2671 sqlite3DbFree(db, pTmp); 2856 sqlite3DbFree(db, pTmp);
2672 db->nSavepoint--; 2857 db->nSavepoint--;
2673 } 2858 }
2674 2859
2675 /* If it is a RELEASE, then destroy the savepoint being operated on 2860 /* If it is a RELEASE, then destroy the savepoint being operated on
2676 ** too. If it is a ROLLBACK TO, then set the number of deferred 2861 ** too. If it is a ROLLBACK TO, then set the number of deferred
2677 ** constraint violations present in the database to the value stored 2862 ** constraint violations present in the database to the value stored
2678 ** when the savepoint was created. */ 2863 ** when the savepoint was created. */
2679 if( p1==SAVEPOINT_RELEASE ){ 2864 if( p1==SAVEPOINT_RELEASE ){
2680 assert( pSavepoint==db->pSavepoint ); 2865 assert( pSavepoint==db->pSavepoint );
2681 db->pSavepoint = pSavepoint->pNext; 2866 db->pSavepoint = pSavepoint->pNext;
2682 sqlite3DbFree(db, pSavepoint); 2867 sqlite3DbFree(db, pSavepoint);
2683 if( !isTransaction ){ 2868 if( !isTransaction ){
2684 db->nSavepoint--; 2869 db->nSavepoint--;
2685 } 2870 }
2686 }else{ 2871 }else{
2687 db->nDeferredCons = pSavepoint->nDeferredCons; 2872 db->nDeferredCons = pSavepoint->nDeferredCons;
2873 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
2874 }
2875
2876 if( !isTransaction ){
2877 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
2878 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2688 } 2879 }
2689 } 2880 }
2690 } 2881 }
2691 2882
2692 break; 2883 break;
2693 } 2884 }
2694 2885
2695 /* Opcode: AutoCommit P1 P2 * * * 2886 /* Opcode: AutoCommit P1 P2 * * *
2696 ** 2887 **
2697 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll 2888 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2698 ** back any currently active btree transactions. If there are any active 2889 ** back any currently active btree transactions. If there are any active
2699 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if 2890 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
2700 ** there are active writing VMs or active VMs that use shared cache. 2891 ** there are active writing VMs or active VMs that use shared cache.
2701 ** 2892 **
2702 ** This instruction causes the VM to halt. 2893 ** This instruction causes the VM to halt.
2703 */ 2894 */
2704 case OP_AutoCommit: { 2895 case OP_AutoCommit: {
2705 int desiredAutoCommit; 2896 int desiredAutoCommit;
2706 int iRollback; 2897 int iRollback;
2707 int turnOnAC; 2898 int turnOnAC;
2708 2899
2709 desiredAutoCommit = pOp->p1; 2900 desiredAutoCommit = pOp->p1;
2710 iRollback = pOp->p2; 2901 iRollback = pOp->p2;
2711 turnOnAC = desiredAutoCommit && !db->autoCommit; 2902 turnOnAC = desiredAutoCommit && !db->autoCommit;
2712 assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); 2903 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
2713 assert( desiredAutoCommit==1 || iRollback==0 ); 2904 assert( desiredAutoCommit==1 || iRollback==0 );
2714 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */ 2905 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
2906 assert( p->bIsReader );
2715 2907
2716 if( turnOnAC && iRollback && db->activeVdbeCnt>1 ){ 2908 #if 0
2909 if( turnOnAC && iRollback && db->nVdbeActive>1 ){
2717 /* If this instruction implements a ROLLBACK and other VMs are 2910 /* If this instruction implements a ROLLBACK and other VMs are
2718 ** still running, and a transaction is active, return an error indicating 2911 ** still running, and a transaction is active, return an error indicating
2719 ** that the other VMs must complete first. 2912 ** that the other VMs must complete first.
2720 */ 2913 */
2721 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - " 2914 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
2722 "SQL statements in progress"); 2915 "SQL statements in progress");
2723 rc = SQLITE_BUSY; 2916 rc = SQLITE_BUSY;
2724 }else if( turnOnAC && !iRollback && db->writeVdbeCnt>0 ){ 2917 }else
2918 #endif
2919 if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
2725 /* If this instruction implements a COMMIT and other VMs are writing 2920 /* If this instruction implements a COMMIT and other VMs are writing
2726 ** return an error indicating that the other VMs must complete first. 2921 ** return an error indicating that the other VMs must complete first.
2727 */ 2922 */
2728 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - " 2923 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
2729 "SQL statements in progress"); 2924 "SQL statements in progress");
2730 rc = SQLITE_BUSY; 2925 rc = SQLITE_BUSY;
2731 }else if( desiredAutoCommit!=db->autoCommit ){ 2926 }else if( desiredAutoCommit!=db->autoCommit ){
2732 if( iRollback ){ 2927 if( iRollback ){
2733 assert( desiredAutoCommit==1 ); 2928 assert( desiredAutoCommit==1 );
2734 sqlite3RollbackAll(db); 2929 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
2735 db->autoCommit = 1; 2930 db->autoCommit = 1;
2736 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ 2931 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
2737 goto vdbe_return; 2932 goto vdbe_return;
2738 }else{ 2933 }else{
2739 db->autoCommit = (u8)desiredAutoCommit; 2934 db->autoCommit = (u8)desiredAutoCommit;
2740 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ 2935 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2741 p->pc = pc; 2936 p->pc = pc;
2742 db->autoCommit = (u8)(1-desiredAutoCommit); 2937 db->autoCommit = (u8)(1-desiredAutoCommit);
2743 p->rc = rc = SQLITE_BUSY; 2938 p->rc = rc = SQLITE_BUSY;
2744 goto vdbe_return; 2939 goto vdbe_return;
(...skipping 11 matching lines...) Expand all
2756 sqlite3SetString(&p->zErrMsg, db, 2951 sqlite3SetString(&p->zErrMsg, db,
2757 (!desiredAutoCommit)?"cannot start a transaction within a transaction":( 2952 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
2758 (iRollback)?"cannot rollback - no transaction is active": 2953 (iRollback)?"cannot rollback - no transaction is active":
2759 "cannot commit - no transaction is active")); 2954 "cannot commit - no transaction is active"));
2760 2955
2761 rc = SQLITE_ERROR; 2956 rc = SQLITE_ERROR;
2762 } 2957 }
2763 break; 2958 break;
2764 } 2959 }
2765 2960
2766 /* Opcode: Transaction P1 P2 * * * 2961 /* Opcode: Transaction P1 P2 P3 P4 P5
2767 ** 2962 **
2768 ** Begin a transaction. The transaction ends when a Commit or Rollback 2963 ** Begin a transaction on database P1 if a transaction is not already
2769 ** opcode is encountered. Depending on the ON CONFLICT setting, the 2964 ** active.
2770 ** transaction might also be rolled back if an error is encountered. 2965 ** If P2 is non-zero, then a write-transaction is started, or if a
2966 ** read-transaction is already active, it is upgraded to a write-transaction.
2967 ** If P2 is zero, then a read-transaction is started.
2771 ** 2968 **
2772 ** P1 is the index of the database file on which the transaction is 2969 ** P1 is the index of the database file on which the transaction is
2773 ** started. Index 0 is the main database file and index 1 is the 2970 ** started. Index 0 is the main database file and index 1 is the
2774 ** file used for temporary tables. Indices of 2 or more are used for 2971 ** file used for temporary tables. Indices of 2 or more are used for
2775 ** attached databases. 2972 ** attached databases.
2776 ** 2973 **
2777 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
2778 ** obtained on the database file when a write-transaction is started. No
2779 ** other process can start another write transaction while this transaction is
2780 ** underway. Starting a write transaction also creates a rollback journal. A
2781 ** write transaction must be started before any changes can be made to the
2782 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2783 ** on the file.
2784 **
2785 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is 2974 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
2786 ** true (this flag is set if the Vdbe may modify more than one row and may 2975 ** true (this flag is set if the Vdbe may modify more than one row and may
2787 ** throw an ABORT exception), a statement transaction may also be opened. 2976 ** throw an ABORT exception), a statement transaction may also be opened.
2788 ** More specifically, a statement transaction is opened iff the database 2977 ** More specifically, a statement transaction is opened iff the database
2789 ** connection is currently not in autocommit mode, or if there are other 2978 ** connection is currently not in autocommit mode, or if there are other
2790 ** active statements. A statement transaction allows the affects of this 2979 ** active statements. A statement transaction allows the changes made by this
2791 ** VDBE to be rolled back after an error without having to roll back the 2980 ** VDBE to be rolled back after an error without having to roll back the
2792 ** entire transaction. If no error is encountered, the statement transaction 2981 ** entire transaction. If no error is encountered, the statement transaction
2793 ** will automatically commit when the VDBE halts. 2982 ** will automatically commit when the VDBE halts.
2794 ** 2983 **
2795 ** If P2 is zero, then a read-lock is obtained on the database file. 2984 ** If P5!=0 then this opcode also checks the schema cookie against P3
2985 ** and the schema generation counter against P4.
2986 ** The cookie changes its value whenever the database schema changes.
2987 ** This operation is used to detect when that the cookie has changed
2988 ** and that the current process needs to reread the schema. If the schema
2989 ** cookie in P3 differs from the schema cookie in the database header or
2990 ** if the schema generation counter in P4 differs from the current
2991 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
2992 ** halts. The sqlite3_step() wrapper function might then reprepare the
2993 ** statement and rerun it from the beginning.
2796 */ 2994 */
2797 case OP_Transaction: { 2995 case OP_Transaction: {
2798 Btree *pBt; 2996 Btree *pBt;
2997 int iMeta;
2998 int iGen;
2799 2999
3000 assert( p->bIsReader );
3001 assert( p->readOnly==0 || pOp->p2==0 );
2800 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3002 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2801 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 ); 3003 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3004 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3005 rc = SQLITE_READONLY;
3006 goto abort_due_to_error;
3007 }
2802 pBt = db->aDb[pOp->p1].pBt; 3008 pBt = db->aDb[pOp->p1].pBt;
2803 3009
2804 if( pBt ){ 3010 if( pBt ){
2805 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); 3011 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2806 if( rc==SQLITE_BUSY ){ 3012 if( rc==SQLITE_BUSY ){
2807 p->pc = pc; 3013 p->pc = pc;
2808 p->rc = rc = SQLITE_BUSY; 3014 p->rc = rc = SQLITE_BUSY;
2809 goto vdbe_return; 3015 goto vdbe_return;
2810 } 3016 }
2811 if( rc!=SQLITE_OK ){ 3017 if( rc!=SQLITE_OK ){
2812 goto abort_due_to_error; 3018 goto abort_due_to_error;
2813 } 3019 }
2814 3020
2815 if( pOp->p2 && p->usesStmtJournal 3021 if( pOp->p2 && p->usesStmtJournal
2816 && (db->autoCommit==0 || db->activeVdbeCnt>1) 3022 && (db->autoCommit==0 || db->nVdbeRead>1)
2817 ){ 3023 ){
2818 assert( sqlite3BtreeIsInTrans(pBt) ); 3024 assert( sqlite3BtreeIsInTrans(pBt) );
2819 if( p->iStatement==0 ){ 3025 if( p->iStatement==0 ){
2820 assert( db->nStatement>=0 && db->nSavepoint>=0 ); 3026 assert( db->nStatement>=0 && db->nSavepoint>=0 );
2821 db->nStatement++; 3027 db->nStatement++;
2822 p->iStatement = db->nSavepoint + db->nStatement; 3028 p->iStatement = db->nSavepoint + db->nStatement;
2823 } 3029 }
2824 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); 3030
3031 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3032 if( rc==SQLITE_OK ){
3033 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3034 }
2825 3035
2826 /* Store the current value of the database handles deferred constraint 3036 /* Store the current value of the database handles deferred constraint
2827 ** counter. If the statement transaction needs to be rolled back, 3037 ** counter. If the statement transaction needs to be rolled back,
2828 ** the value of this counter needs to be restored too. */ 3038 ** the value of this counter needs to be restored too. */
2829 p->nStmtDefCons = db->nDeferredCons; 3039 p->nStmtDefCons = db->nDeferredCons;
3040 p->nStmtDefImmCons = db->nDeferredImmCons;
2830 } 3041 }
3042
3043 /* Gather the schema version number for checking */
3044 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
3045 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
3046 }else{
3047 iGen = iMeta = 0;
3048 }
3049 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3050 if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
3051 sqlite3DbFree(db, p->zErrMsg);
3052 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3053 /* If the schema-cookie from the database file matches the cookie
3054 ** stored with the in-memory representation of the schema, do
3055 ** not reload the schema from the database file.
3056 **
3057 ** If virtual-tables are in use, this is not just an optimization.
3058 ** Often, v-tables store their data in other SQLite tables, which
3059 ** are queried from within xNext() and other v-table methods using
3060 ** prepared queries. If such a query is out-of-date, we do not want to
3061 ** discard the database schema, as the user code implementing the
3062 ** v-table would have to be ready for the sqlite3_vtab structure itself
3063 ** to be invalidated whenever sqlite3_step() is called from within
3064 ** a v-table method.
3065 */
3066 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3067 sqlite3ResetOneSchema(db, pOp->p1);
3068 }
3069 p->expired = 1;
3070 rc = SQLITE_SCHEMA;
2831 } 3071 }
2832 break; 3072 break;
2833 } 3073 }
2834 3074
2835 /* Opcode: ReadCookie P1 P2 P3 * * 3075 /* Opcode: ReadCookie P1 P2 P3 * *
2836 ** 3076 **
2837 ** Read cookie number P3 from database P1 and write it into register P2. 3077 ** Read cookie number P3 from database P1 and write it into register P2.
2838 ** P3==1 is the schema version. P3==2 is the database format. 3078 ** P3==1 is the schema version. P3==2 is the database format.
2839 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is 3079 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
2840 ** the main database file and P1==1 is the database file used to store 3080 ** the main database file and P1==1 is the database file used to store
2841 ** temporary tables. 3081 ** temporary tables.
2842 ** 3082 **
2843 ** There must be a read-lock on the database (either a transaction 3083 ** There must be a read-lock on the database (either a transaction
2844 ** must be started or there must be an open cursor) before 3084 ** must be started or there must be an open cursor) before
2845 ** executing this instruction. 3085 ** executing this instruction.
2846 */ 3086 */
2847 case OP_ReadCookie: { /* out2-prerelease */ 3087 case OP_ReadCookie: { /* out2-prerelease */
2848 int iMeta; 3088 int iMeta;
2849 int iDb; 3089 int iDb;
2850 int iCookie; 3090 int iCookie;
2851 3091
3092 assert( p->bIsReader );
2852 iDb = pOp->p1; 3093 iDb = pOp->p1;
2853 iCookie = pOp->p3; 3094 iCookie = pOp->p3;
2854 assert( pOp->p3<SQLITE_N_BTREE_META ); 3095 assert( pOp->p3<SQLITE_N_BTREE_META );
2855 assert( iDb>=0 && iDb<db->nDb ); 3096 assert( iDb>=0 && iDb<db->nDb );
2856 assert( db->aDb[iDb].pBt!=0 ); 3097 assert( db->aDb[iDb].pBt!=0 );
2857 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 ); 3098 assert( DbMaskTest(p->btreeMask, iDb) );
2858 3099
2859 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); 3100 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
2860 pOut->u.i = iMeta; 3101 pOut->u.i = iMeta;
2861 break; 3102 break;
2862 } 3103 }
2863 3104
2864 /* Opcode: SetCookie P1 P2 P3 * * 3105 /* Opcode: SetCookie P1 P2 P3 * *
2865 ** 3106 **
2866 ** Write the content of register P3 (interpreted as an integer) 3107 ** Write the content of register P3 (interpreted as an integer)
2867 ** into cookie number P2 of database P1. P2==1 is the schema version. 3108 ** into cookie number P2 of database P1. P2==1 is the schema version.
2868 ** P2==2 is the database format. P2==3 is the recommended pager cache 3109 ** P2==2 is the database format. P2==3 is the recommended pager cache
2869 ** size, and so forth. P1==0 is the main database file and P1==1 is the 3110 ** size, and so forth. P1==0 is the main database file and P1==1 is the
2870 ** database file used to store temporary tables. 3111 ** database file used to store temporary tables.
2871 ** 3112 **
2872 ** A transaction must be started before executing this opcode. 3113 ** A transaction must be started before executing this opcode.
2873 */ 3114 */
2874 case OP_SetCookie: { /* in3 */ 3115 case OP_SetCookie: { /* in3 */
2875 Db *pDb; 3116 Db *pDb;
2876 assert( pOp->p2<SQLITE_N_BTREE_META ); 3117 assert( pOp->p2<SQLITE_N_BTREE_META );
2877 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 3118 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2878 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 ); 3119 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3120 assert( p->readOnly==0 );
2879 pDb = &db->aDb[pOp->p1]; 3121 pDb = &db->aDb[pOp->p1];
2880 assert( pDb->pBt!=0 ); 3122 assert( pDb->pBt!=0 );
2881 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); 3123 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
2882 pIn3 = &aMem[pOp->p3]; 3124 pIn3 = &aMem[pOp->p3];
2883 sqlite3VdbeMemIntegerify(pIn3); 3125 sqlite3VdbeMemIntegerify(pIn3);
2884 /* See note about index shifting on OP_ReadCookie */ 3126 /* See note about index shifting on OP_ReadCookie */
2885 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i); 3127 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
2886 if( pOp->p2==BTREE_SCHEMA_VERSION ){ 3128 if( pOp->p2==BTREE_SCHEMA_VERSION ){
2887 /* When the schema cookie changes, record the new cookie internally */ 3129 /* When the schema cookie changes, record the new cookie internally */
2888 pDb->pSchema->schema_cookie = (int)pIn3->u.i; 3130 pDb->pSchema->schema_cookie = (int)pIn3->u.i;
2889 db->flags |= SQLITE_InternChanges; 3131 db->flags |= SQLITE_InternChanges;
2890 }else if( pOp->p2==BTREE_FILE_FORMAT ){ 3132 }else if( pOp->p2==BTREE_FILE_FORMAT ){
2891 /* Record changes in the file format */ 3133 /* Record changes in the file format */
2892 pDb->pSchema->file_format = (u8)pIn3->u.i; 3134 pDb->pSchema->file_format = (u8)pIn3->u.i;
2893 } 3135 }
2894 if( pOp->p1==1 ){ 3136 if( pOp->p1==1 ){
2895 /* Invalidate all prepared statements whenever the TEMP database 3137 /* Invalidate all prepared statements whenever the TEMP database
2896 ** schema is changed. Ticket #1644 */ 3138 ** schema is changed. Ticket #1644 */
2897 sqlite3ExpirePreparedStatements(db); 3139 sqlite3ExpirePreparedStatements(db);
2898 p->expired = 0; 3140 p->expired = 0;
2899 } 3141 }
2900 break; 3142 break;
2901 } 3143 }
2902 3144
2903 /* Opcode: VerifyCookie P1 P2 P3 * *
2904 **
2905 ** Check the value of global database parameter number 0 (the
2906 ** schema version) and make sure it is equal to P2 and that the
2907 ** generation counter on the local schema parse equals P3.
2908 **
2909 ** P1 is the database number which is 0 for the main database file
2910 ** and 1 for the file holding temporary tables and some higher number
2911 ** for auxiliary databases.
2912 **
2913 ** The cookie changes its value whenever the database schema changes.
2914 ** This operation is used to detect when that the cookie has changed
2915 ** and that the current process needs to reread the schema.
2916 **
2917 ** Either a transaction needs to have been started or an OP_Open needs
2918 ** to be executed (to establish a read lock) before this opcode is
2919 ** invoked.
2920 */
2921 case OP_VerifyCookie: {
2922 int iMeta;
2923 int iGen;
2924 Btree *pBt;
2925
2926 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2927 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
2928 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
2929 pBt = db->aDb[pOp->p1].pBt;
2930 if( pBt ){
2931 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
2932 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
2933 }else{
2934 iGen = iMeta = 0;
2935 }
2936 if( iMeta!=pOp->p2 || iGen!=pOp->p3 ){
2937 sqlite3DbFree(db, p->zErrMsg);
2938 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
2939 /* If the schema-cookie from the database file matches the cookie
2940 ** stored with the in-memory representation of the schema, do
2941 ** not reload the schema from the database file.
2942 **
2943 ** If virtual-tables are in use, this is not just an optimization.
2944 ** Often, v-tables store their data in other SQLite tables, which
2945 ** are queried from within xNext() and other v-table methods using
2946 ** prepared queries. If such a query is out-of-date, we do not want to
2947 ** discard the database schema, as the user code implementing the
2948 ** v-table would have to be ready for the sqlite3_vtab structure itself
2949 ** to be invalidated whenever sqlite3_step() is called from within
2950 ** a v-table method.
2951 */
2952 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2953 sqlite3ResetInternalSchema(db, pOp->p1);
2954 }
2955
2956 p->expired = 1;
2957 rc = SQLITE_SCHEMA;
2958 }
2959 break;
2960 }
2961
2962 /* Opcode: OpenRead P1 P2 P3 P4 P5 3145 /* Opcode: OpenRead P1 P2 P3 P4 P5
3146 ** Synopsis: root=P2 iDb=P3
2963 ** 3147 **
2964 ** Open a read-only cursor for the database table whose root page is 3148 ** Open a read-only cursor for the database table whose root page is
2965 ** P2 in a database file. The database file is determined by P3. 3149 ** P2 in a database file. The database file is determined by P3.
2966 ** P3==0 means the main database, P3==1 means the database used for 3150 ** P3==0 means the main database, P3==1 means the database used for
2967 ** temporary tables, and P3>1 means used the corresponding attached 3151 ** temporary tables, and P3>1 means used the corresponding attached
2968 ** database. Give the new cursor an identifier of P1. The P1 3152 ** database. Give the new cursor an identifier of P1. The P1
2969 ** values need not be contiguous but all P1 values should be small integers. 3153 ** values need not be contiguous but all P1 values should be small integers.
2970 ** It is an error for P1 to be negative. 3154 ** It is an error for P1 to be negative.
2971 ** 3155 **
2972 ** If P5!=0 then use the content of register P2 as the root page, not 3156 ** If P5!=0 then use the content of register P2 as the root page, not
2973 ** the value of P2 itself. 3157 ** the value of P2 itself.
2974 ** 3158 **
2975 ** There will be a read lock on the database whenever there is an 3159 ** There will be a read lock on the database whenever there is an
2976 ** open cursor. If the database was unlocked prior to this instruction 3160 ** open cursor. If the database was unlocked prior to this instruction
2977 ** then a read lock is acquired as part of this instruction. A read 3161 ** then a read lock is acquired as part of this instruction. A read
2978 ** lock allows other processes to read the database but prohibits 3162 ** lock allows other processes to read the database but prohibits
2979 ** any other process from modifying the database. The read lock is 3163 ** any other process from modifying the database. The read lock is
2980 ** released when all cursors are closed. If this instruction attempts 3164 ** released when all cursors are closed. If this instruction attempts
2981 ** to get a read lock but fails, the script terminates with an 3165 ** to get a read lock but fails, the script terminates with an
2982 ** SQLITE_BUSY error code. 3166 ** SQLITE_BUSY error code.
2983 ** 3167 **
2984 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3168 ** The P4 value may be either an integer (P4_INT32) or a pointer to
2985 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3169 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
2986 ** structure, then said structure defines the content and collating 3170 ** structure, then said structure defines the content and collating
2987 ** sequence of the index being opened. Otherwise, if P4 is an integer 3171 ** sequence of the index being opened. Otherwise, if P4 is an integer
2988 ** value, it is set to the number of columns in the table. 3172 ** value, it is set to the number of columns in the table.
2989 ** 3173 **
2990 ** See also OpenWrite. 3174 ** See also: OpenWrite, ReopenIdx
3175 */
3176 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3177 ** Synopsis: root=P2 iDb=P3
3178 **
3179 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
3180 ** checks to see if the cursor on P1 is already open with a root page
3181 ** number of P2 and if it is this opcode becomes a no-op. In other words,
3182 ** if the cursor is already open, do not reopen it.
3183 **
3184 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
3185 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
3186 ** every other ReopenIdx or OpenRead for the same cursor number.
3187 **
3188 ** See the OpenRead opcode documentation for additional information.
2991 */ 3189 */
2992 /* Opcode: OpenWrite P1 P2 P3 P4 P5 3190 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3191 ** Synopsis: root=P2 iDb=P3
2993 ** 3192 **
2994 ** Open a read/write cursor named P1 on the table or index whose root 3193 ** Open a read/write cursor named P1 on the table or index whose root
2995 ** page is P2. Or if P5!=0 use the content of register P2 to find the 3194 ** page is P2. Or if P5!=0 use the content of register P2 to find the
2996 ** root page. 3195 ** root page.
2997 ** 3196 **
2998 ** The P4 value may be either an integer (P4_INT32) or a pointer to 3197 ** The P4 value may be either an integer (P4_INT32) or a pointer to
2999 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 3198 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3000 ** structure, then said structure defines the content and collating 3199 ** structure, then said structure defines the content and collating
3001 ** sequence of the index being opened. Otherwise, if P4 is an integer 3200 ** sequence of the index being opened. Otherwise, if P4 is an integer
3002 ** value, it is set to the number of columns in the table, or to the 3201 ** value, it is set to the number of columns in the table, or to the
3003 ** largest index of any column of the table that is actually used. 3202 ** largest index of any column of the table that is actually used.
3004 ** 3203 **
3005 ** This instruction works just like OpenRead except that it opens the cursor 3204 ** This instruction works just like OpenRead except that it opens the cursor
3006 ** in read/write mode. For a given table, there can be one or more read-only 3205 ** in read/write mode. For a given table, there can be one or more read-only
3007 ** cursors or a single read/write cursor but not both. 3206 ** cursors or a single read/write cursor but not both.
3008 ** 3207 **
3009 ** See also OpenRead. 3208 ** See also OpenRead.
3010 */ 3209 */
3210 case OP_ReopenIdx: {
3211 VdbeCursor *pCur;
3212
3213 assert( pOp->p5==0 );
3214 assert( pOp->p4type==P4_KEYINFO );
3215 pCur = p->apCsr[pOp->p1];
3216 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3217 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3218 break;
3219 }
3220 /* If the cursor is not currently open or is open on a different
3221 ** index, then fall through into OP_OpenRead to force a reopen */
3222 }
3011 case OP_OpenRead: 3223 case OP_OpenRead:
3012 case OP_OpenWrite: { 3224 case OP_OpenWrite: {
3013 int nField; 3225 int nField;
3014 KeyInfo *pKeyInfo; 3226 KeyInfo *pKeyInfo;
3015 int p2; 3227 int p2;
3016 int iDb; 3228 int iDb;
3017 int wrFlag; 3229 int wrFlag;
3018 Btree *pX; 3230 Btree *pX;
3019 VdbeCursor *pCur; 3231 VdbeCursor *pCur;
3020 Db *pDb; 3232 Db *pDb;
3021 3233
3234 assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
3235 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
3236 assert( p->bIsReader );
3237 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3238 || p->readOnly==0 );
3239
3022 if( p->expired ){ 3240 if( p->expired ){
3023 rc = SQLITE_ABORT; 3241 rc = SQLITE_ABORT_ROLLBACK;
3024 break; 3242 break;
3025 } 3243 }
3026 3244
3027 nField = 0; 3245 nField = 0;
3028 pKeyInfo = 0; 3246 pKeyInfo = 0;
3029 p2 = pOp->p2; 3247 p2 = pOp->p2;
3030 iDb = pOp->p3; 3248 iDb = pOp->p3;
3031 assert( iDb>=0 && iDb<db->nDb ); 3249 assert( iDb>=0 && iDb<db->nDb );
3032 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 ); 3250 assert( DbMaskTest(p->btreeMask, iDb) );
3033 pDb = &db->aDb[iDb]; 3251 pDb = &db->aDb[iDb];
3034 pX = pDb->pBt; 3252 pX = pDb->pBt;
3035 assert( pX!=0 ); 3253 assert( pX!=0 );
3036 if( pOp->opcode==OP_OpenWrite ){ 3254 if( pOp->opcode==OP_OpenWrite ){
3037 wrFlag = 1; 3255 wrFlag = 1;
3038 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); 3256 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3039 if( pDb->pSchema->file_format < p->minWriteFileFormat ){ 3257 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3040 p->minWriteFileFormat = pDb->pSchema->file_format; 3258 p->minWriteFileFormat = pDb->pSchema->file_format;
3041 } 3259 }
3042 }else{ 3260 }else{
3043 wrFlag = 0; 3261 wrFlag = 0;
3044 } 3262 }
3045 if( pOp->p5 ){ 3263 if( pOp->p5 & OPFLAG_P2ISREG ){
3046 assert( p2>0 ); 3264 assert( p2>0 );
3047 assert( p2<=p->nMem ); 3265 assert( p2<=(p->nMem-p->nCursor) );
3048 pIn2 = &aMem[p2]; 3266 pIn2 = &aMem[p2];
3049 assert( memIsValid(pIn2) ); 3267 assert( memIsValid(pIn2) );
3050 assert( (pIn2->flags & MEM_Int)!=0 ); 3268 assert( (pIn2->flags & MEM_Int)!=0 );
3051 sqlite3VdbeMemIntegerify(pIn2); 3269 sqlite3VdbeMemIntegerify(pIn2);
3052 p2 = (int)pIn2->u.i; 3270 p2 = (int)pIn2->u.i;
3053 /* The p2 value always comes from a prior OP_CreateTable opcode and 3271 /* The p2 value always comes from a prior OP_CreateTable opcode and
3054 ** that opcode will always set the p2 value to 2 or more or else fail. 3272 ** that opcode will always set the p2 value to 2 or more or else fail.
3055 ** If there were a failure, the prepared statement would have halted 3273 ** If there were a failure, the prepared statement would have halted
3056 ** before reaching this instruction. */ 3274 ** before reaching this instruction. */
3057 if( NEVER(p2<2) ) { 3275 if( NEVER(p2<2) ) {
3058 rc = SQLITE_CORRUPT_BKPT; 3276 rc = SQLITE_CORRUPT_BKPT;
3059 goto abort_due_to_error; 3277 goto abort_due_to_error;
3060 } 3278 }
3061 } 3279 }
3062 if( pOp->p4type==P4_KEYINFO ){ 3280 if( pOp->p4type==P4_KEYINFO ){
3063 pKeyInfo = pOp->p4.pKeyInfo; 3281 pKeyInfo = pOp->p4.pKeyInfo;
3064 pKeyInfo->enc = ENC(p->db); 3282 assert( pKeyInfo->enc==ENC(db) );
3065 nField = pKeyInfo->nField+1; 3283 assert( pKeyInfo->db==db );
3284 nField = pKeyInfo->nField+pKeyInfo->nXField;
3066 }else if( pOp->p4type==P4_INT32 ){ 3285 }else if( pOp->p4type==P4_INT32 ){
3067 nField = pOp->p4.i; 3286 nField = pOp->p4.i;
3068 } 3287 }
3069 assert( pOp->p1>=0 ); 3288 assert( pOp->p1>=0 );
3289 assert( nField>=0 );
3290 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3070 pCur = allocateCursor(p, pOp->p1, nField, iDb, 1); 3291 pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
3071 if( pCur==0 ) goto no_mem; 3292 if( pCur==0 ) goto no_mem;
3072 pCur->nullRow = 1; 3293 pCur->nullRow = 1;
3073 pCur->isOrdered = 1; 3294 pCur->isOrdered = 1;
3295 pCur->pgnoRoot = p2;
3074 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor); 3296 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
3075 pCur->pKeyInfo = pKeyInfo; 3297 pCur->pKeyInfo = pKeyInfo;
3298 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3299 sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
3076 3300
3077 /* Since it performs no memory allocation or IO, the only values that 3301 /* Set the VdbeCursor.isTable variable. Previous versions of
3078 ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
3079 ** SQLITE_EMPTY is only returned when attempting to open the table
3080 ** rooted at page 1 of a zero-byte database. */
3081 assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
3082 if( rc==SQLITE_EMPTY ){
3083 pCur->pCursor = 0;
3084 rc = SQLITE_OK;
3085 }
3086
3087 /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
3088 ** SQLite used to check if the root-page flags were sane at this point 3302 ** SQLite used to check if the root-page flags were sane at this point
3089 ** and report database corruption if they were not, but this check has 3303 ** and report database corruption if they were not, but this check has
3090 ** since moved into the btree layer. */ 3304 ** since moved into the btree layer. */
3091 pCur->isTable = pOp->p4type!=P4_KEYINFO; 3305 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3092 pCur->isIndex = !pCur->isTable;
3093 break; 3306 break;
3094 } 3307 }
3095 3308
3096 /* Opcode: OpenEphemeral P1 P2 * P4 * 3309 /* Opcode: OpenEphemeral P1 P2 * P4 P5
3310 ** Synopsis: nColumn=P2
3097 ** 3311 **
3098 ** Open a new cursor P1 to a transient table. 3312 ** Open a new cursor P1 to a transient table.
3099 ** The cursor is always opened read/write even if 3313 ** The cursor is always opened read/write even if
3100 ** the main database is read-only. The ephemeral 3314 ** the main database is read-only. The ephemeral
3101 ** table is deleted automatically when the cursor is closed. 3315 ** table is deleted automatically when the cursor is closed.
3102 ** 3316 **
3103 ** P2 is the number of columns in the ephemeral table. 3317 ** P2 is the number of columns in the ephemeral table.
3104 ** The cursor points to a BTree table if P4==0 and to a BTree index 3318 ** The cursor points to a BTree table if P4==0 and to a BTree index
3105 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure 3319 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3106 ** that defines the format of keys in the index. 3320 ** that defines the format of keys in the index.
3107 ** 3321 **
3108 ** This opcode was once called OpenTemp. But that created 3322 ** The P5 parameter can be a mask of the BTREE_* flags defined
3109 ** confusion because the term "temp table", might refer either 3323 ** in btree.h. These flags control aspects of the operation of
3110 ** to a TEMP table at the SQL level, or to a table opened by 3324 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3111 ** this opcode. Then this opcode was call OpenVirtual. But 3325 ** added automatically.
3112 ** that created confusion with the whole virtual-table idea.
3113 */ 3326 */
3114 /* Opcode: OpenAutoindex P1 P2 * P4 * 3327 /* Opcode: OpenAutoindex P1 P2 * P4 *
3328 ** Synopsis: nColumn=P2
3115 ** 3329 **
3116 ** This opcode works the same as OP_OpenEphemeral. It has a 3330 ** This opcode works the same as OP_OpenEphemeral. It has a
3117 ** different name to distinguish its use. Tables created using 3331 ** different name to distinguish its use. Tables created using
3118 ** by this opcode will be used for automatically created transient 3332 ** by this opcode will be used for automatically created transient
3119 ** indices in joins. 3333 ** indices in joins.
3120 */ 3334 */
3121 case OP_OpenAutoindex: 3335 case OP_OpenAutoindex:
3122 case OP_OpenEphemeral: { 3336 case OP_OpenEphemeral: {
3123 VdbeCursor *pCx; 3337 VdbeCursor *pCx;
3338 KeyInfo *pKeyInfo;
3339
3124 static const int vfsFlags = 3340 static const int vfsFlags =
3125 SQLITE_OPEN_READWRITE | 3341 SQLITE_OPEN_READWRITE |
3126 SQLITE_OPEN_CREATE | 3342 SQLITE_OPEN_CREATE |
3127 SQLITE_OPEN_EXCLUSIVE | 3343 SQLITE_OPEN_EXCLUSIVE |
3128 SQLITE_OPEN_DELETEONCLOSE | 3344 SQLITE_OPEN_DELETEONCLOSE |
3129 SQLITE_OPEN_TRANSIENT_DB; 3345 SQLITE_OPEN_TRANSIENT_DB;
3130
3131 assert( pOp->p1>=0 ); 3346 assert( pOp->p1>=0 );
3347 assert( pOp->p2>=0 );
3132 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1); 3348 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
3133 if( pCx==0 ) goto no_mem; 3349 if( pCx==0 ) goto no_mem;
3134 pCx->nullRow = 1; 3350 pCx->nullRow = 1;
3135 rc = sqlite3BtreeOpen(0, db, &pCx->pBt, 3351 pCx->isEphemeral = 1;
3352 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
3136 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); 3353 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
3137 if( rc==SQLITE_OK ){ 3354 if( rc==SQLITE_OK ){
3138 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1); 3355 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
3139 } 3356 }
3140 if( rc==SQLITE_OK ){ 3357 if( rc==SQLITE_OK ){
3141 /* If a transient index is required, create it by calling 3358 /* If a transient index is required, create it by calling
3142 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before 3359 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3143 ** opening it. If a transient table is required, just use the 3360 ** opening it. If a transient table is required, just use the
3144 ** automatically created table with root-page 1 (an BLOB_INTKEY table). 3361 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3145 */ 3362 */
3146 if( pOp->p4.pKeyInfo ){ 3363 if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3147 int pgno; 3364 int pgno;
3148 assert( pOp->p4type==P4_KEYINFO ); 3365 assert( pOp->p4type==P4_KEYINFO );
3149 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY); 3366 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
3150 if( rc==SQLITE_OK ){ 3367 if( rc==SQLITE_OK ){
3151 assert( pgno==MASTER_ROOT+1 ); 3368 assert( pgno==MASTER_ROOT+1 );
3152 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 3369 assert( pKeyInfo->db==db );
3153 (KeyInfo*)pOp->p4.z, pCx->pCursor); 3370 assert( pKeyInfo->enc==ENC(db) );
3154 pCx->pKeyInfo = pOp->p4.pKeyInfo; 3371 pCx->pKeyInfo = pKeyInfo;
3155 pCx->pKeyInfo->enc = ENC(p->db); 3372 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
3156 } 3373 }
3157 pCx->isTable = 0; 3374 pCx->isTable = 0;
3158 }else{ 3375 }else{
3159 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor); 3376 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
3160 pCx->isTable = 1; 3377 pCx->isTable = 1;
3161 } 3378 }
3162 } 3379 }
3163 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); 3380 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3164 pCx->isIndex = !pCx->isTable; 3381 break;
3382 }
3383
3384 /* Opcode: SorterOpen P1 P2 P3 P4 *
3385 **
3386 ** This opcode works like OP_OpenEphemeral except that it opens
3387 ** a transient index that is specifically designed to sort large
3388 ** tables using an external merge-sort algorithm.
3389 **
3390 ** If argument P3 is non-zero, then it indicates that the sorter may
3391 ** assume that a stable sort considering the first P3 fields of each
3392 ** key is sufficient to produce the required results.
3393 */
3394 case OP_SorterOpen: {
3395 VdbeCursor *pCx;
3396
3397 assert( pOp->p1>=0 );
3398 assert( pOp->p2>=0 );
3399 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
3400 if( pCx==0 ) goto no_mem;
3401 pCx->pKeyInfo = pOp->p4.pKeyInfo;
3402 assert( pCx->pKeyInfo->db==db );
3403 assert( pCx->pKeyInfo->enc==ENC(db) );
3404 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
3405 break;
3406 }
3407
3408 /* Opcode: SequenceTest P1 P2 * * *
3409 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
3410 **
3411 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
3412 ** to P2. Regardless of whether or not the jump is taken, increment the
3413 ** the sequence value.
3414 */
3415 case OP_SequenceTest: {
3416 VdbeCursor *pC;
3417 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3418 pC = p->apCsr[pOp->p1];
3419 assert( pC->pSorter );
3420 if( (pC->seqCount++)==0 ){
3421 pc = pOp->p2 - 1;
3422 }
3165 break; 3423 break;
3166 } 3424 }
3167 3425
3168 /* Opcode: OpenPseudo P1 P2 P3 * * 3426 /* Opcode: OpenPseudo P1 P2 P3 * *
3427 ** Synopsis: P3 columns in r[P2]
3169 ** 3428 **
3170 ** Open a new cursor that points to a fake table that contains a single 3429 ** Open a new cursor that points to a fake table that contains a single
3171 ** row of data. The content of that one row in the content of memory 3430 ** row of data. The content of that one row is the content of memory
3172 ** register P2. In other words, cursor P1 becomes an alias for the 3431 ** register P2. In other words, cursor P1 becomes an alias for the
3173 ** MEM_Blob content contained in register P2. 3432 ** MEM_Blob content contained in register P2.
3174 ** 3433 **
3175 ** A pseudo-table created by this opcode is used to hold a single 3434 ** A pseudo-table created by this opcode is used to hold a single
3176 ** row output from the sorter so that the row can be decomposed into 3435 ** row output from the sorter so that the row can be decomposed into
3177 ** individual columns using the OP_Column opcode. The OP_Column opcode 3436 ** individual columns using the OP_Column opcode. The OP_Column opcode
3178 ** is the only cursor opcode that works with a pseudo-table. 3437 ** is the only cursor opcode that works with a pseudo-table.
3179 ** 3438 **
3180 ** P3 is the number of fields in the records that will be stored by 3439 ** P3 is the number of fields in the records that will be stored by
3181 ** the pseudo-table. 3440 ** the pseudo-table.
3182 */ 3441 */
3183 case OP_OpenPseudo: { 3442 case OP_OpenPseudo: {
3184 VdbeCursor *pCx; 3443 VdbeCursor *pCx;
3185 3444
3186 assert( pOp->p1>=0 ); 3445 assert( pOp->p1>=0 );
3446 assert( pOp->p3>=0 );
3187 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0); 3447 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
3188 if( pCx==0 ) goto no_mem; 3448 if( pCx==0 ) goto no_mem;
3189 pCx->nullRow = 1; 3449 pCx->nullRow = 1;
3190 pCx->pseudoTableReg = pOp->p2; 3450 pCx->pseudoTableReg = pOp->p2;
3191 pCx->isTable = 1; 3451 pCx->isTable = 1;
3192 pCx->isIndex = 0; 3452 assert( pOp->p5==0 );
3193 break; 3453 break;
3194 } 3454 }
3195 3455
3196 /* Opcode: Close P1 * * * * 3456 /* Opcode: Close P1 * * * *
3197 ** 3457 **
3198 ** Close a cursor previously opened as P1. If P1 is not 3458 ** Close a cursor previously opened as P1. If P1 is not
3199 ** currently open, this instruction is a no-op. 3459 ** currently open, this instruction is a no-op.
3200 */ 3460 */
3201 case OP_Close: { 3461 case OP_Close: {
3202 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3462 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3203 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); 3463 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
3204 p->apCsr[pOp->p1] = 0; 3464 p->apCsr[pOp->p1] = 0;
3205 break; 3465 break;
3206 } 3466 }
3207 3467
3208 /* Opcode: SeekGe P1 P2 P3 P4 * 3468 /* Opcode: SeekGE P1 P2 P3 P4 *
3469 ** Synopsis: key=r[P3@P4]
3209 ** 3470 **
3210 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 3471 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3211 ** use the value in register P3 as the key. If cursor P1 refers 3472 ** use the value in register P3 as the key. If cursor P1 refers
3212 ** to an SQL index, then P3 is the first in an array of P4 registers 3473 ** to an SQL index, then P3 is the first in an array of P4 registers
3213 ** that are used as an unpacked index key. 3474 ** that are used as an unpacked index key.
3214 ** 3475 **
3215 ** Reposition cursor P1 so that it points to the smallest entry that 3476 ** Reposition cursor P1 so that it points to the smallest entry that
3216 ** is greater than or equal to the key value. If there are no records 3477 ** is greater than or equal to the key value. If there are no records
3217 ** greater than or equal to the key and P2 is not zero, then jump to P2. 3478 ** greater than or equal to the key and P2 is not zero, then jump to P2.
3218 ** 3479 **
3219 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe 3480 ** This opcode leaves the cursor configured to move in forward order,
3481 ** from the beginning toward the end. In other words, the cursor is
3482 ** configured to use Next, not Prev.
3483 **
3484 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
3220 */ 3485 */
3221 /* Opcode: SeekGt P1 P2 P3 P4 * 3486 /* Opcode: SeekGT P1 P2 P3 P4 *
3487 ** Synopsis: key=r[P3@P4]
3222 ** 3488 **
3223 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 3489 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3224 ** use the value in register P3 as a key. If cursor P1 refers 3490 ** use the value in register P3 as a key. If cursor P1 refers
3225 ** to an SQL index, then P3 is the first in an array of P4 registers 3491 ** to an SQL index, then P3 is the first in an array of P4 registers
3226 ** that are used as an unpacked index key. 3492 ** that are used as an unpacked index key.
3227 ** 3493 **
3228 ** Reposition cursor P1 so that it points to the smallest entry that 3494 ** Reposition cursor P1 so that it points to the smallest entry that
3229 ** is greater than the key value. If there are no records greater than 3495 ** is greater than the key value. If there are no records greater than
3230 ** the key and P2 is not zero, then jump to P2. 3496 ** the key and P2 is not zero, then jump to P2.
3231 ** 3497 **
3232 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe 3498 ** This opcode leaves the cursor configured to move in forward order,
3499 ** from the beginning toward the end. In other words, the cursor is
3500 ** configured to use Next, not Prev.
3501 **
3502 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
3233 */ 3503 */
3234 /* Opcode: SeekLt P1 P2 P3 P4 * 3504 /* Opcode: SeekLT P1 P2 P3 P4 *
3505 ** Synopsis: key=r[P3@P4]
3235 ** 3506 **
3236 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 3507 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3237 ** use the value in register P3 as a key. If cursor P1 refers 3508 ** use the value in register P3 as a key. If cursor P1 refers
3238 ** to an SQL index, then P3 is the first in an array of P4 registers 3509 ** to an SQL index, then P3 is the first in an array of P4 registers
3239 ** that are used as an unpacked index key. 3510 ** that are used as an unpacked index key.
3240 ** 3511 **
3241 ** Reposition cursor P1 so that it points to the largest entry that 3512 ** Reposition cursor P1 so that it points to the largest entry that
3242 ** is less than the key value. If there are no records less than 3513 ** is less than the key value. If there are no records less than
3243 ** the key and P2 is not zero, then jump to P2. 3514 ** the key and P2 is not zero, then jump to P2.
3244 ** 3515 **
3245 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe 3516 ** This opcode leaves the cursor configured to move in reverse order,
3517 ** from the end toward the beginning. In other words, the cursor is
3518 ** configured to use Prev, not Next.
3519 **
3520 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
3246 */ 3521 */
3247 /* Opcode: SeekLe P1 P2 P3 P4 * 3522 /* Opcode: SeekLE P1 P2 P3 P4 *
3523 ** Synopsis: key=r[P3@P4]
3248 ** 3524 **
3249 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 3525 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
3250 ** use the value in register P3 as a key. If cursor P1 refers 3526 ** use the value in register P3 as a key. If cursor P1 refers
3251 ** to an SQL index, then P3 is the first in an array of P4 registers 3527 ** to an SQL index, then P3 is the first in an array of P4 registers
3252 ** that are used as an unpacked index key. 3528 ** that are used as an unpacked index key.
3253 ** 3529 **
3254 ** Reposition cursor P1 so that it points to the largest entry that 3530 ** Reposition cursor P1 so that it points to the largest entry that
3255 ** is less than or equal to the key value. If there are no records 3531 ** is less than or equal to the key value. If there are no records
3256 ** less than or equal to the key and P2 is not zero, then jump to P2. 3532 ** less than or equal to the key and P2 is not zero, then jump to P2.
3257 ** 3533 **
3258 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt 3534 ** This opcode leaves the cursor configured to move in reverse order,
3535 ** from the end toward the beginning. In other words, the cursor is
3536 ** configured to use Prev, not Next.
3537 **
3538 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
3259 */ 3539 */
3260 case OP_SeekLt: /* jump, in3 */ 3540 case OP_SeekLT: /* jump, in3 */
3261 case OP_SeekLe: /* jump, in3 */ 3541 case OP_SeekLE: /* jump, in3 */
3262 case OP_SeekGe: /* jump, in3 */ 3542 case OP_SeekGE: /* jump, in3 */
3263 case OP_SeekGt: { /* jump, in3 */ 3543 case OP_SeekGT: { /* jump, in3 */
3264 int res; 3544 int res;
3265 int oc; 3545 int oc;
3266 VdbeCursor *pC; 3546 VdbeCursor *pC;
3267 UnpackedRecord r; 3547 UnpackedRecord r;
3268 int nField; 3548 int nField;
3269 i64 iKey; /* The rowid we are to seek to */ 3549 i64 iKey; /* The rowid we are to seek to */
3270 3550
3271 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3551 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3272 assert( pOp->p2!=0 ); 3552 assert( pOp->p2!=0 );
3273 pC = p->apCsr[pOp->p1]; 3553 pC = p->apCsr[pOp->p1];
3274 assert( pC!=0 ); 3554 assert( pC!=0 );
3275 assert( pC->pseudoTableReg==0 ); 3555 assert( pC->pseudoTableReg==0 );
3276 assert( OP_SeekLe == OP_SeekLt+1 ); 3556 assert( OP_SeekLE == OP_SeekLT+1 );
3277 assert( OP_SeekGe == OP_SeekLt+2 ); 3557 assert( OP_SeekGE == OP_SeekLT+2 );
3278 assert( OP_SeekGt == OP_SeekLt+3 ); 3558 assert( OP_SeekGT == OP_SeekLT+3 );
3279 assert( pC->isOrdered ); 3559 assert( pC->isOrdered );
3280 if( pC->pCursor!=0 ){ 3560 assert( pC->pCursor!=0 );
3281 oc = pOp->opcode; 3561 oc = pOp->opcode;
3282 pC->nullRow = 0; 3562 pC->nullRow = 0;
3283 if( pC->isTable ){ 3563 #ifdef SQLITE_DEBUG
3284 /* The input value in P3 might be of any type: integer, real, string, 3564 pC->seekOp = pOp->opcode;
3285 ** blob, or NULL. But it needs to be an integer before we can do 3565 #endif
3286 ** the seek, so covert it. */ 3566 if( pC->isTable ){
3287 pIn3 = &aMem[pOp->p3]; 3567 /* The input value in P3 might be of any type: integer, real, string,
3288 applyNumericAffinity(pIn3); 3568 ** blob, or NULL. But it needs to be an integer before we can do
3289 iKey = sqlite3VdbeIntValue(pIn3); 3569 ** the seek, so convert it. */
3290 pC->rowidIsValid = 0; 3570 pIn3 = &aMem[pOp->p3];
3571 if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
3572 applyNumericAffinity(pIn3, 0);
3573 }
3574 iKey = sqlite3VdbeIntValue(pIn3);
3291 3575
3292 /* If the P3 value could not be converted into an integer without 3576 /* If the P3 value could not be converted into an integer without
3293 ** loss of information, then special processing is required... */ 3577 ** loss of information, then special processing is required... */
3294 if( (pIn3->flags & MEM_Int)==0 ){ 3578 if( (pIn3->flags & MEM_Int)==0 ){
3295 if( (pIn3->flags & MEM_Real)==0 ){ 3579 if( (pIn3->flags & MEM_Real)==0 ){
3296 /* If the P3 value cannot be converted into any kind of a number, 3580 /* If the P3 value cannot be converted into any kind of a number,
3297 ** then the seek is not possible, so jump to P2 */ 3581 ** then the seek is not possible, so jump to P2 */
3298 pc = pOp->p2 - 1; 3582 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
3299 break; 3583 break;
3300 } 3584 }
3301 /* If we reach this point, then the P3 value must be a floating
3302 ** point number. */
3303 assert( (pIn3->flags & MEM_Real)!=0 );
3304 3585
3305 if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){ 3586 /* If the approximation iKey is larger than the actual real search
3306 /* The P3 value is too large in magnitude to be expressed as an 3587 ** term, substitute >= for > and < for <=. e.g. if the search term
3307 ** integer. */ 3588 ** is 4.9 and the integer approximation 5:
3308 res = 1; 3589 **
3309 if( pIn3->r<0 ){ 3590 ** (x > 4.9) -> (x >= 5)
3310 if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt ); 3591 ** (x <= 4.9) -> (x < 5)
3311 rc = sqlite3BtreeFirst(pC->pCursor, &res); 3592 */
3312 if( rc!=SQLITE_OK ) goto abort_due_to_error; 3593 if( pIn3->u.r<(double)iKey ){
3313 } 3594 assert( OP_SeekGE==(OP_SeekGT-1) );
3314 }else{ 3595 assert( OP_SeekLT==(OP_SeekLE-1) );
3315 if( oc<=OP_SeekLe ){ assert( oc==OP_SeekLt || oc==OP_SeekLe ); 3596 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
3316 rc = sqlite3BtreeLast(pC->pCursor, &res); 3597 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
3317 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3318 }
3319 }
3320 if( res ){
3321 pc = pOp->p2 - 1;
3322 }
3323 break;
3324 }else if( oc==OP_SeekLt || oc==OP_SeekGe ){
3325 /* Use the ceiling() function to convert real->int */
3326 if( pIn3->r > (double)iKey ) iKey++;
3327 }else{
3328 /* Use the floor() function to convert real->int */
3329 assert( oc==OP_SeekLe || oc==OP_SeekGt );
3330 if( pIn3->r < (double)iKey ) iKey--;
3331 }
3332 }
3333 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
3334 if( rc!=SQLITE_OK ){
3335 goto abort_due_to_error;
3336 } 3598 }
3337 if( res==0 ){ 3599
3338 pC->rowidIsValid = 1; 3600 /* If the approximation iKey is smaller than the actual real search
3339 pC->lastRowid = iKey; 3601 ** term, substitute <= for < and > for >=. */
3602 else if( pIn3->u.r>(double)iKey ){
3603 assert( OP_SeekLE==(OP_SeekLT+1) );
3604 assert( OP_SeekGT==(OP_SeekGE+1) );
3605 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
3606 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
3340 } 3607 }
3341 }else{ 3608 }
3342 nField = pOp->p4.i; 3609 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
3343 assert( pOp->p4type==P4_INT32 ); 3610 pC->movetoTarget = iKey; /* Used by OP_Delete */
3344 assert( nField>0 ); 3611 if( rc!=SQLITE_OK ){
3345 r.pKeyInfo = pC->pKeyInfo; 3612 goto abort_due_to_error;
3346 r.nField = (u16)nField;
3347
3348 /* The next line of code computes as follows, only faster:
3349 ** if( oc==OP_SeekGt || oc==OP_SeekLe ){
3350 ** r.flags = UNPACKED_INCRKEY;
3351 ** }else{
3352 ** r.flags = 0;
3353 ** }
3354 */
3355 r.flags = (u16)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt)));
3356 assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY );
3357 assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY );
3358 assert( oc!=OP_SeekGe || r.flags==0 );
3359 assert( oc!=OP_SeekLt || r.flags==0 );
3360
3361 r.aMem = &aMem[pOp->p3];
3362 #ifdef SQLITE_DEBUG
3363 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3364 #endif
3365 ExpandBlob(r.aMem);
3366 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
3367 if( rc!=SQLITE_OK ){
3368 goto abort_due_to_error;
3369 }
3370 pC->rowidIsValid = 0;
3371 }
3372 pC->deferredMoveto = 0;
3373 pC->cacheStatus = CACHE_STALE;
3374 #ifdef SQLITE_TEST
3375 sqlite3_search_count++;
3376 #endif
3377 if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt );
3378 if( res<0 || (res==0 && oc==OP_SeekGt) ){
3379 rc = sqlite3BtreeNext(pC->pCursor, &res);
3380 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3381 pC->rowidIsValid = 0;
3382 }else{
3383 res = 0;
3384 }
3385 }else{
3386 assert( oc==OP_SeekLt || oc==OP_SeekLe );
3387 if( res>0 || (res==0 && oc==OP_SeekLt) ){
3388 rc = sqlite3BtreePrevious(pC->pCursor, &res);
3389 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3390 pC->rowidIsValid = 0;
3391 }else{
3392 /* res might be negative because the table is empty. Check to
3393 ** see if this is the case.
3394 */
3395 res = sqlite3BtreeEof(pC->pCursor);
3396 }
3397 }
3398 assert( pOp->p2>0 );
3399 if( res ){
3400 pc = pOp->p2 - 1;
3401 } 3613 }
3402 }else{ 3614 }else{
3403 /* This happens when attempting to open the sqlite3_master table 3615 nField = pOp->p4.i;
3404 ** for read access returns SQLITE_EMPTY. In this case always 3616 assert( pOp->p4type==P4_INT32 );
3405 ** take the jump (since there are no records in the table). 3617 assert( nField>0 );
3618 r.pKeyInfo = pC->pKeyInfo;
3619 r.nField = (u16)nField;
3620
3621 /* The next line of code computes as follows, only faster:
3622 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
3623 ** r.default_rc = -1;
3624 ** }else{
3625 ** r.default_rc = +1;
3626 ** }
3406 */ 3627 */
3628 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
3629 assert( oc!=OP_SeekGT || r.default_rc==-1 );
3630 assert( oc!=OP_SeekLE || r.default_rc==-1 );
3631 assert( oc!=OP_SeekGE || r.default_rc==+1 );
3632 assert( oc!=OP_SeekLT || r.default_rc==+1 );
3633
3634 r.aMem = &aMem[pOp->p3];
3635 #ifdef SQLITE_DEBUG
3636 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3637 #endif
3638 ExpandBlob(r.aMem);
3639 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
3640 if( rc!=SQLITE_OK ){
3641 goto abort_due_to_error;
3642 }
3643 }
3644 pC->deferredMoveto = 0;
3645 pC->cacheStatus = CACHE_STALE;
3646 #ifdef SQLITE_TEST
3647 sqlite3_search_count++;
3648 #endif
3649 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
3650 if( res<0 || (res==0 && oc==OP_SeekGT) ){
3651 res = 0;
3652 rc = sqlite3BtreeNext(pC->pCursor, &res);
3653 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3654 }else{
3655 res = 0;
3656 }
3657 }else{
3658 assert( oc==OP_SeekLT || oc==OP_SeekLE );
3659 if( res>0 || (res==0 && oc==OP_SeekLT) ){
3660 res = 0;
3661 rc = sqlite3BtreePrevious(pC->pCursor, &res);
3662 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3663 }else{
3664 /* res might be negative because the table is empty. Check to
3665 ** see if this is the case.
3666 */
3667 res = sqlite3BtreeEof(pC->pCursor);
3668 }
3669 }
3670 assert( pOp->p2>0 );
3671 VdbeBranchTaken(res!=0,2);
3672 if( res ){
3407 pc = pOp->p2 - 1; 3673 pc = pOp->p2 - 1;
3408 } 3674 }
3409 break; 3675 break;
3410 } 3676 }
3411 3677
3412 /* Opcode: Seek P1 P2 * * * 3678 /* Opcode: Seek P1 P2 * * *
3679 ** Synopsis: intkey=r[P2]
3413 ** 3680 **
3414 ** P1 is an open table cursor and P2 is a rowid integer. Arrange 3681 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
3415 ** for P1 to move so that it points to the rowid given by P2. 3682 ** for P1 to move so that it points to the rowid given by P2.
3416 ** 3683 **
3417 ** This is actually a deferred seek. Nothing actually happens until 3684 ** This is actually a deferred seek. Nothing actually happens until
3418 ** the cursor is used to read a record. That way, if no reads 3685 ** the cursor is used to read a record. That way, if no reads
3419 ** occur, no unnecessary I/O happens. 3686 ** occur, no unnecessary I/O happens.
3420 */ 3687 */
3421 case OP_Seek: { /* in2 */ 3688 case OP_Seek: { /* in2 */
3422 VdbeCursor *pC; 3689 VdbeCursor *pC;
3423 3690
3424 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3691 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3425 pC = p->apCsr[pOp->p1]; 3692 pC = p->apCsr[pOp->p1];
3426 assert( pC!=0 ); 3693 assert( pC!=0 );
3427 if( ALWAYS(pC->pCursor!=0) ){ 3694 assert( pC->pCursor!=0 );
3428 assert( pC->isTable ); 3695 assert( pC->isTable );
3429 pC->nullRow = 0; 3696 pC->nullRow = 0;
3430 pIn2 = &aMem[pOp->p2]; 3697 pIn2 = &aMem[pOp->p2];
3431 pC->movetoTarget = sqlite3VdbeIntValue(pIn2); 3698 pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
3432 pC->rowidIsValid = 0; 3699 pC->deferredMoveto = 1;
3433 pC->deferredMoveto = 1;
3434 }
3435 break; 3700 break;
3436 } 3701 }
3437 3702
3438 3703
3439 /* Opcode: Found P1 P2 P3 P4 * 3704 /* Opcode: Found P1 P2 P3 P4 *
3705 ** Synopsis: key=r[P3@P4]
3440 ** 3706 **
3441 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 3707 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3442 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 3708 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3443 ** record. 3709 ** record.
3444 ** 3710 **
3445 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 3711 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3446 ** is a prefix of any entry in P1 then a jump is made to P2 and 3712 ** is a prefix of any entry in P1 then a jump is made to P2 and
3447 ** P1 is left pointing at the matching entry. 3713 ** P1 is left pointing at the matching entry.
3714 **
3715 ** This operation leaves the cursor in a state where it can be
3716 ** advanced in the forward direction. The Next instruction will work,
3717 ** but not the Prev instruction.
3718 **
3719 ** See also: NotFound, NoConflict, NotExists. SeekGe
3448 */ 3720 */
3449 /* Opcode: NotFound P1 P2 P3 P4 * 3721 /* Opcode: NotFound P1 P2 P3 P4 *
3722 ** Synopsis: key=r[P3@P4]
3450 ** 3723 **
3451 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If 3724 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3452 ** P4>0 then register P3 is the first of P4 registers that form an unpacked 3725 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3453 ** record. 3726 ** record.
3454 ** 3727 **
3455 ** Cursor P1 is on an index btree. If the record identified by P3 and P4 3728 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3456 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1 3729 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
3457 ** does contain an entry whose prefix matches the P3/P4 record then control 3730 ** does contain an entry whose prefix matches the P3/P4 record then control
3458 ** falls through to the next instruction and P1 is left pointing at the 3731 ** falls through to the next instruction and P1 is left pointing at the
3459 ** matching entry. 3732 ** matching entry.
3460 ** 3733 **
3461 ** See also: Found, NotExists, IsUnique 3734 ** This operation leaves the cursor in a state where it cannot be
3735 ** advanced in either direction. In other words, the Next and Prev
3736 ** opcodes do not work after this operation.
3737 **
3738 ** See also: Found, NotExists, NoConflict
3462 */ 3739 */
3740 /* Opcode: NoConflict P1 P2 P3 P4 *
3741 ** Synopsis: key=r[P3@P4]
3742 **
3743 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
3744 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
3745 ** record.
3746 **
3747 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
3748 ** contains any NULL value, jump immediately to P2. If all terms of the
3749 ** record are not-NULL then a check is done to determine if any row in the
3750 ** P1 index btree has a matching key prefix. If there are no matches, jump
3751 ** immediately to P2. If there is a match, fall through and leave the P1
3752 ** cursor pointing to the matching row.
3753 **
3754 ** This opcode is similar to OP_NotFound with the exceptions that the
3755 ** branch is always taken if any part of the search key input is NULL.
3756 **
3757 ** This operation leaves the cursor in a state where it cannot be
3758 ** advanced in either direction. In other words, the Next and Prev
3759 ** opcodes do not work after this operation.
3760 **
3761 ** See also: NotFound, Found, NotExists
3762 */
3763 case OP_NoConflict: /* jump, in3 */
3463 case OP_NotFound: /* jump, in3 */ 3764 case OP_NotFound: /* jump, in3 */
3464 case OP_Found: { /* jump, in3 */ 3765 case OP_Found: { /* jump, in3 */
3465 int alreadyExists; 3766 int alreadyExists;
3767 int ii;
3466 VdbeCursor *pC; 3768 VdbeCursor *pC;
3467 int res; 3769 int res;
3770 char *pFree;
3468 UnpackedRecord *pIdxKey; 3771 UnpackedRecord *pIdxKey;
3469 UnpackedRecord r; 3772 UnpackedRecord r;
3470 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7]; 3773 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
3471 3774
3472 #ifdef SQLITE_TEST 3775 #ifdef SQLITE_TEST
3473 sqlite3_found_count++; 3776 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
3474 #endif 3777 #endif
3475 3778
3476 alreadyExists = 0;
3477 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3779 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3478 assert( pOp->p4type==P4_INT32 ); 3780 assert( pOp->p4type==P4_INT32 );
3479 pC = p->apCsr[pOp->p1]; 3781 pC = p->apCsr[pOp->p1];
3480 assert( pC!=0 ); 3782 assert( pC!=0 );
3783 #ifdef SQLITE_DEBUG
3784 pC->seekOp = pOp->opcode;
3785 #endif
3481 pIn3 = &aMem[pOp->p3]; 3786 pIn3 = &aMem[pOp->p3];
3482 if( ALWAYS(pC->pCursor!=0) ){ 3787 assert( pC->pCursor!=0 );
3483 3788 assert( pC->isTable==0 );
3484 assert( pC->isTable==0 ); 3789 pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
3485 if( pOp->p4.i>0 ){ 3790 if( pOp->p4.i>0 ){
3486 r.pKeyInfo = pC->pKeyInfo; 3791 r.pKeyInfo = pC->pKeyInfo;
3487 r.nField = (u16)pOp->p4.i; 3792 r.nField = (u16)pOp->p4.i;
3488 r.aMem = pIn3; 3793 r.aMem = pIn3;
3794 for(ii=0; ii<r.nField; ii++){
3795 assert( memIsValid(&r.aMem[ii]) );
3796 ExpandBlob(&r.aMem[ii]);
3489 #ifdef SQLITE_DEBUG 3797 #ifdef SQLITE_DEBUG
3490 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } 3798 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
3491 #endif 3799 #endif
3492 r.flags = UNPACKED_PREFIX_MATCH; 3800 }
3493 pIdxKey = &r; 3801 pIdxKey = &r;
3494 }else{ 3802 }else{
3495 assert( pIn3->flags & MEM_Blob ); 3803 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
3496 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */ 3804 pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
3497 pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, 3805 );
3498 aTempRec, sizeof(aTempRec)); 3806 if( pIdxKey==0 ) goto no_mem;
3499 if( pIdxKey==0 ){ 3807 assert( pIn3->flags & MEM_Blob );
3500 goto no_mem; 3808 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
3809 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
3810 }
3811 pIdxKey->default_rc = 0;
3812 if( pOp->opcode==OP_NoConflict ){
3813 /* For the OP_NoConflict opcode, take the jump if any of the
3814 ** input fields are NULL, since any key with a NULL will not
3815 ** conflict */
3816 for(ii=0; ii<r.nField; ii++){
3817 if( r.aMem[ii].flags & MEM_Null ){
3818 pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
3819 break;
3501 } 3820 }
3502 pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
3503 } 3821 }
3504 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
3505 if( pOp->p4.i==0 ){
3506 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
3507 }
3508 if( rc!=SQLITE_OK ){
3509 break;
3510 }
3511 alreadyExists = (res==0);
3512 pC->deferredMoveto = 0;
3513 pC->cacheStatus = CACHE_STALE;
3514 } 3822 }
3823 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
3824 if( pOp->p4.i==0 ){
3825 sqlite3DbFree(db, pFree);
3826 }
3827 if( rc!=SQLITE_OK ){
3828 break;
3829 }
3830 pC->seekResult = res;
3831 alreadyExists = (res==0);
3832 pC->nullRow = 1-alreadyExists;
3833 pC->deferredMoveto = 0;
3834 pC->cacheStatus = CACHE_STALE;
3515 if( pOp->opcode==OP_Found ){ 3835 if( pOp->opcode==OP_Found ){
3836 VdbeBranchTaken(alreadyExists!=0,2);
3516 if( alreadyExists ) pc = pOp->p2 - 1; 3837 if( alreadyExists ) pc = pOp->p2 - 1;
3517 }else{ 3838 }else{
3839 VdbeBranchTaken(alreadyExists==0,2);
3518 if( !alreadyExists ) pc = pOp->p2 - 1; 3840 if( !alreadyExists ) pc = pOp->p2 - 1;
3519 } 3841 }
3520 break; 3842 break;
3521 } 3843 }
3522 3844
3523 /* Opcode: IsUnique P1 P2 P3 P4 * 3845 /* Opcode: NotExists P1 P2 P3 * *
3846 ** Synopsis: intkey=r[P3]
3524 ** 3847 **
3525 ** Cursor P1 is open on an index b-tree - that is to say, a btree which 3848 ** P1 is the index of a cursor open on an SQL table btree (with integer
3526 ** no data and where the key are records generated by OP_MakeRecord with 3849 ** keys). P3 is an integer rowid. If P1 does not contain a record with
3527 ** the list field being the integer ROWID of the entry that the index 3850 ** rowid P3 then jump immediately to P2. If P1 does contain a record
3528 ** entry refers to. 3851 ** with rowid P3 then leave the cursor pointing at that record and fall
3852 ** through to the next instruction.
3529 ** 3853 **
3530 ** The P3 register contains an integer record number. Call this record 3854 ** The OP_NotFound opcode performs the same operation on index btrees
3531 ** number R. Register P4 is the first in a set of N contiguous registers 3855 ** (with arbitrary multi-value keys).
3532 ** that make up an unpacked index key that can be used with cursor P1.
3533 ** The value of N can be inferred from the cursor. N includes the rowid
3534 ** value appended to the end of the index record. This rowid value may
3535 ** or may not be the same as R.
3536 ** 3856 **
3537 ** If any of the N registers beginning with register P4 contains a NULL 3857 ** This opcode leaves the cursor in a state where it cannot be advanced
3538 ** value, jump immediately to P2. 3858 ** in either direction. In other words, the Next and Prev opcodes will
3859 ** not work following this opcode.
3539 ** 3860 **
3540 ** Otherwise, this instruction checks if cursor P1 contains an entry 3861 ** See also: Found, NotFound, NoConflict
3541 ** where the first (N-1) fields match but the rowid value at the end
3542 ** of the index entry is not R. If there is no such entry, control jumps
3543 ** to instruction P2. Otherwise, the rowid of the conflicting index
3544 ** entry is copied to register P3 and control falls through to the next
3545 ** instruction.
3546 **
3547 ** See also: NotFound, NotExists, Found
3548 */
3549 case OP_IsUnique: { /* jump, in3 */
3550 u16 ii;
3551 VdbeCursor *pCx;
3552 BtCursor *pCrsr;
3553 u16 nField;
3554 Mem *aMx;
3555 UnpackedRecord r; /* B-Tree index search key */
3556 i64 R; /* Rowid stored in register P3 */
3557
3558 pIn3 = &aMem[pOp->p3];
3559 aMx = &aMem[pOp->p4.i];
3560 /* Assert that the values of parameters P1 and P4 are in range. */
3561 assert( pOp->p4type==P4_INT32 );
3562 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
3563 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3564
3565 /* Find the index cursor. */
3566 pCx = p->apCsr[pOp->p1];
3567 assert( pCx->deferredMoveto==0 );
3568 pCx->seekResult = 0;
3569 pCx->cacheStatus = CACHE_STALE;
3570 pCrsr = pCx->pCursor;
3571
3572 /* If any of the values are NULL, take the jump. */
3573 nField = pCx->pKeyInfo->nField;
3574 for(ii=0; ii<nField; ii++){
3575 if( aMx[ii].flags & MEM_Null ){
3576 pc = pOp->p2 - 1;
3577 pCrsr = 0;
3578 break;
3579 }
3580 }
3581 assert( (aMx[nField].flags & MEM_Null)==0 );
3582
3583 if( pCrsr!=0 ){
3584 /* Populate the index search key. */
3585 r.pKeyInfo = pCx->pKeyInfo;
3586 r.nField = nField + 1;
3587 r.flags = UNPACKED_PREFIX_SEARCH;
3588 r.aMem = aMx;
3589 #ifdef SQLITE_DEBUG
3590 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
3591 #endif
3592
3593 /* Extract the value of R from register P3. */
3594 sqlite3VdbeMemIntegerify(pIn3);
3595 R = pIn3->u.i;
3596
3597 /* Search the B-Tree index. If no conflicting record is found, jump
3598 ** to P2. Otherwise, copy the rowid of the conflicting record to
3599 ** register P3 and fall through to the next instruction. */
3600 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult);
3601 if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){
3602 pc = pOp->p2 - 1;
3603 }else{
3604 pIn3->u.i = r.rowid;
3605 }
3606 }
3607 break;
3608 }
3609
3610 /* Opcode: NotExists P1 P2 P3 * *
3611 **
3612 ** Use the content of register P3 as a integer key. If a record
3613 ** with that key does not exist in table of P1, then jump to P2.
3614 ** If the record does exist, then fall through. The cursor is left
3615 ** pointing to the record if it exists.
3616 **
3617 ** The difference between this operation and NotFound is that this
3618 ** operation assumes the key is an integer and that P1 is a table whereas
3619 ** NotFound assumes key is a blob constructed from MakeRecord and
3620 ** P1 is an index.
3621 **
3622 ** See also: Found, NotFound, IsUnique
3623 */ 3862 */
3624 case OP_NotExists: { /* jump, in3 */ 3863 case OP_NotExists: { /* jump, in3 */
3625 VdbeCursor *pC; 3864 VdbeCursor *pC;
3626 BtCursor *pCrsr; 3865 BtCursor *pCrsr;
3627 int res; 3866 int res;
3628 u64 iKey; 3867 u64 iKey;
3629 3868
3630 pIn3 = &aMem[pOp->p3]; 3869 pIn3 = &aMem[pOp->p3];
3631 assert( pIn3->flags & MEM_Int ); 3870 assert( pIn3->flags & MEM_Int );
3632 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3871 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3633 pC = p->apCsr[pOp->p1]; 3872 pC = p->apCsr[pOp->p1];
3634 assert( pC!=0 ); 3873 assert( pC!=0 );
3874 #ifdef SQLITE_DEBUG
3875 pC->seekOp = 0;
3876 #endif
3635 assert( pC->isTable ); 3877 assert( pC->isTable );
3636 assert( pC->pseudoTableReg==0 ); 3878 assert( pC->pseudoTableReg==0 );
3637 pCrsr = pC->pCursor; 3879 pCrsr = pC->pCursor;
3638 if( pCrsr!=0 ){ 3880 assert( pCrsr!=0 );
3639 res = 0; 3881 res = 0;
3640 iKey = pIn3->u.i; 3882 iKey = pIn3->u.i;
3641 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); 3883 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
3642 pC->lastRowid = pIn3->u.i; 3884 pC->movetoTarget = iKey; /* Used by OP_Delete */
3643 pC->rowidIsValid = res==0 ?1:0; 3885 pC->nullRow = 0;
3644 pC->nullRow = 0; 3886 pC->cacheStatus = CACHE_STALE;
3645 pC->cacheStatus = CACHE_STALE; 3887 pC->deferredMoveto = 0;
3646 pC->deferredMoveto = 0; 3888 VdbeBranchTaken(res!=0,2);
3647 if( res!=0 ){ 3889 if( res!=0 ){
3648 pc = pOp->p2 - 1;
3649 assert( pC->rowidIsValid==0 );
3650 }
3651 pC->seekResult = res;
3652 }else{
3653 /* This happens when an attempt to open a read cursor on the
3654 ** sqlite_master table returns SQLITE_EMPTY.
3655 */
3656 pc = pOp->p2 - 1; 3890 pc = pOp->p2 - 1;
3657 assert( pC->rowidIsValid==0 );
3658 pC->seekResult = 0;
3659 } 3891 }
3892 pC->seekResult = res;
3660 break; 3893 break;
3661 } 3894 }
3662 3895
3663 /* Opcode: Sequence P1 P2 * * * 3896 /* Opcode: Sequence P1 P2 * * *
3897 ** Synopsis: r[P2]=cursor[P1].ctr++
3664 ** 3898 **
3665 ** Find the next available sequence number for cursor P1. 3899 ** Find the next available sequence number for cursor P1.
3666 ** Write the sequence number into register P2. 3900 ** Write the sequence number into register P2.
3667 ** The sequence number on the cursor is incremented after this 3901 ** The sequence number on the cursor is incremented after this
3668 ** instruction. 3902 ** instruction.
3669 */ 3903 */
3670 case OP_Sequence: { /* out2-prerelease */ 3904 case OP_Sequence: { /* out2-prerelease */
3671 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 3905 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3672 assert( p->apCsr[pOp->p1]!=0 ); 3906 assert( p->apCsr[pOp->p1]!=0 );
3673 pOut->u.i = p->apCsr[pOp->p1]->seqCount++; 3907 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
3674 break; 3908 break;
3675 } 3909 }
3676 3910
3677 3911
3678 /* Opcode: NewRowid P1 P2 P3 * * 3912 /* Opcode: NewRowid P1 P2 P3 * *
3913 ** Synopsis: r[P2]=rowid
3679 ** 3914 **
3680 ** Get a new integer record number (a.k.a "rowid") used as the key to a table. 3915 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3681 ** The record number is not previously used as a key in the database 3916 ** The record number is not previously used as a key in the database
3682 ** table that cursor P1 points to. The new record number is written 3917 ** table that cursor P1 points to. The new record number is written
3683 ** written to register P2. 3918 ** written to register P2.
3684 ** 3919 **
3685 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 3920 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
3686 ** the largest previously generated record number. No new record numbers are 3921 ** the largest previously generated record number. No new record numbers are
3687 ** allowed to be less than this value. When this value reaches its maximum, 3922 ** allowed to be less than this value. When this value reaches its maximum,
3688 ** a SQLITE_FULL error is generated. The P3 register is updated with the ' 3923 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
3689 ** generated record number. This P3 mechanism is used to help implement the 3924 ** generated record number. This P3 mechanism is used to help implement the
3690 ** AUTOINCREMENT feature. 3925 ** AUTOINCREMENT feature.
3691 */ 3926 */
3692 case OP_NewRowid: { /* out2-prerelease */ 3927 case OP_NewRowid: { /* out2-prerelease */
3693 i64 v; /* The new rowid */ 3928 i64 v; /* The new rowid */
3694 VdbeCursor *pC; /* Cursor of table to get the new rowid */ 3929 VdbeCursor *pC; /* Cursor of table to get the new rowid */
3695 int res; /* Result of an sqlite3BtreeLast() */ 3930 int res; /* Result of an sqlite3BtreeLast() */
3696 int cnt; /* Counter to limit the number of searches */ 3931 int cnt; /* Counter to limit the number of searches */
3697 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ 3932 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
3698 VdbeFrame *pFrame; /* Root frame of VDBE */ 3933 VdbeFrame *pFrame; /* Root frame of VDBE */
(...skipping 25 matching lines...) Expand all
3724 # define MAX_ROWID 0x7fffffff 3959 # define MAX_ROWID 0x7fffffff
3725 #else 3960 #else
3726 /* Some compilers complain about constants of the form 0x7fffffffffffffff. 3961 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3727 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems 3962 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
3728 ** to provide the constant while making all compilers happy. 3963 ** to provide the constant while making all compilers happy.
3729 */ 3964 */
3730 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) 3965 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3731 #endif 3966 #endif
3732 3967
3733 if( !pC->useRandomRowid ){ 3968 if( !pC->useRandomRowid ){
3734 v = sqlite3BtreeGetCachedRowid(pC->pCursor); 3969 rc = sqlite3BtreeLast(pC->pCursor, &res);
3735 if( v==0 ){ 3970 if( rc!=SQLITE_OK ){
3736 rc = sqlite3BtreeLast(pC->pCursor, &res); 3971 goto abort_due_to_error;
3737 if( rc!=SQLITE_OK ){ 3972 }
3738 goto abort_due_to_error; 3973 if( res ){
3739 } 3974 v = 1; /* IMP: R-61914-48074 */
3740 if( res ){ 3975 }else{
3741 v = 1; /* IMP: R-61914-48074 */ 3976 assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
3977 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
3978 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
3979 if( v>=MAX_ROWID ){
3980 pC->useRandomRowid = 1;
3742 }else{ 3981 }else{
3743 assert( sqlite3BtreeCursorIsValid(pC->pCursor) ); 3982 v++; /* IMP: R-29538-34987 */
3744 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
3745 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
3746 if( v==MAX_ROWID ){
3747 pC->useRandomRowid = 1;
3748 }else{
3749 v++; /* IMP: R-29538-34987 */
3750 }
3751 } 3983 }
3752 } 3984 }
3985 }
3753 3986
3754 #ifndef SQLITE_OMIT_AUTOINCREMENT 3987 #ifndef SQLITE_OMIT_AUTOINCREMENT
3755 if( pOp->p3 ){ 3988 if( pOp->p3 ){
3989 /* Assert that P3 is a valid memory cell. */
3990 assert( pOp->p3>0 );
3991 if( p->pFrame ){
3992 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
3756 /* Assert that P3 is a valid memory cell. */ 3993 /* Assert that P3 is a valid memory cell. */
3757 assert( pOp->p3>0 ); 3994 assert( pOp->p3<=pFrame->nMem );
3758 if( p->pFrame ){ 3995 pMem = &pFrame->aMem[pOp->p3];
3759 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 3996 }else{
3760 /* Assert that P3 is a valid memory cell. */ 3997 /* Assert that P3 is a valid memory cell. */
3761 assert( pOp->p3<=pFrame->nMem ); 3998 assert( pOp->p3<=(p->nMem-p->nCursor) );
3762 pMem = &pFrame->aMem[pOp->p3]; 3999 pMem = &aMem[pOp->p3];
3763 }else{ 4000 memAboutToChange(p, pMem);
3764 /* Assert that P3 is a valid memory cell. */ 4001 }
3765 assert( pOp->p3<=p->nMem ); 4002 assert( memIsValid(pMem) );
3766 pMem = &aMem[pOp->p3];
3767 memAboutToChange(p, pMem);
3768 }
3769 assert( memIsValid(pMem) );
3770 4003
3771 REGISTER_TRACE(pOp->p3, pMem); 4004 REGISTER_TRACE(pOp->p3, pMem);
3772 sqlite3VdbeMemIntegerify(pMem); 4005 sqlite3VdbeMemIntegerify(pMem);
3773 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ 4006 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
3774 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ 4007 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3775 rc = SQLITE_FULL; /* IMP: R-12275-61338 */ 4008 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
3776 goto abort_due_to_error; 4009 goto abort_due_to_error;
3777 }
3778 if( v<pMem->u.i+1 ){
3779 v = pMem->u.i + 1;
3780 }
3781 pMem->u.i = v;
3782 } 4010 }
4011 if( v<pMem->u.i+1 ){
4012 v = pMem->u.i + 1;
4013 }
4014 pMem->u.i = v;
4015 }
3783 #endif 4016 #endif
3784
3785 sqlite3BtreeSetCachedRowid(pC->pCursor, v<MAX_ROWID ? v+1 : 0);
3786 }
3787 if( pC->useRandomRowid ){ 4017 if( pC->useRandomRowid ){
3788 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the 4018 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
3789 ** largest possible integer (9223372036854775807) then the database 4019 ** largest possible integer (9223372036854775807) then the database
3790 ** engine starts picking positive candidate ROWIDs at random until 4020 ** engine starts picking positive candidate ROWIDs at random until
3791 ** it finds one that is not previously used. */ 4021 ** it finds one that is not previously used. */
3792 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is 4022 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
3793 ** an AUTOINCREMENT table. */ 4023 ** an AUTOINCREMENT table. */
3794 /* on the first attempt, simply do one more than previous */
3795 v = db->lastRowid;
3796 v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
3797 v++; /* ensure non-zero */
3798 cnt = 0; 4024 cnt = 0;
3799 while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v, 4025 do{
4026 sqlite3_randomness(sizeof(v), &v);
4027 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
4028 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
3800 0, &res))==SQLITE_OK) 4029 0, &res))==SQLITE_OK)
3801 && (res==0) 4030 && (res==0)
3802 && (++cnt<100)){ 4031 && (++cnt<100));
3803 /* collision - try another random rowid */
3804 sqlite3_randomness(sizeof(v), &v);
3805 if( cnt<5 ){
3806 /* try "small" random rowids for the initial attempts */
3807 v &= 0xffffff;
3808 }else{
3809 v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
3810 }
3811 v++; /* ensure non-zero */
3812 }
3813 if( rc==SQLITE_OK && res==0 ){ 4032 if( rc==SQLITE_OK && res==0 ){
3814 rc = SQLITE_FULL; /* IMP: R-38219-53002 */ 4033 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
3815 goto abort_due_to_error; 4034 goto abort_due_to_error;
3816 } 4035 }
3817 assert( v>0 ); /* EV: R-40812-03570 */ 4036 assert( v>0 ); /* EV: R-40812-03570 */
3818 } 4037 }
3819 pC->rowidIsValid = 0;
3820 pC->deferredMoveto = 0; 4038 pC->deferredMoveto = 0;
3821 pC->cacheStatus = CACHE_STALE; 4039 pC->cacheStatus = CACHE_STALE;
3822 } 4040 }
3823 pOut->u.i = v; 4041 pOut->u.i = v;
3824 break; 4042 break;
3825 } 4043 }
3826 4044
3827 /* Opcode: Insert P1 P2 P3 P4 P5 4045 /* Opcode: Insert P1 P2 P3 P4 P5
4046 ** Synopsis: intkey=r[P3] data=r[P2]
3828 ** 4047 **
3829 ** Write an entry into the table of cursor P1. A new entry is 4048 ** Write an entry into the table of cursor P1. A new entry is
3830 ** created if it doesn't already exist or the data for an existing 4049 ** created if it doesn't already exist or the data for an existing
3831 ** entry is overwritten. The data is the value MEM_Blob stored in register 4050 ** entry is overwritten. The data is the value MEM_Blob stored in register
3832 ** number P2. The key is stored in register P3. The key must 4051 ** number P2. The key is stored in register P3. The key must
3833 ** be a MEM_Int. 4052 ** be a MEM_Int.
3834 ** 4053 **
3835 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is 4054 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
3836 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, 4055 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
3837 ** then rowid is stored for subsequent return by the 4056 ** then rowid is stored for subsequent return by the
(...skipping 19 matching lines...) Expand all
3857 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically 4076 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
3858 ** allocated, then ownership of P2 is transferred to the pseudo-cursor 4077 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
3859 ** and register P2 becomes ephemeral. If the cursor is changed, the 4078 ** and register P2 becomes ephemeral. If the cursor is changed, the
3860 ** value of register P2 will then change. Make sure this does not 4079 ** value of register P2 will then change. Make sure this does not
3861 ** cause any problems.) 4080 ** cause any problems.)
3862 ** 4081 **
3863 ** This instruction only works on tables. The equivalent instruction 4082 ** This instruction only works on tables. The equivalent instruction
3864 ** for indices is OP_IdxInsert. 4083 ** for indices is OP_IdxInsert.
3865 */ 4084 */
3866 /* Opcode: InsertInt P1 P2 P3 P4 P5 4085 /* Opcode: InsertInt P1 P2 P3 P4 P5
4086 ** Synopsis: intkey=P3 data=r[P2]
3867 ** 4087 **
3868 ** This works exactly like OP_Insert except that the key is the 4088 ** This works exactly like OP_Insert except that the key is the
3869 ** integer value P3, not the value of the integer stored in register P3. 4089 ** integer value P3, not the value of the integer stored in register P3.
3870 */ 4090 */
3871 case OP_Insert: 4091 case OP_Insert:
3872 case OP_InsertInt: { 4092 case OP_InsertInt: {
3873 Mem *pData; /* MEM cell holding data for the record to be inserted */ 4093 Mem *pData; /* MEM cell holding data for the record to be inserted */
3874 Mem *pKey; /* MEM cell holding key for the record */ 4094 Mem *pKey; /* MEM cell holding key for the record */
3875 i64 iKey; /* The integer ROWID or key for the record to be inserted */ 4095 i64 iKey; /* The integer ROWID or key for the record to be inserted */
3876 VdbeCursor *pC; /* Cursor to table into which insert is written */ 4096 VdbeCursor *pC; /* Cursor to table into which insert is written */
(...skipping 18 matching lines...) Expand all
3895 assert( pKey->flags & MEM_Int ); 4115 assert( pKey->flags & MEM_Int );
3896 assert( memIsValid(pKey) ); 4116 assert( memIsValid(pKey) );
3897 REGISTER_TRACE(pOp->p3, pKey); 4117 REGISTER_TRACE(pOp->p3, pKey);
3898 iKey = pKey->u.i; 4118 iKey = pKey->u.i;
3899 }else{ 4119 }else{
3900 assert( pOp->opcode==OP_InsertInt ); 4120 assert( pOp->opcode==OP_InsertInt );
3901 iKey = pOp->p3; 4121 iKey = pOp->p3;
3902 } 4122 }
3903 4123
3904 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; 4124 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
3905 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = iKey; 4125 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
3906 if( pData->flags & MEM_Null ){ 4126 if( pData->flags & MEM_Null ){
3907 pData->z = 0; 4127 pData->z = 0;
3908 pData->n = 0; 4128 pData->n = 0;
3909 }else{ 4129 }else{
3910 assert( pData->flags & (MEM_Blob|MEM_Str) ); 4130 assert( pData->flags & (MEM_Blob|MEM_Str) );
3911 } 4131 }
3912 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); 4132 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
3913 if( pData->flags & MEM_Zero ){ 4133 if( pData->flags & MEM_Zero ){
3914 nZero = pData->u.nZero; 4134 nZero = pData->u.nZero;
3915 }else{ 4135 }else{
3916 nZero = 0; 4136 nZero = 0;
3917 } 4137 }
3918 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
3919 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, 4138 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3920 pData->z, pData->n, nZero, 4139 pData->z, pData->n, nZero,
3921 pOp->p5 & OPFLAG_APPEND, seekResult 4140 (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
3922 ); 4141 );
3923 pC->rowidIsValid = 0;
3924 pC->deferredMoveto = 0; 4142 pC->deferredMoveto = 0;
3925 pC->cacheStatus = CACHE_STALE; 4143 pC->cacheStatus = CACHE_STALE;
3926 4144
3927 /* Invoke the update-hook if required. */ 4145 /* Invoke the update-hook if required. */
3928 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ 4146 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
3929 zDb = db->aDb[pC->iDb].zName; 4147 zDb = db->aDb[pC->iDb].zName;
3930 zTbl = pOp->p4.z; 4148 zTbl = pOp->p4.z;
3931 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); 4149 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3932 assert( pC->isTable ); 4150 assert( pC->isTable );
3933 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey); 4151 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3934 assert( pC->iDb>=0 ); 4152 assert( pC->iDb>=0 );
3935 } 4153 }
3936 break; 4154 break;
3937 } 4155 }
3938 4156
3939 /* Opcode: Delete P1 P2 * P4 * 4157 /* Opcode: Delete P1 P2 * P4 *
3940 ** 4158 **
3941 ** Delete the record at which the P1 cursor is currently pointing. 4159 ** Delete the record at which the P1 cursor is currently pointing.
3942 ** 4160 **
3943 ** The cursor will be left pointing at either the next or the previous 4161 ** The cursor will be left pointing at either the next or the previous
3944 ** record in the table. If it is left pointing at the next record, then 4162 ** record in the table. If it is left pointing at the next record, then
3945 ** the next Next instruction will be a no-op. Hence it is OK to delete 4163 ** the next Next instruction will be a no-op. Hence it is OK to delete
3946 ** a record from within an Next loop. 4164 ** a record from within a Next loop.
3947 ** 4165 **
3948 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is 4166 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3949 ** incremented (otherwise not). 4167 ** incremented (otherwise not).
3950 ** 4168 **
3951 ** P1 must not be pseudo-table. It has to be a real table with 4169 ** P1 must not be pseudo-table. It has to be a real table with
3952 ** multiple rows. 4170 ** multiple rows.
3953 ** 4171 **
3954 ** If P4 is not NULL, then it is the name of the table that P1 is 4172 ** If P4 is not NULL, then it is the name of the table that P1 is
3955 ** pointing to. The update hook will be invoked, if it exists. 4173 ** pointing to. The update hook will be invoked, if it exists.
3956 ** If P4 is not NULL then the P1 cursor must have been positioned 4174 ** If P4 is not NULL then the P1 cursor must have been positioned
3957 ** using OP_NotFound prior to invoking this opcode. 4175 ** using OP_NotFound prior to invoking this opcode.
3958 */ 4176 */
3959 case OP_Delete: { 4177 case OP_Delete: {
3960 i64 iKey;
3961 VdbeCursor *pC; 4178 VdbeCursor *pC;
3962 4179
3963 iKey = 0;
3964 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4180 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3965 pC = p->apCsr[pOp->p1]; 4181 pC = p->apCsr[pOp->p1];
3966 assert( pC!=0 ); 4182 assert( pC!=0 );
3967 assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */ 4183 assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
4184 assert( pC->deferredMoveto==0 );
3968 4185
3969 /* If the update-hook will be invoked, set iKey to the rowid of the 4186 #ifdef SQLITE_DEBUG
3970 ** row being deleted. 4187 /* The seek operation that positioned the cursor prior to OP_Delete will
3971 */ 4188 ** have also set the pC->movetoTarget field to the rowid of the row that
3972 if( db->xUpdateCallback && pOp->p4.z ){ 4189 ** is being deleted */
3973 assert( pC->isTable ); 4190 if( pOp->p4.z && pC->isTable ){
3974 assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */ 4191 i64 iKey = 0;
3975 iKey = pC->lastRowid; 4192 sqlite3BtreeKeySize(pC->pCursor, &iKey);
4193 assert( pC->movetoTarget==iKey );
3976 } 4194 }
3977 4195 #endif
3978 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or 4196
3979 ** OP_Column on the same table without any intervening operations that
3980 ** might move or invalidate the cursor. Hence cursor pC is always pointing
3981 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
3982 ** below is always a no-op and cannot fail. We will run it anyhow, though,
3983 ** to guard against future changes to the code generator.
3984 **/
3985 assert( pC->deferredMoveto==0 );
3986 rc = sqlite3VdbeCursorMoveto(pC);
3987 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
3988
3989 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
3990 rc = sqlite3BtreeDelete(pC->pCursor); 4197 rc = sqlite3BtreeDelete(pC->pCursor);
3991 pC->cacheStatus = CACHE_STALE; 4198 pC->cacheStatus = CACHE_STALE;
3992 4199
3993 /* Invoke the update-hook if required. */ 4200 /* Invoke the update-hook if required. */
3994 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ 4201 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
3995 const char *zDb = db->aDb[pC->iDb].zName; 4202 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
3996 const char *zTbl = pOp->p4.z; 4203 db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
3997 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3998 assert( pC->iDb>=0 ); 4204 assert( pC->iDb>=0 );
3999 } 4205 }
4000 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++; 4206 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
4001 break; 4207 break;
4002 } 4208 }
4003 /* Opcode: ResetCount * * * * * 4209 /* Opcode: ResetCount * * * * *
4004 ** 4210 **
4005 ** The value of the change counter is copied to the database handle 4211 ** The value of the change counter is copied to the database handle
4006 ** change counter (returned by subsequent calls to sqlite3_changes()). 4212 ** change counter (returned by subsequent calls to sqlite3_changes()).
4007 ** Then the VMs internal change counter resets to 0. 4213 ** Then the VMs internal change counter resets to 0.
4008 ** This is used by trigger programs. 4214 ** This is used by trigger programs.
4009 */ 4215 */
4010 case OP_ResetCount: { 4216 case OP_ResetCount: {
4011 sqlite3VdbeSetChanges(db, p->nChange); 4217 sqlite3VdbeSetChanges(db, p->nChange);
4012 p->nChange = 0; 4218 p->nChange = 0;
4013 break; 4219 break;
4014 } 4220 }
4015 4221
4222 /* Opcode: SorterCompare P1 P2 P3 P4
4223 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
4224 **
4225 ** P1 is a sorter cursor. This instruction compares a prefix of the
4226 ** record blob in register P3 against a prefix of the entry that
4227 ** the sorter cursor currently points to. Only the first P4 fields
4228 ** of r[P3] and the sorter record are compared.
4229 **
4230 ** If either P3 or the sorter contains a NULL in one of their significant
4231 ** fields (not counting the P4 fields at the end which are ignored) then
4232 ** the comparison is assumed to be equal.
4233 **
4234 ** Fall through to next instruction if the two records compare equal to
4235 ** each other. Jump to P2 if they are different.
4236 */
4237 case OP_SorterCompare: {
4238 VdbeCursor *pC;
4239 int res;
4240 int nKeyCol;
4241
4242 pC = p->apCsr[pOp->p1];
4243 assert( isSorter(pC) );
4244 assert( pOp->p4type==P4_INT32 );
4245 pIn3 = &aMem[pOp->p3];
4246 nKeyCol = pOp->p4.i;
4247 res = 0;
4248 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
4249 VdbeBranchTaken(res!=0,2);
4250 if( res ){
4251 pc = pOp->p2-1;
4252 }
4253 break;
4254 };
4255
4256 /* Opcode: SorterData P1 P2 P3 * *
4257 ** Synopsis: r[P2]=data
4258 **
4259 ** Write into register P2 the current sorter data for sorter cursor P1.
4260 ** Then clear the column header cache on cursor P3.
4261 **
4262 ** This opcode is normally use to move a record out of the sorter and into
4263 ** a register that is the source for a pseudo-table cursor created using
4264 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
4265 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
4266 ** us from having to issue a separate NullRow instruction to clear that cache.
4267 */
4268 case OP_SorterData: {
4269 VdbeCursor *pC;
4270
4271 pOut = &aMem[pOp->p2];
4272 pC = p->apCsr[pOp->p1];
4273 assert( isSorter(pC) );
4274 rc = sqlite3VdbeSorterRowkey(pC, pOut);
4275 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
4276 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4277 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
4278 break;
4279 }
4280
4016 /* Opcode: RowData P1 P2 * * * 4281 /* Opcode: RowData P1 P2 * * *
4282 ** Synopsis: r[P2]=data
4017 ** 4283 **
4018 ** Write into register P2 the complete row data for cursor P1. 4284 ** Write into register P2 the complete row data for cursor P1.
4019 ** There is no interpretation of the data. 4285 ** There is no interpretation of the data.
4020 ** It is just copied onto the P2 register exactly as 4286 ** It is just copied onto the P2 register exactly as
4021 ** it is found in the database file. 4287 ** it is found in the database file.
4022 ** 4288 **
4023 ** If the P1 cursor must be pointing to a valid row (not a NULL row) 4289 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4024 ** of a real table, not a pseudo-table. 4290 ** of a real table, not a pseudo-table.
4025 */ 4291 */
4026 /* Opcode: RowKey P1 P2 * * * 4292 /* Opcode: RowKey P1 P2 * * *
4293 ** Synopsis: r[P2]=key
4027 ** 4294 **
4028 ** Write into register P2 the complete row key for cursor P1. 4295 ** Write into register P2 the complete row key for cursor P1.
4029 ** There is no interpretation of the data. 4296 ** There is no interpretation of the data.
4030 ** The key is copied onto the P3 register exactly as 4297 ** The key is copied onto the P2 register exactly as
4031 ** it is found in the database file. 4298 ** it is found in the database file.
4032 ** 4299 **
4033 ** If the P1 cursor must be pointing to a valid row (not a NULL row) 4300 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
4034 ** of a real table, not a pseudo-table. 4301 ** of a real table, not a pseudo-table.
4035 */ 4302 */
4036 case OP_RowKey: 4303 case OP_RowKey:
4037 case OP_RowData: { 4304 case OP_RowData: {
4038 VdbeCursor *pC; 4305 VdbeCursor *pC;
4039 BtCursor *pCrsr; 4306 BtCursor *pCrsr;
4040 u32 n; 4307 u32 n;
4041 i64 n64; 4308 i64 n64;
4042 4309
4043 pOut = &aMem[pOp->p2]; 4310 pOut = &aMem[pOp->p2];
4044 memAboutToChange(p, pOut); 4311 memAboutToChange(p, pOut);
4045 4312
4046 /* Note that RowKey and RowData are really exactly the same instruction */ 4313 /* Note that RowKey and RowData are really exactly the same instruction */
4047 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4314 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4048 pC = p->apCsr[pOp->p1]; 4315 pC = p->apCsr[pOp->p1];
4049 assert( pC->isTable || pOp->opcode==OP_RowKey ); 4316 assert( isSorter(pC)==0 );
4050 assert( pC->isIndex || pOp->opcode==OP_RowData ); 4317 assert( pC->isTable || pOp->opcode!=OP_RowData );
4318 assert( pC->isTable==0 || pOp->opcode==OP_RowData );
4051 assert( pC!=0 ); 4319 assert( pC!=0 );
4052 assert( pC->nullRow==0 ); 4320 assert( pC->nullRow==0 );
4053 assert( pC->pseudoTableReg==0 ); 4321 assert( pC->pseudoTableReg==0 );
4054 assert( pC->pCursor!=0 ); 4322 assert( pC->pCursor!=0 );
4055 pCrsr = pC->pCursor; 4323 pCrsr = pC->pCursor;
4056 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4057 4324
4058 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or 4325 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
4059 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate 4326 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
4060 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always 4327 ** the cursor. If this where not the case, on of the following assert()s
4061 ** a no-op and can never fail. But we leave it in place as a safety. 4328 ** would fail. Should this ever change (because of changes in the code
4329 ** generator) then the fix would be to insert a call to
4330 ** sqlite3VdbeCursorMoveto().
4062 */ 4331 */
4063 assert( pC->deferredMoveto==0 ); 4332 assert( pC->deferredMoveto==0 );
4333 assert( sqlite3BtreeCursorIsValid(pCrsr) );
4334 #if 0 /* Not required due to the previous to assert() statements */
4064 rc = sqlite3VdbeCursorMoveto(pC); 4335 rc = sqlite3VdbeCursorMoveto(pC);
4065 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; 4336 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4337 #endif
4066 4338
4067 if( pC->isIndex ){ 4339 if( pC->isTable==0 ){
4068 assert( !pC->isTable ); 4340 assert( !pC->isTable );
4069 rc = sqlite3BtreeKeySize(pCrsr, &n64); 4341 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
4070 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */ 4342 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
4071 if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 4343 if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
4072 goto too_big; 4344 goto too_big;
4073 } 4345 }
4074 n = (u32)n64; 4346 n = (u32)n64;
4075 }else{ 4347 }else{
4076 rc = sqlite3BtreeDataSize(pCrsr, &n); 4348 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
4077 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */ 4349 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
4078 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ 4350 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
4079 goto too_big; 4351 goto too_big;
4080 } 4352 }
4081 } 4353 }
4082 if( sqlite3VdbeMemGrow(pOut, n, 0) ){ 4354 testcase( n==0 );
4355 if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
4083 goto no_mem; 4356 goto no_mem;
4084 } 4357 }
4085 pOut->n = n; 4358 pOut->n = n;
4086 MemSetTypeFlag(pOut, MEM_Blob); 4359 MemSetTypeFlag(pOut, MEM_Blob);
4087 if( pC->isIndex ){ 4360 if( pC->isTable==0 ){
4088 rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z); 4361 rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
4089 }else{ 4362 }else{
4090 rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z); 4363 rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
4091 } 4364 }
4092 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ 4365 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
4093 UPDATE_MAX_BLOBSIZE(pOut); 4366 UPDATE_MAX_BLOBSIZE(pOut);
4367 REGISTER_TRACE(pOp->p2, pOut);
4094 break; 4368 break;
4095 } 4369 }
4096 4370
4097 /* Opcode: Rowid P1 P2 * * * 4371 /* Opcode: Rowid P1 P2 * * *
4372 ** Synopsis: r[P2]=rowid
4098 ** 4373 **
4099 ** Store in register P2 an integer which is the key of the table entry that 4374 ** Store in register P2 an integer which is the key of the table entry that
4100 ** P1 is currently point to. 4375 ** P1 is currently point to.
4101 ** 4376 **
4102 ** P1 can be either an ordinary table or a virtual table. There used to 4377 ** P1 can be either an ordinary table or a virtual table. There used to
4103 ** be a separate OP_VRowid opcode for use with virtual tables, but this 4378 ** be a separate OP_VRowid opcode for use with virtual tables, but this
4104 ** one opcode now works for both table types. 4379 ** one opcode now works for both table types.
4105 */ 4380 */
4106 case OP_Rowid: { /* out2-prerelease */ 4381 case OP_Rowid: { /* out2-prerelease */
4107 VdbeCursor *pC; 4382 VdbeCursor *pC;
4108 i64 v; 4383 i64 v;
4109 sqlite3_vtab *pVtab; 4384 sqlite3_vtab *pVtab;
4110 const sqlite3_module *pModule; 4385 const sqlite3_module *pModule;
4111 4386
4112 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4387 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4113 pC = p->apCsr[pOp->p1]; 4388 pC = p->apCsr[pOp->p1];
4114 assert( pC!=0 ); 4389 assert( pC!=0 );
4115 assert( pC->pseudoTableReg==0 ); 4390 assert( pC->pseudoTableReg==0 || pC->nullRow );
4116 if( pC->nullRow ){ 4391 if( pC->nullRow ){
4117 pOut->flags = MEM_Null; 4392 pOut->flags = MEM_Null;
4118 break; 4393 break;
4119 }else if( pC->deferredMoveto ){ 4394 }else if( pC->deferredMoveto ){
4120 v = pC->movetoTarget; 4395 v = pC->movetoTarget;
4121 #ifndef SQLITE_OMIT_VIRTUALTABLE 4396 #ifndef SQLITE_OMIT_VIRTUALTABLE
4122 }else if( pC->pVtabCursor ){ 4397 }else if( pC->pVtabCursor ){
4123 pVtab = pC->pVtabCursor->pVtab; 4398 pVtab = pC->pVtabCursor->pVtab;
4124 pModule = pVtab->pModule; 4399 pModule = pVtab->pModule;
4125 assert( pModule->xRowid ); 4400 assert( pModule->xRowid );
4126 rc = pModule->xRowid(pC->pVtabCursor, &v); 4401 rc = pModule->xRowid(pC->pVtabCursor, &v);
4127 importVtabErrMsg(p, pVtab); 4402 sqlite3VtabImportErrmsg(p, pVtab);
4128 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 4403 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4129 }else{ 4404 }else{
4130 assert( pC->pCursor!=0 ); 4405 assert( pC->pCursor!=0 );
4131 rc = sqlite3VdbeCursorMoveto(pC); 4406 rc = sqlite3VdbeCursorRestore(pC);
4132 if( rc ) goto abort_due_to_error; 4407 if( rc ) goto abort_due_to_error;
4133 if( pC->rowidIsValid ){ 4408 if( pC->nullRow ){
4134 v = pC->lastRowid; 4409 pOut->flags = MEM_Null;
4135 }else{ 4410 break;
4136 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
4137 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
4138 } 4411 }
4412 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
4413 assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
4139 } 4414 }
4140 pOut->u.i = v; 4415 pOut->u.i = v;
4141 break; 4416 break;
4142 } 4417 }
4143 4418
4144 /* Opcode: NullRow P1 * * * * 4419 /* Opcode: NullRow P1 * * * *
4145 ** 4420 **
4146 ** Move the cursor P1 to a null row. Any OP_Column operations 4421 ** Move the cursor P1 to a null row. Any OP_Column operations
4147 ** that occur while the cursor is on the null row will always 4422 ** that occur while the cursor is on the null row will always
4148 ** write a NULL. 4423 ** write a NULL.
4149 */ 4424 */
4150 case OP_NullRow: { 4425 case OP_NullRow: {
4151 VdbeCursor *pC; 4426 VdbeCursor *pC;
4152 4427
4153 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4428 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4154 pC = p->apCsr[pOp->p1]; 4429 pC = p->apCsr[pOp->p1];
4155 assert( pC!=0 ); 4430 assert( pC!=0 );
4156 pC->nullRow = 1; 4431 pC->nullRow = 1;
4157 pC->rowidIsValid = 0; 4432 pC->cacheStatus = CACHE_STALE;
4158 if( pC->pCursor ){ 4433 if( pC->pCursor ){
4159 sqlite3BtreeClearCursor(pC->pCursor); 4434 sqlite3BtreeClearCursor(pC->pCursor);
4160 } 4435 }
4161 break; 4436 break;
4162 } 4437 }
4163 4438
4164 /* Opcode: Last P1 P2 * * * 4439 /* Opcode: Last P1 P2 * * *
4165 ** 4440 **
4166 ** The next use of the Rowid or Column or Next instruction for P1 4441 ** The next use of the Rowid or Column or Prev instruction for P1
4167 ** will refer to the last entry in the database table or index. 4442 ** will refer to the last entry in the database table or index.
4168 ** If the table or index is empty and P2>0, then jump immediately to P2. 4443 ** If the table or index is empty and P2>0, then jump immediately to P2.
4169 ** If P2 is 0 or if the table or index is not empty, fall through 4444 ** If P2 is 0 or if the table or index is not empty, fall through
4170 ** to the following instruction. 4445 ** to the following instruction.
4446 **
4447 ** This opcode leaves the cursor configured to move in reverse order,
4448 ** from the end toward the beginning. In other words, the cursor is
4449 ** configured to use Prev, not Next.
4171 */ 4450 */
4172 case OP_Last: { /* jump */ 4451 case OP_Last: { /* jump */
4173 VdbeCursor *pC; 4452 VdbeCursor *pC;
4174 BtCursor *pCrsr; 4453 BtCursor *pCrsr;
4175 int res; 4454 int res;
4176 4455
4177 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4456 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4178 pC = p->apCsr[pOp->p1]; 4457 pC = p->apCsr[pOp->p1];
4179 assert( pC!=0 ); 4458 assert( pC!=0 );
4180 pCrsr = pC->pCursor; 4459 pCrsr = pC->pCursor;
4181 if( pCrsr==0 ){ 4460 res = 0;
4182 res = 1; 4461 assert( pCrsr!=0 );
4183 }else{ 4462 rc = sqlite3BtreeLast(pCrsr, &res);
4184 rc = sqlite3BtreeLast(pCrsr, &res);
4185 }
4186 pC->nullRow = (u8)res; 4463 pC->nullRow = (u8)res;
4187 pC->deferredMoveto = 0; 4464 pC->deferredMoveto = 0;
4188 pC->rowidIsValid = 0;
4189 pC->cacheStatus = CACHE_STALE; 4465 pC->cacheStatus = CACHE_STALE;
4190 if( pOp->p2>0 && res ){ 4466 #ifdef SQLITE_DEBUG
4191 pc = pOp->p2 - 1; 4467 pC->seekOp = OP_Last;
4468 #endif
4469 if( pOp->p2>0 ){
4470 VdbeBranchTaken(res!=0,2);
4471 if( res ) pc = pOp->p2 - 1;
4192 } 4472 }
4193 break; 4473 break;
4194 } 4474 }
4195 4475
4196 4476
4197 /* Opcode: Sort P1 P2 * * * 4477 /* Opcode: Sort P1 P2 * * *
4198 ** 4478 **
4199 ** This opcode does exactly the same thing as OP_Rewind except that 4479 ** This opcode does exactly the same thing as OP_Rewind except that
4200 ** it increments an undocumented global variable used for testing. 4480 ** it increments an undocumented global variable used for testing.
4201 ** 4481 **
4202 ** Sorting is accomplished by writing records into a sorting index, 4482 ** Sorting is accomplished by writing records into a sorting index,
4203 ** then rewinding that index and playing it back from beginning to 4483 ** then rewinding that index and playing it back from beginning to
4204 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the 4484 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
4205 ** rewinding so that the global variable will be incremented and 4485 ** rewinding so that the global variable will be incremented and
4206 ** regression tests can determine whether or not the optimizer is 4486 ** regression tests can determine whether or not the optimizer is
4207 ** correctly optimizing out sorts. 4487 ** correctly optimizing out sorts.
4208 */ 4488 */
4489 case OP_SorterSort: /* jump */
4209 case OP_Sort: { /* jump */ 4490 case OP_Sort: { /* jump */
4210 #ifdef SQLITE_TEST 4491 #ifdef SQLITE_TEST
4211 sqlite3_sort_count++; 4492 sqlite3_sort_count++;
4212 sqlite3_search_count--; 4493 sqlite3_search_count--;
4213 #endif 4494 #endif
4214 p->aCounter[SQLITE_STMTSTATUS_SORT-1]++; 4495 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
4215 /* Fall through into OP_Rewind */ 4496 /* Fall through into OP_Rewind */
4216 } 4497 }
4217 /* Opcode: Rewind P1 P2 * * * 4498 /* Opcode: Rewind P1 P2 * * *
4218 ** 4499 **
4219 ** The next use of the Rowid or Column or Next instruction for P1 4500 ** The next use of the Rowid or Column or Next instruction for P1
4220 ** will refer to the first entry in the database table or index. 4501 ** will refer to the first entry in the database table or index.
4221 ** If the table or index is empty and P2>0, then jump immediately to P2. 4502 ** If the table or index is empty and P2>0, then jump immediately to P2.
4222 ** If P2 is 0 or if the table or index is not empty, fall through 4503 ** If P2 is 0 or if the table or index is not empty, fall through
4223 ** to the following instruction. 4504 ** to the following instruction.
4505 **
4506 ** This opcode leaves the cursor configured to move in forward order,
4507 ** from the beginning toward the end. In other words, the cursor is
4508 ** configured to use Next, not Prev.
4224 */ 4509 */
4225 case OP_Rewind: { /* jump */ 4510 case OP_Rewind: { /* jump */
4226 VdbeCursor *pC; 4511 VdbeCursor *pC;
4227 BtCursor *pCrsr; 4512 BtCursor *pCrsr;
4228 int res; 4513 int res;
4229 4514
4230 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4515 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4231 pC = p->apCsr[pOp->p1]; 4516 pC = p->apCsr[pOp->p1];
4232 assert( pC!=0 ); 4517 assert( pC!=0 );
4518 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
4233 res = 1; 4519 res = 1;
4234 if( (pCrsr = pC->pCursor)!=0 ){ 4520 #ifdef SQLITE_DEBUG
4521 pC->seekOp = OP_Rewind;
4522 #endif
4523 if( isSorter(pC) ){
4524 rc = sqlite3VdbeSorterRewind(pC, &res);
4525 }else{
4526 pCrsr = pC->pCursor;
4527 assert( pCrsr );
4235 rc = sqlite3BtreeFirst(pCrsr, &res); 4528 rc = sqlite3BtreeFirst(pCrsr, &res);
4236 pC->atFirst = res==0 ?1:0;
4237 pC->deferredMoveto = 0; 4529 pC->deferredMoveto = 0;
4238 pC->cacheStatus = CACHE_STALE; 4530 pC->cacheStatus = CACHE_STALE;
4239 pC->rowidIsValid = 0;
4240 } 4531 }
4241 pC->nullRow = (u8)res; 4532 pC->nullRow = (u8)res;
4242 assert( pOp->p2>0 && pOp->p2<p->nOp ); 4533 assert( pOp->p2>0 && pOp->p2<p->nOp );
4534 VdbeBranchTaken(res!=0,2);
4243 if( res ){ 4535 if( res ){
4244 pc = pOp->p2 - 1; 4536 pc = pOp->p2 - 1;
4245 } 4537 }
4246 break; 4538 break;
4247 } 4539 }
4248 4540
4249 /* Opcode: Next P1 P2 * * P5 4541 /* Opcode: Next P1 P2 P3 P4 P5
4250 ** 4542 **
4251 ** Advance cursor P1 so that it points to the next key/data pair in its 4543 ** Advance cursor P1 so that it points to the next key/data pair in its
4252 ** table or index. If there are no more key/value pairs then fall through 4544 ** table or index. If there are no more key/value pairs then fall through
4253 ** to the following instruction. But if the cursor advance was successful, 4545 ** to the following instruction. But if the cursor advance was successful,
4254 ** jump immediately to P2. 4546 ** jump immediately to P2.
4255 ** 4547 **
4256 ** The P1 cursor must be for a real table, not a pseudo-table. 4548 ** The Next opcode is only valid following an SeekGT, SeekGE, or
4549 ** OP_Rewind opcode used to position the cursor. Next is not allowed
4550 ** to follow SeekLT, SeekLE, or OP_Last.
4551 **
4552 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
4553 ** been opened prior to this opcode or the program will segfault.
4554 **
4555 ** The P3 value is a hint to the btree implementation. If P3==1, that
4556 ** means P1 is an SQL index and that this instruction could have been
4557 ** omitted if that index had been unique. P3 is usually 0. P3 is
4558 ** always either 0 or 1.
4559 **
4560 ** P4 is always of type P4_ADVANCE. The function pointer points to
4561 ** sqlite3BtreeNext().
4257 ** 4562 **
4258 ** If P5 is positive and the jump is taken, then event counter 4563 ** If P5 is positive and the jump is taken, then event counter
4259 ** number P5-1 in the prepared statement is incremented. 4564 ** number P5-1 in the prepared statement is incremented.
4260 ** 4565 **
4261 ** See also: Prev 4566 ** See also: Prev, NextIfOpen
4262 */ 4567 */
4263 /* Opcode: Prev P1 P2 * * P5 4568 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
4569 **
4570 ** This opcode works just like Next except that if cursor P1 is not
4571 ** open it behaves a no-op.
4572 */
4573 /* Opcode: Prev P1 P2 P3 P4 P5
4264 ** 4574 **
4265 ** Back up cursor P1 so that it points to the previous key/data pair in its 4575 ** Back up cursor P1 so that it points to the previous key/data pair in its
4266 ** table or index. If there is no previous key/value pairs then fall through 4576 ** table or index. If there is no previous key/value pairs then fall through
4267 ** to the following instruction. But if the cursor backup was successful, 4577 ** to the following instruction. But if the cursor backup was successful,
4268 ** jump immediately to P2. 4578 ** jump immediately to P2.
4269 ** 4579 **
4270 ** The P1 cursor must be for a real table, not a pseudo-table. 4580 **
4581 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
4582 ** OP_Last opcode used to position the cursor. Prev is not allowed
4583 ** to follow SeekGT, SeekGE, or OP_Rewind.
4584 **
4585 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
4586 ** not open then the behavior is undefined.
4587 **
4588 ** The P3 value is a hint to the btree implementation. If P3==1, that
4589 ** means P1 is an SQL index and that this instruction could have been
4590 ** omitted if that index had been unique. P3 is usually 0. P3 is
4591 ** always either 0 or 1.
4592 **
4593 ** P4 is always of type P4_ADVANCE. The function pointer points to
4594 ** sqlite3BtreePrevious().
4271 ** 4595 **
4272 ** If P5 is positive and the jump is taken, then event counter 4596 ** If P5 is positive and the jump is taken, then event counter
4273 ** number P5-1 in the prepared statement is incremented. 4597 ** number P5-1 in the prepared statement is incremented.
4274 */ 4598 */
4275 case OP_Prev: /* jump */ 4599 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
4276 case OP_Next: { /* jump */ 4600 **
4601 ** This opcode works just like Prev except that if cursor P1 is not
4602 ** open it behaves a no-op.
4603 */
4604 case OP_SorterNext: { /* jump */
4277 VdbeCursor *pC; 4605 VdbeCursor *pC;
4278 BtCursor *pCrsr;
4279 int res; 4606 int res;
4280 4607
4281 CHECK_FOR_INTERRUPT; 4608 pC = p->apCsr[pOp->p1];
4609 assert( isSorter(pC) );
4610 res = 0;
4611 rc = sqlite3VdbeSorterNext(db, pC, &res);
4612 goto next_tail;
4613 case OP_PrevIfOpen: /* jump */
4614 case OP_NextIfOpen: /* jump */
4615 if( p->apCsr[pOp->p1]==0 ) break;
4616 /* Fall through */
4617 case OP_Prev: /* jump */
4618 case OP_Next: /* jump */
4282 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4619 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4283 assert( pOp->p5<=ArraySize(p->aCounter) ); 4620 assert( pOp->p5<ArraySize(p->aCounter) );
4284 pC = p->apCsr[pOp->p1]; 4621 pC = p->apCsr[pOp->p1];
4285 if( pC==0 ){ 4622 res = pOp->p3;
4286 break; /* See ticket #2273 */ 4623 assert( pC!=0 );
4287 }
4288 pCrsr = pC->pCursor;
4289 if( pCrsr==0 ){
4290 pC->nullRow = 1;
4291 break;
4292 }
4293 res = 1;
4294 assert( pC->deferredMoveto==0 ); 4624 assert( pC->deferredMoveto==0 );
4295 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) : 4625 assert( pC->pCursor );
4296 sqlite3BtreePrevious(pCrsr, &res); 4626 assert( res==0 || (res==1 && pC->isTable==0) );
4297 pC->nullRow = (u8)res; 4627 testcase( res==1 );
4628 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
4629 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
4630 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
4631 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
4632
4633 /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
4634 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
4635 assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
4636 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
4637 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
4638 assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
4639 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
4640 || pC->seekOp==OP_Last );
4641
4642 rc = pOp->p4.xAdvance(pC->pCursor, &res);
4643 next_tail:
4298 pC->cacheStatus = CACHE_STALE; 4644 pC->cacheStatus = CACHE_STALE;
4645 VdbeBranchTaken(res==0,2);
4299 if( res==0 ){ 4646 if( res==0 ){
4647 pC->nullRow = 0;
4300 pc = pOp->p2 - 1; 4648 pc = pOp->p2 - 1;
4301 if( pOp->p5 ) p->aCounter[pOp->p5-1]++; 4649 p->aCounter[pOp->p5]++;
4302 #ifdef SQLITE_TEST 4650 #ifdef SQLITE_TEST
4303 sqlite3_search_count++; 4651 sqlite3_search_count++;
4304 #endif 4652 #endif
4653 }else{
4654 pC->nullRow = 1;
4305 } 4655 }
4306 pC->rowidIsValid = 0; 4656 goto check_for_interrupt;
4307 break;
4308 } 4657 }
4309 4658
4310 /* Opcode: IdxInsert P1 P2 P3 * P5 4659 /* Opcode: IdxInsert P1 P2 P3 * P5
4660 ** Synopsis: key=r[P2]
4311 ** 4661 **
4312 ** Register P2 holds a SQL index key made using the 4662 ** Register P2 holds an SQL index key made using the
4313 ** MakeRecord instructions. This opcode writes that key 4663 ** MakeRecord instructions. This opcode writes that key
4314 ** into the index P1. Data for the entry is nil. 4664 ** into the index P1. Data for the entry is nil.
4315 ** 4665 **
4316 ** P3 is a flag that provides a hint to the b-tree layer that this 4666 ** P3 is a flag that provides a hint to the b-tree layer that this
4317 ** insert is likely to be an append. 4667 ** insert is likely to be an append.
4318 ** 4668 **
4669 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
4670 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
4671 ** then the change counter is unchanged.
4672 **
4673 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
4674 ** just done a seek to the spot where the new entry is to be inserted.
4675 ** This flag avoids doing an extra seek.
4676 **
4319 ** This instruction only works for indices. The equivalent instruction 4677 ** This instruction only works for indices. The equivalent instruction
4320 ** for tables is OP_Insert. 4678 ** for tables is OP_Insert.
4321 */ 4679 */
4680 case OP_SorterInsert: /* in2 */
4322 case OP_IdxInsert: { /* in2 */ 4681 case OP_IdxInsert: { /* in2 */
4323 VdbeCursor *pC; 4682 VdbeCursor *pC;
4324 BtCursor *pCrsr; 4683 BtCursor *pCrsr;
4325 int nKey; 4684 int nKey;
4326 const char *zKey; 4685 const char *zKey;
4327 4686
4328 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4687 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4329 pC = p->apCsr[pOp->p1]; 4688 pC = p->apCsr[pOp->p1];
4330 assert( pC!=0 ); 4689 assert( pC!=0 );
4690 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
4331 pIn2 = &aMem[pOp->p2]; 4691 pIn2 = &aMem[pOp->p2];
4332 assert( pIn2->flags & MEM_Blob ); 4692 assert( pIn2->flags & MEM_Blob );
4333 pCrsr = pC->pCursor; 4693 pCrsr = pC->pCursor;
4334 if( ALWAYS(pCrsr!=0) ){ 4694 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
4335 assert( pC->isTable==0 ); 4695 assert( pCrsr!=0 );
4336 rc = ExpandBlob(pIn2); 4696 assert( pC->isTable==0 );
4337 if( rc==SQLITE_OK ){ 4697 rc = ExpandBlob(pIn2);
4698 if( rc==SQLITE_OK ){
4699 if( isSorter(pC) ){
4700 rc = sqlite3VdbeSorterWrite(pC, pIn2);
4701 }else{
4338 nKey = pIn2->n; 4702 nKey = pIn2->n;
4339 zKey = pIn2->z; 4703 zKey = pIn2->z;
4340 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, 4704 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
4341 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) 4705 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
4342 ); 4706 );
4343 assert( pC->deferredMoveto==0 ); 4707 assert( pC->deferredMoveto==0 );
4344 pC->cacheStatus = CACHE_STALE; 4708 pC->cacheStatus = CACHE_STALE;
4345 } 4709 }
4346 } 4710 }
4347 break; 4711 break;
4348 } 4712 }
4349 4713
4350 /* Opcode: IdxDelete P1 P2 P3 * * 4714 /* Opcode: IdxDelete P1 P2 P3 * *
4715 ** Synopsis: key=r[P2@P3]
4351 ** 4716 **
4352 ** The content of P3 registers starting at register P2 form 4717 ** The content of P3 registers starting at register P2 form
4353 ** an unpacked index key. This opcode removes that entry from the 4718 ** an unpacked index key. This opcode removes that entry from the
4354 ** index opened by cursor P1. 4719 ** index opened by cursor P1.
4355 */ 4720 */
4356 case OP_IdxDelete: { 4721 case OP_IdxDelete: {
4357 VdbeCursor *pC; 4722 VdbeCursor *pC;
4358 BtCursor *pCrsr; 4723 BtCursor *pCrsr;
4359 int res; 4724 int res;
4360 UnpackedRecord r; 4725 UnpackedRecord r;
4361 4726
4362 assert( pOp->p3>0 ); 4727 assert( pOp->p3>0 );
4363 assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 ); 4728 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
4364 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4729 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4365 pC = p->apCsr[pOp->p1]; 4730 pC = p->apCsr[pOp->p1];
4366 assert( pC!=0 ); 4731 assert( pC!=0 );
4367 pCrsr = pC->pCursor; 4732 pCrsr = pC->pCursor;
4368 if( ALWAYS(pCrsr!=0) ){ 4733 assert( pCrsr!=0 );
4369 r.pKeyInfo = pC->pKeyInfo; 4734 assert( pOp->p5==0 );
4370 r.nField = (u16)pOp->p3; 4735 r.pKeyInfo = pC->pKeyInfo;
4371 r.flags = 0; 4736 r.nField = (u16)pOp->p3;
4372 r.aMem = &aMem[pOp->p2]; 4737 r.default_rc = 0;
4738 r.aMem = &aMem[pOp->p2];
4373 #ifdef SQLITE_DEBUG 4739 #ifdef SQLITE_DEBUG
4374 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } 4740 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4375 #endif 4741 #endif
4376 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); 4742 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
4377 if( rc==SQLITE_OK && res==0 ){ 4743 if( rc==SQLITE_OK && res==0 ){
4378 rc = sqlite3BtreeDelete(pCrsr); 4744 rc = sqlite3BtreeDelete(pCrsr);
4379 }
4380 assert( pC->deferredMoveto==0 );
4381 pC->cacheStatus = CACHE_STALE;
4382 } 4745 }
4746 assert( pC->deferredMoveto==0 );
4747 pC->cacheStatus = CACHE_STALE;
4383 break; 4748 break;
4384 } 4749 }
4385 4750
4386 /* Opcode: IdxRowid P1 P2 * * * 4751 /* Opcode: IdxRowid P1 P2 * * *
4752 ** Synopsis: r[P2]=rowid
4387 ** 4753 **
4388 ** Write into register P2 an integer which is the last entry in the record at 4754 ** Write into register P2 an integer which is the last entry in the record at
4389 ** the end of the index key pointed to by cursor P1. This integer should be 4755 ** the end of the index key pointed to by cursor P1. This integer should be
4390 ** the rowid of the table entry to which this index entry points. 4756 ** the rowid of the table entry to which this index entry points.
4391 ** 4757 **
4392 ** See also: Rowid, MakeRecord. 4758 ** See also: Rowid, MakeRecord.
4393 */ 4759 */
4394 case OP_IdxRowid: { /* out2-prerelease */ 4760 case OP_IdxRowid: { /* out2-prerelease */
4395 BtCursor *pCrsr; 4761 BtCursor *pCrsr;
4396 VdbeCursor *pC; 4762 VdbeCursor *pC;
4397 i64 rowid; 4763 i64 rowid;
4398 4764
4399 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4765 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4400 pC = p->apCsr[pOp->p1]; 4766 pC = p->apCsr[pOp->p1];
4401 assert( pC!=0 ); 4767 assert( pC!=0 );
4402 pCrsr = pC->pCursor; 4768 pCrsr = pC->pCursor;
4769 assert( pCrsr!=0 );
4403 pOut->flags = MEM_Null; 4770 pOut->flags = MEM_Null;
4404 if( ALWAYS(pCrsr!=0) ){ 4771 assert( pC->isTable==0 );
4405 rc = sqlite3VdbeCursorMoveto(pC); 4772 assert( pC->deferredMoveto==0 );
4406 if( NEVER(rc) ) goto abort_due_to_error; 4773
4407 assert( pC->deferredMoveto==0 ); 4774 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
4408 assert( pC->isTable==0 ); 4775 ** out from under the cursor. That will never happend for an IdxRowid
4409 if( !pC->nullRow ){ 4776 ** opcode, hence the NEVER() arround the check of the return value.
4410 rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid); 4777 */
4411 if( rc!=SQLITE_OK ){ 4778 rc = sqlite3VdbeCursorRestore(pC);
4412 goto abort_due_to_error; 4779 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
4413 } 4780
4414 pOut->u.i = rowid; 4781 if( !pC->nullRow ){
4415 pOut->flags = MEM_Int; 4782 rowid = 0; /* Not needed. Only used to silence a warning. */
4783 rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
4784 if( rc!=SQLITE_OK ){
4785 goto abort_due_to_error;
4416 } 4786 }
4787 pOut->u.i = rowid;
4788 pOut->flags = MEM_Int;
4417 } 4789 }
4418 break; 4790 break;
4419 } 4791 }
4420 4792
4421 /* Opcode: IdxGE P1 P2 P3 P4 P5 4793 /* Opcode: IdxGE P1 P2 P3 P4 P5
4794 ** Synopsis: key=r[P3@P4]
4422 ** 4795 **
4423 ** The P4 register values beginning with P3 form an unpacked index 4796 ** The P4 register values beginning with P3 form an unpacked index
4424 ** key that omits the ROWID. Compare this key value against the index 4797 ** key that omits the PRIMARY KEY. Compare this key value against the index
4425 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index. 4798 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
4799 ** fields at the end.
4426 ** 4800 **
4427 ** If the P1 index entry is greater than or equal to the key value 4801 ** If the P1 index entry is greater than or equal to the key value
4428 ** then jump to P2. Otherwise fall through to the next instruction. 4802 ** then jump to P2. Otherwise fall through to the next instruction.
4803 */
4804 /* Opcode: IdxGT P1 P2 P3 P4 P5
4805 ** Synopsis: key=r[P3@P4]
4429 ** 4806 **
4430 ** If P5 is non-zero then the key value is increased by an epsilon 4807 ** The P4 register values beginning with P3 form an unpacked index
4431 ** prior to the comparison. This make the opcode work like IdxGT except 4808 ** key that omits the PRIMARY KEY. Compare this key value against the index
4432 ** that if the key from register P3 is a prefix of the key in the cursor, 4809 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
4433 ** the result is false whereas it would be true with IdxGT. 4810 ** fields at the end.
4811 **
4812 ** If the P1 index entry is greater than the key value
4813 ** then jump to P2. Otherwise fall through to the next instruction.
4434 */ 4814 */
4435 /* Opcode: IdxLT P1 P2 P3 P4 P5 4815 /* Opcode: IdxLT P1 P2 P3 P4 P5
4816 ** Synopsis: key=r[P3@P4]
4436 ** 4817 **
4437 ** The P4 register values beginning with P3 form an unpacked index 4818 ** The P4 register values beginning with P3 form an unpacked index
4438 ** key that omits the ROWID. Compare this key value against the index 4819 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
4439 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index. 4820 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
4821 ** ROWID on the P1 index.
4440 ** 4822 **
4441 ** If the P1 index entry is less than the key value then jump to P2. 4823 ** If the P1 index entry is less than the key value then jump to P2.
4442 ** Otherwise fall through to the next instruction. 4824 ** Otherwise fall through to the next instruction.
4825 */
4826 /* Opcode: IdxLE P1 P2 P3 P4 P5
4827 ** Synopsis: key=r[P3@P4]
4443 ** 4828 **
4444 ** If P5 is non-zero then the key value is increased by an epsilon prior 4829 ** The P4 register values beginning with P3 form an unpacked index
4445 ** to the comparison. This makes the opcode work like IdxLE. 4830 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
4831 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
4832 ** ROWID on the P1 index.
4833 **
4834 ** If the P1 index entry is less than or equal to the key value then jump
4835 ** to P2. Otherwise fall through to the next instruction.
4446 */ 4836 */
4837 case OP_IdxLE: /* jump */
4838 case OP_IdxGT: /* jump */
4447 case OP_IdxLT: /* jump */ 4839 case OP_IdxLT: /* jump */
4448 case OP_IdxGE: { /* jump */ 4840 case OP_IdxGE: { /* jump */
4449 VdbeCursor *pC; 4841 VdbeCursor *pC;
4450 int res; 4842 int res;
4451 UnpackedRecord r; 4843 UnpackedRecord r;
4452 4844
4453 assert( pOp->p1>=0 && pOp->p1<p->nCursor ); 4845 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4454 pC = p->apCsr[pOp->p1]; 4846 pC = p->apCsr[pOp->p1];
4455 assert( pC!=0 ); 4847 assert( pC!=0 );
4456 assert( pC->isOrdered ); 4848 assert( pC->isOrdered );
4457 if( ALWAYS(pC->pCursor!=0) ){ 4849 assert( pC->pCursor!=0);
4458 assert( pC->deferredMoveto==0 ); 4850 assert( pC->deferredMoveto==0 );
4459 assert( pOp->p5==0 || pOp->p5==1 ); 4851 assert( pOp->p5==0 || pOp->p5==1 );
4460 assert( pOp->p4type==P4_INT32 ); 4852 assert( pOp->p4type==P4_INT32 );
4461 r.pKeyInfo = pC->pKeyInfo; 4853 r.pKeyInfo = pC->pKeyInfo;
4462 r.nField = (u16)pOp->p4.i; 4854 r.nField = (u16)pOp->p4.i;
4463 if( pOp->p5 ){ 4855 if( pOp->opcode<OP_IdxLT ){
4464 r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID; 4856 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
4465 }else{ 4857 r.default_rc = -1;
4466 r.flags = UNPACKED_IGNORE_ROWID; 4858 }else{
4467 } 4859 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
4468 r.aMem = &aMem[pOp->p3]; 4860 r.default_rc = 0;
4861 }
4862 r.aMem = &aMem[pOp->p3];
4469 #ifdef SQLITE_DEBUG 4863 #ifdef SQLITE_DEBUG
4470 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } 4864 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4471 #endif 4865 #endif
4472 rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res); 4866 res = 0; /* Not needed. Only used to silence a warning. */
4473 if( pOp->opcode==OP_IdxLT ){ 4867 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4474 res = -res; 4868 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
4475 }else{ 4869 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
4476 assert( pOp->opcode==OP_IdxGE ); 4870 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
4477 res++; 4871 res = -res;
4478 } 4872 }else{
4479 if( res>0 ){ 4873 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
4480 pc = pOp->p2 - 1 ; 4874 res++;
4481 } 4875 }
4876 VdbeBranchTaken(res>0,2);
4877 if( res>0 ){
4878 pc = pOp->p2 - 1 ;
4482 } 4879 }
4483 break; 4880 break;
4484 } 4881 }
4485 4882
4486 /* Opcode: Destroy P1 P2 P3 * * 4883 /* Opcode: Destroy P1 P2 P3 * *
4487 ** 4884 **
4488 ** Delete an entire database table or index whose root page in the database 4885 ** Delete an entire database table or index whose root page in the database
4489 ** file is given by P1. 4886 ** file is given by P1.
4490 ** 4887 **
4491 ** The table being destroyed is in the main database file if P3==0. If 4888 ** The table being destroyed is in the main database file if P3==0. If
4492 ** P3==1 then the table to be clear is in the auxiliary database file 4889 ** P3==1 then the table to be clear is in the auxiliary database file
4493 ** that is used to store tables create using CREATE TEMPORARY TABLE. 4890 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4494 ** 4891 **
4495 ** If AUTOVACUUM is enabled then it is possible that another root page 4892 ** If AUTOVACUUM is enabled then it is possible that another root page
4496 ** might be moved into the newly deleted root page in order to keep all 4893 ** might be moved into the newly deleted root page in order to keep all
4497 ** root pages contiguous at the beginning of the database. The former 4894 ** root pages contiguous at the beginning of the database. The former
4498 ** value of the root page that moved - its value before the move occurred - 4895 ** value of the root page that moved - its value before the move occurred -
4499 ** is stored in register P2. If no page 4896 ** is stored in register P2. If no page
4500 ** movement was required (because the table being dropped was already 4897 ** movement was required (because the table being dropped was already
4501 ** the last one in the database) then a zero is stored in register P2. 4898 ** the last one in the database) then a zero is stored in register P2.
4502 ** If AUTOVACUUM is disabled then a zero is stored in register P2. 4899 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
4503 ** 4900 **
4504 ** See also: Clear 4901 ** See also: Clear
4505 */ 4902 */
4506 case OP_Destroy: { /* out2-prerelease */ 4903 case OP_Destroy: { /* out2-prerelease */
4507 int iMoved; 4904 int iMoved;
4508 int iCnt; 4905 int iCnt;
4509 Vdbe *pVdbe; 4906 Vdbe *pVdbe;
4510 int iDb; 4907 int iDb;
4908
4909 assert( p->readOnly==0 );
4511 #ifndef SQLITE_OMIT_VIRTUALTABLE 4910 #ifndef SQLITE_OMIT_VIRTUALTABLE
4512 iCnt = 0; 4911 iCnt = 0;
4513 for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){ 4912 for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
4514 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){ 4913 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
4914 && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
4915 ){
4515 iCnt++; 4916 iCnt++;
4516 } 4917 }
4517 } 4918 }
4518 #else 4919 #else
4519 iCnt = db->activeVdbeCnt; 4920 iCnt = db->nVdbeRead;
4520 #endif 4921 #endif
4521 pOut->flags = MEM_Null; 4922 pOut->flags = MEM_Null;
4522 if( iCnt>1 ){ 4923 if( iCnt>1 ){
4523 rc = SQLITE_LOCKED; 4924 rc = SQLITE_LOCKED;
4524 p->errorAction = OE_Abort; 4925 p->errorAction = OE_Abort;
4525 }else{ 4926 }else{
4526 iDb = pOp->p3; 4927 iDb = pOp->p3;
4527 assert( iCnt==1 ); 4928 assert( iCnt==1 );
4528 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 ); 4929 assert( DbMaskTest(p->btreeMask, iDb) );
4930 iMoved = 0; /* Not needed. Only to silence a warning. */
4529 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); 4931 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
4530 pOut->flags = MEM_Int; 4932 pOut->flags = MEM_Int;
4531 pOut->u.i = iMoved; 4933 pOut->u.i = iMoved;
4532 #ifndef SQLITE_OMIT_AUTOVACUUM 4934 #ifndef SQLITE_OMIT_AUTOVACUUM
4533 if( rc==SQLITE_OK && iMoved!=0 ){ 4935 if( rc==SQLITE_OK && iMoved!=0 ){
4534 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); 4936 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
4535 /* All OP_Destroy operations occur on the same btree */ 4937 /* All OP_Destroy operations occur on the same btree */
4536 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); 4938 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
4537 resetSchemaOnFault = iDb+1; 4939 resetSchemaOnFault = iDb+1;
4538 } 4940 }
(...skipping 17 matching lines...) Expand all
4556 ** count is incremented by the number of rows in the table being cleared. 4958 ** count is incremented by the number of rows in the table being cleared.
4557 ** If P3 is greater than zero, then the value stored in register P3 is 4959 ** If P3 is greater than zero, then the value stored in register P3 is
4558 ** also incremented by the number of rows in the table being cleared. 4960 ** also incremented by the number of rows in the table being cleared.
4559 ** 4961 **
4560 ** See also: Destroy 4962 ** See also: Destroy
4561 */ 4963 */
4562 case OP_Clear: { 4964 case OP_Clear: {
4563 int nChange; 4965 int nChange;
4564 4966
4565 nChange = 0; 4967 nChange = 0;
4566 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 ); 4968 assert( p->readOnly==0 );
4969 assert( DbMaskTest(p->btreeMask, pOp->p2) );
4567 rc = sqlite3BtreeClearTable( 4970 rc = sqlite3BtreeClearTable(
4568 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) 4971 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
4569 ); 4972 );
4570 if( pOp->p3 ){ 4973 if( pOp->p3 ){
4571 p->nChange += nChange; 4974 p->nChange += nChange;
4572 if( pOp->p3>0 ){ 4975 if( pOp->p3>0 ){
4573 assert( memIsValid(&aMem[pOp->p3]) ); 4976 assert( memIsValid(&aMem[pOp->p3]) );
4574 memAboutToChange(p, &aMem[pOp->p3]); 4977 memAboutToChange(p, &aMem[pOp->p3]);
4575 aMem[pOp->p3].u.i += nChange; 4978 aMem[pOp->p3].u.i += nChange;
4576 } 4979 }
4577 } 4980 }
4578 break; 4981 break;
4579 } 4982 }
4580 4983
4984 /* Opcode: ResetSorter P1 * * * *
4985 **
4986 ** Delete all contents from the ephemeral table or sorter
4987 ** that is open on cursor P1.
4988 **
4989 ** This opcode only works for cursors used for sorting and
4990 ** opened with OP_OpenEphemeral or OP_SorterOpen.
4991 */
4992 case OP_ResetSorter: {
4993 VdbeCursor *pC;
4994
4995 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4996 pC = p->apCsr[pOp->p1];
4997 assert( pC!=0 );
4998 if( pC->pSorter ){
4999 sqlite3VdbeSorterReset(db, pC->pSorter);
5000 }else{
5001 assert( pC->isEphemeral );
5002 rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
5003 }
5004 break;
5005 }
5006
4581 /* Opcode: CreateTable P1 P2 * * * 5007 /* Opcode: CreateTable P1 P2 * * *
5008 ** Synopsis: r[P2]=root iDb=P1
4582 ** 5009 **
4583 ** Allocate a new table in the main database file if P1==0 or in the 5010 ** Allocate a new table in the main database file if P1==0 or in the
4584 ** auxiliary database file if P1==1 or in an attached database if 5011 ** auxiliary database file if P1==1 or in an attached database if
4585 ** P1>1. Write the root page number of the new table into 5012 ** P1>1. Write the root page number of the new table into
4586 ** register P2 5013 ** register P2
4587 ** 5014 **
4588 ** The difference between a table and an index is this: A table must 5015 ** The difference between a table and an index is this: A table must
4589 ** have a 4-byte integer key and can have arbitrary data. An index 5016 ** have a 4-byte integer key and can have arbitrary data. An index
4590 ** has an arbitrary key but no data. 5017 ** has an arbitrary key but no data.
4591 ** 5018 **
4592 ** See also: CreateIndex 5019 ** See also: CreateIndex
4593 */ 5020 */
4594 /* Opcode: CreateIndex P1 P2 * * * 5021 /* Opcode: CreateIndex P1 P2 * * *
5022 ** Synopsis: r[P2]=root iDb=P1
4595 ** 5023 **
4596 ** Allocate a new index in the main database file if P1==0 or in the 5024 ** Allocate a new index in the main database file if P1==0 or in the
4597 ** auxiliary database file if P1==1 or in an attached database if 5025 ** auxiliary database file if P1==1 or in an attached database if
4598 ** P1>1. Write the root page number of the new table into 5026 ** P1>1. Write the root page number of the new table into
4599 ** register P2. 5027 ** register P2.
4600 ** 5028 **
4601 ** See documentation on OP_CreateTable for additional information. 5029 ** See documentation on OP_CreateTable for additional information.
4602 */ 5030 */
4603 case OP_CreateIndex: /* out2-prerelease */ 5031 case OP_CreateIndex: /* out2-prerelease */
4604 case OP_CreateTable: { /* out2-prerelease */ 5032 case OP_CreateTable: { /* out2-prerelease */
4605 int pgno; 5033 int pgno;
4606 int flags; 5034 int flags;
4607 Db *pDb; 5035 Db *pDb;
4608 5036
4609 pgno = 0; 5037 pgno = 0;
4610 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 5038 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4611 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 ); 5039 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5040 assert( p->readOnly==0 );
4612 pDb = &db->aDb[pOp->p1]; 5041 pDb = &db->aDb[pOp->p1];
4613 assert( pDb->pBt!=0 ); 5042 assert( pDb->pBt!=0 );
4614 if( pOp->opcode==OP_CreateTable ){ 5043 if( pOp->opcode==OP_CreateTable ){
4615 /* flags = BTREE_INTKEY; */ 5044 /* flags = BTREE_INTKEY; */
4616 flags = BTREE_INTKEY; 5045 flags = BTREE_INTKEY;
4617 }else{ 5046 }else{
4618 flags = BTREE_BLOBKEY; 5047 flags = BTREE_BLOBKEY;
4619 } 5048 }
4620 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); 5049 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4621 pOut->u.i = pgno; 5050 pOut->u.i = pgno;
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
4663 assert( db->init.busy==0 ); 5092 assert( db->init.busy==0 );
4664 db->init.busy = 1; 5093 db->init.busy = 1;
4665 initData.rc = SQLITE_OK; 5094 initData.rc = SQLITE_OK;
4666 assert( !db->mallocFailed ); 5095 assert( !db->mallocFailed );
4667 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); 5096 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4668 if( rc==SQLITE_OK ) rc = initData.rc; 5097 if( rc==SQLITE_OK ) rc = initData.rc;
4669 sqlite3DbFree(db, zSql); 5098 sqlite3DbFree(db, zSql);
4670 db->init.busy = 0; 5099 db->init.busy = 0;
4671 } 5100 }
4672 } 5101 }
5102 if( rc ) sqlite3ResetAllSchemasOfConnection(db);
4673 if( rc==SQLITE_NOMEM ){ 5103 if( rc==SQLITE_NOMEM ){
4674 goto no_mem; 5104 goto no_mem;
4675 } 5105 }
4676 break; 5106 break;
4677 } 5107 }
4678 5108
4679 #if !defined(SQLITE_OMIT_ANALYZE) 5109 #if !defined(SQLITE_OMIT_ANALYZE)
4680 /* Opcode: LoadAnalysis P1 * * * * 5110 /* Opcode: LoadAnalysis P1 * * * *
4681 ** 5111 **
4682 ** Read the sqlite_stat1 table for database P1 and load the content 5112 ** Read the sqlite_stat1 table for database P1 and load the content
4683 ** of that table into the internal index hash table. This will cause 5113 ** of that table into the internal index hash table. This will cause
4684 ** the analysis to be used when preparing all subsequent queries. 5114 ** the analysis to be used when preparing all subsequent queries.
4685 */ 5115 */
4686 case OP_LoadAnalysis: { 5116 case OP_LoadAnalysis: {
4687 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 5117 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4688 rc = sqlite3AnalysisLoad(db, pOp->p1); 5118 rc = sqlite3AnalysisLoad(db, pOp->p1);
4689 break; 5119 break;
4690 } 5120 }
4691 #endif /* !defined(SQLITE_OMIT_ANALYZE) */ 5121 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
4692 5122
4693 /* Opcode: DropTable P1 * * P4 * 5123 /* Opcode: DropTable P1 * * P4 *
4694 ** 5124 **
4695 ** Remove the internal (in-memory) data structures that describe 5125 ** Remove the internal (in-memory) data structures that describe
4696 ** the table named P4 in database P1. This is called after a table 5126 ** the table named P4 in database P1. This is called after a table
4697 ** is dropped in order to keep the internal representation of the 5127 ** is dropped from disk (using the Destroy opcode) in order to keep
5128 ** the internal representation of the
4698 ** schema consistent with what is on disk. 5129 ** schema consistent with what is on disk.
4699 */ 5130 */
4700 case OP_DropTable: { 5131 case OP_DropTable: {
4701 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); 5132 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
4702 break; 5133 break;
4703 } 5134 }
4704 5135
4705 /* Opcode: DropIndex P1 * * P4 * 5136 /* Opcode: DropIndex P1 * * P4 *
4706 ** 5137 **
4707 ** Remove the internal (in-memory) data structures that describe 5138 ** Remove the internal (in-memory) data structures that describe
4708 ** the index named P4 in database P1. This is called after an index 5139 ** the index named P4 in database P1. This is called after an index
4709 ** is dropped in order to keep the internal representation of the 5140 ** is dropped from disk (using the Destroy opcode)
5141 ** in order to keep the internal representation of the
4710 ** schema consistent with what is on disk. 5142 ** schema consistent with what is on disk.
4711 */ 5143 */
4712 case OP_DropIndex: { 5144 case OP_DropIndex: {
4713 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); 5145 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
4714 break; 5146 break;
4715 } 5147 }
4716 5148
4717 /* Opcode: DropTrigger P1 * * P4 * 5149 /* Opcode: DropTrigger P1 * * P4 *
4718 ** 5150 **
4719 ** Remove the internal (in-memory) data structures that describe 5151 ** Remove the internal (in-memory) data structures that describe
4720 ** the trigger named P4 in database P1. This is called after a trigger 5152 ** the trigger named P4 in database P1. This is called after a trigger
4721 ** is dropped in order to keep the internal representation of the 5153 ** is dropped from disk (using the Destroy opcode) in order to keep
5154 ** the internal representation of the
4722 ** schema consistent with what is on disk. 5155 ** schema consistent with what is on disk.
4723 */ 5156 */
4724 case OP_DropTrigger: { 5157 case OP_DropTrigger: {
4725 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); 5158 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
4726 break; 5159 break;
4727 } 5160 }
4728 5161
4729 5162
4730 #ifndef SQLITE_OMIT_INTEGRITY_CHECK 5163 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
4731 /* Opcode: IntegrityCk P1 P2 P3 * P5 5164 /* Opcode: IntegrityCk P1 P2 P3 * P5
(...skipping 16 matching lines...) Expand all
4748 ** 5181 **
4749 ** This opcode is used to implement the integrity_check pragma. 5182 ** This opcode is used to implement the integrity_check pragma.
4750 */ 5183 */
4751 case OP_IntegrityCk: { 5184 case OP_IntegrityCk: {
4752 int nRoot; /* Number of tables to check. (Number of root pages.) */ 5185 int nRoot; /* Number of tables to check. (Number of root pages.) */
4753 int *aRoot; /* Array of rootpage numbers for tables to be checked */ 5186 int *aRoot; /* Array of rootpage numbers for tables to be checked */
4754 int j; /* Loop counter */ 5187 int j; /* Loop counter */
4755 int nErr; /* Number of errors reported */ 5188 int nErr; /* Number of errors reported */
4756 char *z; /* Text of the error report */ 5189 char *z; /* Text of the error report */
4757 Mem *pnErr; /* Register keeping track of errors remaining */ 5190 Mem *pnErr; /* Register keeping track of errors remaining */
4758 5191
5192 assert( p->bIsReader );
4759 nRoot = pOp->p2; 5193 nRoot = pOp->p2;
4760 assert( nRoot>0 ); 5194 assert( nRoot>0 );
4761 aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) ); 5195 aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
4762 if( aRoot==0 ) goto no_mem; 5196 if( aRoot==0 ) goto no_mem;
4763 assert( pOp->p3>0 && pOp->p3<=p->nMem ); 5197 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
4764 pnErr = &aMem[pOp->p3]; 5198 pnErr = &aMem[pOp->p3];
4765 assert( (pnErr->flags & MEM_Int)!=0 ); 5199 assert( (pnErr->flags & MEM_Int)!=0 );
4766 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); 5200 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
4767 pIn1 = &aMem[pOp->p1]; 5201 pIn1 = &aMem[pOp->p1];
4768 for(j=0; j<nRoot; j++){ 5202 for(j=0; j<nRoot; j++){
4769 aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]); 5203 aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
4770 } 5204 }
4771 aRoot[j] = 0; 5205 aRoot[j] = 0;
4772 assert( pOp->p5<db->nDb ); 5206 assert( pOp->p5<db->nDb );
4773 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 ); 5207 assert( DbMaskTest(p->btreeMask, pOp->p5) );
4774 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, 5208 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
4775 (int)pnErr->u.i, &nErr); 5209 (int)pnErr->u.i, &nErr);
4776 sqlite3DbFree(db, aRoot); 5210 sqlite3DbFree(db, aRoot);
4777 pnErr->u.i -= nErr; 5211 pnErr->u.i -= nErr;
4778 sqlite3VdbeMemSetNull(pIn1); 5212 sqlite3VdbeMemSetNull(pIn1);
4779 if( nErr==0 ){ 5213 if( nErr==0 ){
4780 assert( z==0 ); 5214 assert( z==0 );
4781 }else if( z==0 ){ 5215 }else if( z==0 ){
4782 goto no_mem; 5216 goto no_mem;
4783 }else{ 5217 }else{
4784 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); 5218 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
4785 } 5219 }
4786 UPDATE_MAX_BLOBSIZE(pIn1); 5220 UPDATE_MAX_BLOBSIZE(pIn1);
4787 sqlite3VdbeChangeEncoding(pIn1, encoding); 5221 sqlite3VdbeChangeEncoding(pIn1, encoding);
4788 break; 5222 break;
4789 } 5223 }
4790 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ 5224 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4791 5225
4792 /* Opcode: RowSetAdd P1 P2 * * * 5226 /* Opcode: RowSetAdd P1 P2 * * *
5227 ** Synopsis: rowset(P1)=r[P2]
4793 ** 5228 **
4794 ** Insert the integer value held by register P2 into a boolean index 5229 ** Insert the integer value held by register P2 into a boolean index
4795 ** held in register P1. 5230 ** held in register P1.
4796 ** 5231 **
4797 ** An assertion fails if P2 is not an integer. 5232 ** An assertion fails if P2 is not an integer.
4798 */ 5233 */
4799 case OP_RowSetAdd: { /* in1, in2 */ 5234 case OP_RowSetAdd: { /* in1, in2 */
4800 pIn1 = &aMem[pOp->p1]; 5235 pIn1 = &aMem[pOp->p1];
4801 pIn2 = &aMem[pOp->p2]; 5236 pIn2 = &aMem[pOp->p2];
4802 assert( (pIn2->flags & MEM_Int)!=0 ); 5237 assert( (pIn2->flags & MEM_Int)!=0 );
4803 if( (pIn1->flags & MEM_RowSet)==0 ){ 5238 if( (pIn1->flags & MEM_RowSet)==0 ){
4804 sqlite3VdbeMemSetRowSet(pIn1); 5239 sqlite3VdbeMemSetRowSet(pIn1);
4805 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; 5240 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
4806 } 5241 }
4807 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); 5242 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
4808 break; 5243 break;
4809 } 5244 }
4810 5245
4811 /* Opcode: RowSetRead P1 P2 P3 * * 5246 /* Opcode: RowSetRead P1 P2 P3 * *
5247 ** Synopsis: r[P3]=rowset(P1)
4812 ** 5248 **
4813 ** Extract the smallest value from boolean index P1 and put that value into 5249 ** Extract the smallest value from boolean index P1 and put that value into
4814 ** register P3. Or, if boolean index P1 is initially empty, leave P3 5250 ** register P3. Or, if boolean index P1 is initially empty, leave P3
4815 ** unchanged and jump to instruction P2. 5251 ** unchanged and jump to instruction P2.
4816 */ 5252 */
4817 case OP_RowSetRead: { /* jump, in1, out3 */ 5253 case OP_RowSetRead: { /* jump, in1, out3 */
4818 i64 val; 5254 i64 val;
4819 CHECK_FOR_INTERRUPT; 5255
4820 pIn1 = &aMem[pOp->p1]; 5256 pIn1 = &aMem[pOp->p1];
4821 if( (pIn1->flags & MEM_RowSet)==0 5257 if( (pIn1->flags & MEM_RowSet)==0
4822 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0 5258 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
4823 ){ 5259 ){
4824 /* The boolean index is empty */ 5260 /* The boolean index is empty */
4825 sqlite3VdbeMemSetNull(pIn1); 5261 sqlite3VdbeMemSetNull(pIn1);
4826 pc = pOp->p2 - 1; 5262 pc = pOp->p2 - 1;
5263 VdbeBranchTaken(1,2);
4827 }else{ 5264 }else{
4828 /* A value was pulled from the index */ 5265 /* A value was pulled from the index */
4829 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); 5266 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
5267 VdbeBranchTaken(0,2);
4830 } 5268 }
4831 break; 5269 goto check_for_interrupt;
4832 } 5270 }
4833 5271
4834 /* Opcode: RowSetTest P1 P2 P3 P4 5272 /* Opcode: RowSetTest P1 P2 P3 P4
5273 ** Synopsis: if r[P3] in rowset(P1) goto P2
4835 ** 5274 **
4836 ** Register P3 is assumed to hold a 64-bit integer value. If register P1 5275 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
4837 ** contains a RowSet object and that RowSet object contains 5276 ** contains a RowSet object and that RowSet object contains
4838 ** the value held in P3, jump to register P2. Otherwise, insert the 5277 ** the value held in P3, jump to register P2. Otherwise, insert the
4839 ** integer in P3 into the RowSet and continue on to the 5278 ** integer in P3 into the RowSet and continue on to the
4840 ** next opcode. 5279 ** next opcode.
4841 ** 5280 **
4842 ** The RowSet object is optimized for the case where successive sets 5281 ** The RowSet object is optimized for the case where successive sets
4843 ** of integers, where each set contains no duplicates. Each set 5282 ** of integers, where each set contains no duplicates. Each set
4844 ** of values is identified by a unique P4 value. The first set 5283 ** of values is identified by a unique P4 value. The first set
(...skipping 22 matching lines...) Expand all
4867 ** delete it now and initialize P1 with an empty rowset 5306 ** delete it now and initialize P1 with an empty rowset
4868 */ 5307 */
4869 if( (pIn1->flags & MEM_RowSet)==0 ){ 5308 if( (pIn1->flags & MEM_RowSet)==0 ){
4870 sqlite3VdbeMemSetRowSet(pIn1); 5309 sqlite3VdbeMemSetRowSet(pIn1);
4871 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; 5310 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
4872 } 5311 }
4873 5312
4874 assert( pOp->p4type==P4_INT32 ); 5313 assert( pOp->p4type==P4_INT32 );
4875 assert( iSet==-1 || iSet>=0 ); 5314 assert( iSet==-1 || iSet>=0 );
4876 if( iSet ){ 5315 if( iSet ){
4877 exists = sqlite3RowSetTest(pIn1->u.pRowSet, 5316 exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
4878 (u8)(iSet>=0 ? iSet & 0xf : 0xff), 5317 VdbeBranchTaken(exists!=0,2);
4879 pIn3->u.i);
4880 if( exists ){ 5318 if( exists ){
4881 pc = pOp->p2 - 1; 5319 pc = pOp->p2 - 1;
4882 break; 5320 break;
4883 } 5321 }
4884 } 5322 }
4885 if( iSet>=0 ){ 5323 if( iSet>=0 ){
4886 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); 5324 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
4887 } 5325 }
4888 break; 5326 break;
4889 } 5327 }
4890 5328
4891 5329
4892 #ifndef SQLITE_OMIT_TRIGGER 5330 #ifndef SQLITE_OMIT_TRIGGER
4893 5331
4894 /* Opcode: Program P1 P2 P3 P4 * 5332 /* Opcode: Program P1 P2 P3 P4 P5
4895 ** 5333 **
4896 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 5334 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
4897 ** 5335 **
4898 ** P1 contains the address of the memory cell that contains the first memory 5336 ** P1 contains the address of the memory cell that contains the first memory
4899 ** cell in an array of values used as arguments to the sub-program. P2 5337 ** cell in an array of values used as arguments to the sub-program. P2
4900 ** contains the address to jump to if the sub-program throws an IGNORE 5338 ** contains the address to jump to if the sub-program throws an IGNORE
4901 ** exception using the RAISE() function. Register P3 contains the address 5339 ** exception using the RAISE() function. Register P3 contains the address
4902 ** of a memory cell in this (the parent) VM that is used to allocate the 5340 ** of a memory cell in this (the parent) VM that is used to allocate the
4903 ** memory required by the sub-vdbe at runtime. 5341 ** memory required by the sub-vdbe at runtime.
4904 ** 5342 **
4905 ** P4 is a pointer to the VM containing the trigger program. 5343 ** P4 is a pointer to the VM containing the trigger program.
5344 **
5345 ** If P5 is non-zero, then recursive program invocation is enabled.
4906 */ 5346 */
4907 case OP_Program: { /* jump */ 5347 case OP_Program: { /* jump */
4908 int nMem; /* Number of memory registers for sub-program */ 5348 int nMem; /* Number of memory registers for sub-program */
4909 int nByte; /* Bytes of runtime space required for sub-program */ 5349 int nByte; /* Bytes of runtime space required for sub-program */
4910 Mem *pRt; /* Register to allocate runtime space */ 5350 Mem *pRt; /* Register to allocate runtime space */
4911 Mem *pMem; /* Used to iterate through memory cells */ 5351 Mem *pMem; /* Used to iterate through memory cells */
4912 Mem *pEnd; /* Last memory cell in new array */ 5352 Mem *pEnd; /* Last memory cell in new array */
4913 VdbeFrame *pFrame; /* New vdbe frame to execute in */ 5353 VdbeFrame *pFrame; /* New vdbe frame to execute in */
4914 SubProgram *pProgram; /* Sub-program to execute */ 5354 SubProgram *pProgram; /* Sub-program to execute */
4915 void *t; /* Token identifying trigger */ 5355 void *t; /* Token identifying trigger */
4916 5356
4917 pProgram = pOp->p4.pProgram; 5357 pProgram = pOp->p4.pProgram;
4918 pRt = &aMem[pOp->p3]; 5358 pRt = &aMem[pOp->p3];
4919 assert( memIsValid(pRt) );
4920 assert( pProgram->nOp>0 ); 5359 assert( pProgram->nOp>0 );
4921 5360
4922 /* If the p5 flag is clear, then recursive invocation of triggers is 5361 /* If the p5 flag is clear, then recursive invocation of triggers is
4923 ** disabled for backwards compatibility (p5 is set if this sub-program 5362 ** disabled for backwards compatibility (p5 is set if this sub-program
4924 ** is really a trigger, not a foreign key action, and the flag set 5363 ** is really a trigger, not a foreign key action, and the flag set
4925 ** and cleared by the "PRAGMA recursive_triggers" command is clear). 5364 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
4926 ** 5365 **
4927 ** It is recursive invocation of triggers, at the SQL level, that is 5366 ** It is recursive invocation of triggers, at the SQL level, that is
4928 ** disabled. In some cases a single trigger may generate more than one 5367 ** disabled. In some cases a single trigger may generate more than one
4929 ** SubProgram (if the trigger may be executed with more than one different 5368 ** SubProgram (if the trigger may be executed with more than one different
(...skipping 18 matching lines...) Expand all
4948 ** is already allocated. Otherwise, it must be initialized. */ 5387 ** is already allocated. Otherwise, it must be initialized. */
4949 if( (pRt->flags&MEM_Frame)==0 ){ 5388 if( (pRt->flags&MEM_Frame)==0 ){
4950 /* SubProgram.nMem is set to the number of memory cells used by the 5389 /* SubProgram.nMem is set to the number of memory cells used by the
4951 ** program stored in SubProgram.aOp. As well as these, one memory 5390 ** program stored in SubProgram.aOp. As well as these, one memory
4952 ** cell is required for each cursor used by the program. Set local 5391 ** cell is required for each cursor used by the program. Set local
4953 ** variable nMem (and later, VdbeFrame.nChildMem) to this value. 5392 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
4954 */ 5393 */
4955 nMem = pProgram->nMem + pProgram->nCsr; 5394 nMem = pProgram->nMem + pProgram->nCsr;
4956 nByte = ROUND8(sizeof(VdbeFrame)) 5395 nByte = ROUND8(sizeof(VdbeFrame))
4957 + nMem * sizeof(Mem) 5396 + nMem * sizeof(Mem)
4958 + pProgram->nCsr * sizeof(VdbeCursor *); 5397 + pProgram->nCsr * sizeof(VdbeCursor *)
5398 + pProgram->nOnce * sizeof(u8);
4959 pFrame = sqlite3DbMallocZero(db, nByte); 5399 pFrame = sqlite3DbMallocZero(db, nByte);
4960 if( !pFrame ){ 5400 if( !pFrame ){
4961 goto no_mem; 5401 goto no_mem;
4962 } 5402 }
4963 sqlite3VdbeMemRelease(pRt); 5403 sqlite3VdbeMemRelease(pRt);
4964 pRt->flags = MEM_Frame; 5404 pRt->flags = MEM_Frame;
4965 pRt->u.pFrame = pFrame; 5405 pRt->u.pFrame = pFrame;
4966 5406
4967 pFrame->v = p; 5407 pFrame->v = p;
4968 pFrame->nChildMem = nMem; 5408 pFrame->nChildMem = nMem;
4969 pFrame->nChildCsr = pProgram->nCsr; 5409 pFrame->nChildCsr = pProgram->nCsr;
4970 pFrame->pc = pc; 5410 pFrame->pc = pc;
4971 pFrame->aMem = p->aMem; 5411 pFrame->aMem = p->aMem;
4972 pFrame->nMem = p->nMem; 5412 pFrame->nMem = p->nMem;
4973 pFrame->apCsr = p->apCsr; 5413 pFrame->apCsr = p->apCsr;
4974 pFrame->nCursor = p->nCursor; 5414 pFrame->nCursor = p->nCursor;
4975 pFrame->aOp = p->aOp; 5415 pFrame->aOp = p->aOp;
4976 pFrame->nOp = p->nOp; 5416 pFrame->nOp = p->nOp;
4977 pFrame->token = pProgram->token; 5417 pFrame->token = pProgram->token;
5418 pFrame->aOnceFlag = p->aOnceFlag;
5419 pFrame->nOnceFlag = p->nOnceFlag;
4978 5420
4979 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; 5421 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
4980 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ 5422 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
4981 pMem->flags = MEM_Null; 5423 pMem->flags = MEM_Undefined;
4982 pMem->db = db; 5424 pMem->db = db;
4983 } 5425 }
4984 }else{ 5426 }else{
4985 pFrame = pRt->u.pFrame; 5427 pFrame = pRt->u.pFrame;
4986 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem ); 5428 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
4987 assert( pProgram->nCsr==pFrame->nChildCsr ); 5429 assert( pProgram->nCsr==pFrame->nChildCsr );
4988 assert( pc==pFrame->pc ); 5430 assert( pc==pFrame->pc );
4989 } 5431 }
4990 5432
4991 p->nFrame++; 5433 p->nFrame++;
4992 pFrame->pParent = p->pFrame; 5434 pFrame->pParent = p->pFrame;
4993 pFrame->lastRowid = db->lastRowid; 5435 pFrame->lastRowid = lastRowid;
4994 pFrame->nChange = p->nChange; 5436 pFrame->nChange = p->nChange;
4995 p->nChange = 0; 5437 p->nChange = 0;
4996 p->pFrame = pFrame; 5438 p->pFrame = pFrame;
4997 p->aMem = aMem = &VdbeFrameMem(pFrame)[-1]; 5439 p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
4998 p->nMem = pFrame->nChildMem; 5440 p->nMem = pFrame->nChildMem;
4999 p->nCursor = (u16)pFrame->nChildCsr; 5441 p->nCursor = (u16)pFrame->nChildCsr;
5000 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1]; 5442 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
5001 p->aOp = aOp = pProgram->aOp; 5443 p->aOp = aOp = pProgram->aOp;
5002 p->nOp = pProgram->nOp; 5444 p->nOp = pProgram->nOp;
5445 p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
5446 p->nOnceFlag = pProgram->nOnce;
5003 pc = -1; 5447 pc = -1;
5448 memset(p->aOnceFlag, 0, p->nOnceFlag);
5004 5449
5005 break; 5450 break;
5006 } 5451 }
5007 5452
5008 /* Opcode: Param P1 P2 * * * 5453 /* Opcode: Param P1 P2 * * *
5009 ** 5454 **
5010 ** This opcode is only ever present in sub-programs called via the 5455 ** This opcode is only ever present in sub-programs called via the
5011 ** OP_Program instruction. Copy a value currently stored in a memory 5456 ** OP_Program instruction. Copy a value currently stored in a memory
5012 ** cell of the calling (parent) frame to cell P2 in the current frames 5457 ** cell of the calling (parent) frame to cell P2 in the current frames
5013 ** address space. This is used by trigger programs to access the new.* 5458 ** address space. This is used by trigger programs to access the new.*
5014 ** and old.* values. 5459 ** and old.* values.
5015 ** 5460 **
5016 ** The address of the cell in the parent frame is determined by adding 5461 ** The address of the cell in the parent frame is determined by adding
5017 ** the value of the P1 argument to the value of the P1 argument to the 5462 ** the value of the P1 argument to the value of the P1 argument to the
5018 ** calling OP_Program instruction. 5463 ** calling OP_Program instruction.
5019 */ 5464 */
5020 case OP_Param: { /* out2-prerelease */ 5465 case OP_Param: { /* out2-prerelease */
5021 VdbeFrame *pFrame; 5466 VdbeFrame *pFrame;
5022 Mem *pIn; 5467 Mem *pIn;
5023 pFrame = p->pFrame; 5468 pFrame = p->pFrame;
5024 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; 5469 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
5025 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); 5470 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
5026 break; 5471 break;
5027 } 5472 }
5028 5473
5029 #endif /* #ifndef SQLITE_OMIT_TRIGGER */ 5474 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
5030 5475
5031 #ifndef SQLITE_OMIT_FOREIGN_KEY 5476 #ifndef SQLITE_OMIT_FOREIGN_KEY
5032 /* Opcode: FkCounter P1 P2 * * * 5477 /* Opcode: FkCounter P1 P2 * * *
5478 ** Synopsis: fkctr[P1]+=P2
5033 ** 5479 **
5034 ** Increment a "constraint counter" by P2 (P2 may be negative or positive). 5480 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
5035 ** If P1 is non-zero, the database constraint counter is incremented 5481 ** If P1 is non-zero, the database constraint counter is incremented
5036 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 5482 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
5037 ** statement counter is incremented (immediate foreign key constraints). 5483 ** statement counter is incremented (immediate foreign key constraints).
5038 */ 5484 */
5039 case OP_FkCounter: { 5485 case OP_FkCounter: {
5040 if( pOp->p1 ){ 5486 if( db->flags & SQLITE_DeferFKs ){
5487 db->nDeferredImmCons += pOp->p2;
5488 }else if( pOp->p1 ){
5041 db->nDeferredCons += pOp->p2; 5489 db->nDeferredCons += pOp->p2;
5042 }else{ 5490 }else{
5043 p->nFkConstraint += pOp->p2; 5491 p->nFkConstraint += pOp->p2;
5044 } 5492 }
5045 break; 5493 break;
5046 } 5494 }
5047 5495
5048 /* Opcode: FkIfZero P1 P2 * * * 5496 /* Opcode: FkIfZero P1 P2 * * *
5497 ** Synopsis: if fkctr[P1]==0 goto P2
5049 ** 5498 **
5050 ** This opcode tests if a foreign key constraint-counter is currently zero. 5499 ** This opcode tests if a foreign key constraint-counter is currently zero.
5051 ** If so, jump to instruction P2. Otherwise, fall through to the next 5500 ** If so, jump to instruction P2. Otherwise, fall through to the next
5052 ** instruction. 5501 ** instruction.
5053 ** 5502 **
5054 ** If P1 is non-zero, then the jump is taken if the database constraint-counter 5503 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
5055 ** is zero (the one that counts deferred constraint violations). If P1 is 5504 ** is zero (the one that counts deferred constraint violations). If P1 is
5056 ** zero, the jump is taken if the statement constraint-counter is zero 5505 ** zero, the jump is taken if the statement constraint-counter is zero
5057 ** (immediate foreign key constraint violations). 5506 ** (immediate foreign key constraint violations).
5058 */ 5507 */
5059 case OP_FkIfZero: { /* jump */ 5508 case OP_FkIfZero: { /* jump */
5060 if( pOp->p1 ){ 5509 if( pOp->p1 ){
5061 if( db->nDeferredCons==0 ) pc = pOp->p2-1; 5510 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
5511 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
5062 }else{ 5512 }else{
5063 if( p->nFkConstraint==0 ) pc = pOp->p2-1; 5513 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
5514 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
5064 } 5515 }
5065 break; 5516 break;
5066 } 5517 }
5067 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ 5518 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
5068 5519
5069 #ifndef SQLITE_OMIT_AUTOINCREMENT 5520 #ifndef SQLITE_OMIT_AUTOINCREMENT
5070 /* Opcode: MemMax P1 P2 * * * 5521 /* Opcode: MemMax P1 P2 * * *
5522 ** Synopsis: r[P1]=max(r[P1],r[P2])
5071 ** 5523 **
5072 ** P1 is a register in the root frame of this VM (the root frame is 5524 ** P1 is a register in the root frame of this VM (the root frame is
5073 ** different from the current frame if this instruction is being executed 5525 ** different from the current frame if this instruction is being executed
5074 ** within a sub-program). Set the value of register P1 to the maximum of 5526 ** within a sub-program). Set the value of register P1 to the maximum of
5075 ** its current value and the value in register P2. 5527 ** its current value and the value in register P2.
5076 ** 5528 **
5077 ** This instruction throws an error if the memory cell is not initially 5529 ** This instruction throws an error if the memory cell is not initially
5078 ** an integer. 5530 ** an integer.
5079 */ 5531 */
5080 case OP_MemMax: { /* in2 */ 5532 case OP_MemMax: { /* in2 */
5081 Mem *pIn1;
5082 VdbeFrame *pFrame; 5533 VdbeFrame *pFrame;
5083 if( p->pFrame ){ 5534 if( p->pFrame ){
5084 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); 5535 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
5085 pIn1 = &pFrame->aMem[pOp->p1]; 5536 pIn1 = &pFrame->aMem[pOp->p1];
5086 }else{ 5537 }else{
5087 pIn1 = &aMem[pOp->p1]; 5538 pIn1 = &aMem[pOp->p1];
5088 } 5539 }
5089 assert( memIsValid(pIn1) ); 5540 assert( memIsValid(pIn1) );
5090 sqlite3VdbeMemIntegerify(pIn1); 5541 sqlite3VdbeMemIntegerify(pIn1);
5091 pIn2 = &aMem[pOp->p2]; 5542 pIn2 = &aMem[pOp->p2];
5092 sqlite3VdbeMemIntegerify(pIn2); 5543 sqlite3VdbeMemIntegerify(pIn2);
5093 if( pIn1->u.i<pIn2->u.i){ 5544 if( pIn1->u.i<pIn2->u.i){
5094 pIn1->u.i = pIn2->u.i; 5545 pIn1->u.i = pIn2->u.i;
5095 } 5546 }
5096 break; 5547 break;
5097 } 5548 }
5098 #endif /* SQLITE_OMIT_AUTOINCREMENT */ 5549 #endif /* SQLITE_OMIT_AUTOINCREMENT */
5099 5550
5100 /* Opcode: IfPos P1 P2 * * * 5551 /* Opcode: IfPos P1 P2 * * *
5552 ** Synopsis: if r[P1]>0 goto P2
5101 ** 5553 **
5102 ** If the value of register P1 is 1 or greater, jump to P2. 5554 ** If the value of register P1 is 1 or greater, jump to P2.
5103 ** 5555 **
5104 ** It is illegal to use this instruction on a register that does 5556 ** It is illegal to use this instruction on a register that does
5105 ** not contain an integer. An assertion fault will result if you try. 5557 ** not contain an integer. An assertion fault will result if you try.
5106 */ 5558 */
5107 case OP_IfPos: { /* jump, in1 */ 5559 case OP_IfPos: { /* jump, in1 */
5108 pIn1 = &aMem[pOp->p1]; 5560 pIn1 = &aMem[pOp->p1];
5109 assert( pIn1->flags&MEM_Int ); 5561 assert( pIn1->flags&MEM_Int );
5562 VdbeBranchTaken( pIn1->u.i>0, 2);
5110 if( pIn1->u.i>0 ){ 5563 if( pIn1->u.i>0 ){
5111 pc = pOp->p2 - 1; 5564 pc = pOp->p2 - 1;
5112 } 5565 }
5113 break; 5566 break;
5114 } 5567 }
5115 5568
5116 /* Opcode: IfNeg P1 P2 * * * 5569 /* Opcode: IfNeg P1 P2 P3 * *
5570 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
5117 ** 5571 **
5118 ** If the value of register P1 is less than zero, jump to P2. 5572 ** Register P1 must contain an integer. Add literal P3 to the value in
5119 ** 5573 ** register P1 then if the value of register P1 is less than zero, jump to P2.
5120 ** It is illegal to use this instruction on a register that does
5121 ** not contain an integer. An assertion fault will result if you try.
5122 */ 5574 */
5123 case OP_IfNeg: { /* jump, in1 */ 5575 case OP_IfNeg: { /* jump, in1 */
5124 pIn1 = &aMem[pOp->p1]; 5576 pIn1 = &aMem[pOp->p1];
5125 assert( pIn1->flags&MEM_Int ); 5577 assert( pIn1->flags&MEM_Int );
5578 pIn1->u.i += pOp->p3;
5579 VdbeBranchTaken(pIn1->u.i<0, 2);
5126 if( pIn1->u.i<0 ){ 5580 if( pIn1->u.i<0 ){
5127 pc = pOp->p2 - 1; 5581 pc = pOp->p2 - 1;
5128 } 5582 }
5129 break; 5583 break;
5130 } 5584 }
5131 5585
5132 /* Opcode: IfZero P1 P2 P3 * * 5586 /* Opcode: IfZero P1 P2 P3 * *
5587 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
5133 ** 5588 **
5134 ** The register P1 must contain an integer. Add literal P3 to the 5589 ** The register P1 must contain an integer. Add literal P3 to the
5135 ** value in register P1. If the result is exactly 0, jump to P2. 5590 ** value in register P1. If the result is exactly 0, jump to P2.
5136 **
5137 ** It is illegal to use this instruction on a register that does
5138 ** not contain an integer. An assertion fault will result if you try.
5139 */ 5591 */
5140 case OP_IfZero: { /* jump, in1 */ 5592 case OP_IfZero: { /* jump, in1 */
5141 pIn1 = &aMem[pOp->p1]; 5593 pIn1 = &aMem[pOp->p1];
5142 assert( pIn1->flags&MEM_Int ); 5594 assert( pIn1->flags&MEM_Int );
5143 pIn1->u.i += pOp->p3; 5595 pIn1->u.i += pOp->p3;
5596 VdbeBranchTaken(pIn1->u.i==0, 2);
5144 if( pIn1->u.i==0 ){ 5597 if( pIn1->u.i==0 ){
5145 pc = pOp->p2 - 1; 5598 pc = pOp->p2 - 1;
5146 } 5599 }
5147 break; 5600 break;
5148 } 5601 }
5149 5602
5150 /* Opcode: AggStep * P2 P3 P4 P5 5603 /* Opcode: AggStep * P2 P3 P4 P5
5604 ** Synopsis: accum=r[P3] step(r[P2@P5])
5151 ** 5605 **
5152 ** Execute the step function for an aggregate. The 5606 ** Execute the step function for an aggregate. The
5153 ** function has P5 arguments. P4 is a pointer to the FuncDef 5607 ** function has P5 arguments. P4 is a pointer to the FuncDef
5154 ** structure that specifies the function. Use register 5608 ** structure that specifies the function. Use register
5155 ** P3 as the accumulator. 5609 ** P3 as the accumulator.
5156 ** 5610 **
5157 ** The P5 arguments are taken from register P2 and its 5611 ** The P5 arguments are taken from register P2 and its
5158 ** successors. 5612 ** successors.
5159 */ 5613 */
5160 case OP_AggStep: { 5614 case OP_AggStep: {
5161 int n; 5615 int n;
5162 int i; 5616 int i;
5163 Mem *pMem; 5617 Mem *pMem;
5164 Mem *pRec; 5618 Mem *pRec;
5619 Mem t;
5165 sqlite3_context ctx; 5620 sqlite3_context ctx;
5166 sqlite3_value **apVal; 5621 sqlite3_value **apVal;
5167 5622
5168 n = pOp->p5; 5623 n = pOp->p5;
5169 assert( n>=0 ); 5624 assert( n>=0 );
5170 pRec = &aMem[pOp->p2]; 5625 pRec = &aMem[pOp->p2];
5171 apVal = p->apArg; 5626 apVal = p->apArg;
5172 assert( apVal || n==0 ); 5627 assert( apVal || n==0 );
5173 for(i=0; i<n; i++, pRec++){ 5628 for(i=0; i<n; i++, pRec++){
5174 assert( memIsValid(pRec) ); 5629 assert( memIsValid(pRec) );
5175 apVal[i] = pRec; 5630 apVal[i] = pRec;
5176 memAboutToChange(p, pRec); 5631 memAboutToChange(p, pRec);
5177 sqlite3VdbeMemStoreType(pRec);
5178 } 5632 }
5179 ctx.pFunc = pOp->p4.pFunc; 5633 ctx.pFunc = pOp->p4.pFunc;
5180 assert( pOp->p3>0 && pOp->p3<=p->nMem ); 5634 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
5181 ctx.pMem = pMem = &aMem[pOp->p3]; 5635 ctx.pMem = pMem = &aMem[pOp->p3];
5182 pMem->n++; 5636 pMem->n++;
5183 ctx.s.flags = MEM_Null; 5637 sqlite3VdbeMemInit(&t, db, MEM_Null);
5184 ctx.s.z = 0; 5638 ctx.pOut = &t;
5185 ctx.s.zMalloc = 0;
5186 ctx.s.xDel = 0;
5187 ctx.s.db = db;
5188 ctx.isError = 0; 5639 ctx.isError = 0;
5189 ctx.pColl = 0; 5640 ctx.pVdbe = p;
5190 if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 5641 ctx.iOp = pc;
5191 assert( pOp>p->aOp ); 5642 ctx.skipFlag = 0;
5192 assert( pOp[-1].p4type==P4_COLLSEQ );
5193 assert( pOp[-1].opcode==OP_CollSeq );
5194 ctx.pColl = pOp[-1].p4.pColl;
5195 }
5196 (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */ 5643 (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
5197 if( ctx.isError ){ 5644 if( ctx.isError ){
5198 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s)); 5645 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
5199 rc = ctx.isError; 5646 rc = ctx.isError;
5200 } 5647 }
5201 5648 if( ctx.skipFlag ){
5202 sqlite3VdbeMemRelease(&ctx.s); 5649 assert( pOp[-1].opcode==OP_CollSeq );
5203 5650 i = pOp[-1].p1;
5651 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
5652 }
5653 sqlite3VdbeMemRelease(&t);
5204 break; 5654 break;
5205 } 5655 }
5206 5656
5207 /* Opcode: AggFinal P1 P2 * P4 * 5657 /* Opcode: AggFinal P1 P2 * P4 *
5658 ** Synopsis: accum=r[P1] N=P2
5208 ** 5659 **
5209 ** Execute the finalizer function for an aggregate. P1 is 5660 ** Execute the finalizer function for an aggregate. P1 is
5210 ** the memory location that is the accumulator for the aggregate. 5661 ** the memory location that is the accumulator for the aggregate.
5211 ** 5662 **
5212 ** P2 is the number of arguments that the step function takes and 5663 ** P2 is the number of arguments that the step function takes and
5213 ** P4 is a pointer to the FuncDef for this function. The P2 5664 ** P4 is a pointer to the FuncDef for this function. The P2
5214 ** argument is not used by this opcode. It is only there to disambiguate 5665 ** argument is not used by this opcode. It is only there to disambiguate
5215 ** functions that can take varying numbers of arguments. The 5666 ** functions that can take varying numbers of arguments. The
5216 ** P4 argument is only needed for the degenerate case where 5667 ** P4 argument is only needed for the degenerate case where
5217 ** the step function was not previously called. 5668 ** the step function was not previously called.
5218 */ 5669 */
5219 case OP_AggFinal: { 5670 case OP_AggFinal: {
5220 Mem *pMem; 5671 Mem *pMem;
5221 assert( pOp->p1>0 && pOp->p1<=p->nMem ); 5672 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
5222 pMem = &aMem[pOp->p1]; 5673 pMem = &aMem[pOp->p1];
5223 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); 5674 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
5224 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); 5675 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
5225 if( rc ){ 5676 if( rc ){
5226 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem)); 5677 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
5227 } 5678 }
5228 sqlite3VdbeChangeEncoding(pMem, encoding); 5679 sqlite3VdbeChangeEncoding(pMem, encoding);
5229 UPDATE_MAX_BLOBSIZE(pMem); 5680 UPDATE_MAX_BLOBSIZE(pMem);
5230 if( sqlite3VdbeMemTooBig(pMem) ){ 5681 if( sqlite3VdbeMemTooBig(pMem) ){
5231 goto too_big; 5682 goto too_big;
(...skipping 11 matching lines...) Expand all
5243 ** WAL after the checkpoint into mem[P3+1] and the number of pages 5694 ** WAL after the checkpoint into mem[P3+1] and the number of pages
5244 ** in the WAL that have been checkpointed after the checkpoint 5695 ** in the WAL that have been checkpointed after the checkpoint
5245 ** completes into mem[P3+2]. However on an error, mem[P3+1] and 5696 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
5246 ** mem[P3+2] are initialized to -1. 5697 ** mem[P3+2] are initialized to -1.
5247 */ 5698 */
5248 case OP_Checkpoint: { 5699 case OP_Checkpoint: {
5249 int i; /* Loop counter */ 5700 int i; /* Loop counter */
5250 int aRes[3]; /* Results */ 5701 int aRes[3]; /* Results */
5251 Mem *pMem; /* Write results here */ 5702 Mem *pMem; /* Write results here */
5252 5703
5704 assert( p->readOnly==0 );
5253 aRes[0] = 0; 5705 aRes[0] = 0;
5254 aRes[1] = aRes[2] = -1; 5706 aRes[1] = aRes[2] = -1;
5255 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE 5707 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
5256 || pOp->p2==SQLITE_CHECKPOINT_FULL 5708 || pOp->p2==SQLITE_CHECKPOINT_FULL
5257 || pOp->p2==SQLITE_CHECKPOINT_RESTART 5709 || pOp->p2==SQLITE_CHECKPOINT_RESTART
5258 ); 5710 );
5259 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); 5711 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
5260 if( rc==SQLITE_BUSY ){ 5712 if( rc==SQLITE_BUSY ){
5261 rc = SQLITE_OK; 5713 rc = SQLITE_OK;
5262 aRes[0] = 1; 5714 aRes[0] = 1;
5263 } 5715 }
5264 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ 5716 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
5265 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); 5717 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
5266 } 5718 }
5267 break; 5719 break;
5268 }; 5720 };
5269 #endif 5721 #endif
5270 5722
5271 #ifndef SQLITE_OMIT_PRAGMA 5723 #ifndef SQLITE_OMIT_PRAGMA
5272 /* Opcode: JournalMode P1 P2 P3 * P5 5724 /* Opcode: JournalMode P1 P2 P3 * *
5273 ** 5725 **
5274 ** Change the journal mode of database P1 to P3. P3 must be one of the 5726 ** Change the journal mode of database P1 to P3. P3 must be one of the
5275 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback 5727 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
5276 ** modes (delete, truncate, persist, off and memory), this is a simple 5728 ** modes (delete, truncate, persist, off and memory), this is a simple
5277 ** operation. No IO is required. 5729 ** operation. No IO is required.
5278 ** 5730 **
5279 ** If changing into or out of WAL mode the procedure is more complicated. 5731 ** If changing into or out of WAL mode the procedure is more complicated.
5280 ** 5732 **
5281 ** Write a string containing the final journal-mode to register P2. 5733 ** Write a string containing the final journal-mode to register P2.
5282 */ 5734 */
5283 case OP_JournalMode: { /* out2-prerelease */ 5735 case OP_JournalMode: { /* out2-prerelease */
5284 Btree *pBt; /* Btree to change journal mode of */ 5736 Btree *pBt; /* Btree to change journal mode of */
5285 Pager *pPager; /* Pager associated with pBt */ 5737 Pager *pPager; /* Pager associated with pBt */
5286 int eNew; /* New journal mode */ 5738 int eNew; /* New journal mode */
5287 int eOld; /* The old journal mode */ 5739 int eOld; /* The old journal mode */
5740 #ifndef SQLITE_OMIT_WAL
5288 const char *zFilename; /* Name of database file for pPager */ 5741 const char *zFilename; /* Name of database file for pPager */
5742 #endif
5289 5743
5290 eNew = pOp->p3; 5744 eNew = pOp->p3;
5291 assert( eNew==PAGER_JOURNALMODE_DELETE 5745 assert( eNew==PAGER_JOURNALMODE_DELETE
5292 || eNew==PAGER_JOURNALMODE_TRUNCATE 5746 || eNew==PAGER_JOURNALMODE_TRUNCATE
5293 || eNew==PAGER_JOURNALMODE_PERSIST 5747 || eNew==PAGER_JOURNALMODE_PERSIST
5294 || eNew==PAGER_JOURNALMODE_OFF 5748 || eNew==PAGER_JOURNALMODE_OFF
5295 || eNew==PAGER_JOURNALMODE_MEMORY 5749 || eNew==PAGER_JOURNALMODE_MEMORY
5296 || eNew==PAGER_JOURNALMODE_WAL 5750 || eNew==PAGER_JOURNALMODE_WAL
5297 || eNew==PAGER_JOURNALMODE_QUERY 5751 || eNew==PAGER_JOURNALMODE_QUERY
5298 ); 5752 );
5299 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 5753 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5754 assert( p->readOnly==0 );
5300 5755
5301 pBt = db->aDb[pOp->p1].pBt; 5756 pBt = db->aDb[pOp->p1].pBt;
5302 pPager = sqlite3BtreePager(pBt); 5757 pPager = sqlite3BtreePager(pBt);
5303 eOld = sqlite3PagerGetJournalMode(pPager); 5758 eOld = sqlite3PagerGetJournalMode(pPager);
5304 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; 5759 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
5305 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; 5760 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
5306 5761
5307 #ifndef SQLITE_OMIT_WAL 5762 #ifndef SQLITE_OMIT_WAL
5308 zFilename = sqlite3PagerFilename(pPager); 5763 zFilename = sqlite3PagerFilename(pPager, 1);
5309 5764
5310 /* Do not allow a transition to journal_mode=WAL for a database 5765 /* Do not allow a transition to journal_mode=WAL for a database
5311 ** in temporary storage or if the VFS does not support shared memory 5766 ** in temporary storage or if the VFS does not support shared memory
5312 */ 5767 */
5313 if( eNew==PAGER_JOURNALMODE_WAL 5768 if( eNew==PAGER_JOURNALMODE_WAL
5314 && (zFilename[0]==0 /* Temp file */ 5769 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
5315 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ 5770 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
5316 ){ 5771 ){
5317 eNew = eOld; 5772 eNew = eOld;
5318 } 5773 }
5319 5774
5320 if( (eNew!=eOld) 5775 if( (eNew!=eOld)
5321 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) 5776 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
5322 ){ 5777 ){
5323 if( !db->autoCommit || db->activeVdbeCnt>1 ){ 5778 if( !db->autoCommit || db->nVdbeRead>1 ){
5324 rc = SQLITE_ERROR; 5779 rc = SQLITE_ERROR;
5325 sqlite3SetString(&p->zErrMsg, db, 5780 sqlite3SetString(&p->zErrMsg, db,
5326 "cannot change %s wal mode from within a transaction", 5781 "cannot change %s wal mode from within a transaction",
5327 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") 5782 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
5328 ); 5783 );
5329 break; 5784 break;
5330 }else{ 5785 }else{
5331 5786
5332 if( eOld==PAGER_JOURNALMODE_WAL ){ 5787 if( eOld==PAGER_JOURNALMODE_WAL ){
5333 /* If leaving WAL mode, close the log file. If successful, the call 5788 /* If leaving WAL mode, close the log file. If successful, the call
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
5372 #endif /* SQLITE_OMIT_PRAGMA */ 5827 #endif /* SQLITE_OMIT_PRAGMA */
5373 5828
5374 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) 5829 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
5375 /* Opcode: Vacuum * * * * * 5830 /* Opcode: Vacuum * * * * *
5376 ** 5831 **
5377 ** Vacuum the entire database. This opcode will cause other virtual 5832 ** Vacuum the entire database. This opcode will cause other virtual
5378 ** machines to be created and run. It may not be called from within 5833 ** machines to be created and run. It may not be called from within
5379 ** a transaction. 5834 ** a transaction.
5380 */ 5835 */
5381 case OP_Vacuum: { 5836 case OP_Vacuum: {
5837 assert( p->readOnly==0 );
5382 rc = sqlite3RunVacuum(&p->zErrMsg, db); 5838 rc = sqlite3RunVacuum(&p->zErrMsg, db);
5383 break; 5839 break;
5384 } 5840 }
5385 #endif 5841 #endif
5386 5842
5387 #if !defined(SQLITE_OMIT_AUTOVACUUM) 5843 #if !defined(SQLITE_OMIT_AUTOVACUUM)
5388 /* Opcode: IncrVacuum P1 P2 * * * 5844 /* Opcode: IncrVacuum P1 P2 * * *
5389 ** 5845 **
5390 ** Perform a single step of the incremental vacuum procedure on 5846 ** Perform a single step of the incremental vacuum procedure on
5391 ** the P1 database. If the vacuum has finished, jump to instruction 5847 ** the P1 database. If the vacuum has finished, jump to instruction
5392 ** P2. Otherwise, fall through to the next instruction. 5848 ** P2. Otherwise, fall through to the next instruction.
5393 */ 5849 */
5394 case OP_IncrVacuum: { /* jump */ 5850 case OP_IncrVacuum: { /* jump */
5395 Btree *pBt; 5851 Btree *pBt;
5396 5852
5397 assert( pOp->p1>=0 && pOp->p1<db->nDb ); 5853 assert( pOp->p1>=0 && pOp->p1<db->nDb );
5398 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 ); 5854 assert( DbMaskTest(p->btreeMask, pOp->p1) );
5855 assert( p->readOnly==0 );
5399 pBt = db->aDb[pOp->p1].pBt; 5856 pBt = db->aDb[pOp->p1].pBt;
5400 rc = sqlite3BtreeIncrVacuum(pBt); 5857 rc = sqlite3BtreeIncrVacuum(pBt);
5858 VdbeBranchTaken(rc==SQLITE_DONE,2);
5401 if( rc==SQLITE_DONE ){ 5859 if( rc==SQLITE_DONE ){
5402 pc = pOp->p2 - 1; 5860 pc = pOp->p2 - 1;
5403 rc = SQLITE_OK; 5861 rc = SQLITE_OK;
5404 } 5862 }
5405 break; 5863 break;
5406 } 5864 }
5407 #endif 5865 #endif
5408 5866
5409 /* Opcode: Expire P1 * * * * 5867 /* Opcode: Expire P1 * * * *
5410 ** 5868 **
5411 ** Cause precompiled statements to become expired. An expired statement 5869 ** Cause precompiled statements to expire. When an expired statement
5412 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 5870 ** is executed using sqlite3_step() it will either automatically
5413 ** (via sqlite3_step()). 5871 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
5872 ** or it will fail with SQLITE_SCHEMA.
5414 ** 5873 **
5415 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, 5874 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
5416 ** then only the currently executing statement is affected. 5875 ** then only the currently executing statement is expired.
5417 */ 5876 */
5418 case OP_Expire: { 5877 case OP_Expire: {
5419 if( !pOp->p1 ){ 5878 if( !pOp->p1 ){
5420 sqlite3ExpirePreparedStatements(db); 5879 sqlite3ExpirePreparedStatements(db);
5421 }else{ 5880 }else{
5422 p->expired = 1; 5881 p->expired = 1;
5423 } 5882 }
5424 break; 5883 break;
5425 } 5884 }
5426 5885
5427 #ifndef SQLITE_OMIT_SHARED_CACHE 5886 #ifndef SQLITE_OMIT_SHARED_CACHE
5428 /* Opcode: TableLock P1 P2 P3 P4 * 5887 /* Opcode: TableLock P1 P2 P3 P4 *
5888 ** Synopsis: iDb=P1 root=P2 write=P3
5429 ** 5889 **
5430 ** Obtain a lock on a particular table. This instruction is only used when 5890 ** Obtain a lock on a particular table. This instruction is only used when
5431 ** the shared-cache feature is enabled. 5891 ** the shared-cache feature is enabled.
5432 ** 5892 **
5433 ** P1 is the index of the database in sqlite3.aDb[] of the database 5893 ** P1 is the index of the database in sqlite3.aDb[] of the database
5434 ** on which the lock is acquired. A readlock is obtained if P3==0 or 5894 ** on which the lock is acquired. A readlock is obtained if P3==0 or
5435 ** a write lock if P3==1. 5895 ** a write lock if P3==1.
5436 ** 5896 **
5437 ** P2 contains the root-page of the table to lock. 5897 ** P2 contains the root-page of the table to lock.
5438 ** 5898 **
5439 ** P4 contains a pointer to the name of the table being locked. This is only 5899 ** P4 contains a pointer to the name of the table being locked. This is only
5440 ** used to generate an error message if the lock cannot be obtained. 5900 ** used to generate an error message if the lock cannot be obtained.
5441 */ 5901 */
5442 case OP_TableLock: { 5902 case OP_TableLock: {
5443 u8 isWriteLock = (u8)pOp->p3; 5903 u8 isWriteLock = (u8)pOp->p3;
5444 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ 5904 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
5445 int p1 = pOp->p1; 5905 int p1 = pOp->p1;
5446 assert( p1>=0 && p1<db->nDb ); 5906 assert( p1>=0 && p1<db->nDb );
5447 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 ); 5907 assert( DbMaskTest(p->btreeMask, p1) );
5448 assert( isWriteLock==0 || isWriteLock==1 ); 5908 assert( isWriteLock==0 || isWriteLock==1 );
5449 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); 5909 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
5450 if( (rc&0xFF)==SQLITE_LOCKED ){ 5910 if( (rc&0xFF)==SQLITE_LOCKED ){
5451 const char *z = pOp->p4.z; 5911 const char *z = pOp->p4.z;
5452 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z); 5912 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
5453 } 5913 }
5454 } 5914 }
5455 break; 5915 break;
5456 } 5916 }
5457 #endif /* SQLITE_OMIT_SHARED_CACHE */ 5917 #endif /* SQLITE_OMIT_SHARED_CACHE */
5458 5918
5459 #ifndef SQLITE_OMIT_VIRTUALTABLE 5919 #ifndef SQLITE_OMIT_VIRTUALTABLE
5460 /* Opcode: VBegin * * * P4 * 5920 /* Opcode: VBegin * * * P4 *
5461 ** 5921 **
5462 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 5922 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
5463 ** xBegin method for that table. 5923 ** xBegin method for that table.
5464 ** 5924 **
5465 ** Also, whether or not P4 is set, check that this is not being called from 5925 ** Also, whether or not P4 is set, check that this is not being called from
5466 ** within a callback to a virtual table xSync() method. If it is, the error 5926 ** within a callback to a virtual table xSync() method. If it is, the error
5467 ** code will be set to SQLITE_LOCKED. 5927 ** code will be set to SQLITE_LOCKED.
5468 */ 5928 */
5469 case OP_VBegin: { 5929 case OP_VBegin: {
5470 VTable *pVTab; 5930 VTable *pVTab;
5471 pVTab = pOp->p4.pVtab; 5931 pVTab = pOp->p4.pVtab;
5472 rc = sqlite3VtabBegin(db, pVTab); 5932 rc = sqlite3VtabBegin(db, pVTab);
5473 if( pVTab ) importVtabErrMsg(p, pVTab->pVtab); 5933 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
5474 break; 5934 break;
5475 } 5935 }
5476 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 5936 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5477 5937
5478 #ifndef SQLITE_OMIT_VIRTUALTABLE 5938 #ifndef SQLITE_OMIT_VIRTUALTABLE
5479 /* Opcode: VCreate P1 * * P4 * 5939 /* Opcode: VCreate P1 * * P4 *
5480 ** 5940 **
5481 ** P4 is the name of a virtual table in database P1. Call the xCreate method 5941 ** P4 is the name of a virtual table in database P1. Call the xCreate method
5482 ** for that table. 5942 ** for that table.
5483 */ 5943 */
(...skipping 23 matching lines...) Expand all
5507 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 5967 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
5508 ** P1 is a cursor number. This opcode opens a cursor to the virtual 5968 ** P1 is a cursor number. This opcode opens a cursor to the virtual
5509 ** table and stores that cursor in P1. 5969 ** table and stores that cursor in P1.
5510 */ 5970 */
5511 case OP_VOpen: { 5971 case OP_VOpen: {
5512 VdbeCursor *pCur; 5972 VdbeCursor *pCur;
5513 sqlite3_vtab_cursor *pVtabCursor; 5973 sqlite3_vtab_cursor *pVtabCursor;
5514 sqlite3_vtab *pVtab; 5974 sqlite3_vtab *pVtab;
5515 sqlite3_module *pModule; 5975 sqlite3_module *pModule;
5516 5976
5977 assert( p->bIsReader );
5517 pCur = 0; 5978 pCur = 0;
5518 pVtabCursor = 0; 5979 pVtabCursor = 0;
5519 pVtab = pOp->p4.pVtab->pVtab; 5980 pVtab = pOp->p4.pVtab->pVtab;
5520 pModule = (sqlite3_module *)pVtab->pModule; 5981 pModule = (sqlite3_module *)pVtab->pModule;
5521 assert(pVtab && pModule); 5982 assert(pVtab && pModule);
5522 rc = pModule->xOpen(pVtab, &pVtabCursor); 5983 rc = pModule->xOpen(pVtab, &pVtabCursor);
5523 importVtabErrMsg(p, pVtab); 5984 sqlite3VtabImportErrmsg(p, pVtab);
5524 if( SQLITE_OK==rc ){ 5985 if( SQLITE_OK==rc ){
5525 /* Initialize sqlite3_vtab_cursor base class */ 5986 /* Initialize sqlite3_vtab_cursor base class */
5526 pVtabCursor->pVtab = pVtab; 5987 pVtabCursor->pVtab = pVtab;
5527 5988
5528 /* Initialise vdbe cursor object */ 5989 /* Initialize vdbe cursor object */
5529 pCur = allocateCursor(p, pOp->p1, 0, -1, 0); 5990 pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
5530 if( pCur ){ 5991 if( pCur ){
5531 pCur->pVtabCursor = pVtabCursor; 5992 pCur->pVtabCursor = pVtabCursor;
5532 pCur->pModule = pVtabCursor->pVtab->pModule;
5533 }else{ 5993 }else{
5534 db->mallocFailed = 1; 5994 db->mallocFailed = 1;
5535 pModule->xClose(pVtabCursor); 5995 pModule->xClose(pVtabCursor);
5536 } 5996 }
5537 } 5997 }
5538 break; 5998 break;
5539 } 5999 }
5540 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 6000 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5541 6001
5542 #ifndef SQLITE_OMIT_VIRTUALTABLE 6002 #ifndef SQLITE_OMIT_VIRTUALTABLE
5543 /* Opcode: VFilter P1 P2 P3 P4 * 6003 /* Opcode: VFilter P1 P2 P3 P4 *
6004 ** Synopsis: iplan=r[P3] zplan='P4'
5544 ** 6005 **
5545 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if 6006 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
5546 ** the filtered result set is empty. 6007 ** the filtered result set is empty.
5547 ** 6008 **
5548 ** P4 is either NULL or a string that was generated by the xBestIndex 6009 ** P4 is either NULL or a string that was generated by the xBestIndex
5549 ** method of the module. The interpretation of the P4 string is left 6010 ** method of the module. The interpretation of the P4 string is left
5550 ** to the module implementation. 6011 ** to the module implementation.
5551 ** 6012 **
5552 ** This opcode invokes the xFilter method on the virtual table specified 6013 ** This opcode invokes the xFilter method on the virtual table specified
5553 ** by P1. The integer query plan parameter to xFilter is stored in register 6014 ** by P1. The integer query plan parameter to xFilter is stored in register
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
5585 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); 6046 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
5586 nArg = (int)pArgc->u.i; 6047 nArg = (int)pArgc->u.i;
5587 iQuery = (int)pQuery->u.i; 6048 iQuery = (int)pQuery->u.i;
5588 6049
5589 /* Invoke the xFilter method */ 6050 /* Invoke the xFilter method */
5590 { 6051 {
5591 res = 0; 6052 res = 0;
5592 apArg = p->apArg; 6053 apArg = p->apArg;
5593 for(i = 0; i<nArg; i++){ 6054 for(i = 0; i<nArg; i++){
5594 apArg[i] = &pArgc[i+1]; 6055 apArg[i] = &pArgc[i+1];
5595 sqlite3VdbeMemStoreType(apArg[i]);
5596 } 6056 }
5597 6057
5598 p->inVtabMethod = 1; 6058 p->inVtabMethod = 1;
5599 rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg); 6059 rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
5600 p->inVtabMethod = 0; 6060 p->inVtabMethod = 0;
5601 importVtabErrMsg(p, pVtab); 6061 sqlite3VtabImportErrmsg(p, pVtab);
5602 if( rc==SQLITE_OK ){ 6062 if( rc==SQLITE_OK ){
5603 res = pModule->xEof(pVtabCursor); 6063 res = pModule->xEof(pVtabCursor);
5604 } 6064 }
5605 6065 VdbeBranchTaken(res!=0,2);
5606 if( res ){ 6066 if( res ){
5607 pc = pOp->p2 - 1; 6067 pc = pOp->p2 - 1;
5608 } 6068 }
5609 } 6069 }
5610 pCur->nullRow = 0; 6070 pCur->nullRow = 0;
5611 6071
5612 break; 6072 break;
5613 } 6073 }
5614 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 6074 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5615 6075
5616 #ifndef SQLITE_OMIT_VIRTUALTABLE 6076 #ifndef SQLITE_OMIT_VIRTUALTABLE
5617 /* Opcode: VColumn P1 P2 P3 * * 6077 /* Opcode: VColumn P1 P2 P3 * *
6078 ** Synopsis: r[P3]=vcolumn(P2)
5618 ** 6079 **
5619 ** Store the value of the P2-th column of 6080 ** Store the value of the P2-th column of
5620 ** the row of the virtual-table that the 6081 ** the row of the virtual-table that the
5621 ** P1 cursor is pointing to into register P3. 6082 ** P1 cursor is pointing to into register P3.
5622 */ 6083 */
5623 case OP_VColumn: { 6084 case OP_VColumn: {
5624 sqlite3_vtab *pVtab; 6085 sqlite3_vtab *pVtab;
5625 const sqlite3_module *pModule; 6086 const sqlite3_module *pModule;
5626 Mem *pDest; 6087 Mem *pDest;
5627 sqlite3_context sContext; 6088 sqlite3_context sContext;
5628 6089
5629 VdbeCursor *pCur = p->apCsr[pOp->p1]; 6090 VdbeCursor *pCur = p->apCsr[pOp->p1];
5630 assert( pCur->pVtabCursor ); 6091 assert( pCur->pVtabCursor );
5631 assert( pOp->p3>0 && pOp->p3<=p->nMem ); 6092 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
5632 pDest = &aMem[pOp->p3]; 6093 pDest = &aMem[pOp->p3];
5633 memAboutToChange(p, pDest); 6094 memAboutToChange(p, pDest);
5634 if( pCur->nullRow ){ 6095 if( pCur->nullRow ){
5635 sqlite3VdbeMemSetNull(pDest); 6096 sqlite3VdbeMemSetNull(pDest);
5636 break; 6097 break;
5637 } 6098 }
5638 pVtab = pCur->pVtabCursor->pVtab; 6099 pVtab = pCur->pVtabCursor->pVtab;
5639 pModule = pVtab->pModule; 6100 pModule = pVtab->pModule;
5640 assert( pModule->xColumn ); 6101 assert( pModule->xColumn );
5641 memset(&sContext, 0, sizeof(sContext)); 6102 memset(&sContext, 0, sizeof(sContext));
5642 6103 sContext.pOut = pDest;
5643 /* The output cell may already have a buffer allocated. Move 6104 MemSetTypeFlag(pDest, MEM_Null);
5644 ** the current contents to sContext.s so in case the user-function
5645 ** can use the already allocated buffer instead of allocating a
5646 ** new one.
5647 */
5648 sqlite3VdbeMemMove(&sContext.s, pDest);
5649 MemSetTypeFlag(&sContext.s, MEM_Null);
5650
5651 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2); 6105 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
5652 importVtabErrMsg(p, pVtab); 6106 sqlite3VtabImportErrmsg(p, pVtab);
5653 if( sContext.isError ){ 6107 if( sContext.isError ){
5654 rc = sContext.isError; 6108 rc = sContext.isError;
5655 } 6109 }
5656 6110 sqlite3VdbeChangeEncoding(pDest, encoding);
5657 /* Copy the result of the function to the P3 register. We
5658 ** do this regardless of whether or not an error occurred to ensure any
5659 ** dynamic allocation in sContext.s (a Mem struct) is released.
5660 */
5661 sqlite3VdbeChangeEncoding(&sContext.s, encoding);
5662 sqlite3VdbeMemMove(pDest, &sContext.s);
5663 REGISTER_TRACE(pOp->p3, pDest); 6111 REGISTER_TRACE(pOp->p3, pDest);
5664 UPDATE_MAX_BLOBSIZE(pDest); 6112 UPDATE_MAX_BLOBSIZE(pDest);
5665 6113
5666 if( sqlite3VdbeMemTooBig(pDest) ){ 6114 if( sqlite3VdbeMemTooBig(pDest) ){
5667 goto too_big; 6115 goto too_big;
5668 } 6116 }
5669 break; 6117 break;
5670 } 6118 }
5671 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 6119 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5672 6120
(...skipping 22 matching lines...) Expand all
5695 6143
5696 /* Invoke the xNext() method of the module. There is no way for the 6144 /* Invoke the xNext() method of the module. There is no way for the
5697 ** underlying implementation to return an error if one occurs during 6145 ** underlying implementation to return an error if one occurs during
5698 ** xNext(). Instead, if an error occurs, true is returned (indicating that 6146 ** xNext(). Instead, if an error occurs, true is returned (indicating that
5699 ** data is available) and the error code returned when xColumn or 6147 ** data is available) and the error code returned when xColumn or
5700 ** some other method is next invoked on the save virtual table cursor. 6148 ** some other method is next invoked on the save virtual table cursor.
5701 */ 6149 */
5702 p->inVtabMethod = 1; 6150 p->inVtabMethod = 1;
5703 rc = pModule->xNext(pCur->pVtabCursor); 6151 rc = pModule->xNext(pCur->pVtabCursor);
5704 p->inVtabMethod = 0; 6152 p->inVtabMethod = 0;
5705 importVtabErrMsg(p, pVtab); 6153 sqlite3VtabImportErrmsg(p, pVtab);
5706 if( rc==SQLITE_OK ){ 6154 if( rc==SQLITE_OK ){
5707 res = pModule->xEof(pCur->pVtabCursor); 6155 res = pModule->xEof(pCur->pVtabCursor);
5708 } 6156 }
5709 6157 VdbeBranchTaken(!res,2);
5710 if( !res ){ 6158 if( !res ){
5711 /* If there is data, jump to P2 */ 6159 /* If there is data, jump to P2 */
5712 pc = pOp->p2 - 1; 6160 pc = pOp->p2 - 1;
5713 } 6161 }
5714 break; 6162 goto check_for_interrupt;
5715 } 6163 }
5716 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 6164 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5717 6165
5718 #ifndef SQLITE_OMIT_VIRTUALTABLE 6166 #ifndef SQLITE_OMIT_VIRTUALTABLE
5719 /* Opcode: VRename P1 * * P4 * 6167 /* Opcode: VRename P1 * * P4 *
5720 ** 6168 **
5721 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 6169 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
5722 ** This opcode invokes the corresponding xRename method. The value 6170 ** This opcode invokes the corresponding xRename method. The value
5723 ** in register P1 is passed as the zName argument to the xRename method. 6171 ** in register P1 is passed as the zName argument to the xRename method.
5724 */ 6172 */
5725 case OP_VRename: { 6173 case OP_VRename: {
5726 sqlite3_vtab *pVtab; 6174 sqlite3_vtab *pVtab;
5727 Mem *pName; 6175 Mem *pName;
5728 6176
5729 pVtab = pOp->p4.pVtab->pVtab; 6177 pVtab = pOp->p4.pVtab->pVtab;
5730 pName = &aMem[pOp->p1]; 6178 pName = &aMem[pOp->p1];
5731 assert( pVtab->pModule->xRename ); 6179 assert( pVtab->pModule->xRename );
5732 assert( memIsValid(pName) ); 6180 assert( memIsValid(pName) );
6181 assert( p->readOnly==0 );
5733 REGISTER_TRACE(pOp->p1, pName); 6182 REGISTER_TRACE(pOp->p1, pName);
5734 assert( pName->flags & MEM_Str ); 6183 assert( pName->flags & MEM_Str );
5735 rc = pVtab->pModule->xRename(pVtab, pName->z); 6184 testcase( pName->enc==SQLITE_UTF8 );
5736 importVtabErrMsg(p, pVtab); 6185 testcase( pName->enc==SQLITE_UTF16BE );
5737 p->expired = 0; 6186 testcase( pName->enc==SQLITE_UTF16LE );
5738 6187 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
6188 if( rc==SQLITE_OK ){
6189 rc = pVtab->pModule->xRename(pVtab, pName->z);
6190 sqlite3VtabImportErrmsg(p, pVtab);
6191 p->expired = 0;
6192 }
5739 break; 6193 break;
5740 } 6194 }
5741 #endif 6195 #endif
5742 6196
5743 #ifndef SQLITE_OMIT_VIRTUALTABLE 6197 #ifndef SQLITE_OMIT_VIRTUALTABLE
5744 /* Opcode: VUpdate P1 P2 P3 P4 * 6198 /* Opcode: VUpdate P1 P2 P3 P4 P5
6199 ** Synopsis: data=r[P3@P2]
5745 ** 6200 **
5746 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. 6201 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
5747 ** This opcode invokes the corresponding xUpdate method. P2 values 6202 ** This opcode invokes the corresponding xUpdate method. P2 values
5748 ** are contiguous memory cells starting at P3 to pass to the xUpdate 6203 ** are contiguous memory cells starting at P3 to pass to the xUpdate
5749 ** invocation. The value in register (P3+P2-1) corresponds to the 6204 ** invocation. The value in register (P3+P2-1) corresponds to the
5750 ** p2th element of the argv array passed to xUpdate. 6205 ** p2th element of the argv array passed to xUpdate.
5751 ** 6206 **
5752 ** The xUpdate method will do a DELETE or an INSERT or both. 6207 ** The xUpdate method will do a DELETE or an INSERT or both.
5753 ** The argv[0] element (which corresponds to memory cell P3) 6208 ** The argv[0] element (which corresponds to memory cell P3)
5754 ** is the rowid of a row to delete. If argv[0] is NULL then no 6209 ** is the rowid of a row to delete. If argv[0] is NULL then no
5755 ** deletion occurs. The argv[1] element is the rowid of the new 6210 ** deletion occurs. The argv[1] element is the rowid of the new
5756 ** row. This can be NULL to have the virtual table select the new 6211 ** row. This can be NULL to have the virtual table select the new
5757 ** rowid for itself. The subsequent elements in the array are 6212 ** rowid for itself. The subsequent elements in the array are
5758 ** the values of columns in the new row. 6213 ** the values of columns in the new row.
5759 ** 6214 **
5760 ** If P2==1 then no insert is performed. argv[0] is the rowid of 6215 ** If P2==1 then no insert is performed. argv[0] is the rowid of
5761 ** a row to delete. 6216 ** a row to delete.
5762 ** 6217 **
5763 ** P1 is a boolean flag. If it is set to true and the xUpdate call 6218 ** P1 is a boolean flag. If it is set to true and the xUpdate call
5764 ** is successful, then the value returned by sqlite3_last_insert_rowid() 6219 ** is successful, then the value returned by sqlite3_last_insert_rowid()
5765 ** is set to the value of the rowid for the row just inserted. 6220 ** is set to the value of the rowid for the row just inserted.
6221 **
6222 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
6223 ** apply in the case of a constraint failure on an insert or update.
5766 */ 6224 */
5767 case OP_VUpdate: { 6225 case OP_VUpdate: {
5768 sqlite3_vtab *pVtab; 6226 sqlite3_vtab *pVtab;
5769 sqlite3_module *pModule; 6227 sqlite3_module *pModule;
5770 int nArg; 6228 int nArg;
5771 int i; 6229 int i;
5772 sqlite_int64 rowid; 6230 sqlite_int64 rowid;
5773 Mem **apArg; 6231 Mem **apArg;
5774 Mem *pX; 6232 Mem *pX;
5775 6233
6234 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
6235 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
6236 );
6237 assert( p->readOnly==0 );
5776 pVtab = pOp->p4.pVtab->pVtab; 6238 pVtab = pOp->p4.pVtab->pVtab;
5777 pModule = (sqlite3_module *)pVtab->pModule; 6239 pModule = (sqlite3_module *)pVtab->pModule;
5778 nArg = pOp->p2; 6240 nArg = pOp->p2;
5779 assert( pOp->p4type==P4_VTAB ); 6241 assert( pOp->p4type==P4_VTAB );
5780 if( ALWAYS(pModule->xUpdate) ){ 6242 if( ALWAYS(pModule->xUpdate) ){
6243 u8 vtabOnConflict = db->vtabOnConflict;
5781 apArg = p->apArg; 6244 apArg = p->apArg;
5782 pX = &aMem[pOp->p3]; 6245 pX = &aMem[pOp->p3];
5783 for(i=0; i<nArg; i++){ 6246 for(i=0; i<nArg; i++){
5784 assert( memIsValid(pX) ); 6247 assert( memIsValid(pX) );
5785 memAboutToChange(p, pX); 6248 memAboutToChange(p, pX);
5786 sqlite3VdbeMemStoreType(pX);
5787 apArg[i] = pX; 6249 apArg[i] = pX;
5788 pX++; 6250 pX++;
5789 } 6251 }
6252 db->vtabOnConflict = pOp->p5;
5790 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); 6253 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
5791 importVtabErrMsg(p, pVtab); 6254 db->vtabOnConflict = vtabOnConflict;
6255 sqlite3VtabImportErrmsg(p, pVtab);
5792 if( rc==SQLITE_OK && pOp->p1 ){ 6256 if( rc==SQLITE_OK && pOp->p1 ){
5793 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); 6257 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
5794 db->lastRowid = rowid; 6258 db->lastRowid = lastRowid = rowid;
5795 } 6259 }
5796 p->nChange++; 6260 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
6261 if( pOp->p5==OE_Ignore ){
6262 rc = SQLITE_OK;
6263 }else{
6264 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
6265 }
6266 }else{
6267 p->nChange++;
6268 }
5797 } 6269 }
5798 break; 6270 break;
5799 } 6271 }
5800 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 6272 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5801 6273
5802 #ifndef SQLITE_OMIT_PAGER_PRAGMAS 6274 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
5803 /* Opcode: Pagecount P1 P2 * * * 6275 /* Opcode: Pagecount P1 P2 * * *
5804 ** 6276 **
5805 ** Write the current number of pages in database P1 to memory cell P2. 6277 ** Write the current number of pages in database P1 to memory cell P2.
5806 */ 6278 */
(...skipping 22 matching lines...) Expand all
5829 if( pOp->p3 ){ 6301 if( pOp->p3 ){
5830 newMax = sqlite3BtreeLastPage(pBt); 6302 newMax = sqlite3BtreeLastPage(pBt);
5831 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; 6303 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
5832 } 6304 }
5833 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); 6305 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
5834 break; 6306 break;
5835 } 6307 }
5836 #endif 6308 #endif
5837 6309
5838 6310
5839 #ifndef SQLITE_OMIT_TRACE 6311 /* Opcode: Init * P2 * P4 *
5840 /* Opcode: Trace * * * P4 * 6312 ** Synopsis: Start at P2
6313 **
6314 ** Programs contain a single instance of this opcode as the very first
6315 ** opcode.
5841 ** 6316 **
5842 ** If tracing is enabled (by the sqlite3_trace()) interface, then 6317 ** If tracing is enabled (by the sqlite3_trace()) interface, then
5843 ** the UTF-8 string contained in P4 is emitted on the trace callback. 6318 ** the UTF-8 string contained in P4 is emitted on the trace callback.
6319 ** Or if P4 is blank, use the string returned by sqlite3_sql().
6320 **
6321 ** If P2 is not zero, jump to instruction P2.
5844 */ 6322 */
5845 case OP_Trace: { 6323 case OP_Init: { /* jump */
5846 char *zTrace; 6324 char *zTrace;
6325 char *z;
5847 6326
6327 if( pOp->p2 ){
6328 pc = pOp->p2 - 1;
6329 }
6330 #ifndef SQLITE_OMIT_TRACE
6331 if( db->xTrace
6332 && !p->doingRerun
6333 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
6334 ){
6335 z = sqlite3VdbeExpandSql(p, zTrace);
6336 db->xTrace(db->pTraceArg, z);
6337 sqlite3DbFree(db, z);
6338 }
6339 #ifdef SQLITE_USE_FCNTL_TRACE
5848 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); 6340 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
5849 if( zTrace ){ 6341 if( zTrace ){
5850 if( db->xTrace ){ 6342 int i;
5851 char *z = sqlite3VdbeExpandSql(p, zTrace); 6343 for(i=0; i<db->nDb; i++){
5852 db->xTrace(db->pTraceArg, z); 6344 if( DbMaskTest(p->btreeMask, i)==0 ) continue;
5853 sqlite3DbFree(db, z); 6345 sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
5854 } 6346 }
6347 }
6348 #endif /* SQLITE_USE_FCNTL_TRACE */
5855 #ifdef SQLITE_DEBUG 6349 #ifdef SQLITE_DEBUG
5856 if( (db->flags & SQLITE_SqlTrace)!=0 ){ 6350 if( (db->flags & SQLITE_SqlTrace)!=0
5857 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); 6351 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
5858 } 6352 ){
6353 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
6354 }
5859 #endif /* SQLITE_DEBUG */ 6355 #endif /* SQLITE_DEBUG */
5860 } 6356 #endif /* SQLITE_OMIT_TRACE */
5861 break; 6357 break;
5862 } 6358 }
5863 #endif
5864 6359
5865 6360
5866 /* Opcode: Noop * * * * * 6361 /* Opcode: Noop * * * * *
5867 ** 6362 **
5868 ** Do nothing. This instruction is often useful as a jump 6363 ** Do nothing. This instruction is often useful as a jump
5869 ** destination. 6364 ** destination.
5870 */ 6365 */
5871 /* 6366 /*
5872 ** The magic Explain opcode are only inserted when explain==2 (which 6367 ** The magic Explain opcode are only inserted when explain==2 (which
5873 ** is to say when the EXPLAIN QUERY PLAN syntax is used.) 6368 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
5874 ** This opcode records information from the optimizer. It is the 6369 ** This opcode records information from the optimizer. It is the
5875 ** the same as a no-op. This opcodesnever appears in a real VM program. 6370 ** the same as a no-op. This opcodesnever appears in a real VM program.
5876 */ 6371 */
5877 default: { /* This is really OP_Noop and OP_Explain */ 6372 default: { /* This is really OP_Noop and OP_Explain */
5878 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); 6373 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
5879 break; 6374 break;
5880 } 6375 }
5881 6376
5882 /***************************************************************************** 6377 /*****************************************************************************
5883 ** The cases of the switch statement above this line should all be indented 6378 ** The cases of the switch statement above this line should all be indented
5884 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the 6379 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
5885 ** readability. From this point on down, the normal indentation rules are 6380 ** readability. From this point on down, the normal indentation rules are
5886 ** restored. 6381 ** restored.
5887 *****************************************************************************/ 6382 *****************************************************************************/
5888 } 6383 }
5889 6384
5890 #ifdef VDBE_PROFILE 6385 #ifdef VDBE_PROFILE
5891 { 6386 {
5892 u64 elapsed = sqlite3Hwtime() - start; 6387 u64 endTime = sqlite3Hwtime();
5893 pOp->cycles += elapsed; 6388 if( endTime>start ) pOp->cycles += endTime - start;
5894 pOp->cnt++; 6389 pOp->cnt++;
5895 #if 0
5896 fprintf(stdout, "%10llu ", elapsed);
5897 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
5898 #endif
5899 } 6390 }
5900 #endif 6391 #endif
5901 6392
5902 /* The following code adds nothing to the actual functionality 6393 /* The following code adds nothing to the actual functionality
5903 ** of the program. It is only here for testing and debugging. 6394 ** of the program. It is only here for testing and debugging.
5904 ** On the other hand, it does burn CPU cycles every time through 6395 ** On the other hand, it does burn CPU cycles every time through
5905 ** the evaluator loop. So we can leave it out when NDEBUG is defined. 6396 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
5906 */ 6397 */
5907 #ifndef NDEBUG 6398 #ifndef NDEBUG
5908 assert( pc>=-1 && pc<p->nOp ); 6399 assert( pc>=-1 && pc<p->nOp );
5909 6400
5910 #ifdef SQLITE_DEBUG 6401 #ifdef SQLITE_DEBUG
5911 if( p->trace ){ 6402 if( db->flags & SQLITE_VdbeTrace ){
5912 if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc); 6403 if( rc!=0 ) printf("rc=%d\n",rc);
5913 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){ 6404 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
5914 registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]); 6405 registerTrace(pOp->p2, &aMem[pOp->p2]);
5915 } 6406 }
5916 if( pOp->opflags & OPFLG_OUT3 ){ 6407 if( pOp->opflags & OPFLG_OUT3 ){
5917 registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]); 6408 registerTrace(pOp->p3, &aMem[pOp->p3]);
5918 } 6409 }
5919 } 6410 }
5920 #endif /* SQLITE_DEBUG */ 6411 #endif /* SQLITE_DEBUG */
5921 #endif /* NDEBUG */ 6412 #endif /* NDEBUG */
5922 } /* The end of the for(;;) loop the loops through opcodes */ 6413 } /* The end of the for(;;) loop the loops through opcodes */
5923 6414
5924 /* If we reach this point, it means that execution is finished with 6415 /* If we reach this point, it means that execution is finished with
5925 ** an error of some kind. 6416 ** an error of some kind.
5926 */ 6417 */
5927 vdbe_error_halt: 6418 vdbe_error_halt:
5928 assert( rc ); 6419 assert( rc );
5929 p->rc = rc; 6420 p->rc = rc;
5930 testcase( sqlite3GlobalConfig.xLog!=0 ); 6421 testcase( sqlite3GlobalConfig.xLog!=0 );
5931 sqlite3_log(rc, "statement aborts at %d: [%s] %s", 6422 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
5932 pc, p->zSql, p->zErrMsg); 6423 pc, p->zSql, p->zErrMsg);
5933 sqlite3VdbeHalt(p); 6424 sqlite3VdbeHalt(p);
5934 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1; 6425 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
5935 rc = SQLITE_ERROR; 6426 rc = SQLITE_ERROR;
5936 if( resetSchemaOnFault>0 ){ 6427 if( resetSchemaOnFault>0 ){
5937 sqlite3ResetInternalSchema(db, resetSchemaOnFault-1); 6428 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
5938 } 6429 }
5939 6430
5940 /* This is the only way out of this procedure. We have to 6431 /* This is the only way out of this procedure. We have to
5941 ** release the mutexes on btrees that were acquired at the 6432 ** release the mutexes on btrees that were acquired at the
5942 ** top. */ 6433 ** top. */
5943 vdbe_return: 6434 vdbe_return:
6435 db->lastRowid = lastRowid;
6436 testcase( nVmStep>0 );
6437 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
5944 sqlite3VdbeLeave(p); 6438 sqlite3VdbeLeave(p);
5945 return rc; 6439 return rc;
5946 6440
5947 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH 6441 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
5948 ** is encountered. 6442 ** is encountered.
5949 */ 6443 */
5950 too_big: 6444 too_big:
5951 sqlite3SetString(&p->zErrMsg, db, "string or blob too big"); 6445 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
5952 rc = SQLITE_TOOBIG; 6446 rc = SQLITE_TOOBIG;
5953 goto vdbe_error_halt; 6447 goto vdbe_error_halt;
(...skipping 20 matching lines...) Expand all
5974 /* Jump to here if the sqlite3_interrupt() API sets the interrupt 6468 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
5975 ** flag. 6469 ** flag.
5976 */ 6470 */
5977 abort_due_to_interrupt: 6471 abort_due_to_interrupt:
5978 assert( db->u1.isInterrupted ); 6472 assert( db->u1.isInterrupted );
5979 rc = SQLITE_INTERRUPT; 6473 rc = SQLITE_INTERRUPT;
5980 p->rc = rc; 6474 p->rc = rc;
5981 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc)); 6475 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
5982 goto vdbe_error_halt; 6476 goto vdbe_error_halt;
5983 } 6477 }
OLDNEW
« no previous file with comments | « third_party/sqlite/sqlite-src-3080704/src/vdbe.h ('k') | third_party/sqlite/sqlite-src-3080704/src/vdbeInt.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698