1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** The code in this file implements the function that runs the
13 ** bytecode of a prepared statement.
14 **
15 ** Various scripts scan this source file in order to generate HTML
16 ** documentation, headers files, or other derived files. The formatting
17 ** of the code in this file is, therefore, important. See other comments
18 ** in this file for details. If in doubt, do not deviate from existing
19 ** commenting and indentation practices when changing or adding code.
20 */
21 #include "sqliteInt.h"
22 #include "vdbeInt.h"
23
24 /*
25 ** Invoke this macro on memory cells just prior to changing the
26 ** value of the cell. This macro verifies that shallow copies are
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.
32 */
33 #ifdef SQLITE_DEBUG
34 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
35 #else
36 # define memAboutToChange(P,M)
37 #endif
38
39 /*
40 ** The following global variable is incremented every time a cursor
41 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
42 ** procedures use this information to make sure that indices are
43 ** working correctly. This variable has no function other than to
44 ** help verify the correct operation of the library.
45 */
46 #ifdef SQLITE_TEST
47 int sqlite3_search_count = 0;
48 #endif
49
50 /*
51 ** When this global variable is positive, it gets decremented once before
52 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
53 ** field of the sqlite3 structure is set in order to simulate an interrupt.
54 **
55 ** This facility is used for testing purposes only. It does not function
56 ** in an ordinary build.
57 */
58 #ifdef SQLITE_TEST
59 int sqlite3_interrupt_count = 0;
60 #endif
61
62 /*
63 ** The next global variable is incremented each type the OP_Sort opcode
64 ** is executed. The test procedures use this information to make sure that
65 ** sorting is occurring or not occurring at appropriate times. This variable
66 ** has no function other than to help verify the correct operation of the
67 ** library.
68 */
69 #ifdef SQLITE_TEST
70 int sqlite3_sort_count = 0;
71 #endif
72
73 /*
74 ** The next global variable records the size of the largest MEM_Blob
75 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
76 ** use this information to make sure that the zero-blob functionality
77 ** is working correctly. This variable has no function other than to
78 ** help verify the correct operation of the library.
79 */
80 #ifdef SQLITE_TEST
81 int sqlite3_max_blobsize = 0;
updateMaxBlobsize(Mem * p)82 static void updateMaxBlobsize(Mem *p){
83 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
84 sqlite3_max_blobsize = p->n;
85 }
86 }
87 #endif
88
89 /*
90 ** This macro evaluates to true if either the update hook or the preupdate
91 ** hook are enabled for database connect DB.
92 */
93 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
94 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
95 #else
96 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
97 #endif
98
99 /*
100 ** The next global variable is incremented each time the OP_Found opcode
101 ** is executed. This is used to test whether or not the foreign key
102 ** operation implemented using OP_FkIsZero is working. This variable
103 ** has no function other than to help verify the correct operation of the
104 ** library.
105 */
106 #ifdef SQLITE_TEST
107 int sqlite3_found_count = 0;
108 #endif
109
110 /*
111 ** Test a register to see if it exceeds the current maximum blob size.
112 ** If it does, record the new maximum blob size.
113 */
114 #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
115 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
116 #else
117 # define UPDATE_MAX_BLOBSIZE(P)
118 #endif
119
120 #ifdef SQLITE_DEBUG
121 /* This routine provides a convenient place to set a breakpoint during
122 ** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after
123 ** each opcode is printed. Variables "pc" (program counter) and pOp are
124 ** available to add conditionals to the breakpoint. GDB example:
125 **
126 ** break test_trace_breakpoint if pc=22
127 **
128 ** Other useful labels for breakpoints include:
129 ** test_addop_breakpoint(pc,pOp)
130 ** sqlite3CorruptError(lineno)
131 ** sqlite3MisuseError(lineno)
132 ** sqlite3CantopenError(lineno)
133 */
test_trace_breakpoint(int pc,Op * pOp,Vdbe * v)134 static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
135 static int n = 0;
136 n++;
137 }
138 #endif
139
140 /*
141 ** Invoke the VDBE coverage callback, if that callback is defined. This
142 ** feature is used for test suite validation only and does not appear an
143 ** production builds.
144 **
145 ** M is the type of branch. I is the direction taken for this instance of
146 ** the branch.
147 **
148 ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
149 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
150 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
151 **
152 ** In other words, if M is 2, then I is either 0 (for fall-through) or
153 ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
154 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
155 ** if the result of comparison is NULL. For M=3, I=2 the jump may or
156 ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
157 ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
158 ** depending on if the operands are less than, equal, or greater than.
159 **
160 ** iSrcLine is the source code line (from the __LINE__ macro) that
161 ** generated the VDBE instruction combined with flag bits. The source
162 ** code line number is in the lower 24 bits of iSrcLine and the upper
163 ** 8 bytes are flags. The lower three bits of the flags indicate
164 ** values for I that should never occur. For example, if the branch is
165 ** always taken, the flags should be 0x05 since the fall-through and
166 ** alternate branch are never taken. If a branch is never taken then
167 ** flags should be 0x06 since only the fall-through approach is allowed.
168 **
169 ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
170 ** interested in equal or not-equal. In other words, I==0 and I==2
171 ** should be treated as equivalent
172 **
173 ** Since only a line number is retained, not the filename, this macro
174 ** only works for amalgamation builds. But that is ok, since these macros
175 ** should be no-ops except for special builds used to measure test coverage.
176 */
177 #if !defined(SQLITE_VDBE_COVERAGE)
178 # define VdbeBranchTaken(I,M)
179 #else
180 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
vdbeTakeBranch(u32 iSrcLine,u8 I,u8 M)181 static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
182 u8 mNever;
183 assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
184 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
185 assert( I<M ); /* I can only be 2 if M is 3 or 4 */
186 /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
187 I = 1<<I;
188 /* The upper 8 bits of iSrcLine are flags. The lower three bits of
189 ** the flags indicate directions that the branch can never go. If
190 ** a branch really does go in one of those directions, assert right
191 ** away. */
192 mNever = iSrcLine >> 24;
193 assert( (I & mNever)==0 );
194 if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
195 /* Invoke the branch coverage callback with three arguments:
196 ** iSrcLine - the line number of the VdbeCoverage() macro, with
197 ** flags removed.
198 ** I - Mask of bits 0x07 indicating which cases are are
199 ** fulfilled by this instance of the jump. 0x01 means
200 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
201 ** impossible cases (ex: if the comparison is never NULL)
202 ** are filled in automatically so that the coverage
203 ** measurement logic does not flag those impossible cases
204 ** as missed coverage.
205 ** M - Type of jump. Same as M argument above
206 */
207 I |= mNever;
208 if( M==2 ) I |= 0x04;
209 if( M==4 ){
210 I |= 0x08;
211 if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
212 }
213 sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
214 iSrcLine&0xffffff, I, M);
215 }
216 #endif
217
218 /*
219 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
220 ** a pointer to a dynamically allocated string where some other entity
221 ** is responsible for deallocating that string. Because the register
222 ** does not control the string, it might be deleted without the register
223 ** knowing it.
224 **
225 ** This routine converts an ephemeral string into a dynamically allocated
226 ** string that the register itself controls. In other words, it
227 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
228 */
229 #define Deephemeralize(P) \
230 if( ((P)->flags&MEM_Ephem)!=0 \
231 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
232
233 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
234 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
235
236 /*
237 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
238 ** if we run out of memory.
239 */
allocateCursor(Vdbe * p,int iCur,int nField,int iDb,u8 eCurType)240 static VdbeCursor *allocateCursor(
241 Vdbe *p, /* The virtual machine */
242 int iCur, /* Index of the new VdbeCursor */
243 int nField, /* Number of fields in the table or index */
244 int iDb, /* Database the cursor belongs to, or -1 */
245 u8 eCurType /* Type of the new cursor */
246 ){
247 /* Find the memory cell that will be used to store the blob of memory
248 ** required for this VdbeCursor structure. It is convenient to use a
249 ** vdbe memory cell to manage the memory allocation required for a
250 ** VdbeCursor structure for the following reasons:
251 **
252 ** * Sometimes cursor numbers are used for a couple of different
253 ** purposes in a vdbe program. The different uses might require
254 ** different sized allocations. Memory cells provide growable
255 ** allocations.
256 **
257 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
258 ** be freed lazily via the sqlite3_release_memory() API. This
259 ** minimizes the number of malloc calls made by the system.
260 **
261 ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
262 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
263 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
264 */
265 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
266
267 int nByte;
268 VdbeCursor *pCx = 0;
269 nByte =
270 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
271 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
272
273 assert( iCur>=0 && iCur<p->nCursor );
274 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
275 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
276 p->apCsr[iCur] = 0;
277 }
278 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
279 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
280 memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
281 pCx->eCurType = eCurType;
282 pCx->iDb = iDb;
283 pCx->nField = nField;
284 pCx->aOffset = &pCx->aType[nField];
285 if( eCurType==CURTYPE_BTREE ){
286 pCx->uc.pCursor = (BtCursor*)
287 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
288 sqlite3BtreeCursorZero(pCx->uc.pCursor);
289 }
290 }
291 return pCx;
292 }
293
294 /*
295 ** The string in pRec is known to look like an integer and to have a
296 ** floating point value of rValue. Return true and set *piValue to the
297 ** integer value if the string is in range to be an integer. Otherwise,
298 ** return false.
299 */
alsoAnInt(Mem * pRec,double rValue,i64 * piValue)300 static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
301 i64 iValue = (double)rValue;
302 if( sqlite3RealSameAsInt(rValue,iValue) ){
303 *piValue = iValue;
304 return 1;
305 }
306 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
307 }
308
309 /*
310 ** Try to convert a value into a numeric representation if we can
311 ** do so without loss of information. In other words, if the string
312 ** looks like a number, convert it into a number. If it does not
313 ** look like a number, leave it alone.
314 **
315 ** If the bTryForInt flag is true, then extra effort is made to give
316 ** an integer representation. Strings that look like floating point
317 ** values but which have no fractional component (example: '48.00')
318 ** will have a MEM_Int representation when bTryForInt is true.
319 **
320 ** If bTryForInt is false, then if the input string contains a decimal
321 ** point or exponential notation, the result is only MEM_Real, even
322 ** if there is an exact integer representation of the quantity.
323 */
applyNumericAffinity(Mem * pRec,int bTryForInt)324 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
325 double rValue;
326 u8 enc = pRec->enc;
327 int rc;
328 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
329 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
330 if( rc<=0 ) return;
331 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
332 pRec->flags |= MEM_Int;
333 }else{
334 pRec->u.r = rValue;
335 pRec->flags |= MEM_Real;
336 if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
337 }
338 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
339 ** string representation after computing a numeric equivalent, because the
340 ** string representation might not be the canonical representation for the
341 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
342 pRec->flags &= ~MEM_Str;
343 }
344
345 /*
346 ** Processing is determine by the affinity parameter:
347 **
348 ** SQLITE_AFF_INTEGER:
349 ** SQLITE_AFF_REAL:
350 ** SQLITE_AFF_NUMERIC:
351 ** Try to convert pRec to an integer representation or a
352 ** floating-point representation if an integer representation
353 ** is not possible. Note that the integer representation is
354 ** always preferred, even if the affinity is REAL, because
355 ** an integer representation is more space efficient on disk.
356 **
357 ** SQLITE_AFF_TEXT:
358 ** Convert pRec to a text representation.
359 **
360 ** SQLITE_AFF_BLOB:
361 ** SQLITE_AFF_NONE:
362 ** No-op. pRec is unchanged.
363 */
applyAffinity(Mem * pRec,char affinity,u8 enc)364 static void applyAffinity(
365 Mem *pRec, /* The value to apply affinity to */
366 char affinity, /* The affinity to be applied */
367 u8 enc /* Use this text encoding */
368 ){
369 if( affinity>=SQLITE_AFF_NUMERIC ){
370 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
371 || affinity==SQLITE_AFF_NUMERIC );
372 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
373 if( (pRec->flags & MEM_Real)==0 ){
374 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
375 }else{
376 sqlite3VdbeIntegerAffinity(pRec);
377 }
378 }
379 }else if( affinity==SQLITE_AFF_TEXT ){
380 /* Only attempt the conversion to TEXT if there is an integer or real
381 ** representation (blob and NULL do not get converted) but no string
382 ** representation. It would be harmless to repeat the conversion if
383 ** there is already a string rep, but it is pointless to waste those
384 ** CPU cycles. */
385 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
386 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
387 testcase( pRec->flags & MEM_Int );
388 testcase( pRec->flags & MEM_Real );
389 testcase( pRec->flags & MEM_IntReal );
390 sqlite3VdbeMemStringify(pRec, enc, 1);
391 }
392 }
393 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
394 }
395 }
396
397 /*
398 ** Try to convert the type of a function argument or a result column
399 ** into a numeric representation. Use either INTEGER or REAL whichever
400 ** is appropriate. But only do the conversion if it is possible without
401 ** loss of information and return the revised type of the argument.
402 */
sqlite3_value_numeric_type(sqlite3_value * pVal)403 int sqlite3_value_numeric_type(sqlite3_value *pVal){
404 int eType = sqlite3_value_type(pVal);
405 if( eType==SQLITE_TEXT ){
406 Mem *pMem = (Mem*)pVal;
407 applyNumericAffinity(pMem, 0);
408 eType = sqlite3_value_type(pVal);
409 }
410 return eType;
411 }
412
413 /*
414 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
415 ** not the internal Mem* type.
416 */
sqlite3ValueApplyAffinity(sqlite3_value * pVal,u8 affinity,u8 enc)417 void sqlite3ValueApplyAffinity(
418 sqlite3_value *pVal,
419 u8 affinity,
420 u8 enc
421 ){
422 applyAffinity((Mem *)pVal, affinity, enc);
423 }
424
425 /*
426 ** pMem currently only holds a string type (or maybe a BLOB that we can
427 ** interpret as a string if we want to). Compute its corresponding
428 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
429 ** accordingly.
430 */
computeNumericType(Mem * pMem)431 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
432 int rc;
433 sqlite3_int64 ix;
434 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
435 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
436 ExpandBlob(pMem);
437 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
438 if( rc<=0 ){
439 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
440 pMem->u.i = ix;
441 return MEM_Int;
442 }else{
443 return MEM_Real;
444 }
445 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
446 pMem->u.i = ix;
447 return MEM_Int;
448 }
449 return MEM_Real;
450 }
451
452 /*
453 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
454 ** none.
455 **
456 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
457 ** But it does set pMem->u.r and pMem->u.i appropriately.
458 */
numericType(Mem * pMem)459 static u16 numericType(Mem *pMem){
460 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){
461 testcase( pMem->flags & MEM_Int );
462 testcase( pMem->flags & MEM_Real );
463 testcase( pMem->flags & MEM_IntReal );
464 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal);
465 }
466 if( pMem->flags & (MEM_Str|MEM_Blob) ){
467 testcase( pMem->flags & MEM_Str );
468 testcase( pMem->flags & MEM_Blob );
469 return computeNumericType(pMem);
470 }
471 return 0;
472 }
473
474 #ifdef SQLITE_DEBUG
475 /*
476 ** Write a nice string representation of the contents of cell pMem
477 ** into buffer zBuf, length nBuf.
478 */
sqlite3VdbeMemPrettyPrint(Mem * pMem,StrAccum * pStr)479 void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
480 int f = pMem->flags;
481 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
482 if( f&MEM_Blob ){
483 int i;
484 char c;
485 if( f & MEM_Dyn ){
486 c = 'z';
487 assert( (f & (MEM_Static|MEM_Ephem))==0 );
488 }else if( f & MEM_Static ){
489 c = 't';
490 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
491 }else if( f & MEM_Ephem ){
492 c = 'e';
493 assert( (f & (MEM_Static|MEM_Dyn))==0 );
494 }else{
495 c = 's';
496 }
497 sqlite3_str_appendf(pStr, "%cx[", c);
498 for(i=0; i<25 && i<pMem->n; i++){
499 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
500 }
501 sqlite3_str_appendf(pStr, "|");
502 for(i=0; i<25 && i<pMem->n; i++){
503 char z = pMem->z[i];
504 sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
505 }
506 sqlite3_str_appendf(pStr,"]");
507 if( f & MEM_Zero ){
508 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
509 }
510 }else if( f & MEM_Str ){
511 int j;
512 u8 c;
513 if( f & MEM_Dyn ){
514 c = 'z';
515 assert( (f & (MEM_Static|MEM_Ephem))==0 );
516 }else if( f & MEM_Static ){
517 c = 't';
518 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
519 }else if( f & MEM_Ephem ){
520 c = 'e';
521 assert( (f & (MEM_Static|MEM_Dyn))==0 );
522 }else{
523 c = 's';
524 }
525 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
526 for(j=0; j<25 && j<pMem->n; j++){
527 c = pMem->z[j];
528 sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
529 }
530 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
531 }
532 }
533 #endif
534
535 #ifdef SQLITE_DEBUG
536 /*
537 ** Print the value of a register for tracing purposes:
538 */
memTracePrint(Mem * p)539 static void memTracePrint(Mem *p){
540 if( p->flags & MEM_Undefined ){
541 printf(" undefined");
542 }else if( p->flags & MEM_Null ){
543 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
544 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
545 printf(" si:%lld", p->u.i);
546 }else if( (p->flags & (MEM_IntReal))!=0 ){
547 printf(" ir:%lld", p->u.i);
548 }else if( p->flags & MEM_Int ){
549 printf(" i:%lld", p->u.i);
550 #ifndef SQLITE_OMIT_FLOATING_POINT
551 }else if( p->flags & MEM_Real ){
552 printf(" r:%.17g", p->u.r);
553 #endif
554 }else if( sqlite3VdbeMemIsRowSet(p) ){
555 printf(" (rowset)");
556 }else{
557 StrAccum acc;
558 char zBuf[1000];
559 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
560 sqlite3VdbeMemPrettyPrint(p, &acc);
561 printf(" %s", sqlite3StrAccumFinish(&acc));
562 }
563 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
564 }
registerTrace(int iReg,Mem * p)565 static void registerTrace(int iReg, Mem *p){
566 printf("R[%d] = ", iReg);
567 memTracePrint(p);
568 if( p->pScopyFrom ){
569 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
570 }
571 printf("\n");
572 sqlite3VdbeCheckMemInvariants(p);
573 }
574 #endif
575
576 #ifdef SQLITE_DEBUG
577 /*
578 ** Show the values of all registers in the virtual machine. Used for
579 ** interactive debugging.
580 */
sqlite3VdbeRegisterDump(Vdbe * v)581 void sqlite3VdbeRegisterDump(Vdbe *v){
582 int i;
583 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
584 }
585 #endif /* SQLITE_DEBUG */
586
587
588 #ifdef SQLITE_DEBUG
589 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
590 #else
591 # define REGISTER_TRACE(R,M)
592 #endif
593
594
595 #ifdef VDBE_PROFILE
596
597 /*
598 ** hwtime.h contains inline assembler code for implementing
599 ** high-performance timing routines.
600 */
601 #include "hwtime.h"
602
603 #endif
604
605 #ifndef NDEBUG
606 /*
607 ** This function is only called from within an assert() expression. It
608 ** checks that the sqlite3.nTransaction variable is correctly set to
609 ** the number of non-transaction savepoints currently in the
610 ** linked list starting at sqlite3.pSavepoint.
611 **
612 ** Usage:
613 **
614 ** assert( checkSavepointCount(db) );
615 */
checkSavepointCount(sqlite3 * db)616 static int checkSavepointCount(sqlite3 *db){
617 int n = 0;
618 Savepoint *p;
619 for(p=db->pSavepoint; p; p=p->pNext) n++;
620 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
621 return 1;
622 }
623 #endif
624
625 /*
626 ** Return the register of pOp->p2 after first preparing it to be
627 ** overwritten with an integer value.
628 */
out2PrereleaseWithClear(Mem * pOut)629 static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
630 sqlite3VdbeMemSetNull(pOut);
631 pOut->flags = MEM_Int;
632 return pOut;
633 }
out2Prerelease(Vdbe * p,VdbeOp * pOp)634 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
635 Mem *pOut;
636 assert( pOp->p2>0 );
637 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
638 pOut = &p->aMem[pOp->p2];
639 memAboutToChange(p, pOut);
640 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
641 return out2PrereleaseWithClear(pOut);
642 }else{
643 pOut->flags = MEM_Int;
644 return pOut;
645 }
646 }
647
648
649 /*
650 ** Execute as much of a VDBE program as we can.
651 ** This is the core of sqlite3_step().
652 */
sqlite3VdbeExec(Vdbe * p)653 int sqlite3VdbeExec(
654 Vdbe *p /* The VDBE */
655 ){
656 Op *aOp = p->aOp; /* Copy of p->aOp */
657 Op *pOp = aOp; /* Current operation */
658 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
659 Op *pOrigOp; /* Value of pOp at the top of the loop */
660 #endif
661 #ifdef SQLITE_DEBUG
662 int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
663 #endif
664 int rc = SQLITE_OK; /* Value to return */
665 sqlite3 *db = p->db; /* The database */
666 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
667 u8 encoding = ENC(db); /* The database encoding */
668 int iCompare = 0; /* Result of last comparison */
669 u64 nVmStep = 0; /* Number of virtual machine steps */
670 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
671 u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
672 #endif
673 Mem *aMem = p->aMem; /* Copy of p->aMem */
674 Mem *pIn1 = 0; /* 1st input operand */
675 Mem *pIn2 = 0; /* 2nd input operand */
676 Mem *pIn3 = 0; /* 3rd input operand */
677 Mem *pOut = 0; /* Output operand */
678 #ifdef VDBE_PROFILE
679 u64 start; /* CPU clock count at start of opcode */
680 #endif
681 /*** INSERT STACK UNION HERE ***/
682
683 assert( p->iVdbeMagic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
684 sqlite3VdbeEnter(p);
685 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
686 if( db->xProgress ){
687 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
688 assert( 0 < db->nProgressOps );
689 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
690 }else{
691 nProgressLimit = LARGEST_UINT64;
692 }
693 #endif
694 if( p->rc==SQLITE_NOMEM ){
695 /* This happens if a malloc() inside a call to sqlite3_column_text() or
696 ** sqlite3_column_text16() failed. */
697 goto no_mem;
698 }
699 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
700 testcase( p->rc!=SQLITE_OK );
701 p->rc = SQLITE_OK;
702 assert( p->bIsReader || p->readOnly!=0 );
703 p->iCurrentTime = 0;
704 assert( p->explain==0 );
705 p->pResultSet = 0;
706 db->busyHandler.nBusy = 0;
707 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
708 sqlite3VdbeIOTraceSql(p);
709 #ifdef SQLITE_DEBUG
710 sqlite3BeginBenignMalloc();
711 if( p->pc==0
712 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
713 ){
714 int i;
715 int once = 1;
716 sqlite3VdbePrintSql(p);
717 if( p->db->flags & SQLITE_VdbeListing ){
718 printf("VDBE Program Listing:\n");
719 for(i=0; i<p->nOp; i++){
720 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
721 }
722 }
723 if( p->db->flags & SQLITE_VdbeEQP ){
724 for(i=0; i<p->nOp; i++){
725 if( aOp[i].opcode==OP_Explain ){
726 if( once ) printf("VDBE Query Plan:\n");
727 printf("%s\n", aOp[i].p4.z);
728 once = 0;
729 }
730 }
731 }
732 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
733 }
734 sqlite3EndBenignMalloc();
735 #endif
736 for(pOp=&aOp[p->pc]; 1; pOp++){
737 /* Errors are detected by individual opcodes, with an immediate
738 ** jumps to abort_due_to_error. */
739 assert( rc==SQLITE_OK );
740
741 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
742 #ifdef VDBE_PROFILE
743 start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
744 #endif
745 nVmStep++;
746 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
747 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
748 #endif
749
750 /* Only allow tracing if SQLITE_DEBUG is defined.
751 */
752 #ifdef SQLITE_DEBUG
753 if( db->flags & SQLITE_VdbeTrace ){
754 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
755 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
756 }
757 #endif
758
759
760 /* Check to see if we need to simulate an interrupt. This only happens
761 ** if we have a special test build.
762 */
763 #ifdef SQLITE_TEST
764 if( sqlite3_interrupt_count>0 ){
765 sqlite3_interrupt_count--;
766 if( sqlite3_interrupt_count==0 ){
767 sqlite3_interrupt(db);
768 }
769 }
770 #endif
771
772 /* Sanity checking on other operands */
773 #ifdef SQLITE_DEBUG
774 {
775 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
776 if( (opProperty & OPFLG_IN1)!=0 ){
777 assert( pOp->p1>0 );
778 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
779 assert( memIsValid(&aMem[pOp->p1]) );
780 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
781 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
782 }
783 if( (opProperty & OPFLG_IN2)!=0 ){
784 assert( pOp->p2>0 );
785 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
786 assert( memIsValid(&aMem[pOp->p2]) );
787 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
788 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
789 }
790 if( (opProperty & OPFLG_IN3)!=0 ){
791 assert( pOp->p3>0 );
792 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
793 assert( memIsValid(&aMem[pOp->p3]) );
794 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
795 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
796 }
797 if( (opProperty & OPFLG_OUT2)!=0 ){
798 assert( pOp->p2>0 );
799 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
800 memAboutToChange(p, &aMem[pOp->p2]);
801 }
802 if( (opProperty & OPFLG_OUT3)!=0 ){
803 assert( pOp->p3>0 );
804 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
805 memAboutToChange(p, &aMem[pOp->p3]);
806 }
807 }
808 #endif
809 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
810 pOrigOp = pOp;
811 #endif
812
813 switch( pOp->opcode ){
814
815 /*****************************************************************************
816 ** What follows is a massive switch statement where each case implements a
817 ** separate instruction in the virtual machine. If we follow the usual
818 ** indentation conventions, each case should be indented by 6 spaces. But
819 ** that is a lot of wasted space on the left margin. So the code within
820 ** the switch statement will break with convention and be flush-left. Another
821 ** big comment (similar to this one) will mark the point in the code where
822 ** we transition back to normal indentation.
823 **
824 ** The formatting of each case is important. The makefile for SQLite
825 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
826 ** file looking for lines that begin with "case OP_". The opcodes.h files
827 ** will be filled with #defines that give unique integer values to each
828 ** opcode and the opcodes.c file is filled with an array of strings where
829 ** each string is the symbolic name for the corresponding opcode. If the
830 ** case statement is followed by a comment of the form "/# same as ... #/"
831 ** that comment is used to determine the particular value of the opcode.
832 **
833 ** Other keywords in the comment that follows each case are used to
834 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
835 ** Keywords include: in1, in2, in3, out2, out3. See
836 ** the mkopcodeh.awk script for additional information.
837 **
838 ** Documentation about VDBE opcodes is generated by scanning this file
839 ** for lines of that contain "Opcode:". That line and all subsequent
840 ** comment lines are used in the generation of the opcode.html documentation
841 ** file.
842 **
843 ** SUMMARY:
844 **
845 ** Formatting is important to scripts that scan this file.
846 ** Do not deviate from the formatting style currently in use.
847 **
848 *****************************************************************************/
849
850 /* Opcode: Goto * P2 * * *
851 **
852 ** An unconditional jump to address P2.
853 ** The next instruction executed will be
854 ** the one at index P2 from the beginning of
855 ** the program.
856 **
857 ** The P1 parameter is not actually used by this opcode. However, it
858 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
859 ** that this Goto is the bottom of a loop and that the lines from P2 down
860 ** to the current line should be indented for EXPLAIN output.
861 */
862 case OP_Goto: { /* jump */
863
864 #ifdef SQLITE_DEBUG
865 /* In debuggging mode, when the p5 flags is set on an OP_Goto, that
866 ** means we should really jump back to the preceeding OP_ReleaseReg
867 ** instruction. */
868 if( pOp->p5 ){
869 assert( pOp->p2 < (int)(pOp - aOp) );
870 assert( pOp->p2 > 1 );
871 pOp = &aOp[pOp->p2 - 2];
872 assert( pOp[1].opcode==OP_ReleaseReg );
873 goto check_for_interrupt;
874 }
875 #endif
876
877 jump_to_p2_and_check_for_interrupt:
878 pOp = &aOp[pOp->p2 - 1];
879
880 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
881 ** OP_VNext, or OP_SorterNext) all jump here upon
882 ** completion. Check to see if sqlite3_interrupt() has been called
883 ** or if the progress callback needs to be invoked.
884 **
885 ** This code uses unstructured "goto" statements and does not look clean.
886 ** But that is not due to sloppy coding habits. The code is written this
887 ** way for performance, to avoid having to run the interrupt and progress
888 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
889 ** faster according to "valgrind --tool=cachegrind" */
890 check_for_interrupt:
891 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
892 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
893 /* Call the progress callback if it is configured and the required number
894 ** of VDBE ops have been executed (either since this invocation of
895 ** sqlite3VdbeExec() or since last time the progress callback was called).
896 ** If the progress callback returns non-zero, exit the virtual machine with
897 ** a return code SQLITE_ABORT.
898 */
899 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
900 assert( db->nProgressOps!=0 );
901 nProgressLimit += db->nProgressOps;
902 if( db->xProgress(db->pProgressArg) ){
903 nProgressLimit = LARGEST_UINT64;
904 rc = SQLITE_INTERRUPT;
905 goto abort_due_to_error;
906 }
907 }
908 #endif
909
910 break;
911 }
912
913 /* Opcode: Gosub P1 P2 * * *
914 **
915 ** Write the current address onto register P1
916 ** and then jump to address P2.
917 */
918 case OP_Gosub: { /* jump */
919 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
920 pIn1 = &aMem[pOp->p1];
921 assert( VdbeMemDynamic(pIn1)==0 );
922 memAboutToChange(p, pIn1);
923 pIn1->flags = MEM_Int;
924 pIn1->u.i = (int)(pOp-aOp);
925 REGISTER_TRACE(pOp->p1, pIn1);
926
927 /* Most jump operations do a goto to this spot in order to update
928 ** the pOp pointer. */
929 jump_to_p2:
930 pOp = &aOp[pOp->p2 - 1];
931 break;
932 }
933
934 /* Opcode: Return P1 * * * *
935 **
936 ** Jump to the next instruction after the address in register P1. After
937 ** the jump, register P1 becomes undefined.
938 */
939 case OP_Return: { /* in1 */
940 pIn1 = &aMem[pOp->p1];
941 assert( pIn1->flags==MEM_Int );
942 pOp = &aOp[pIn1->u.i];
943 pIn1->flags = MEM_Undefined;
944 break;
945 }
946
947 /* Opcode: InitCoroutine P1 P2 P3 * *
948 **
949 ** Set up register P1 so that it will Yield to the coroutine
950 ** located at address P3.
951 **
952 ** If P2!=0 then the coroutine implementation immediately follows
953 ** this opcode. So jump over the coroutine implementation to
954 ** address P2.
955 **
956 ** See also: EndCoroutine
957 */
958 case OP_InitCoroutine: { /* jump */
959 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
960 assert( pOp->p2>=0 && pOp->p2<p->nOp );
961 assert( pOp->p3>=0 && pOp->p3<p->nOp );
962 pOut = &aMem[pOp->p1];
963 assert( !VdbeMemDynamic(pOut) );
964 pOut->u.i = pOp->p3 - 1;
965 pOut->flags = MEM_Int;
966 if( pOp->p2 ) goto jump_to_p2;
967 break;
968 }
969
970 /* Opcode: EndCoroutine P1 * * * *
971 **
972 ** The instruction at the address in register P1 is a Yield.
973 ** Jump to the P2 parameter of that Yield.
974 ** After the jump, register P1 becomes undefined.
975 **
976 ** See also: InitCoroutine
977 */
978 case OP_EndCoroutine: { /* in1 */
979 VdbeOp *pCaller;
980 pIn1 = &aMem[pOp->p1];
981 assert( pIn1->flags==MEM_Int );
982 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
983 pCaller = &aOp[pIn1->u.i];
984 assert( pCaller->opcode==OP_Yield );
985 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
986 pOp = &aOp[pCaller->p2 - 1];
987 pIn1->flags = MEM_Undefined;
988 break;
989 }
990
991 /* Opcode: Yield P1 P2 * * *
992 **
993 ** Swap the program counter with the value in register P1. This
994 ** has the effect of yielding to a coroutine.
995 **
996 ** If the coroutine that is launched by this instruction ends with
997 ** Yield or Return then continue to the next instruction. But if
998 ** the coroutine launched by this instruction ends with
999 ** EndCoroutine, then jump to P2 rather than continuing with the
1000 ** next instruction.
1001 **
1002 ** See also: InitCoroutine
1003 */
1004 case OP_Yield: { /* in1, jump */
1005 int pcDest;
1006 pIn1 = &aMem[pOp->p1];
1007 assert( VdbeMemDynamic(pIn1)==0 );
1008 pIn1->flags = MEM_Int;
1009 pcDest = (int)pIn1->u.i;
1010 pIn1->u.i = (int)(pOp - aOp);
1011 REGISTER_TRACE(pOp->p1, pIn1);
1012 pOp = &aOp[pcDest];
1013 break;
1014 }
1015
1016 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
1017 ** Synopsis: if r[P3]=null halt
1018 **
1019 ** Check the value in register P3. If it is NULL then Halt using
1020 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
1021 ** value in register P3 is not NULL, then this routine is a no-op.
1022 ** The P5 parameter should be 1.
1023 */
1024 case OP_HaltIfNull: { /* in3 */
1025 pIn3 = &aMem[pOp->p3];
1026 #ifdef SQLITE_DEBUG
1027 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1028 #endif
1029 if( (pIn3->flags & MEM_Null)==0 ) break;
1030 /* Fall through into OP_Halt */
1031 /* no break */ deliberate_fall_through
1032 }
1033
1034 /* Opcode: Halt P1 P2 * P4 P5
1035 **
1036 ** Exit immediately. All open cursors, etc are closed
1037 ** automatically.
1038 **
1039 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
1040 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
1041 ** For errors, it can be some other value. If P1!=0 then P2 will determine
1042 ** whether or not to rollback the current transaction. Do not rollback
1043 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
1044 ** then back out all changes that have occurred during this execution of the
1045 ** VDBE, but do not rollback the transaction.
1046 **
1047 ** If P4 is not null then it is an error message string.
1048 **
1049 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
1050 **
1051 ** 0: (no change)
1052 ** 1: NOT NULL contraint failed: P4
1053 ** 2: UNIQUE constraint failed: P4
1054 ** 3: CHECK constraint failed: P4
1055 ** 4: FOREIGN KEY constraint failed: P4
1056 **
1057 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
1058 ** omitted.
1059 **
1060 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1061 ** every program. So a jump past the last instruction of the program
1062 ** is the same as executing Halt.
1063 */
1064 case OP_Halt: {
1065 VdbeFrame *pFrame;
1066 int pcx;
1067
1068 pcx = (int)(pOp - aOp);
1069 #ifdef SQLITE_DEBUG
1070 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
1071 #endif
1072 if( pOp->p1==SQLITE_OK && p->pFrame ){
1073 /* Halt the sub-program. Return control to the parent frame. */
1074 pFrame = p->pFrame;
1075 p->pFrame = pFrame->pParent;
1076 p->nFrame--;
1077 sqlite3VdbeSetChanges(db, p->nChange);
1078 pcx = sqlite3VdbeFrameRestore(pFrame);
1079 if( pOp->p2==OE_Ignore ){
1080 /* Instruction pcx is the OP_Program that invoked the sub-program
1081 ** currently being halted. If the p2 instruction of this OP_Halt
1082 ** instruction is set to OE_Ignore, then the sub-program is throwing
1083 ** an IGNORE exception. In this case jump to the address specified
1084 ** as the p2 of the calling OP_Program. */
1085 pcx = p->aOp[pcx].p2-1;
1086 }
1087 aOp = p->aOp;
1088 aMem = p->aMem;
1089 pOp = &aOp[pcx];
1090 break;
1091 }
1092 p->rc = pOp->p1;
1093 p->errorAction = (u8)pOp->p2;
1094 p->pc = pcx;
1095 assert( pOp->p5<=4 );
1096 if( p->rc ){
1097 if( pOp->p5 ){
1098 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
1099 "FOREIGN KEY" };
1100 testcase( pOp->p5==1 );
1101 testcase( pOp->p5==2 );
1102 testcase( pOp->p5==3 );
1103 testcase( pOp->p5==4 );
1104 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
1105 if( pOp->p4.z ){
1106 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
1107 }
1108 }else{
1109 sqlite3VdbeError(p, "%s", pOp->p4.z);
1110 }
1111 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
1112 }
1113 rc = sqlite3VdbeHalt(p);
1114 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
1115 if( rc==SQLITE_BUSY ){
1116 p->rc = SQLITE_BUSY;
1117 }else{
1118 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
1119 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
1120 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
1121 }
1122 goto vdbe_return;
1123 }
1124
1125 /* Opcode: Integer P1 P2 * * *
1126 ** Synopsis: r[P2]=P1
1127 **
1128 ** The 32-bit integer value P1 is written into register P2.
1129 */
1130 case OP_Integer: { /* out2 */
1131 pOut = out2Prerelease(p, pOp);
1132 pOut->u.i = pOp->p1;
1133 break;
1134 }
1135
1136 /* Opcode: Int64 * P2 * P4 *
1137 ** Synopsis: r[P2]=P4
1138 **
1139 ** P4 is a pointer to a 64-bit integer value.
1140 ** Write that value into register P2.
1141 */
1142 case OP_Int64: { /* out2 */
1143 pOut = out2Prerelease(p, pOp);
1144 assert( pOp->p4.pI64!=0 );
1145 pOut->u.i = *pOp->p4.pI64;
1146 break;
1147 }
1148
1149 #ifndef SQLITE_OMIT_FLOATING_POINT
1150 /* Opcode: Real * P2 * P4 *
1151 ** Synopsis: r[P2]=P4
1152 **
1153 ** P4 is a pointer to a 64-bit floating point value.
1154 ** Write that value into register P2.
1155 */
1156 case OP_Real: { /* same as TK_FLOAT, out2 */
1157 pOut = out2Prerelease(p, pOp);
1158 pOut->flags = MEM_Real;
1159 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
1160 pOut->u.r = *pOp->p4.pReal;
1161 break;
1162 }
1163 #endif
1164
1165 /* Opcode: String8 * P2 * P4 *
1166 ** Synopsis: r[P2]='P4'
1167 **
1168 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
1169 ** into a String opcode before it is executed for the first time. During
1170 ** this transformation, the length of string P4 is computed and stored
1171 ** as the P1 parameter.
1172 */
1173 case OP_String8: { /* same as TK_STRING, out2 */
1174 assert( pOp->p4.z!=0 );
1175 pOut = out2Prerelease(p, pOp);
1176 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
1177
1178 #ifndef SQLITE_OMIT_UTF16
1179 if( encoding!=SQLITE_UTF8 ){
1180 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
1181 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
1182 if( rc ) goto too_big;
1183 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
1184 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
1185 assert( VdbeMemDynamic(pOut)==0 );
1186 pOut->szMalloc = 0;
1187 pOut->flags |= MEM_Static;
1188 if( pOp->p4type==P4_DYNAMIC ){
1189 sqlite3DbFree(db, pOp->p4.z);
1190 }
1191 pOp->p4type = P4_DYNAMIC;
1192 pOp->p4.z = pOut->z;
1193 pOp->p1 = pOut->n;
1194 }
1195 #endif
1196 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1197 goto too_big;
1198 }
1199 pOp->opcode = OP_String;
1200 assert( rc==SQLITE_OK );
1201 /* Fall through to the next case, OP_String */
1202 /* no break */ deliberate_fall_through
1203 }
1204
1205 /* Opcode: String P1 P2 P3 P4 P5
1206 ** Synopsis: r[P2]='P4' (len=P1)
1207 **
1208 ** The string value P4 of length P1 (bytes) is stored in register P2.
1209 **
1210 ** If P3 is not zero and the content of register P3 is equal to P5, then
1211 ** the datatype of the register P2 is converted to BLOB. The content is
1212 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
1213 ** of a string, as if it had been CAST. In other words:
1214 **
1215 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
1216 */
1217 case OP_String: { /* out2 */
1218 assert( pOp->p4.z!=0 );
1219 pOut = out2Prerelease(p, pOp);
1220 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
1221 pOut->z = pOp->p4.z;
1222 pOut->n = pOp->p1;
1223 pOut->enc = encoding;
1224 UPDATE_MAX_BLOBSIZE(pOut);
1225 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
1226 if( pOp->p3>0 ){
1227 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1228 pIn3 = &aMem[pOp->p3];
1229 assert( pIn3->flags & MEM_Int );
1230 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
1231 }
1232 #endif
1233 break;
1234 }
1235
1236 /* Opcode: Null P1 P2 P3 * *
1237 ** Synopsis: r[P2..P3]=NULL
1238 **
1239 ** Write a NULL into registers P2. If P3 greater than P2, then also write
1240 ** NULL into register P3 and every register in between P2 and P3. If P3
1241 ** is less than P2 (typically P3 is zero) then only register P2 is
1242 ** set to NULL.
1243 **
1244 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
1245 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
1246 ** OP_Ne or OP_Eq.
1247 */
1248 case OP_Null: { /* out2 */
1249 int cnt;
1250 u16 nullFlag;
1251 pOut = out2Prerelease(p, pOp);
1252 cnt = pOp->p3-pOp->p2;
1253 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
1254 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
1255 pOut->n = 0;
1256 #ifdef SQLITE_DEBUG
1257 pOut->uTemp = 0;
1258 #endif
1259 while( cnt>0 ){
1260 pOut++;
1261 memAboutToChange(p, pOut);
1262 sqlite3VdbeMemSetNull(pOut);
1263 pOut->flags = nullFlag;
1264 pOut->n = 0;
1265 cnt--;
1266 }
1267 break;
1268 }
1269
1270 /* Opcode: SoftNull P1 * * * *
1271 ** Synopsis: r[P1]=NULL
1272 **
1273 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
1274 ** instruction, but do not free any string or blob memory associated with
1275 ** the register, so that if the value was a string or blob that was
1276 ** previously copied using OP_SCopy, the copies will continue to be valid.
1277 */
1278 case OP_SoftNull: {
1279 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
1280 pOut = &aMem[pOp->p1];
1281 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
1282 break;
1283 }
1284
1285 /* Opcode: Blob P1 P2 * P4 *
1286 ** Synopsis: r[P2]=P4 (len=P1)
1287 **
1288 ** P4 points to a blob of data P1 bytes long. Store this
1289 ** blob in register P2.
1290 */
1291 case OP_Blob: { /* out2 */
1292 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
1293 pOut = out2Prerelease(p, pOp);
1294 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
1295 pOut->enc = encoding;
1296 UPDATE_MAX_BLOBSIZE(pOut);
1297 break;
1298 }
1299
1300 /* Opcode: Variable P1 P2 * P4 *
1301 ** Synopsis: r[P2]=parameter(P1,P4)
1302 **
1303 ** Transfer the values of bound parameter P1 into register P2
1304 **
1305 ** If the parameter is named, then its name appears in P4.
1306 ** The P4 value is used by sqlite3_bind_parameter_name().
1307 */
1308 case OP_Variable: { /* out2 */
1309 Mem *pVar; /* Value being transferred */
1310
1311 assert( pOp->p1>0 && pOp->p1<=p->nVar );
1312 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
1313 pVar = &p->aVar[pOp->p1 - 1];
1314 if( sqlite3VdbeMemTooBig(pVar) ){
1315 goto too_big;
1316 }
1317 pOut = &aMem[pOp->p2];
1318 if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
1319 memcpy(pOut, pVar, MEMCELLSIZE);
1320 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
1321 pOut->flags |= MEM_Static|MEM_FromBind;
1322 UPDATE_MAX_BLOBSIZE(pOut);
1323 break;
1324 }
1325
1326 /* Opcode: Move P1 P2 P3 * *
1327 ** Synopsis: r[P2@P3]=r[P1@P3]
1328 **
1329 ** Move the P3 values in register P1..P1+P3-1 over into
1330 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
1331 ** left holding a NULL. It is an error for register ranges
1332 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
1333 ** for P3 to be less than 1.
1334 */
1335 case OP_Move: {
1336 int n; /* Number of registers left to copy */
1337 int p1; /* Register to copy from */
1338 int p2; /* Register to copy to */
1339
1340 n = pOp->p3;
1341 p1 = pOp->p1;
1342 p2 = pOp->p2;
1343 assert( n>0 && p1>0 && p2>0 );
1344 assert( p1+n<=p2 || p2+n<=p1 );
1345
1346 pIn1 = &aMem[p1];
1347 pOut = &aMem[p2];
1348 do{
1349 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
1350 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
1351 assert( memIsValid(pIn1) );
1352 memAboutToChange(p, pOut);
1353 sqlite3VdbeMemMove(pOut, pIn1);
1354 #ifdef SQLITE_DEBUG
1355 pIn1->pScopyFrom = 0;
1356 { int i;
1357 for(i=1; i<p->nMem; i++){
1358 if( aMem[i].pScopyFrom==pIn1 ){
1359 aMem[i].pScopyFrom = pOut;
1360 }
1361 }
1362 }
1363 #endif
1364 Deephemeralize(pOut);
1365 REGISTER_TRACE(p2++, pOut);
1366 pIn1++;
1367 pOut++;
1368 }while( --n );
1369 break;
1370 }
1371
1372 /* Opcode: Copy P1 P2 P3 * *
1373 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
1374 **
1375 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
1376 **
1377 ** This instruction makes a deep copy of the value. A duplicate
1378 ** is made of any string or blob constant. See also OP_SCopy.
1379 */
1380 case OP_Copy: {
1381 int n;
1382
1383 n = pOp->p3;
1384 pIn1 = &aMem[pOp->p1];
1385 pOut = &aMem[pOp->p2];
1386 assert( pOut!=pIn1 );
1387 while( 1 ){
1388 memAboutToChange(p, pOut);
1389 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1390 Deephemeralize(pOut);
1391 #ifdef SQLITE_DEBUG
1392 pOut->pScopyFrom = 0;
1393 #endif
1394 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
1395 if( (n--)==0 ) break;
1396 pOut++;
1397 pIn1++;
1398 }
1399 break;
1400 }
1401
1402 /* Opcode: SCopy P1 P2 * * *
1403 ** Synopsis: r[P2]=r[P1]
1404 **
1405 ** Make a shallow copy of register P1 into register P2.
1406 **
1407 ** This instruction makes a shallow copy of the value. If the value
1408 ** is a string or blob, then the copy is only a pointer to the
1409 ** original and hence if the original changes so will the copy.
1410 ** Worse, if the original is deallocated, the copy becomes invalid.
1411 ** Thus the program must guarantee that the original will not change
1412 ** during the lifetime of the copy. Use OP_Copy to make a complete
1413 ** copy.
1414 */
1415 case OP_SCopy: { /* out2 */
1416 pIn1 = &aMem[pOp->p1];
1417 pOut = &aMem[pOp->p2];
1418 assert( pOut!=pIn1 );
1419 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1420 #ifdef SQLITE_DEBUG
1421 pOut->pScopyFrom = pIn1;
1422 pOut->mScopyFlags = pIn1->flags;
1423 #endif
1424 break;
1425 }
1426
1427 /* Opcode: IntCopy P1 P2 * * *
1428 ** Synopsis: r[P2]=r[P1]
1429 **
1430 ** Transfer the integer value held in register P1 into register P2.
1431 **
1432 ** This is an optimized version of SCopy that works only for integer
1433 ** values.
1434 */
1435 case OP_IntCopy: { /* out2 */
1436 pIn1 = &aMem[pOp->p1];
1437 assert( (pIn1->flags & MEM_Int)!=0 );
1438 pOut = &aMem[pOp->p2];
1439 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
1440 break;
1441 }
1442
1443 /* Opcode: ChngCntRow P1 P2 * * *
1444 ** Synopsis: output=r[P1]
1445 **
1446 ** Output value in register P1 as the chance count for a DML statement,
1447 ** due to the "PRAGMA count_changes=ON" setting. Or, if there was a
1448 ** foreign key error in the statement, trigger the error now.
1449 **
1450 ** This opcode is a variant of OP_ResultRow that checks the foreign key
1451 ** immediate constraint count and throws an error if the count is
1452 ** non-zero. The P2 opcode must be 1.
1453 */
1454 case OP_ChngCntRow: {
1455 assert( pOp->p2==1 );
1456 if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){
1457 goto abort_due_to_error;
1458 }
1459 /* Fall through to the next case, OP_ResultRow */
1460 /* no break */ deliberate_fall_through
1461 }
1462
1463 /* Opcode: ResultRow P1 P2 * * *
1464 ** Synopsis: output=r[P1@P2]
1465 **
1466 ** The registers P1 through P1+P2-1 contain a single row of
1467 ** results. This opcode causes the sqlite3_step() call to terminate
1468 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1469 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
1470 ** the result row.
1471 */
1472 case OP_ResultRow: {
1473 Mem *pMem;
1474 int i;
1475 assert( p->nResColumn==pOp->p2 );
1476 assert( pOp->p1>0 );
1477 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
1478
1479 /* Invalidate all ephemeral cursor row caches */
1480 p->cacheCtr = (p->cacheCtr + 2)|1;
1481
1482 /* Make sure the results of the current row are \000 terminated
1483 ** and have an assigned type. The results are de-ephemeralized as
1484 ** a side effect.
1485 */
1486 pMem = p->pResultSet = &aMem[pOp->p1];
1487 for(i=0; i<pOp->p2; i++){
1488 assert( memIsValid(&pMem[i]) );
1489 Deephemeralize(&pMem[i]);
1490 assert( (pMem[i].flags & MEM_Ephem)==0
1491 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
1492 sqlite3VdbeMemNulTerminate(&pMem[i]);
1493 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1494 #ifdef SQLITE_DEBUG
1495 /* The registers in the result will not be used again when the
1496 ** prepared statement restarts. This is because sqlite3_column()
1497 ** APIs might have caused type conversions of made other changes to
1498 ** the register values. Therefore, we can go ahead and break any
1499 ** OP_SCopy dependencies. */
1500 pMem[i].pScopyFrom = 0;
1501 #endif
1502 }
1503 if( db->mallocFailed ) goto no_mem;
1504
1505 if( db->mTrace & SQLITE_TRACE_ROW ){
1506 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
1507 }
1508
1509
1510 /* Return SQLITE_ROW
1511 */
1512 p->pc = (int)(pOp - aOp) + 1;
1513 rc = SQLITE_ROW;
1514 goto vdbe_return;
1515 }
1516
1517 /* Opcode: Concat P1 P2 P3 * *
1518 ** Synopsis: r[P3]=r[P2]+r[P1]
1519 **
1520 ** Add the text in register P1 onto the end of the text in
1521 ** register P2 and store the result in register P3.
1522 ** If either the P1 or P2 text are NULL then store NULL in P3.
1523 **
1524 ** P3 = P2 || P1
1525 **
1526 ** It is illegal for P1 and P3 to be the same register. Sometimes,
1527 ** if P3 is the same register as P2, the implementation is able
1528 ** to avoid a memcpy().
1529 */
1530 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1531 i64 nByte; /* Total size of the output string or blob */
1532 u16 flags1; /* Initial flags for P1 */
1533 u16 flags2; /* Initial flags for P2 */
1534
1535 pIn1 = &aMem[pOp->p1];
1536 pIn2 = &aMem[pOp->p2];
1537 pOut = &aMem[pOp->p3];
1538 testcase( pOut==pIn2 );
1539 assert( pIn1!=pOut );
1540 flags1 = pIn1->flags;
1541 testcase( flags1 & MEM_Null );
1542 testcase( pIn2->flags & MEM_Null );
1543 if( (flags1 | pIn2->flags) & MEM_Null ){
1544 sqlite3VdbeMemSetNull(pOut);
1545 break;
1546 }
1547 if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
1548 if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
1549 flags1 = pIn1->flags & ~MEM_Str;
1550 }else if( (flags1 & MEM_Zero)!=0 ){
1551 if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
1552 flags1 = pIn1->flags & ~MEM_Str;
1553 }
1554 flags2 = pIn2->flags;
1555 if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
1556 if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
1557 flags2 = pIn2->flags & ~MEM_Str;
1558 }else if( (flags2 & MEM_Zero)!=0 ){
1559 if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
1560 flags2 = pIn2->flags & ~MEM_Str;
1561 }
1562 nByte = pIn1->n + pIn2->n;
1563 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1564 goto too_big;
1565 }
1566 if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){
1567 goto no_mem;
1568 }
1569 MemSetTypeFlag(pOut, MEM_Str);
1570 if( pOut!=pIn2 ){
1571 memcpy(pOut->z, pIn2->z, pIn2->n);
1572 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
1573 pIn2->flags = flags2;
1574 }
1575 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1576 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
1577 pIn1->flags = flags1;
1578 pOut->z[nByte]=0;
1579 pOut->z[nByte+1] = 0;
1580 pOut->z[nByte+2] = 0;
1581 pOut->flags |= MEM_Term;
1582 pOut->n = (int)nByte;
1583 pOut->enc = encoding;
1584 UPDATE_MAX_BLOBSIZE(pOut);
1585 break;
1586 }
1587
1588 /* Opcode: Add P1 P2 P3 * *
1589 ** Synopsis: r[P3]=r[P1]+r[P2]
1590 **
1591 ** Add the value in register P1 to the value in register P2
1592 ** and store the result in register P3.
1593 ** If either input is NULL, the result is NULL.
1594 */
1595 /* Opcode: Multiply P1 P2 P3 * *
1596 ** Synopsis: r[P3]=r[P1]*r[P2]
1597 **
1598 **
1599 ** Multiply the value in register P1 by the value in register P2
1600 ** and store the result in register P3.
1601 ** If either input is NULL, the result is NULL.
1602 */
1603 /* Opcode: Subtract P1 P2 P3 * *
1604 ** Synopsis: r[P3]=r[P2]-r[P1]
1605 **
1606 ** Subtract the value in register P1 from the value in register P2
1607 ** and store the result in register P3.
1608 ** If either input is NULL, the result is NULL.
1609 */
1610 /* Opcode: Divide P1 P2 P3 * *
1611 ** Synopsis: r[P3]=r[P2]/r[P1]
1612 **
1613 ** Divide the value in register P1 by the value in register P2
1614 ** and store the result in register P3 (P3=P2/P1). If the value in
1615 ** register P1 is zero, then the result is NULL. If either input is
1616 ** NULL, the result is NULL.
1617 */
1618 /* Opcode: Remainder P1 P2 P3 * *
1619 ** Synopsis: r[P3]=r[P2]%r[P1]
1620 **
1621 ** Compute the remainder after integer register P2 is divided by
1622 ** register P1 and store the result in register P3.
1623 ** If the value in register P1 is zero the result is NULL.
1624 ** If either operand is NULL, the result is NULL.
1625 */
1626 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1627 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1628 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1629 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1630 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1631 u16 flags; /* Combined MEM_* flags from both inputs */
1632 u16 type1; /* Numeric type of left operand */
1633 u16 type2; /* Numeric type of right operand */
1634 i64 iA; /* Integer value of left operand */
1635 i64 iB; /* Integer value of right operand */
1636 double rA; /* Real value of left operand */
1637 double rB; /* Real value of right operand */
1638
1639 pIn1 = &aMem[pOp->p1];
1640 type1 = numericType(pIn1);
1641 pIn2 = &aMem[pOp->p2];
1642 type2 = numericType(pIn2);
1643 pOut = &aMem[pOp->p3];
1644 flags = pIn1->flags | pIn2->flags;
1645 if( (type1 & type2 & MEM_Int)!=0 ){
1646 iA = pIn1->u.i;
1647 iB = pIn2->u.i;
1648 switch( pOp->opcode ){
1649 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
1650 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
1651 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
1652 case OP_Divide: {
1653 if( iA==0 ) goto arithmetic_result_is_null;
1654 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
1655 iB /= iA;
1656 break;
1657 }
1658 default: {
1659 if( iA==0 ) goto arithmetic_result_is_null;
1660 if( iA==-1 ) iA = 1;
1661 iB %= iA;
1662 break;
1663 }
1664 }
1665 pOut->u.i = iB;
1666 MemSetTypeFlag(pOut, MEM_Int);
1667 }else if( (flags & MEM_Null)!=0 ){
1668 goto arithmetic_result_is_null;
1669 }else{
1670 fp_math:
1671 rA = sqlite3VdbeRealValue(pIn1);
1672 rB = sqlite3VdbeRealValue(pIn2);
1673 switch( pOp->opcode ){
1674 case OP_Add: rB += rA; break;
1675 case OP_Subtract: rB -= rA; break;
1676 case OP_Multiply: rB *= rA; break;
1677 case OP_Divide: {
1678 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1679 if( rA==(double)0 ) goto arithmetic_result_is_null;
1680 rB /= rA;
1681 break;
1682 }
1683 default: {
1684 iA = sqlite3VdbeIntValue(pIn1);
1685 iB = sqlite3VdbeIntValue(pIn2);
1686 if( iA==0 ) goto arithmetic_result_is_null;
1687 if( iA==-1 ) iA = 1;
1688 rB = (double)(iB % iA);
1689 break;
1690 }
1691 }
1692 #ifdef SQLITE_OMIT_FLOATING_POINT
1693 pOut->u.i = rB;
1694 MemSetTypeFlag(pOut, MEM_Int);
1695 #else
1696 if( sqlite3IsNaN(rB) ){
1697 goto arithmetic_result_is_null;
1698 }
1699 pOut->u.r = rB;
1700 MemSetTypeFlag(pOut, MEM_Real);
1701 #endif
1702 }
1703 break;
1704
1705 arithmetic_result_is_null:
1706 sqlite3VdbeMemSetNull(pOut);
1707 break;
1708 }
1709
1710 /* Opcode: CollSeq P1 * * P4
1711 **
1712 ** P4 is a pointer to a CollSeq object. If the next call to a user function
1713 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1714 ** be returned. This is used by the built-in min(), max() and nullif()
1715 ** functions.
1716 **
1717 ** If P1 is not zero, then it is a register that a subsequent min() or
1718 ** max() aggregate will set to 1 if the current row is not the minimum or
1719 ** maximum. The P1 register is initialized to 0 by this instruction.
1720 **
1721 ** The interface used by the implementation of the aforementioned functions
1722 ** to retrieve the collation sequence set by this opcode is not available
1723 ** publicly. Only built-in functions have access to this feature.
1724 */
1725 case OP_CollSeq: {
1726 assert( pOp->p4type==P4_COLLSEQ );
1727 if( pOp->p1 ){
1728 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
1729 }
1730 break;
1731 }
1732
1733 /* Opcode: BitAnd P1 P2 P3 * *
1734 ** Synopsis: r[P3]=r[P1]&r[P2]
1735 **
1736 ** Take the bit-wise AND of the values in register P1 and P2 and
1737 ** store the result in register P3.
1738 ** If either input is NULL, the result is NULL.
1739 */
1740 /* Opcode: BitOr P1 P2 P3 * *
1741 ** Synopsis: r[P3]=r[P1]|r[P2]
1742 **
1743 ** Take the bit-wise OR of the values in register P1 and P2 and
1744 ** store the result in register P3.
1745 ** If either input is NULL, the result is NULL.
1746 */
1747 /* Opcode: ShiftLeft P1 P2 P3 * *
1748 ** Synopsis: r[P3]=r[P2]<<r[P1]
1749 **
1750 ** Shift the integer value in register P2 to the left by the
1751 ** number of bits specified by the integer in register P1.
1752 ** Store the result in register P3.
1753 ** If either input is NULL, the result is NULL.
1754 */
1755 /* Opcode: ShiftRight P1 P2 P3 * *
1756 ** Synopsis: r[P3]=r[P2]>>r[P1]
1757 **
1758 ** Shift the integer value in register P2 to the right by the
1759 ** number of bits specified by the integer in register P1.
1760 ** Store the result in register P3.
1761 ** If either input is NULL, the result is NULL.
1762 */
1763 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1764 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1765 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1766 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1767 i64 iA;
1768 u64 uA;
1769 i64 iB;
1770 u8 op;
1771
1772 pIn1 = &aMem[pOp->p1];
1773 pIn2 = &aMem[pOp->p2];
1774 pOut = &aMem[pOp->p3];
1775 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1776 sqlite3VdbeMemSetNull(pOut);
1777 break;
1778 }
1779 iA = sqlite3VdbeIntValue(pIn2);
1780 iB = sqlite3VdbeIntValue(pIn1);
1781 op = pOp->opcode;
1782 if( op==OP_BitAnd ){
1783 iA &= iB;
1784 }else if( op==OP_BitOr ){
1785 iA |= iB;
1786 }else if( iB!=0 ){
1787 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
1788
1789 /* If shifting by a negative amount, shift in the other direction */
1790 if( iB<0 ){
1791 assert( OP_ShiftRight==OP_ShiftLeft+1 );
1792 op = 2*OP_ShiftLeft + 1 - op;
1793 iB = iB>(-64) ? -iB : 64;
1794 }
1795
1796 if( iB>=64 ){
1797 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
1798 }else{
1799 memcpy(&uA, &iA, sizeof(uA));
1800 if( op==OP_ShiftLeft ){
1801 uA <<= iB;
1802 }else{
1803 uA >>= iB;
1804 /* Sign-extend on a right shift of a negative number */
1805 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
1806 }
1807 memcpy(&iA, &uA, sizeof(iA));
1808 }
1809 }
1810 pOut->u.i = iA;
1811 MemSetTypeFlag(pOut, MEM_Int);
1812 break;
1813 }
1814
1815 /* Opcode: AddImm P1 P2 * * *
1816 ** Synopsis: r[P1]=r[P1]+P2
1817 **
1818 ** Add the constant P2 to the value in register P1.
1819 ** The result is always an integer.
1820 **
1821 ** To force any register to be an integer, just add 0.
1822 */
1823 case OP_AddImm: { /* in1 */
1824 pIn1 = &aMem[pOp->p1];
1825 memAboutToChange(p, pIn1);
1826 sqlite3VdbeMemIntegerify(pIn1);
1827 pIn1->u.i += pOp->p2;
1828 break;
1829 }
1830
1831 /* Opcode: MustBeInt P1 P2 * * *
1832 **
1833 ** Force the value in register P1 to be an integer. If the value
1834 ** in P1 is not an integer and cannot be converted into an integer
1835 ** without data loss, then jump immediately to P2, or if P2==0
1836 ** raise an SQLITE_MISMATCH exception.
1837 */
1838 case OP_MustBeInt: { /* jump, in1 */
1839 pIn1 = &aMem[pOp->p1];
1840 if( (pIn1->flags & MEM_Int)==0 ){
1841 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1842 if( (pIn1->flags & MEM_Int)==0 ){
1843 VdbeBranchTaken(1, 2);
1844 if( pOp->p2==0 ){
1845 rc = SQLITE_MISMATCH;
1846 goto abort_due_to_error;
1847 }else{
1848 goto jump_to_p2;
1849 }
1850 }
1851 }
1852 VdbeBranchTaken(0, 2);
1853 MemSetTypeFlag(pIn1, MEM_Int);
1854 break;
1855 }
1856
1857 #ifndef SQLITE_OMIT_FLOATING_POINT
1858 /* Opcode: RealAffinity P1 * * * *
1859 **
1860 ** If register P1 holds an integer convert it to a real value.
1861 **
1862 ** This opcode is used when extracting information from a column that
1863 ** has REAL affinity. Such column values may still be stored as
1864 ** integers, for space efficiency, but after extraction we want them
1865 ** to have only a real value.
1866 */
1867 case OP_RealAffinity: { /* in1 */
1868 pIn1 = &aMem[pOp->p1];
1869 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
1870 testcase( pIn1->flags & MEM_Int );
1871 testcase( pIn1->flags & MEM_IntReal );
1872 sqlite3VdbeMemRealify(pIn1);
1873 REGISTER_TRACE(pOp->p1, pIn1);
1874 }
1875 break;
1876 }
1877 #endif
1878
1879 #ifndef SQLITE_OMIT_CAST
1880 /* Opcode: Cast P1 P2 * * *
1881 ** Synopsis: affinity(r[P1])
1882 **
1883 ** Force the value in register P1 to be the type defined by P2.
1884 **
1885 ** <ul>
1886 ** <li> P2=='A' → BLOB
1887 ** <li> P2=='B' → TEXT
1888 ** <li> P2=='C' → NUMERIC
1889 ** <li> P2=='D' → INTEGER
1890 ** <li> P2=='E' → REAL
1891 ** </ul>
1892 **
1893 ** A NULL value is not changed by this routine. It remains NULL.
1894 */
1895 case OP_Cast: { /* in1 */
1896 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
1897 testcase( pOp->p2==SQLITE_AFF_TEXT );
1898 testcase( pOp->p2==SQLITE_AFF_BLOB );
1899 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
1900 testcase( pOp->p2==SQLITE_AFF_INTEGER );
1901 testcase( pOp->p2==SQLITE_AFF_REAL );
1902 pIn1 = &aMem[pOp->p1];
1903 memAboutToChange(p, pIn1);
1904 rc = ExpandBlob(pIn1);
1905 if( rc ) goto abort_due_to_error;
1906 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
1907 if( rc ) goto abort_due_to_error;
1908 UPDATE_MAX_BLOBSIZE(pIn1);
1909 REGISTER_TRACE(pOp->p1, pIn1);
1910 break;
1911 }
1912 #endif /* SQLITE_OMIT_CAST */
1913
1914 /* Opcode: Eq P1 P2 P3 P4 P5
1915 ** Synopsis: IF r[P3]==r[P1]
1916 **
1917 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
1918 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
1919 ** store the result of comparison in register P2.
1920 **
1921 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1922 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1923 ** to coerce both inputs according to this affinity before the
1924 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1925 ** affinity is used. Note that the affinity conversions are stored
1926 ** back into the input registers P1 and P3. So this opcode can cause
1927 ** persistent changes to registers P1 and P3.
1928 **
1929 ** Once any conversions have taken place, and neither value is NULL,
1930 ** the values are compared. If both values are blobs then memcmp() is
1931 ** used to determine the results of the comparison. If both values
1932 ** are text, then the appropriate collating function specified in
1933 ** P4 is used to do the comparison. If P4 is not specified then
1934 ** memcmp() is used to compare text string. If both values are
1935 ** numeric, then a numeric comparison is used. If the two values
1936 ** are of different types, then numbers are considered less than
1937 ** strings and strings are considered less than blobs.
1938 **
1939 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
1940 ** true or false and is never NULL. If both operands are NULL then the result
1941 ** of comparison is true. If either operand is NULL then the result is false.
1942 ** If neither operand is NULL the result is the same as it would be if
1943 ** the SQLITE_NULLEQ flag were omitted from P5.
1944 **
1945 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1946 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
1947 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
1948 */
1949 /* Opcode: Ne P1 P2 P3 P4 P5
1950 ** Synopsis: IF r[P3]!=r[P1]
1951 **
1952 ** This works just like the Eq opcode except that the jump is taken if
1953 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
1954 ** additional information.
1955 **
1956 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
1957 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
1958 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
1959 */
1960 /* Opcode: Lt P1 P2 P3 P4 P5
1961 ** Synopsis: IF r[P3]<r[P1]
1962 **
1963 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1964 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
1965 ** the result of comparison (0 or 1 or NULL) into register P2.
1966 **
1967 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1968 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
1969 ** bit is clear then fall through if either operand is NULL.
1970 **
1971 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1972 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1973 ** to coerce both inputs according to this affinity before the
1974 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1975 ** affinity is used. Note that the affinity conversions are stored
1976 ** back into the input registers P1 and P3. So this opcode can cause
1977 ** persistent changes to registers P1 and P3.
1978 **
1979 ** Once any conversions have taken place, and neither value is NULL,
1980 ** the values are compared. If both values are blobs then memcmp() is
1981 ** used to determine the results of the comparison. If both values
1982 ** are text, then the appropriate collating function specified in
1983 ** P4 is used to do the comparison. If P4 is not specified then
1984 ** memcmp() is used to compare text string. If both values are
1985 ** numeric, then a numeric comparison is used. If the two values
1986 ** are of different types, then numbers are considered less than
1987 ** strings and strings are considered less than blobs.
1988 */
1989 /* Opcode: Le P1 P2 P3 P4 P5
1990 ** Synopsis: IF r[P3]<=r[P1]
1991 **
1992 ** This works just like the Lt opcode except that the jump is taken if
1993 ** the content of register P3 is less than or equal to the content of
1994 ** register P1. See the Lt opcode for additional information.
1995 */
1996 /* Opcode: Gt P1 P2 P3 P4 P5
1997 ** Synopsis: IF r[P3]>r[P1]
1998 **
1999 ** This works just like the Lt opcode except that the jump is taken if
2000 ** the content of register P3 is greater than the content of
2001 ** register P1. See the Lt opcode for additional information.
2002 */
2003 /* Opcode: Ge P1 P2 P3 P4 P5
2004 ** Synopsis: IF r[P3]>=r[P1]
2005 **
2006 ** This works just like the Lt opcode except that the jump is taken if
2007 ** the content of register P3 is greater than or equal to the content of
2008 ** register P1. See the Lt opcode for additional information.
2009 */
2010 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
2011 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
2012 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
2013 case OP_Le: /* same as TK_LE, jump, in1, in3 */
2014 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
2015 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
2016 int res, res2; /* Result of the comparison of pIn1 against pIn3 */
2017 char affinity; /* Affinity to use for comparison */
2018 u16 flags1; /* Copy of initial value of pIn1->flags */
2019 u16 flags3; /* Copy of initial value of pIn3->flags */
2020
2021 pIn1 = &aMem[pOp->p1];
2022 pIn3 = &aMem[pOp->p3];
2023 flags1 = pIn1->flags;
2024 flags3 = pIn3->flags;
2025 if( (flags1 | flags3)&MEM_Null ){
2026 /* One or both operands are NULL */
2027 if( pOp->p5 & SQLITE_NULLEQ ){
2028 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
2029 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
2030 ** or not both operands are null.
2031 */
2032 assert( (flags1 & MEM_Cleared)==0 );
2033 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
2034 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
2035 if( (flags1&flags3&MEM_Null)!=0
2036 && (flags3&MEM_Cleared)==0
2037 ){
2038 res = 0; /* Operands are equal */
2039 }else{
2040 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
2041 }
2042 }else{
2043 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
2044 ** then the result is always NULL.
2045 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
2046 */
2047 if( pOp->p5 & SQLITE_STOREP2 ){
2048 pOut = &aMem[pOp->p2];
2049 iCompare = 1; /* Operands are not equal */
2050 memAboutToChange(p, pOut);
2051 MemSetTypeFlag(pOut, MEM_Null);
2052 REGISTER_TRACE(pOp->p2, pOut);
2053 }else{
2054 VdbeBranchTaken(2,3);
2055 if( pOp->p5 & SQLITE_JUMPIFNULL ){
2056 goto jump_to_p2;
2057 }
2058 }
2059 break;
2060 }
2061 }else{
2062 /* Neither operand is NULL. Do a comparison. */
2063 affinity = pOp->p5 & SQLITE_AFF_MASK;
2064 if( affinity>=SQLITE_AFF_NUMERIC ){
2065 if( (flags1 | flags3)&MEM_Str ){
2066 if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2067 applyNumericAffinity(pIn1,0);
2068 testcase( flags3==pIn3->flags );
2069 flags3 = pIn3->flags;
2070 }
2071 if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
2072 applyNumericAffinity(pIn3,0);
2073 }
2074 }
2075 /* Handle the common case of integer comparison here, as an
2076 ** optimization, to avoid a call to sqlite3MemCompare() */
2077 if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
2078 if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
2079 if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
2080 res = 0;
2081 goto compare_op;
2082 }
2083 }else if( affinity==SQLITE_AFF_TEXT ){
2084 if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2085 testcase( pIn1->flags & MEM_Int );
2086 testcase( pIn1->flags & MEM_Real );
2087 testcase( pIn1->flags & MEM_IntReal );
2088 sqlite3VdbeMemStringify(pIn1, encoding, 1);
2089 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
2090 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
2091 if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
2092 }
2093 if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
2094 testcase( pIn3->flags & MEM_Int );
2095 testcase( pIn3->flags & MEM_Real );
2096 testcase( pIn3->flags & MEM_IntReal );
2097 sqlite3VdbeMemStringify(pIn3, encoding, 1);
2098 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
2099 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
2100 }
2101 }
2102 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
2103 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
2104 }
2105 compare_op:
2106 /* At this point, res is negative, zero, or positive if reg[P1] is
2107 ** less than, equal to, or greater than reg[P3], respectively. Compute
2108 ** the answer to this operator in res2, depending on what the comparison
2109 ** operator actually is. The next block of code depends on the fact
2110 ** that the 6 comparison operators are consecutive integers in this
2111 ** order: NE, EQ, GT, LE, LT, GE */
2112 assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
2113 assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
2114 if( res<0 ){ /* ne, eq, gt, le, lt, ge */
2115 static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
2116 res2 = aLTb[pOp->opcode - OP_Ne];
2117 }else if( res==0 ){
2118 static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
2119 res2 = aEQb[pOp->opcode - OP_Ne];
2120 }else{
2121 static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
2122 res2 = aGTb[pOp->opcode - OP_Ne];
2123 }
2124
2125 /* Undo any changes made by applyAffinity() to the input registers. */
2126 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
2127 pIn3->flags = flags3;
2128 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
2129 pIn1->flags = flags1;
2130
2131 if( pOp->p5 & SQLITE_STOREP2 ){
2132 pOut = &aMem[pOp->p2];
2133 iCompare = res;
2134 if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
2135 /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
2136 ** and prevents OP_Ne from overwriting NULL with 0. This flag
2137 ** is only used in contexts where either:
2138 ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
2139 ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
2140 ** Therefore it is not necessary to check the content of r[P2] for
2141 ** NULL. */
2142 assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
2143 assert( res2==0 || res2==1 );
2144 testcase( res2==0 && pOp->opcode==OP_Eq );
2145 testcase( res2==1 && pOp->opcode==OP_Eq );
2146 testcase( res2==0 && pOp->opcode==OP_Ne );
2147 testcase( res2==1 && pOp->opcode==OP_Ne );
2148 if( (pOp->opcode==OP_Eq)==res2 ) break;
2149 }
2150 memAboutToChange(p, pOut);
2151 MemSetTypeFlag(pOut, MEM_Int);
2152 pOut->u.i = res2;
2153 REGISTER_TRACE(pOp->p2, pOut);
2154 }else{
2155 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
2156 if( res2 ){
2157 goto jump_to_p2;
2158 }
2159 }
2160 break;
2161 }
2162
2163 /* Opcode: ElseNotEq * P2 * * *
2164 **
2165 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
2166 ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
2167 ** opcodes are allowed to occur between this instruction and the previous
2168 ** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the
2169 ** SQLITE_STOREP2 bit set in the P5 field.
2170 **
2171 ** If result of an OP_Eq comparison on the same two operands as the
2172 ** prior OP_Lt or OP_Gt would have been NULL or false (0), then then
2173 ** jump to P2. If the result of an OP_Eq comparison on the two previous
2174 ** operands would have been true (1), then fall through.
2175 */
2176 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
2177
2178 #ifdef SQLITE_DEBUG
2179 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
2180 ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening
2181 ** OP_ReleaseReg opcodes */
2182 int iAddr;
2183 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
2184 if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
2185 assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
2186 assert( aOp[iAddr].p5 & SQLITE_STOREP2 );
2187 break;
2188 }
2189 #endif /* SQLITE_DEBUG */
2190 VdbeBranchTaken(iCompare!=0, 2);
2191 if( iCompare!=0 ) goto jump_to_p2;
2192 break;
2193 }
2194
2195
2196 /* Opcode: Permutation * * * P4 *
2197 **
2198 ** Set the permutation used by the OP_Compare operator in the next
2199 ** instruction. The permutation is stored in the P4 operand.
2200 **
2201 ** The permutation is only valid until the next OP_Compare that has
2202 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
2203 ** occur immediately prior to the OP_Compare.
2204 **
2205 ** The first integer in the P4 integer array is the length of the array
2206 ** and does not become part of the permutation.
2207 */
2208 case OP_Permutation: {
2209 assert( pOp->p4type==P4_INTARRAY );
2210 assert( pOp->p4.ai );
2211 assert( pOp[1].opcode==OP_Compare );
2212 assert( pOp[1].p5 & OPFLAG_PERMUTE );
2213 break;
2214 }
2215
2216 /* Opcode: Compare P1 P2 P3 P4 P5
2217 ** Synopsis: r[P1@P3] <-> r[P2@P3]
2218 **
2219 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
2220 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
2221 ** the comparison for use by the next OP_Jump instruct.
2222 **
2223 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
2224 ** determined by the most recent OP_Permutation operator. If the
2225 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
2226 ** order.
2227 **
2228 ** P4 is a KeyInfo structure that defines collating sequences and sort
2229 ** orders for the comparison. The permutation applies to registers
2230 ** only. The KeyInfo elements are used sequentially.
2231 **
2232 ** The comparison is a sort comparison, so NULLs compare equal,
2233 ** NULLs are less than numbers, numbers are less than strings,
2234 ** and strings are less than blobs.
2235 */
2236 case OP_Compare: {
2237 int n;
2238 int i;
2239 int p1;
2240 int p2;
2241 const KeyInfo *pKeyInfo;
2242 u32 idx;
2243 CollSeq *pColl; /* Collating sequence to use on this term */
2244 int bRev; /* True for DESCENDING sort order */
2245 u32 *aPermute; /* The permutation */
2246
2247 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
2248 aPermute = 0;
2249 }else{
2250 assert( pOp>aOp );
2251 assert( pOp[-1].opcode==OP_Permutation );
2252 assert( pOp[-1].p4type==P4_INTARRAY );
2253 aPermute = pOp[-1].p4.ai + 1;
2254 assert( aPermute!=0 );
2255 }
2256 n = pOp->p3;
2257 pKeyInfo = pOp->p4.pKeyInfo;
2258 assert( n>0 );
2259 assert( pKeyInfo!=0 );
2260 p1 = pOp->p1;
2261 p2 = pOp->p2;
2262 #ifdef SQLITE_DEBUG
2263 if( aPermute ){
2264 int k, mx = 0;
2265 for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
2266 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
2267 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
2268 }else{
2269 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
2270 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
2271 }
2272 #endif /* SQLITE_DEBUG */
2273 for(i=0; i<n; i++){
2274 idx = aPermute ? aPermute[i] : (u32)i;
2275 assert( memIsValid(&aMem[p1+idx]) );
2276 assert( memIsValid(&aMem[p2+idx]) );
2277 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
2278 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
2279 assert( i<pKeyInfo->nKeyField );
2280 pColl = pKeyInfo->aColl[i];
2281 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
2282 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
2283 if( iCompare ){
2284 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
2285 && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
2286 ){
2287 iCompare = -iCompare;
2288 }
2289 if( bRev ) iCompare = -iCompare;
2290 break;
2291 }
2292 }
2293 break;
2294 }
2295
2296 /* Opcode: Jump P1 P2 P3 * *
2297 **
2298 ** Jump to the instruction at address P1, P2, or P3 depending on whether
2299 ** in the most recent OP_Compare instruction the P1 vector was less than
2300 ** equal to, or greater than the P2 vector, respectively.
2301 */
2302 case OP_Jump: { /* jump */
2303 if( iCompare<0 ){
2304 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
2305 }else if( iCompare==0 ){
2306 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
2307 }else{
2308 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
2309 }
2310 break;
2311 }
2312
2313 /* Opcode: And P1 P2 P3 * *
2314 ** Synopsis: r[P3]=(r[P1] && r[P2])
2315 **
2316 ** Take the logical AND of the values in registers P1 and P2 and
2317 ** write the result into register P3.
2318 **
2319 ** If either P1 or P2 is 0 (false) then the result is 0 even if
2320 ** the other input is NULL. A NULL and true or two NULLs give
2321 ** a NULL output.
2322 */
2323 /* Opcode: Or P1 P2 P3 * *
2324 ** Synopsis: r[P3]=(r[P1] || r[P2])
2325 **
2326 ** Take the logical OR of the values in register P1 and P2 and
2327 ** store the answer in register P3.
2328 **
2329 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
2330 ** even if the other input is NULL. A NULL and false or two NULLs
2331 ** give a NULL output.
2332 */
2333 case OP_And: /* same as TK_AND, in1, in2, out3 */
2334 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
2335 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2336 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
2337
2338 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
2339 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
2340 if( pOp->opcode==OP_And ){
2341 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2342 v1 = and_logic[v1*3+v2];
2343 }else{
2344 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2345 v1 = or_logic[v1*3+v2];
2346 }
2347 pOut = &aMem[pOp->p3];
2348 if( v1==2 ){
2349 MemSetTypeFlag(pOut, MEM_Null);
2350 }else{
2351 pOut->u.i = v1;
2352 MemSetTypeFlag(pOut, MEM_Int);
2353 }
2354 break;
2355 }
2356
2357 /* Opcode: IsTrue P1 P2 P3 P4 *
2358 ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
2359 **
2360 ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
2361 ** IS NOT FALSE operators.
2362 **
2363 ** Interpret the value in register P1 as a boolean value. Store that
2364 ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
2365 ** NULL, then the P3 is stored in register P2. Invert the answer if P4
2366 ** is 1.
2367 **
2368 ** The logic is summarized like this:
2369 **
2370 ** <ul>
2371 ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
2372 ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
2373 ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
2374 ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
2375 ** </ul>
2376 */
2377 case OP_IsTrue: { /* in1, out2 */
2378 assert( pOp->p4type==P4_INT32 );
2379 assert( pOp->p4.i==0 || pOp->p4.i==1 );
2380 assert( pOp->p3==0 || pOp->p3==1 );
2381 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
2382 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
2383 break;
2384 }
2385
2386 /* Opcode: Not P1 P2 * * *
2387 ** Synopsis: r[P2]= !r[P1]
2388 **
2389 ** Interpret the value in register P1 as a boolean value. Store the
2390 ** boolean complement in register P2. If the value in register P1 is
2391 ** NULL, then a NULL is stored in P2.
2392 */
2393 case OP_Not: { /* same as TK_NOT, in1, out2 */
2394 pIn1 = &aMem[pOp->p1];
2395 pOut = &aMem[pOp->p2];
2396 if( (pIn1->flags & MEM_Null)==0 ){
2397 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
2398 }else{
2399 sqlite3VdbeMemSetNull(pOut);
2400 }
2401 break;
2402 }
2403
2404 /* Opcode: BitNot P1 P2 * * *
2405 ** Synopsis: r[P2]= ~r[P1]
2406 **
2407 ** Interpret the content of register P1 as an integer. Store the
2408 ** ones-complement of the P1 value into register P2. If P1 holds
2409 ** a NULL then store a NULL in P2.
2410 */
2411 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
2412 pIn1 = &aMem[pOp->p1];
2413 pOut = &aMem[pOp->p2];
2414 sqlite3VdbeMemSetNull(pOut);
2415 if( (pIn1->flags & MEM_Null)==0 ){
2416 pOut->flags = MEM_Int;
2417 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
2418 }
2419 break;
2420 }
2421
2422 /* Opcode: Once P1 P2 * * *
2423 **
2424 ** Fall through to the next instruction the first time this opcode is
2425 ** encountered on each invocation of the byte-code program. Jump to P2
2426 ** on the second and all subsequent encounters during the same invocation.
2427 **
2428 ** Top-level programs determine first invocation by comparing the P1
2429 ** operand against the P1 operand on the OP_Init opcode at the beginning
2430 ** of the program. If the P1 values differ, then fall through and make
2431 ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
2432 ** the same then take the jump.
2433 **
2434 ** For subprograms, there is a bitmask in the VdbeFrame that determines
2435 ** whether or not the jump should be taken. The bitmask is necessary
2436 ** because the self-altering code trick does not work for recursive
2437 ** triggers.
2438 */
2439 case OP_Once: { /* jump */
2440 u32 iAddr; /* Address of this instruction */
2441 assert( p->aOp[0].opcode==OP_Init );
2442 if( p->pFrame ){
2443 iAddr = (int)(pOp - p->aOp);
2444 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
2445 VdbeBranchTaken(1, 2);
2446 goto jump_to_p2;
2447 }
2448 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
2449 }else{
2450 if( p->aOp[0].p1==pOp->p1 ){
2451 VdbeBranchTaken(1, 2);
2452 goto jump_to_p2;
2453 }
2454 }
2455 VdbeBranchTaken(0, 2);
2456 pOp->p1 = p->aOp[0].p1;
2457 break;
2458 }
2459
2460 /* Opcode: If P1 P2 P3 * *
2461 **
2462 ** Jump to P2 if the value in register P1 is true. The value
2463 ** is considered true if it is numeric and non-zero. If the value
2464 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2465 */
2466 case OP_If: { /* jump, in1 */
2467 int c;
2468 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
2469 VdbeBranchTaken(c!=0, 2);
2470 if( c ) goto jump_to_p2;
2471 break;
2472 }
2473
2474 /* Opcode: IfNot P1 P2 P3 * *
2475 **
2476 ** Jump to P2 if the value in register P1 is False. The value
2477 ** is considered false if it has a numeric value of zero. If the value
2478 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
2479 */
2480 case OP_IfNot: { /* jump, in1 */
2481 int c;
2482 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
2483 VdbeBranchTaken(c!=0, 2);
2484 if( c ) goto jump_to_p2;
2485 break;
2486 }
2487
2488 /* Opcode: IsNull P1 P2 * * *
2489 ** Synopsis: if r[P1]==NULL goto P2
2490 **
2491 ** Jump to P2 if the value in register P1 is NULL.
2492 */
2493 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
2494 pIn1 = &aMem[pOp->p1];
2495 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
2496 if( (pIn1->flags & MEM_Null)!=0 ){
2497 goto jump_to_p2;
2498 }
2499 break;
2500 }
2501
2502 /* Opcode: NotNull P1 P2 * * *
2503 ** Synopsis: if r[P1]!=NULL goto P2
2504 **
2505 ** Jump to P2 if the value in register P1 is not NULL.
2506 */
2507 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
2508 pIn1 = &aMem[pOp->p1];
2509 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
2510 if( (pIn1->flags & MEM_Null)==0 ){
2511 goto jump_to_p2;
2512 }
2513 break;
2514 }
2515
2516 /* Opcode: IfNullRow P1 P2 P3 * *
2517 ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
2518 **
2519 ** Check the cursor P1 to see if it is currently pointing at a NULL row.
2520 ** If it is, then set register P3 to NULL and jump immediately to P2.
2521 ** If P1 is not on a NULL row, then fall through without making any
2522 ** changes.
2523 */
2524 case OP_IfNullRow: { /* jump */
2525 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2526 assert( p->apCsr[pOp->p1]!=0 );
2527 if( p->apCsr[pOp->p1]->nullRow ){
2528 sqlite3VdbeMemSetNull(aMem + pOp->p3);
2529 goto jump_to_p2;
2530 }
2531 break;
2532 }
2533
2534 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2535 /* Opcode: Offset P1 P2 P3 * *
2536 ** Synopsis: r[P3] = sqlite_offset(P1)
2537 **
2538 ** Store in register r[P3] the byte offset into the database file that is the
2539 ** start of the payload for the record at which that cursor P1 is currently
2540 ** pointing.
2541 **
2542 ** P2 is the column number for the argument to the sqlite_offset() function.
2543 ** This opcode does not use P2 itself, but the P2 value is used by the
2544 ** code generator. The P1, P2, and P3 operands to this opcode are the
2545 ** same as for OP_Column.
2546 **
2547 ** This opcode is only available if SQLite is compiled with the
2548 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
2549 */
2550 case OP_Offset: { /* out3 */
2551 VdbeCursor *pC; /* The VDBE cursor */
2552 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2553 pC = p->apCsr[pOp->p1];
2554 pOut = &p->aMem[pOp->p3];
2555 if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
2556 sqlite3VdbeMemSetNull(pOut);
2557 }else{
2558 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
2559 }
2560 break;
2561 }
2562 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
2563
2564 /* Opcode: Column P1 P2 P3 P4 P5
2565 ** Synopsis: r[P3]=PX
2566 **
2567 ** Interpret the data that cursor P1 points to as a structure built using
2568 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
2569 ** information about the format of the data.) Extract the P2-th column
2570 ** from this record. If there are less that (P2+1)
2571 ** values in the record, extract a NULL.
2572 **
2573 ** The value extracted is stored in register P3.
2574 **
2575 ** If the record contains fewer than P2 fields, then extract a NULL. Or,
2576 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
2577 ** the result.
2578 **
2579 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
2580 ** the result is guaranteed to only be used as the argument of a length()
2581 ** or typeof() function, respectively. The loading of large blobs can be
2582 ** skipped for length() and all content loading can be skipped for typeof().
2583 */
2584 case OP_Column: {
2585 u32 p2; /* column number to retrieve */
2586 VdbeCursor *pC; /* The VDBE cursor */
2587 BtCursor *pCrsr; /* The BTree cursor */
2588 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
2589 int len; /* The length of the serialized data for the column */
2590 int i; /* Loop counter */
2591 Mem *pDest; /* Where to write the extracted value */
2592 Mem sMem; /* For storing the record being decoded */
2593 const u8 *zData; /* Part of the record being decoded */
2594 const u8 *zHdr; /* Next unparsed byte of the header */
2595 const u8 *zEndHdr; /* Pointer to first byte after the header */
2596 u64 offset64; /* 64-bit offset */
2597 u32 t; /* A type code from the record header */
2598 Mem *pReg; /* PseudoTable input register */
2599
2600 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
2601 pC = p->apCsr[pOp->p1];
2602 assert( pC!=0 );
2603 p2 = (u32)pOp->p2;
2604
2605 /* If the cursor cache is stale (meaning it is not currently point at
2606 ** the correct row) then bring it up-to-date by doing the necessary
2607 ** B-Tree seek. */
2608 rc = sqlite3VdbeCursorMoveto(&pC, &p2);
2609 if( rc ) goto abort_due_to_error;
2610
2611 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
2612 pDest = &aMem[pOp->p3];
2613 memAboutToChange(p, pDest);
2614 assert( pC!=0 );
2615 assert( p2<(u32)pC->nField );
2616 aOffset = pC->aOffset;
2617 assert( pC->eCurType!=CURTYPE_VTAB );
2618 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
2619 assert( pC->eCurType!=CURTYPE_SORTER );
2620
2621 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
2622 if( pC->nullRow ){
2623 if( pC->eCurType==CURTYPE_PSEUDO ){
2624 /* For the special case of as pseudo-cursor, the seekResult field
2625 ** identifies the register that holds the record */
2626 assert( pC->seekResult>0 );
2627 pReg = &aMem[pC->seekResult];
2628 assert( pReg->flags & MEM_Blob );
2629 assert( memIsValid(pReg) );
2630 pC->payloadSize = pC->szRow = pReg->n;
2631 pC->aRow = (u8*)pReg->z;
2632 }else{
2633 sqlite3VdbeMemSetNull(pDest);
2634 goto op_column_out;
2635 }
2636 }else{
2637 pCrsr = pC->uc.pCursor;
2638 assert( pC->eCurType==CURTYPE_BTREE );
2639 assert( pCrsr );
2640 assert( sqlite3BtreeCursorIsValid(pCrsr) );
2641 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
2642 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
2643 assert( pC->szRow<=pC->payloadSize );
2644 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
2645 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
2646 goto too_big;
2647 }
2648 }
2649 pC->cacheStatus = p->cacheCtr;
2650 pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
2651 pC->nHdrParsed = 0;
2652
2653
2654 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
2655 /* pC->aRow does not have to hold the entire row, but it does at least
2656 ** need to cover the header of the record. If pC->aRow does not contain
2657 ** the complete header, then set it to zero, forcing the header to be
2658 ** dynamically allocated. */
2659 pC->aRow = 0;
2660 pC->szRow = 0;
2661
2662 /* Make sure a corrupt database has not given us an oversize header.
2663 ** Do this now to avoid an oversize memory allocation.
2664 **
2665 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
2666 ** types use so much data space that there can only be 4096 and 32 of
2667 ** them, respectively. So the maximum header length results from a
2668 ** 3-byte type for each of the maximum of 32768 columns plus three
2669 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
2670 */
2671 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
2672 goto op_column_corrupt;
2673 }
2674 }else{
2675 /* This is an optimization. By skipping over the first few tests
2676 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
2677 ** measurable performance gain.
2678 **
2679 ** This branch is taken even if aOffset[0]==0. Such a record is never
2680 ** generated by SQLite, and could be considered corruption, but we
2681 ** accept it for historical reasons. When aOffset[0]==0, the code this
2682 ** branch jumps to reads past the end of the record, but never more
2683 ** than a few bytes. Even if the record occurs at the end of the page
2684 ** content area, the "page header" comes after the page content and so
2685 ** this overread is harmless. Similar overreads can occur for a corrupt
2686 ** database file.
2687 */
2688 zData = pC->aRow;
2689 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
2690 testcase( aOffset[0]==0 );
2691 goto op_column_read_header;
2692 }
2693 }
2694
2695 /* Make sure at least the first p2+1 entries of the header have been
2696 ** parsed and valid information is in aOffset[] and pC->aType[].
2697 */
2698 if( pC->nHdrParsed<=p2 ){
2699 /* If there is more header available for parsing in the record, try
2700 ** to extract additional fields up through the p2+1-th field
2701 */
2702 if( pC->iHdrOffset<aOffset[0] ){
2703 /* Make sure zData points to enough of the record to cover the header. */
2704 if( pC->aRow==0 ){
2705 memset(&sMem, 0, sizeof(sMem));
2706 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
2707 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2708 zData = (u8*)sMem.z;
2709 }else{
2710 zData = pC->aRow;
2711 }
2712
2713 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
2714 op_column_read_header:
2715 i = pC->nHdrParsed;
2716 offset64 = aOffset[i];
2717 zHdr = zData + pC->iHdrOffset;
2718 zEndHdr = zData + aOffset[0];
2719 testcase( zHdr>=zEndHdr );
2720 do{
2721 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
2722 zHdr++;
2723 offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
2724 }else{
2725 zHdr += sqlite3GetVarint32(zHdr, &t);
2726 pC->aType[i] = t;
2727 offset64 += sqlite3VdbeSerialTypeLen(t);
2728 }
2729 aOffset[++i] = (u32)(offset64 & 0xffffffff);
2730 }while( (u32)i<=p2 && zHdr<zEndHdr );
2731
2732 /* The record is corrupt if any of the following are true:
2733 ** (1) the bytes of the header extend past the declared header size
2734 ** (2) the entire header was used but not all data was used
2735 ** (3) the end of the data extends beyond the end of the record.
2736 */
2737 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
2738 || (offset64 > pC->payloadSize)
2739 ){
2740 if( aOffset[0]==0 ){
2741 i = 0;
2742 zHdr = zEndHdr;
2743 }else{
2744 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2745 goto op_column_corrupt;
2746 }
2747 }
2748
2749 pC->nHdrParsed = i;
2750 pC->iHdrOffset = (u32)(zHdr - zData);
2751 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
2752 }else{
2753 t = 0;
2754 }
2755
2756 /* If after trying to extract new entries from the header, nHdrParsed is
2757 ** still not up to p2, that means that the record has fewer than p2
2758 ** columns. So the result will be either the default value or a NULL.
2759 */
2760 if( pC->nHdrParsed<=p2 ){
2761 if( pOp->p4type==P4_MEM ){
2762 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2763 }else{
2764 sqlite3VdbeMemSetNull(pDest);
2765 }
2766 goto op_column_out;
2767 }
2768 }else{
2769 t = pC->aType[p2];
2770 }
2771
2772 /* Extract the content for the p2+1-th column. Control can only
2773 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
2774 ** all valid.
2775 */
2776 assert( p2<pC->nHdrParsed );
2777 assert( rc==SQLITE_OK );
2778 assert( sqlite3VdbeCheckMemInvariants(pDest) );
2779 if( VdbeMemDynamic(pDest) ){
2780 sqlite3VdbeMemSetNull(pDest);
2781 }
2782 assert( t==pC->aType[p2] );
2783 if( pC->szRow>=aOffset[p2+1] ){
2784 /* This is the common case where the desired content fits on the original
2785 ** page - where the content is not on an overflow page */
2786 zData = pC->aRow + aOffset[p2];
2787 if( t<12 ){
2788 sqlite3VdbeSerialGet(zData, t, pDest);
2789 }else{
2790 /* If the column value is a string, we need a persistent value, not
2791 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
2792 ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
2793 */
2794 static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
2795 pDest->n = len = (t-12)/2;
2796 pDest->enc = encoding;
2797 if( pDest->szMalloc < len+2 ){
2798 pDest->flags = MEM_Null;
2799 if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
2800 }else{
2801 pDest->z = pDest->zMalloc;
2802 }
2803 memcpy(pDest->z, zData, len);
2804 pDest->z[len] = 0;
2805 pDest->z[len+1] = 0;
2806 pDest->flags = aFlag[t&1];
2807 }
2808 }else{
2809 pDest->enc = encoding;
2810 /* This branch happens only when content is on overflow pages */
2811 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
2812 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
2813 || (len = sqlite3VdbeSerialTypeLen(t))==0
2814 ){
2815 /* Content is irrelevant for
2816 ** 1. the typeof() function,
2817 ** 2. the length(X) function if X is a blob, and
2818 ** 3. if the content length is zero.
2819 ** So we might as well use bogus content rather than reading
2820 ** content from disk.
2821 **
2822 ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
2823 ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
2824 ** read more. Use the global constant sqlite3CtypeMap[] as the array,
2825 ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
2826 ** and it begins with a bunch of zeros.
2827 */
2828 sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
2829 }else{
2830 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
2831 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2832 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
2833 pDest->flags &= ~MEM_Ephem;
2834 }
2835 }
2836
2837 op_column_out:
2838 UPDATE_MAX_BLOBSIZE(pDest);
2839 REGISTER_TRACE(pOp->p3, pDest);
2840 break;
2841
2842 op_column_corrupt:
2843 if( aOp[0].p3>0 ){
2844 pOp = &aOp[aOp[0].p3-1];
2845 break;
2846 }else{
2847 rc = SQLITE_CORRUPT_BKPT;
2848 goto abort_due_to_error;
2849 }
2850 }
2851
2852 /* Opcode: Affinity P1 P2 * P4 *
2853 ** Synopsis: affinity(r[P1@P2])
2854 **
2855 ** Apply affinities to a range of P2 registers starting with P1.
2856 **
2857 ** P4 is a string that is P2 characters long. The N-th character of the
2858 ** string indicates the column affinity that should be used for the N-th
2859 ** memory cell in the range.
2860 */
2861 case OP_Affinity: {
2862 const char *zAffinity; /* The affinity to be applied */
2863
2864 zAffinity = pOp->p4.z;
2865 assert( zAffinity!=0 );
2866 assert( pOp->p2>0 );
2867 assert( zAffinity[pOp->p2]==0 );
2868 pIn1 = &aMem[pOp->p1];
2869 while( 1 /*exit-by-break*/ ){
2870 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
2871 assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
2872 applyAffinity(pIn1, zAffinity[0], encoding);
2873 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
2874 /* When applying REAL affinity, if the result is still an MEM_Int
2875 ** that will fit in 6 bytes, then change the type to MEM_IntReal
2876 ** so that we keep the high-resolution integer value but know that
2877 ** the type really wants to be REAL. */
2878 testcase( pIn1->u.i==140737488355328LL );
2879 testcase( pIn1->u.i==140737488355327LL );
2880 testcase( pIn1->u.i==-140737488355328LL );
2881 testcase( pIn1->u.i==-140737488355329LL );
2882 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
2883 pIn1->flags |= MEM_IntReal;
2884 pIn1->flags &= ~MEM_Int;
2885 }else{
2886 pIn1->u.r = (double)pIn1->u.i;
2887 pIn1->flags |= MEM_Real;
2888 pIn1->flags &= ~MEM_Int;
2889 }
2890 }
2891 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
2892 zAffinity++;
2893 if( zAffinity[0]==0 ) break;
2894 pIn1++;
2895 }
2896 break;
2897 }
2898
2899 /* Opcode: MakeRecord P1 P2 P3 P4 *
2900 ** Synopsis: r[P3]=mkrec(r[P1@P2])
2901 **
2902 ** Convert P2 registers beginning with P1 into the [record format]
2903 ** use as a data record in a database table or as a key
2904 ** in an index. The OP_Column opcode can decode the record later.
2905 **
2906 ** P4 may be a string that is P2 characters long. The N-th character of the
2907 ** string indicates the column affinity that should be used for the N-th
2908 ** field of the index key.
2909 **
2910 ** The mapping from character to affinity is given by the SQLITE_AFF_
2911 ** macros defined in sqliteInt.h.
2912 **
2913 ** If P4 is NULL then all index fields have the affinity BLOB.
2914 **
2915 ** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
2916 ** compile-time option is enabled:
2917 **
2918 ** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
2919 ** of the right-most table that can be null-trimmed.
2920 **
2921 ** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
2922 ** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
2923 ** accept no-change records with serial_type 10. This value is
2924 ** only used inside an assert() and does not affect the end result.
2925 */
2926 case OP_MakeRecord: {
2927 Mem *pRec; /* The new record */
2928 u64 nData; /* Number of bytes of data space */
2929 int nHdr; /* Number of bytes of header space */
2930 i64 nByte; /* Data space required for this record */
2931 i64 nZero; /* Number of zero bytes at the end of the record */
2932 int nVarint; /* Number of bytes in a varint */
2933 u32 serial_type; /* Type field */
2934 Mem *pData0; /* First field to be combined into the record */
2935 Mem *pLast; /* Last field of the record */
2936 int nField; /* Number of fields in the record */
2937 char *zAffinity; /* The affinity string for the record */
2938 int file_format; /* File format to use for encoding */
2939 u32 len; /* Length of a field */
2940 u8 *zHdr; /* Where to write next byte of the header */
2941 u8 *zPayload; /* Where to write next byte of the payload */
2942
2943 /* Assuming the record contains N fields, the record format looks
2944 ** like this:
2945 **
2946 ** ------------------------------------------------------------------------
2947 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2948 ** ------------------------------------------------------------------------
2949 **
2950 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
2951 ** and so forth.
2952 **
2953 ** Each type field is a varint representing the serial type of the
2954 ** corresponding data element (see sqlite3VdbeSerialType()). The
2955 ** hdr-size field is also a varint which is the offset from the beginning
2956 ** of the record to data0.
2957 */
2958 nData = 0; /* Number of bytes of data space */
2959 nHdr = 0; /* Number of bytes of header space */
2960 nZero = 0; /* Number of zero bytes at the end of the record */
2961 nField = pOp->p1;
2962 zAffinity = pOp->p4.z;
2963 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
2964 pData0 = &aMem[nField];
2965 nField = pOp->p2;
2966 pLast = &pData0[nField-1];
2967 file_format = p->minWriteFileFormat;
2968
2969 /* Identify the output register */
2970 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2971 pOut = &aMem[pOp->p3];
2972 memAboutToChange(p, pOut);
2973
2974 /* Apply the requested affinity to all inputs
2975 */
2976 assert( pData0<=pLast );
2977 if( zAffinity ){
2978 pRec = pData0;
2979 do{
2980 applyAffinity(pRec, zAffinity[0], encoding);
2981 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
2982 pRec->flags |= MEM_IntReal;
2983 pRec->flags &= ~(MEM_Int);
2984 }
2985 REGISTER_TRACE((int)(pRec-aMem), pRec);
2986 zAffinity++;
2987 pRec++;
2988 assert( zAffinity[0]==0 || pRec<=pLast );
2989 }while( zAffinity[0] );
2990 }
2991
2992 #ifdef SQLITE_ENABLE_NULL_TRIM
2993 /* NULLs can be safely trimmed from the end of the record, as long as
2994 ** as the schema format is 2 or more and none of the omitted columns
2995 ** have a non-NULL default value. Also, the record must be left with
2996 ** at least one field. If P5>0 then it will be one more than the
2997 ** index of the right-most column with a non-NULL default value */
2998 if( pOp->p5 ){
2999 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
3000 pLast--;
3001 nField--;
3002 }
3003 }
3004 #endif
3005
3006 /* Loop through the elements that will make up the record to figure
3007 ** out how much space is required for the new record. After this loop,
3008 ** the Mem.uTemp field of each term should hold the serial-type that will
3009 ** be used for that term in the generated record:
3010 **
3011 ** Mem.uTemp value type
3012 ** --------------- ---------------
3013 ** 0 NULL
3014 ** 1 1-byte signed integer
3015 ** 2 2-byte signed integer
3016 ** 3 3-byte signed integer
3017 ** 4 4-byte signed integer
3018 ** 5 6-byte signed integer
3019 ** 6 8-byte signed integer
3020 ** 7 IEEE float
3021 ** 8 Integer constant 0
3022 ** 9 Integer constant 1
3023 ** 10,11 reserved for expansion
3024 ** N>=12 and even BLOB
3025 ** N>=13 and odd text
3026 **
3027 ** The following additional values are computed:
3028 ** nHdr Number of bytes needed for the record header
3029 ** nData Number of bytes of data space needed for the record
3030 ** nZero Zero bytes at the end of the record
3031 */
3032 pRec = pLast;
3033 do{
3034 assert( memIsValid(pRec) );
3035 if( pRec->flags & MEM_Null ){
3036 if( pRec->flags & MEM_Zero ){
3037 /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
3038 ** table methods that never invoke sqlite3_result_xxxxx() while
3039 ** computing an unchanging column value in an UPDATE statement.
3040 ** Give such values a special internal-use-only serial-type of 10
3041 ** so that they can be passed through to xUpdate and have
3042 ** a true sqlite3_value_nochange(). */
3043 #ifndef SQLITE_ENABLE_NULL_TRIM
3044 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
3045 #endif
3046 pRec->uTemp = 10;
3047 }else{
3048 pRec->uTemp = 0;
3049 }
3050 nHdr++;
3051 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
3052 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
3053 i64 i = pRec->u.i;
3054 u64 uu;
3055 testcase( pRec->flags & MEM_Int );
3056 testcase( pRec->flags & MEM_IntReal );
3057 if( i<0 ){
3058 uu = ~i;
3059 }else{
3060 uu = i;
3061 }
3062 nHdr++;
3063 testcase( uu==127 ); testcase( uu==128 );
3064 testcase( uu==32767 ); testcase( uu==32768 );
3065 testcase( uu==8388607 ); testcase( uu==8388608 );
3066 testcase( uu==2147483647 ); testcase( uu==2147483648 );
3067 testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
3068 if( uu<=127 ){
3069 if( (i&1)==i && file_format>=4 ){
3070 pRec->uTemp = 8+(u32)uu;
3071 }else{
3072 nData++;
3073 pRec->uTemp = 1;
3074 }
3075 }else if( uu<=32767 ){
3076 nData += 2;
3077 pRec->uTemp = 2;
3078 }else if( uu<=8388607 ){
3079 nData += 3;
3080 pRec->uTemp = 3;
3081 }else if( uu<=2147483647 ){
3082 nData += 4;
3083 pRec->uTemp = 4;
3084 }else if( uu<=140737488355327LL ){
3085 nData += 6;
3086 pRec->uTemp = 5;
3087 }else{
3088 nData += 8;
3089 if( pRec->flags & MEM_IntReal ){
3090 /* If the value is IntReal and is going to take up 8 bytes to store
3091 ** as an integer, then we might as well make it an 8-byte floating
3092 ** point value */
3093 pRec->u.r = (double)pRec->u.i;
3094 pRec->flags &= ~MEM_IntReal;
3095 pRec->flags |= MEM_Real;
3096 pRec->uTemp = 7;
3097 }else{
3098 pRec->uTemp = 6;
3099 }
3100 }
3101 }else if( pRec->flags & MEM_Real ){
3102 nHdr++;
3103 nData += 8;
3104 pRec->uTemp = 7;
3105 }else{
3106 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
3107 assert( pRec->n>=0 );
3108 len = (u32)pRec->n;
3109 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
3110 if( pRec->flags & MEM_Zero ){
3111 serial_type += pRec->u.nZero*2;
3112 if( nData ){
3113 if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
3114 len += pRec->u.nZero;
3115 }else{
3116 nZero += pRec->u.nZero;
3117 }
3118 }
3119 nData += len;
3120 nHdr += sqlite3VarintLen(serial_type);
3121 pRec->uTemp = serial_type;
3122 }
3123 if( pRec==pData0 ) break;
3124 pRec--;
3125 }while(1);
3126
3127 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
3128 ** which determines the total number of bytes in the header. The varint
3129 ** value is the size of the header in bytes including the size varint
3130 ** itself. */
3131 testcase( nHdr==126 );
3132 testcase( nHdr==127 );
3133 if( nHdr<=126 ){
3134 /* The common case */
3135 nHdr += 1;
3136 }else{
3137 /* Rare case of a really large header */
3138 nVarint = sqlite3VarintLen(nHdr);
3139 nHdr += nVarint;
3140 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
3141 }
3142 nByte = nHdr+nData;
3143
3144 /* Make sure the output register has a buffer large enough to store
3145 ** the new record. The output register (pOp->p3) is not allowed to
3146 ** be one of the input registers (because the following call to
3147 ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
3148 */
3149 if( nByte+nZero<=pOut->szMalloc ){
3150 /* The output register is already large enough to hold the record.
3151 ** No error checks or buffer enlargement is required */
3152 pOut->z = pOut->zMalloc;
3153 }else{
3154 /* Need to make sure that the output is not too big and then enlarge
3155 ** the output register to hold the full result */
3156 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3157 goto too_big;
3158 }
3159 if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
3160 goto no_mem;
3161 }
3162 }
3163 pOut->n = (int)nByte;
3164 pOut->flags = MEM_Blob;
3165 if( nZero ){
3166 pOut->u.nZero = nZero;
3167 pOut->flags |= MEM_Zero;
3168 }
3169 UPDATE_MAX_BLOBSIZE(pOut);
3170 zHdr = (u8 *)pOut->z;
3171 zPayload = zHdr + nHdr;
3172
3173 /* Write the record */
3174 zHdr += putVarint32(zHdr, nHdr);
3175 assert( pData0<=pLast );
3176 pRec = pData0;
3177 do{
3178 serial_type = pRec->uTemp;
3179 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
3180 ** additional varints, one per column. */
3181 zHdr += putVarint32(zHdr, serial_type); /* serial type */
3182 /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
3183 ** immediately follow the header. */
3184 zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
3185 }while( (++pRec)<=pLast );
3186 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
3187 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
3188
3189 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
3190 REGISTER_TRACE(pOp->p3, pOut);
3191 break;
3192 }
3193
3194 /* Opcode: Count P1 P2 p3 * *
3195 ** Synopsis: r[P2]=count()
3196 **
3197 ** Store the number of entries (an integer value) in the table or index
3198 ** opened by cursor P1 in register P2.
3199 **
3200 ** If P3==0, then an exact count is obtained, which involves visiting
3201 ** every btree page of the table. But if P3 is non-zero, an estimate
3202 ** is returned based on the current cursor position.
3203 */
3204 case OP_Count: { /* out2 */
3205 i64 nEntry;
3206 BtCursor *pCrsr;
3207
3208 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
3209 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
3210 assert( pCrsr );
3211 if( pOp->p3 ){
3212 nEntry = sqlite3BtreeRowCountEst(pCrsr);
3213 }else{
3214 nEntry = 0; /* Not needed. Only used to silence a warning. */
3215 rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
3216 if( rc ) goto abort_due_to_error;
3217 }
3218 pOut = out2Prerelease(p, pOp);
3219 pOut->u.i = nEntry;
3220 goto check_for_interrupt;
3221 }
3222
3223 /* Opcode: Savepoint P1 * * P4 *
3224 **
3225 ** Open, release or rollback the savepoint named by parameter P4, depending
3226 ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
3227 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
3228 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
3229 */
3230 case OP_Savepoint: {
3231 int p1; /* Value of P1 operand */
3232 char *zName; /* Name of savepoint */
3233 int nName;
3234 Savepoint *pNew;
3235 Savepoint *pSavepoint;
3236 Savepoint *pTmp;
3237 int iSavepoint;
3238 int ii;
3239
3240 p1 = pOp->p1;
3241 zName = pOp->p4.z;
3242
3243 /* Assert that the p1 parameter is valid. Also that if there is no open
3244 ** transaction, then there cannot be any savepoints.
3245 */
3246 assert( db->pSavepoint==0 || db->autoCommit==0 );
3247 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
3248 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
3249 assert( checkSavepointCount(db) );
3250 assert( p->bIsReader );
3251
3252 if( p1==SAVEPOINT_BEGIN ){
3253 if( db->nVdbeWrite>0 ){
3254 /* A new savepoint cannot be created if there are active write
3255 ** statements (i.e. open read/write incremental blob handles).
3256 */
3257 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
3258 rc = SQLITE_BUSY;
3259 }else{
3260 nName = sqlite3Strlen30(zName);
3261
3262 #ifndef SQLITE_OMIT_VIRTUALTABLE
3263 /* This call is Ok even if this savepoint is actually a transaction
3264 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
3265 ** If this is a transaction savepoint being opened, it is guaranteed
3266 ** that the db->aVTrans[] array is empty. */
3267 assert( db->autoCommit==0 || db->nVTrans==0 );
3268 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
3269 db->nStatement+db->nSavepoint);
3270 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3271 #endif
3272
3273 /* Create a new savepoint structure. */
3274 pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
3275 if( pNew ){
3276 pNew->zName = (char *)&pNew[1];
3277 memcpy(pNew->zName, zName, nName+1);
3278
3279 /* If there is no open transaction, then mark this as a special
3280 ** "transaction savepoint". */
3281 if( db->autoCommit ){
3282 db->autoCommit = 0;
3283 db->isTransactionSavepoint = 1;
3284 }else{
3285 db->nSavepoint++;
3286 }
3287
3288 /* Link the new savepoint into the database handle's list. */
3289 pNew->pNext = db->pSavepoint;
3290 db->pSavepoint = pNew;
3291 pNew->nDeferredCons = db->nDeferredCons;
3292 pNew->nDeferredImmCons = db->nDeferredImmCons;
3293 }
3294 }
3295 }else{
3296 assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
3297 iSavepoint = 0;
3298
3299 /* Find the named savepoint. If there is no such savepoint, then an
3300 ** an error is returned to the user. */
3301 for(
3302 pSavepoint = db->pSavepoint;
3303 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
3304 pSavepoint = pSavepoint->pNext
3305 ){
3306 iSavepoint++;
3307 }
3308 if( !pSavepoint ){
3309 sqlite3VdbeError(p, "no such savepoint: %s", zName);
3310 rc = SQLITE_ERROR;
3311 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
3312 /* It is not possible to release (commit) a savepoint if there are
3313 ** active write statements.
3314 */
3315 sqlite3VdbeError(p, "cannot release savepoint - "
3316 "SQL statements in progress");
3317 rc = SQLITE_BUSY;
3318 }else{
3319
3320 /* Determine whether or not this is a transaction savepoint. If so,
3321 ** and this is a RELEASE command, then the current transaction
3322 ** is committed.
3323 */
3324 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
3325 if( isTransaction && p1==SAVEPOINT_RELEASE ){
3326 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3327 goto vdbe_return;
3328 }
3329 db->autoCommit = 1;
3330 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3331 p->pc = (int)(pOp - aOp);
3332 db->autoCommit = 0;
3333 p->rc = rc = SQLITE_BUSY;
3334 goto vdbe_return;
3335 }
3336 rc = p->rc;
3337 if( rc ){
3338 db->autoCommit = 0;
3339 }else{
3340 db->isTransactionSavepoint = 0;
3341 }
3342 }else{
3343 int isSchemaChange;
3344 iSavepoint = db->nSavepoint - iSavepoint - 1;
3345 if( p1==SAVEPOINT_ROLLBACK ){
3346 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
3347 for(ii=0; ii<db->nDb; ii++){
3348 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
3349 SQLITE_ABORT_ROLLBACK,
3350 isSchemaChange==0);
3351 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3352 }
3353 }else{
3354 assert( p1==SAVEPOINT_RELEASE );
3355 isSchemaChange = 0;
3356 }
3357 for(ii=0; ii<db->nDb; ii++){
3358 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
3359 if( rc!=SQLITE_OK ){
3360 goto abort_due_to_error;
3361 }
3362 }
3363 if( isSchemaChange ){
3364 sqlite3ExpirePreparedStatements(db, 0);
3365 sqlite3ResetAllSchemasOfConnection(db);
3366 db->mDbFlags |= DBFLAG_SchemaChange;
3367 }
3368 }
3369 if( rc ) goto abort_due_to_error;
3370
3371 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
3372 ** savepoints nested inside of the savepoint being operated on. */
3373 while( db->pSavepoint!=pSavepoint ){
3374 pTmp = db->pSavepoint;
3375 db->pSavepoint = pTmp->pNext;
3376 sqlite3DbFree(db, pTmp);
3377 db->nSavepoint--;
3378 }
3379
3380 /* If it is a RELEASE, then destroy the savepoint being operated on
3381 ** too. If it is a ROLLBACK TO, then set the number of deferred
3382 ** constraint violations present in the database to the value stored
3383 ** when the savepoint was created. */
3384 if( p1==SAVEPOINT_RELEASE ){
3385 assert( pSavepoint==db->pSavepoint );
3386 db->pSavepoint = pSavepoint->pNext;
3387 sqlite3DbFree(db, pSavepoint);
3388 if( !isTransaction ){
3389 db->nSavepoint--;
3390 }
3391 }else{
3392 assert( p1==SAVEPOINT_ROLLBACK );
3393 db->nDeferredCons = pSavepoint->nDeferredCons;
3394 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
3395 }
3396
3397 if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
3398 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
3399 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3400 }
3401 }
3402 }
3403 if( rc ) goto abort_due_to_error;
3404
3405 break;
3406 }
3407
3408 /* Opcode: AutoCommit P1 P2 * * *
3409 **
3410 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
3411 ** back any currently active btree transactions. If there are any active
3412 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
3413 ** there are active writing VMs or active VMs that use shared cache.
3414 **
3415 ** This instruction causes the VM to halt.
3416 */
3417 case OP_AutoCommit: {
3418 int desiredAutoCommit;
3419 int iRollback;
3420
3421 desiredAutoCommit = pOp->p1;
3422 iRollback = pOp->p2;
3423 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
3424 assert( desiredAutoCommit==1 || iRollback==0 );
3425 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
3426 assert( p->bIsReader );
3427
3428 if( desiredAutoCommit!=db->autoCommit ){
3429 if( iRollback ){
3430 assert( desiredAutoCommit==1 );
3431 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
3432 db->autoCommit = 1;
3433 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
3434 /* If this instruction implements a COMMIT and other VMs are writing
3435 ** return an error indicating that the other VMs must complete first.
3436 */
3437 sqlite3VdbeError(p, "cannot commit transaction - "
3438 "SQL statements in progress");
3439 rc = SQLITE_BUSY;
3440 goto abort_due_to_error;
3441 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
3442 goto vdbe_return;
3443 }else{
3444 db->autoCommit = (u8)desiredAutoCommit;
3445 }
3446 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
3447 p->pc = (int)(pOp - aOp);
3448 db->autoCommit = (u8)(1-desiredAutoCommit);
3449 p->rc = rc = SQLITE_BUSY;
3450 goto vdbe_return;
3451 }
3452 sqlite3CloseSavepoints(db);
3453 if( p->rc==SQLITE_OK ){
3454 rc = SQLITE_DONE;
3455 }else{
3456 rc = SQLITE_ERROR;
3457 }
3458 goto vdbe_return;
3459 }else{
3460 sqlite3VdbeError(p,
3461 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
3462 (iRollback)?"cannot rollback - no transaction is active":
3463 "cannot commit - no transaction is active"));
3464
3465 rc = SQLITE_ERROR;
3466 goto abort_due_to_error;
3467 }
3468 /*NOTREACHED*/ assert(0);
3469 }
3470
3471 /* Opcode: Transaction P1 P2 P3 P4 P5
3472 **
3473 ** Begin a transaction on database P1 if a transaction is not already
3474 ** active.
3475 ** If P2 is non-zero, then a write-transaction is started, or if a
3476 ** read-transaction is already active, it is upgraded to a write-transaction.
3477 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
3478 ** then an exclusive transaction is started.
3479 **
3480 ** P1 is the index of the database file on which the transaction is
3481 ** started. Index 0 is the main database file and index 1 is the
3482 ** file used for temporary tables. Indices of 2 or more are used for
3483 ** attached databases.
3484 **
3485 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
3486 ** true (this flag is set if the Vdbe may modify more than one row and may
3487 ** throw an ABORT exception), a statement transaction may also be opened.
3488 ** More specifically, a statement transaction is opened iff the database
3489 ** connection is currently not in autocommit mode, or if there are other
3490 ** active statements. A statement transaction allows the changes made by this
3491 ** VDBE to be rolled back after an error without having to roll back the
3492 ** entire transaction. If no error is encountered, the statement transaction
3493 ** will automatically commit when the VDBE halts.
3494 **
3495 ** If P5!=0 then this opcode also checks the schema cookie against P3
3496 ** and the schema generation counter against P4.
3497 ** The cookie changes its value whenever the database schema changes.
3498 ** This operation is used to detect when that the cookie has changed
3499 ** and that the current process needs to reread the schema. If the schema
3500 ** cookie in P3 differs from the schema cookie in the database header or
3501 ** if the schema generation counter in P4 differs from the current
3502 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
3503 ** halts. The sqlite3_step() wrapper function might then reprepare the
3504 ** statement and rerun it from the beginning.
3505 */
3506 case OP_Transaction: {
3507 Btree *pBt;
3508 int iMeta = 0;
3509
3510 assert( p->bIsReader );
3511 assert( p->readOnly==0 || pOp->p2==0 );
3512 assert( pOp->p2>=0 && pOp->p2<=2 );
3513 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3514 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3515 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
3516 rc = SQLITE_READONLY;
3517 goto abort_due_to_error;
3518 }
3519 pBt = db->aDb[pOp->p1].pBt;
3520
3521 if( pBt ){
3522 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
3523 testcase( rc==SQLITE_BUSY_SNAPSHOT );
3524 testcase( rc==SQLITE_BUSY_RECOVERY );
3525 if( rc!=SQLITE_OK ){
3526 if( (rc&0xff)==SQLITE_BUSY ){
3527 p->pc = (int)(pOp - aOp);
3528 p->rc = rc;
3529 goto vdbe_return;
3530 }
3531 goto abort_due_to_error;
3532 }
3533
3534 if( p->usesStmtJournal
3535 && pOp->p2
3536 && (db->autoCommit==0 || db->nVdbeRead>1)
3537 ){
3538 assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
3539 if( p->iStatement==0 ){
3540 assert( db->nStatement>=0 && db->nSavepoint>=0 );
3541 db->nStatement++;
3542 p->iStatement = db->nSavepoint + db->nStatement;
3543 }
3544
3545 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
3546 if( rc==SQLITE_OK ){
3547 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
3548 }
3549
3550 /* Store the current value of the database handles deferred constraint
3551 ** counter. If the statement transaction needs to be rolled back,
3552 ** the value of this counter needs to be restored too. */
3553 p->nStmtDefCons = db->nDeferredCons;
3554 p->nStmtDefImmCons = db->nDeferredImmCons;
3555 }
3556 }
3557 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
3558 if( pOp->p5
3559 && (iMeta!=pOp->p3
3560 || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
3561 ){
3562 /*
3563 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
3564 ** version is checked to ensure that the schema has not changed since the
3565 ** SQL statement was prepared.
3566 */
3567 sqlite3DbFree(db, p->zErrMsg);
3568 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
3569 /* If the schema-cookie from the database file matches the cookie
3570 ** stored with the in-memory representation of the schema, do
3571 ** not reload the schema from the database file.
3572 **
3573 ** If virtual-tables are in use, this is not just an optimization.
3574 ** Often, v-tables store their data in other SQLite tables, which
3575 ** are queried from within xNext() and other v-table methods using
3576 ** prepared queries. If such a query is out-of-date, we do not want to
3577 ** discard the database schema, as the user code implementing the
3578 ** v-table would have to be ready for the sqlite3_vtab structure itself
3579 ** to be invalidated whenever sqlite3_step() is called from within
3580 ** a v-table method.
3581 */
3582 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
3583 sqlite3ResetOneSchema(db, pOp->p1);
3584 }
3585 p->expired = 1;
3586 rc = SQLITE_SCHEMA;
3587 }
3588 if( rc ) goto abort_due_to_error;
3589 break;
3590 }
3591
3592 /* Opcode: ReadCookie P1 P2 P3 * *
3593 **
3594 ** Read cookie number P3 from database P1 and write it into register P2.
3595 ** P3==1 is the schema version. P3==2 is the database format.
3596 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
3597 ** the main database file and P1==1 is the database file used to store
3598 ** temporary tables.
3599 **
3600 ** There must be a read-lock on the database (either a transaction
3601 ** must be started or there must be an open cursor) before
3602 ** executing this instruction.
3603 */
3604 case OP_ReadCookie: { /* out2 */
3605 int iMeta;
3606 int iDb;
3607 int iCookie;
3608
3609 assert( p->bIsReader );
3610 iDb = pOp->p1;
3611 iCookie = pOp->p3;
3612 assert( pOp->p3<SQLITE_N_BTREE_META );
3613 assert( iDb>=0 && iDb<db->nDb );
3614 assert( db->aDb[iDb].pBt!=0 );
3615 assert( DbMaskTest(p->btreeMask, iDb) );
3616
3617 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
3618 pOut = out2Prerelease(p, pOp);
3619 pOut->u.i = iMeta;
3620 break;
3621 }
3622
3623 /* Opcode: SetCookie P1 P2 P3 * P5
3624 **
3625 ** Write the integer value P3 into cookie number P2 of database P1.
3626 ** P2==1 is the schema version. P2==2 is the database format.
3627 ** P2==3 is the recommended pager cache
3628 ** size, and so forth. P1==0 is the main database file and P1==1 is the
3629 ** database file used to store temporary tables.
3630 **
3631 ** A transaction must be started before executing this opcode.
3632 **
3633 ** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
3634 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
3635 ** has P5 set to 1, so that the internal schema version will be different
3636 ** from the database schema version, resulting in a schema reset.
3637 */
3638 case OP_SetCookie: {
3639 Db *pDb;
3640
3641 sqlite3VdbeIncrWriteCounter(p, 0);
3642 assert( pOp->p2<SQLITE_N_BTREE_META );
3643 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3644 assert( DbMaskTest(p->btreeMask, pOp->p1) );
3645 assert( p->readOnly==0 );
3646 pDb = &db->aDb[pOp->p1];
3647 assert( pDb->pBt!=0 );
3648 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
3649 /* See note about index shifting on OP_ReadCookie */
3650 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
3651 if( pOp->p2==BTREE_SCHEMA_VERSION ){
3652 /* When the schema cookie changes, record the new cookie internally */
3653 pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
3654 db->mDbFlags |= DBFLAG_SchemaChange;
3655 }else if( pOp->p2==BTREE_FILE_FORMAT ){
3656 /* Record changes in the file format */
3657 pDb->pSchema->file_format = pOp->p3;
3658 }
3659 if( pOp->p1==1 ){
3660 /* Invalidate all prepared statements whenever the TEMP database
3661 ** schema is changed. Ticket #1644 */
3662 sqlite3ExpirePreparedStatements(db, 0);
3663 p->expired = 0;
3664 }
3665 if( rc ) goto abort_due_to_error;
3666 break;
3667 }
3668
3669 /* Opcode: OpenRead P1 P2 P3 P4 P5
3670 ** Synopsis: root=P2 iDb=P3
3671 **
3672 ** Open a read-only cursor for the database table whose root page is
3673 ** P2 in a database file. The database file is determined by P3.
3674 ** P3==0 means the main database, P3==1 means the database used for
3675 ** temporary tables, and P3>1 means used the corresponding attached
3676 ** database. Give the new cursor an identifier of P1. The P1
3677 ** values need not be contiguous but all P1 values should be small integers.
3678 ** It is an error for P1 to be negative.
3679 **
3680 ** Allowed P5 bits:
3681 ** <ul>
3682 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3683 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3684 ** of OP_SeekLE/OP_IdxLT)
3685 ** </ul>
3686 **
3687 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3688 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3689 ** object, then table being opened must be an [index b-tree] where the
3690 ** KeyInfo object defines the content and collating
3691 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3692 ** value, then the table being opened must be a [table b-tree] with a
3693 ** number of columns no less than the value of P4.
3694 **
3695 ** See also: OpenWrite, ReopenIdx
3696 */
3697 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
3698 ** Synopsis: root=P2 iDb=P3
3699 **
3700 ** The ReopenIdx opcode works like OP_OpenRead except that it first
3701 ** checks to see if the cursor on P1 is already open on the same
3702 ** b-tree and if it is this opcode becomes a no-op. In other words,
3703 ** if the cursor is already open, do not reopen it.
3704 **
3705 ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
3706 ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
3707 ** be the same as every other ReopenIdx or OpenRead for the same cursor
3708 ** number.
3709 **
3710 ** Allowed P5 bits:
3711 ** <ul>
3712 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3713 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3714 ** of OP_SeekLE/OP_IdxLT)
3715 ** </ul>
3716 **
3717 ** See also: OP_OpenRead, OP_OpenWrite
3718 */
3719 /* Opcode: OpenWrite P1 P2 P3 P4 P5
3720 ** Synopsis: root=P2 iDb=P3
3721 **
3722 ** Open a read/write cursor named P1 on the table or index whose root
3723 ** page is P2 (or whose root page is held in register P2 if the
3724 ** OPFLAG_P2ISREG bit is set in P5 - see below).
3725 **
3726 ** The P4 value may be either an integer (P4_INT32) or a pointer to
3727 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
3728 ** object, then table being opened must be an [index b-tree] where the
3729 ** KeyInfo object defines the content and collating
3730 ** sequence of that index b-tree. Otherwise, if P4 is an integer
3731 ** value, then the table being opened must be a [table b-tree] with a
3732 ** number of columns no less than the value of P4.
3733 **
3734 ** Allowed P5 bits:
3735 ** <ul>
3736 ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
3737 ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
3738 ** of OP_SeekLE/OP_IdxLT)
3739 ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
3740 ** and subsequently delete entries in an index btree. This is a
3741 ** hint to the storage engine that the storage engine is allowed to
3742 ** ignore. The hint is not used by the official SQLite b*tree storage
3743 ** engine, but is used by COMDB2.
3744 ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
3745 ** as the root page, not the value of P2 itself.
3746 ** </ul>
3747 **
3748 ** This instruction works like OpenRead except that it opens the cursor
3749 ** in read/write mode.
3750 **
3751 ** See also: OP_OpenRead, OP_ReopenIdx
3752 */
3753 case OP_ReopenIdx: {
3754 int nField;
3755 KeyInfo *pKeyInfo;
3756 u32 p2;
3757 int iDb;
3758 int wrFlag;
3759 Btree *pX;
3760 VdbeCursor *pCur;
3761 Db *pDb;
3762
3763 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3764 assert( pOp->p4type==P4_KEYINFO );
3765 pCur = p->apCsr[pOp->p1];
3766 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
3767 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
3768 goto open_cursor_set_hints;
3769 }
3770 /* If the cursor is not currently open or is open on a different
3771 ** index, then fall through into OP_OpenRead to force a reopen */
3772 case OP_OpenRead:
3773 case OP_OpenWrite:
3774
3775 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
3776 assert( p->bIsReader );
3777 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
3778 || p->readOnly==0 );
3779
3780 if( p->expired==1 ){
3781 rc = SQLITE_ABORT_ROLLBACK;
3782 goto abort_due_to_error;
3783 }
3784
3785 nField = 0;
3786 pKeyInfo = 0;
3787 p2 = (u32)pOp->p2;
3788 iDb = pOp->p3;
3789 assert( iDb>=0 && iDb<db->nDb );
3790 assert( DbMaskTest(p->btreeMask, iDb) );
3791 pDb = &db->aDb[iDb];
3792 pX = pDb->pBt;
3793 assert( pX!=0 );
3794 if( pOp->opcode==OP_OpenWrite ){
3795 assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
3796 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
3797 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3798 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
3799 p->minWriteFileFormat = pDb->pSchema->file_format;
3800 }
3801 }else{
3802 wrFlag = 0;
3803 }
3804 if( pOp->p5 & OPFLAG_P2ISREG ){
3805 assert( p2>0 );
3806 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
3807 assert( pOp->opcode==OP_OpenWrite );
3808 pIn2 = &aMem[p2];
3809 assert( memIsValid(pIn2) );
3810 assert( (pIn2->flags & MEM_Int)!=0 );
3811 sqlite3VdbeMemIntegerify(pIn2);
3812 p2 = (int)pIn2->u.i;
3813 /* The p2 value always comes from a prior OP_CreateBtree opcode and
3814 ** that opcode will always set the p2 value to 2 or more or else fail.
3815 ** If there were a failure, the prepared statement would have halted
3816 ** before reaching this instruction. */
3817 assert( p2>=2 );
3818 }
3819 if( pOp->p4type==P4_KEYINFO ){
3820 pKeyInfo = pOp->p4.pKeyInfo;
3821 assert( pKeyInfo->enc==ENC(db) );
3822 assert( pKeyInfo->db==db );
3823 nField = pKeyInfo->nAllField;
3824 }else if( pOp->p4type==P4_INT32 ){
3825 nField = pOp->p4.i;
3826 }
3827 assert( pOp->p1>=0 );
3828 assert( nField>=0 );
3829 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
3830 pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
3831 if( pCur==0 ) goto no_mem;
3832 pCur->nullRow = 1;
3833 pCur->isOrdered = 1;
3834 pCur->pgnoRoot = p2;
3835 #ifdef SQLITE_DEBUG
3836 pCur->wrFlag = wrFlag;
3837 #endif
3838 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
3839 pCur->pKeyInfo = pKeyInfo;
3840 /* Set the VdbeCursor.isTable variable. Previous versions of
3841 ** SQLite used to check if the root-page flags were sane at this point
3842 ** and report database corruption if they were not, but this check has
3843 ** since moved into the btree layer. */
3844 pCur->isTable = pOp->p4type!=P4_KEYINFO;
3845
3846 open_cursor_set_hints:
3847 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
3848 assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
3849 testcase( pOp->p5 & OPFLAG_BULKCSR );
3850 testcase( pOp->p2 & OPFLAG_SEEKEQ );
3851 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
3852 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
3853 if( rc ) goto abort_due_to_error;
3854 break;
3855 }
3856
3857 /* Opcode: OpenDup P1 P2 * * *
3858 **
3859 ** Open a new cursor P1 that points to the same ephemeral table as
3860 ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
3861 ** opcode. Only ephemeral cursors may be duplicated.
3862 **
3863 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
3864 */
3865 case OP_OpenDup: {
3866 VdbeCursor *pOrig; /* The original cursor to be duplicated */
3867 VdbeCursor *pCx; /* The new cursor */
3868
3869 pOrig = p->apCsr[pOp->p2];
3870 assert( pOrig );
3871 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
3872
3873 pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
3874 if( pCx==0 ) goto no_mem;
3875 pCx->nullRow = 1;
3876 pCx->isEphemeral = 1;
3877 pCx->pKeyInfo = pOrig->pKeyInfo;
3878 pCx->isTable = pOrig->isTable;
3879 pCx->pgnoRoot = pOrig->pgnoRoot;
3880 pCx->isOrdered = pOrig->isOrdered;
3881 pCx->pBtx = pOrig->pBtx;
3882 pCx->hasBeenDuped = 1;
3883 pOrig->hasBeenDuped = 1;
3884 rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
3885 pCx->pKeyInfo, pCx->uc.pCursor);
3886 /* The sqlite3BtreeCursor() routine can only fail for the first cursor
3887 ** opened for a database. Since there is already an open cursor when this
3888 ** opcode is run, the sqlite3BtreeCursor() cannot fail */
3889 assert( rc==SQLITE_OK );
3890 break;
3891 }
3892
3893
3894 /* Opcode: OpenEphemeral P1 P2 P3 P4 P5
3895 ** Synopsis: nColumn=P2
3896 **
3897 ** Open a new cursor P1 to a transient table.
3898 ** The cursor is always opened read/write even if
3899 ** the main database is read-only. The ephemeral
3900 ** table is deleted automatically when the cursor is closed.
3901 **
3902 ** If the cursor P1 is already opened on an ephemeral table, the table
3903 ** is cleared (all content is erased).
3904 **
3905 ** P2 is the number of columns in the ephemeral table.
3906 ** The cursor points to a BTree table if P4==0 and to a BTree index
3907 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
3908 ** that defines the format of keys in the index.
3909 **
3910 ** The P5 parameter can be a mask of the BTREE_* flags defined
3911 ** in btree.h. These flags control aspects of the operation of
3912 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
3913 ** added automatically.
3914 **
3915 ** If P3 is positive, then reg[P3] is modified slightly so that it
3916 ** can be used as zero-length data for OP_Insert. This is an optimization
3917 ** that avoids an extra OP_Blob opcode to initialize that register.
3918 */
3919 /* Opcode: OpenAutoindex P1 P2 * P4 *
3920 ** Synopsis: nColumn=P2
3921 **
3922 ** This opcode works the same as OP_OpenEphemeral. It has a
3923 ** different name to distinguish its use. Tables created using
3924 ** by this opcode will be used for automatically created transient
3925 ** indices in joins.
3926 */
3927 case OP_OpenAutoindex:
3928 case OP_OpenEphemeral: {
3929 VdbeCursor *pCx;
3930 KeyInfo *pKeyInfo;
3931
3932 static const int vfsFlags =
3933 SQLITE_OPEN_READWRITE |
3934 SQLITE_OPEN_CREATE |
3935 SQLITE_OPEN_EXCLUSIVE |
3936 SQLITE_OPEN_DELETEONCLOSE |
3937 SQLITE_OPEN_TRANSIENT_DB;
3938 assert( pOp->p1>=0 );
3939 assert( pOp->p2>=0 );
3940 if( pOp->p3>0 ){
3941 /* Make register reg[P3] into a value that can be used as the data
3942 ** form sqlite3BtreeInsert() where the length of the data is zero. */
3943 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
3944 assert( pOp->opcode==OP_OpenEphemeral );
3945 assert( aMem[pOp->p3].flags & MEM_Null );
3946 aMem[pOp->p3].n = 0;
3947 aMem[pOp->p3].z = "";
3948 }
3949 pCx = p->apCsr[pOp->p1];
3950 if( pCx && !pCx->hasBeenDuped ){
3951 /* If the ephermeral table is already open and has no duplicates from
3952 ** OP_OpenDup, then erase all existing content so that the table is
3953 ** empty again, rather than creating a new table. */
3954 assert( pCx->isEphemeral );
3955 pCx->seqCount = 0;
3956 pCx->cacheStatus = CACHE_STALE;
3957 rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
3958 }else{
3959 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
3960 if( pCx==0 ) goto no_mem;
3961 pCx->isEphemeral = 1;
3962 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
3963 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
3964 vfsFlags);
3965 if( rc==SQLITE_OK ){
3966 rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
3967 if( rc==SQLITE_OK ){
3968 /* If a transient index is required, create it by calling
3969 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
3970 ** opening it. If a transient table is required, just use the
3971 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
3972 */
3973 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
3974 assert( pOp->p4type==P4_KEYINFO );
3975 rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
3976 BTREE_BLOBKEY | pOp->p5);
3977 if( rc==SQLITE_OK ){
3978 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
3979 assert( pKeyInfo->db==db );
3980 assert( pKeyInfo->enc==ENC(db) );
3981 rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
3982 pKeyInfo, pCx->uc.pCursor);
3983 }
3984 pCx->isTable = 0;
3985 }else{
3986 pCx->pgnoRoot = SCHEMA_ROOT;
3987 rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
3988 0, pCx->uc.pCursor);
3989 pCx->isTable = 1;
3990 }
3991 }
3992 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
3993 if( rc ){
3994 sqlite3BtreeClose(pCx->pBtx);
3995 }
3996 }
3997 }
3998 if( rc ) goto abort_due_to_error;
3999 pCx->nullRow = 1;
4000 break;
4001 }
4002
4003 /* Opcode: SorterOpen P1 P2 P3 P4 *
4004 **
4005 ** This opcode works like OP_OpenEphemeral except that it opens
4006 ** a transient index that is specifically designed to sort large
4007 ** tables using an external merge-sort algorithm.
4008 **
4009 ** If argument P3 is non-zero, then it indicates that the sorter may
4010 ** assume that a stable sort considering the first P3 fields of each
4011 ** key is sufficient to produce the required results.
4012 */
4013 case OP_SorterOpen: {
4014 VdbeCursor *pCx;
4015
4016 assert( pOp->p1>=0 );
4017 assert( pOp->p2>=0 );
4018 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
4019 if( pCx==0 ) goto no_mem;
4020 pCx->pKeyInfo = pOp->p4.pKeyInfo;
4021 assert( pCx->pKeyInfo->db==db );
4022 assert( pCx->pKeyInfo->enc==ENC(db) );
4023 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
4024 if( rc ) goto abort_due_to_error;
4025 break;
4026 }
4027
4028 /* Opcode: SequenceTest P1 P2 * * *
4029 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
4030 **
4031 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
4032 ** to P2. Regardless of whether or not the jump is taken, increment the
4033 ** the sequence value.
4034 */
4035 case OP_SequenceTest: {
4036 VdbeCursor *pC;
4037 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4038 pC = p->apCsr[pOp->p1];
4039 assert( isSorter(pC) );
4040 if( (pC->seqCount++)==0 ){
4041 goto jump_to_p2;
4042 }
4043 break;
4044 }
4045
4046 /* Opcode: OpenPseudo P1 P2 P3 * *
4047 ** Synopsis: P3 columns in r[P2]
4048 **
4049 ** Open a new cursor that points to a fake table that contains a single
4050 ** row of data. The content of that one row is the content of memory
4051 ** register P2. In other words, cursor P1 becomes an alias for the
4052 ** MEM_Blob content contained in register P2.
4053 **
4054 ** A pseudo-table created by this opcode is used to hold a single
4055 ** row output from the sorter so that the row can be decomposed into
4056 ** individual columns using the OP_Column opcode. The OP_Column opcode
4057 ** is the only cursor opcode that works with a pseudo-table.
4058 **
4059 ** P3 is the number of fields in the records that will be stored by
4060 ** the pseudo-table.
4061 */
4062 case OP_OpenPseudo: {
4063 VdbeCursor *pCx;
4064
4065 assert( pOp->p1>=0 );
4066 assert( pOp->p3>=0 );
4067 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
4068 if( pCx==0 ) goto no_mem;
4069 pCx->nullRow = 1;
4070 pCx->seekResult = pOp->p2;
4071 pCx->isTable = 1;
4072 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
4073 ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
4074 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
4075 ** which is a performance optimization */
4076 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
4077 assert( pOp->p5==0 );
4078 break;
4079 }
4080
4081 /* Opcode: Close P1 * * * *
4082 **
4083 ** Close a cursor previously opened as P1. If P1 is not
4084 ** currently open, this instruction is a no-op.
4085 */
4086 case OP_Close: {
4087 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4088 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
4089 p->apCsr[pOp->p1] = 0;
4090 break;
4091 }
4092
4093 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4094 /* Opcode: ColumnsUsed P1 * * P4 *
4095 **
4096 ** This opcode (which only exists if SQLite was compiled with
4097 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
4098 ** table or index for cursor P1 are used. P4 is a 64-bit integer
4099 ** (P4_INT64) in which the first 63 bits are one for each of the
4100 ** first 63 columns of the table or index that are actually used
4101 ** by the cursor. The high-order bit is set if any column after
4102 ** the 64th is used.
4103 */
4104 case OP_ColumnsUsed: {
4105 VdbeCursor *pC;
4106 pC = p->apCsr[pOp->p1];
4107 assert( pC->eCurType==CURTYPE_BTREE );
4108 pC->maskUsed = *(u64*)pOp->p4.pI64;
4109 break;
4110 }
4111 #endif
4112
4113 /* Opcode: SeekGE P1 P2 P3 P4 *
4114 ** Synopsis: key=r[P3@P4]
4115 **
4116 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4117 ** use the value in register P3 as the key. If cursor P1 refers
4118 ** to an SQL index, then P3 is the first in an array of P4 registers
4119 ** that are used as an unpacked index key.
4120 **
4121 ** Reposition cursor P1 so that it points to the smallest entry that
4122 ** is greater than or equal to the key value. If there are no records
4123 ** greater than or equal to the key and P2 is not zero, then jump to P2.
4124 **
4125 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4126 ** opcode will either land on a record that exactly matches the key, or
4127 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4128 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4129 ** The IdxGT opcode will be skipped if this opcode succeeds, but the
4130 ** IdxGT opcode will be used on subsequent loop iterations. The
4131 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4132 ** is an equality search.
4133 **
4134 ** This opcode leaves the cursor configured to move in forward order,
4135 ** from the beginning toward the end. In other words, the cursor is
4136 ** configured to use Next, not Prev.
4137 **
4138 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
4139 */
4140 /* Opcode: SeekGT P1 P2 P3 P4 *
4141 ** Synopsis: key=r[P3@P4]
4142 **
4143 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4144 ** use the value in register P3 as a key. If cursor P1 refers
4145 ** to an SQL index, then P3 is the first in an array of P4 registers
4146 ** that are used as an unpacked index key.
4147 **
4148 ** Reposition cursor P1 so that it points to the smallest entry that
4149 ** is greater than the key value. If there are no records greater than
4150 ** the key and P2 is not zero, then jump to P2.
4151 **
4152 ** This opcode leaves the cursor configured to move in forward order,
4153 ** from the beginning toward the end. In other words, the cursor is
4154 ** configured to use Next, not Prev.
4155 **
4156 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
4157 */
4158 /* Opcode: SeekLT P1 P2 P3 P4 *
4159 ** Synopsis: key=r[P3@P4]
4160 **
4161 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4162 ** use the value in register P3 as a key. If cursor P1 refers
4163 ** to an SQL index, then P3 is the first in an array of P4 registers
4164 ** that are used as an unpacked index key.
4165 **
4166 ** Reposition cursor P1 so that it points to the largest entry that
4167 ** is less than the key value. If there are no records less than
4168 ** the key and P2 is not zero, then jump to P2.
4169 **
4170 ** This opcode leaves the cursor configured to move in reverse order,
4171 ** from the end toward the beginning. In other words, the cursor is
4172 ** configured to use Prev, not Next.
4173 **
4174 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
4175 */
4176 /* Opcode: SeekLE P1 P2 P3 P4 *
4177 ** Synopsis: key=r[P3@P4]
4178 **
4179 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
4180 ** use the value in register P3 as a key. If cursor P1 refers
4181 ** to an SQL index, then P3 is the first in an array of P4 registers
4182 ** that are used as an unpacked index key.
4183 **
4184 ** Reposition cursor P1 so that it points to the largest entry that
4185 ** is less than or equal to the key value. If there are no records
4186 ** less than or equal to the key and P2 is not zero, then jump to P2.
4187 **
4188 ** This opcode leaves the cursor configured to move in reverse order,
4189 ** from the end toward the beginning. In other words, the cursor is
4190 ** configured to use Prev, not Next.
4191 **
4192 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
4193 ** opcode will either land on a record that exactly matches the key, or
4194 ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
4195 ** this opcode must be followed by an IdxLE opcode with the same arguments.
4196 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
4197 ** IdxGE opcode will be used on subsequent loop iterations. The
4198 ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
4199 ** is an equality search.
4200 **
4201 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
4202 */
4203 case OP_SeekLT: /* jump, in3, group */
4204 case OP_SeekLE: /* jump, in3, group */
4205 case OP_SeekGE: /* jump, in3, group */
4206 case OP_SeekGT: { /* jump, in3, group */
4207 int res; /* Comparison result */
4208 int oc; /* Opcode */
4209 VdbeCursor *pC; /* The cursor to seek */
4210 UnpackedRecord r; /* The key to seek for */
4211 int nField; /* Number of columns or fields in the key */
4212 i64 iKey; /* The rowid we are to seek to */
4213 int eqOnly; /* Only interested in == results */
4214
4215 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4216 assert( pOp->p2!=0 );
4217 pC = p->apCsr[pOp->p1];
4218 assert( pC!=0 );
4219 assert( pC->eCurType==CURTYPE_BTREE );
4220 assert( OP_SeekLE == OP_SeekLT+1 );
4221 assert( OP_SeekGE == OP_SeekLT+2 );
4222 assert( OP_SeekGT == OP_SeekLT+3 );
4223 assert( pC->isOrdered );
4224 assert( pC->uc.pCursor!=0 );
4225 oc = pOp->opcode;
4226 eqOnly = 0;
4227 pC->nullRow = 0;
4228 #ifdef SQLITE_DEBUG
4229 pC->seekOp = pOp->opcode;
4230 #endif
4231
4232 pC->deferredMoveto = 0;
4233 pC->cacheStatus = CACHE_STALE;
4234 if( pC->isTable ){
4235 u16 flags3, newType;
4236 /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
4237 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
4238 || CORRUPT_DB );
4239
4240 /* The input value in P3 might be of any type: integer, real, string,
4241 ** blob, or NULL. But it needs to be an integer before we can do
4242 ** the seek, so convert it. */
4243 pIn3 = &aMem[pOp->p3];
4244 flags3 = pIn3->flags;
4245 if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
4246 applyNumericAffinity(pIn3, 0);
4247 }
4248 iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
4249 newType = pIn3->flags; /* Record the type after applying numeric affinity */
4250 pIn3->flags = flags3; /* But convert the type back to its original */
4251
4252 /* If the P3 value could not be converted into an integer without
4253 ** loss of information, then special processing is required... */
4254 if( (newType & (MEM_Int|MEM_IntReal))==0 ){
4255 if( (newType & MEM_Real)==0 ){
4256 if( (newType & MEM_Null) || oc>=OP_SeekGE ){
4257 VdbeBranchTaken(1,2);
4258 goto jump_to_p2;
4259 }else{
4260 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4261 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4262 goto seek_not_found;
4263 }
4264 }else
4265
4266 /* If the approximation iKey is larger than the actual real search
4267 ** term, substitute >= for > and < for <=. e.g. if the search term
4268 ** is 4.9 and the integer approximation 5:
4269 **
4270 ** (x > 4.9) -> (x >= 5)
4271 ** (x <= 4.9) -> (x < 5)
4272 */
4273 if( pIn3->u.r<(double)iKey ){
4274 assert( OP_SeekGE==(OP_SeekGT-1) );
4275 assert( OP_SeekLT==(OP_SeekLE-1) );
4276 assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
4277 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
4278 }
4279
4280 /* If the approximation iKey is smaller than the actual real search
4281 ** term, substitute <= for < and > for >=. */
4282 else if( pIn3->u.r>(double)iKey ){
4283 assert( OP_SeekLE==(OP_SeekLT+1) );
4284 assert( OP_SeekGT==(OP_SeekGE+1) );
4285 assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
4286 if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
4287 }
4288 }
4289 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
4290 pC->movetoTarget = iKey; /* Used by OP_Delete */
4291 if( rc!=SQLITE_OK ){
4292 goto abort_due_to_error;
4293 }
4294 }else{
4295 /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
4296 ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
4297 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
4298 ** with the same key.
4299 */
4300 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
4301 eqOnly = 1;
4302 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
4303 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4304 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
4305 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
4306 assert( pOp[1].p1==pOp[0].p1 );
4307 assert( pOp[1].p2==pOp[0].p2 );
4308 assert( pOp[1].p3==pOp[0].p3 );
4309 assert( pOp[1].p4.i==pOp[0].p4.i );
4310 }
4311
4312 nField = pOp->p4.i;
4313 assert( pOp->p4type==P4_INT32 );
4314 assert( nField>0 );
4315 r.pKeyInfo = pC->pKeyInfo;
4316 r.nField = (u16)nField;
4317
4318 /* The next line of code computes as follows, only faster:
4319 ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
4320 ** r.default_rc = -1;
4321 ** }else{
4322 ** r.default_rc = +1;
4323 ** }
4324 */
4325 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
4326 assert( oc!=OP_SeekGT || r.default_rc==-1 );
4327 assert( oc!=OP_SeekLE || r.default_rc==-1 );
4328 assert( oc!=OP_SeekGE || r.default_rc==+1 );
4329 assert( oc!=OP_SeekLT || r.default_rc==+1 );
4330
4331 r.aMem = &aMem[pOp->p3];
4332 #ifdef SQLITE_DEBUG
4333 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
4334 #endif
4335 r.eqSeen = 0;
4336 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
4337 if( rc!=SQLITE_OK ){
4338 goto abort_due_to_error;
4339 }
4340 if( eqOnly && r.eqSeen==0 ){
4341 assert( res!=0 );
4342 goto seek_not_found;
4343 }
4344 }
4345 #ifdef SQLITE_TEST
4346 sqlite3_search_count++;
4347 #endif
4348 if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
4349 if( res<0 || (res==0 && oc==OP_SeekGT) ){
4350 res = 0;
4351 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4352 if( rc!=SQLITE_OK ){
4353 if( rc==SQLITE_DONE ){
4354 rc = SQLITE_OK;
4355 res = 1;
4356 }else{
4357 goto abort_due_to_error;
4358 }
4359 }
4360 }else{
4361 res = 0;
4362 }
4363 }else{
4364 assert( oc==OP_SeekLT || oc==OP_SeekLE );
4365 if( res>0 || (res==0 && oc==OP_SeekLT) ){
4366 res = 0;
4367 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
4368 if( rc!=SQLITE_OK ){
4369 if( rc==SQLITE_DONE ){
4370 rc = SQLITE_OK;
4371 res = 1;
4372 }else{
4373 goto abort_due_to_error;
4374 }
4375 }
4376 }else{
4377 /* res might be negative because the table is empty. Check to
4378 ** see if this is the case.
4379 */
4380 res = sqlite3BtreeEof(pC->uc.pCursor);
4381 }
4382 }
4383 seek_not_found:
4384 assert( pOp->p2>0 );
4385 VdbeBranchTaken(res!=0,2);
4386 if( res ){
4387 goto jump_to_p2;
4388 }else if( eqOnly ){
4389 assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
4390 pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
4391 }
4392 break;
4393 }
4394
4395
4396 /* Opcode: SeekScan P1 P2 * * *
4397 ** Synopsis: Scan-ahead up to P1 rows
4398 **
4399 ** This opcode is a prefix opcode to OP_SeekGE. In other words, this
4400 ** opcode must be immediately followed by OP_SeekGE. This constraint is
4401 ** checked by assert() statements.
4402 **
4403 ** This opcode uses the P1 through P4 operands of the subsequent
4404 ** OP_SeekGE. In the text that follows, the operands of the subsequent
4405 ** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4. Only
4406 ** the P1 and P2 operands of this opcode are also used, and are called
4407 ** This.P1 and This.P2.
4408 **
4409 ** This opcode helps to optimize IN operators on a multi-column index
4410 ** where the IN operator is on the later terms of the index by avoiding
4411 ** unnecessary seeks on the btree, substituting steps to the next row
4412 ** of the b-tree instead. A correct answer is obtained if this opcode
4413 ** is omitted or is a no-op.
4414 **
4415 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
4416 ** is the desired entry that we want the cursor SeekGE.P1 to be pointing
4417 ** to. Call this SeekGE.P4/P5 row the "target".
4418 **
4419 ** If the SeekGE.P1 cursor is not currently pointing to a valid row,
4420 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
4421 **
4422 ** If the SeekGE.P1 cursor is pointing to a valid row, then that row
4423 ** might be the target row, or it might be near and slightly before the
4424 ** target row. This opcode attempts to position the cursor on the target
4425 ** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
4426 ** between 0 and This.P1 times.
4427 **
4428 ** There are three possible outcomes from this opcode:<ol>
4429 **
4430 ** <li> If after This.P1 steps, the cursor is still pointing to a place that
4431 ** is earlier in the btree than the target row, then fall through
4432 ** into the subsquence OP_SeekGE opcode.
4433 **
4434 ** <li> If the cursor is successfully moved to the target row by 0 or more
4435 ** sqlite3BtreeNext() calls, then jump to This.P2, which will land just
4436 ** past the OP_IdxGT or OP_IdxGE opcode that follows the OP_SeekGE.
4437 **
4438 ** <li> If the cursor ends up past the target row (indicating the the target
4439 ** row does not exist in the btree) then jump to SeekOP.P2.
4440 ** </ol>
4441 */
4442 case OP_SeekScan: {
4443 VdbeCursor *pC;
4444 int res;
4445 int nStep;
4446 UnpackedRecord r;
4447
4448 assert( pOp[1].opcode==OP_SeekGE );
4449
4450 /* pOp->p2 points to the first instruction past the OP_IdxGT that
4451 ** follows the OP_SeekGE. */
4452 assert( pOp->p2>=(int)(pOp-aOp)+2 );
4453 assert( aOp[pOp->p2-1].opcode==OP_IdxGT || aOp[pOp->p2-1].opcode==OP_IdxGE );
4454 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
4455 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
4456 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
4457 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
4458
4459 assert( pOp->p1>0 );
4460 pC = p->apCsr[pOp[1].p1];
4461 assert( pC!=0 );
4462 assert( pC->eCurType==CURTYPE_BTREE );
4463 assert( !pC->isTable );
4464 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
4465 #ifdef SQLITE_DEBUG
4466 if( db->flags&SQLITE_VdbeTrace ){
4467 printf("... cursor not valid - fall through\n");
4468 }
4469 #endif
4470 break;
4471 }
4472 nStep = pOp->p1;
4473 assert( nStep>=1 );
4474 r.pKeyInfo = pC->pKeyInfo;
4475 r.nField = (u16)pOp[1].p4.i;
4476 r.default_rc = 0;
4477 r.aMem = &aMem[pOp[1].p3];
4478 #ifdef SQLITE_DEBUG
4479 {
4480 int i;
4481 for(i=0; i<r.nField; i++){
4482 assert( memIsValid(&r.aMem[i]) );
4483 REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
4484 }
4485 }
4486 #endif
4487 res = 0; /* Not needed. Only used to silence a warning. */
4488 while(1){
4489 rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
4490 if( rc ) goto abort_due_to_error;
4491 if( res>0 ){
4492 seekscan_search_fail:
4493 #ifdef SQLITE_DEBUG
4494 if( db->flags&SQLITE_VdbeTrace ){
4495 printf("... %d steps and then skip\n", pOp->p1 - nStep);
4496 }
4497 #endif
4498 VdbeBranchTaken(1,3);
4499 pOp++;
4500 goto jump_to_p2;
4501 }
4502 if( res==0 ){
4503 #ifdef SQLITE_DEBUG
4504 if( db->flags&SQLITE_VdbeTrace ){
4505 printf("... %d steps and then success\n", pOp->p1 - nStep);
4506 }
4507 #endif
4508 VdbeBranchTaken(2,3);
4509 goto jump_to_p2;
4510 break;
4511 }
4512 if( nStep<=0 ){
4513 #ifdef SQLITE_DEBUG
4514 if( db->flags&SQLITE_VdbeTrace ){
4515 printf("... fall through after %d steps\n", pOp->p1);
4516 }
4517 #endif
4518 VdbeBranchTaken(0,3);
4519 break;
4520 }
4521 nStep--;
4522 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
4523 if( rc ){
4524 if( rc==SQLITE_DONE ){
4525 rc = SQLITE_OK;
4526 goto seekscan_search_fail;
4527 }else{
4528 goto abort_due_to_error;
4529 }
4530 }
4531 }
4532
4533 break;
4534 }
4535
4536
4537 /* Opcode: SeekHit P1 P2 P3 * *
4538 ** Synopsis: set P2<=seekHit<=P3
4539 **
4540 ** Increase or decrease the seekHit value for cursor P1, if necessary,
4541 ** so that it is no less than P2 and no greater than P3.
4542 **
4543 ** The seekHit integer represents the maximum of terms in an index for which
4544 ** there is known to be at least one match. If the seekHit value is smaller
4545 ** than the total number of equality terms in an index lookup, then the
4546 ** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
4547 ** early, thus saving work. This is part of the IN-early-out optimization.
4548 **
4549 ** P1 must be a valid b-tree cursor.
4550 */
4551 case OP_SeekHit: {
4552 VdbeCursor *pC;
4553 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4554 pC = p->apCsr[pOp->p1];
4555 assert( pC!=0 );
4556 assert( pOp->p3>=pOp->p2 );
4557 if( pC->seekHit<pOp->p2 ){
4558 pC->seekHit = pOp->p2;
4559 }else if( pC->seekHit>pOp->p3 ){
4560 pC->seekHit = pOp->p3;
4561 }
4562 break;
4563 }
4564
4565 /* Opcode: IfNotOpen P1 P2 * * *
4566 ** Synopsis: if( !csr[P1] ) goto P2
4567 **
4568 ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
4569 */
4570 case OP_IfNotOpen: { /* jump */
4571 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4572 VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
4573 if( !p->apCsr[pOp->p1] ){
4574 goto jump_to_p2_and_check_for_interrupt;
4575 }
4576 break;
4577 }
4578
4579 /* Opcode: Found P1 P2 P3 P4 *
4580 ** Synopsis: key=r[P3@P4]
4581 **
4582 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4583 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4584 ** record.
4585 **
4586 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4587 ** is a prefix of any entry in P1 then a jump is made to P2 and
4588 ** P1 is left pointing at the matching entry.
4589 **
4590 ** This operation leaves the cursor in a state where it can be
4591 ** advanced in the forward direction. The Next instruction will work,
4592 ** but not the Prev instruction.
4593 **
4594 ** See also: NotFound, NoConflict, NotExists. SeekGe
4595 */
4596 /* Opcode: NotFound P1 P2 P3 P4 *
4597 ** Synopsis: key=r[P3@P4]
4598 **
4599 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4600 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4601 ** record.
4602 **
4603 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4604 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
4605 ** does contain an entry whose prefix matches the P3/P4 record then control
4606 ** falls through to the next instruction and P1 is left pointing at the
4607 ** matching entry.
4608 **
4609 ** This operation leaves the cursor in a state where it cannot be
4610 ** advanced in either direction. In other words, the Next and Prev
4611 ** opcodes do not work after this operation.
4612 **
4613 ** See also: Found, NotExists, NoConflict, IfNoHope
4614 */
4615 /* Opcode: IfNoHope P1 P2 P3 P4 *
4616 ** Synopsis: key=r[P3@P4]
4617 **
4618 ** Register P3 is the first of P4 registers that form an unpacked
4619 ** record. Cursor P1 is an index btree. P2 is a jump destination.
4620 ** In other words, the operands to this opcode are the same as the
4621 ** operands to OP_NotFound and OP_IdxGT.
4622 **
4623 ** This opcode is an optimization attempt only. If this opcode always
4624 ** falls through, the correct answer is still obtained, but extra works
4625 ** is performed.
4626 **
4627 ** A value of N in the seekHit flag of cursor P1 means that there exists
4628 ** a key P3:N that will match some record in the index. We want to know
4629 ** if it is possible for a record P3:P4 to match some record in the
4630 ** index. If it is not possible, we can skips some work. So if seekHit
4631 ** is less than P4, attempt to find out if a match is possible by running
4632 ** OP_NotFound.
4633 **
4634 ** This opcode is used in IN clause processing for a multi-column key.
4635 ** If an IN clause is attached to an element of the key other than the
4636 ** left-most element, and if there are no matches on the most recent
4637 ** seek over the whole key, then it might be that one of the key element
4638 ** to the left is prohibiting a match, and hence there is "no hope" of
4639 ** any match regardless of how many IN clause elements are checked.
4640 ** In such a case, we abandon the IN clause search early, using this
4641 ** opcode. The opcode name comes from the fact that the
4642 ** jump is taken if there is "no hope" of achieving a match.
4643 **
4644 ** See also: NotFound, SeekHit
4645 */
4646 /* Opcode: NoConflict P1 P2 P3 P4 *
4647 ** Synopsis: key=r[P3@P4]
4648 **
4649 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
4650 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
4651 ** record.
4652 **
4653 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
4654 ** contains any NULL value, jump immediately to P2. If all terms of the
4655 ** record are not-NULL then a check is done to determine if any row in the
4656 ** P1 index btree has a matching key prefix. If there are no matches, jump
4657 ** immediately to P2. If there is a match, fall through and leave the P1
4658 ** cursor pointing to the matching row.
4659 **
4660 ** This opcode is similar to OP_NotFound with the exceptions that the
4661 ** branch is always taken if any part of the search key input is NULL.
4662 **
4663 ** This operation leaves the cursor in a state where it cannot be
4664 ** advanced in either direction. In other words, the Next and Prev
4665 ** opcodes do not work after this operation.
4666 **
4667 ** See also: NotFound, Found, NotExists
4668 */
4669 case OP_IfNoHope: { /* jump, in3 */
4670 VdbeCursor *pC;
4671 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4672 pC = p->apCsr[pOp->p1];
4673 assert( pC!=0 );
4674 if( pC->seekHit>=pOp->p4.i ) break;
4675 /* Fall through into OP_NotFound */
4676 /* no break */ deliberate_fall_through
4677 }
4678 case OP_NoConflict: /* jump, in3 */
4679 case OP_NotFound: /* jump, in3 */
4680 case OP_Found: { /* jump, in3 */
4681 int alreadyExists;
4682 int takeJump;
4683 int ii;
4684 VdbeCursor *pC;
4685 int res;
4686 UnpackedRecord *pFree;
4687 UnpackedRecord *pIdxKey;
4688 UnpackedRecord r;
4689
4690 #ifdef SQLITE_TEST
4691 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
4692 #endif
4693
4694 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4695 assert( pOp->p4type==P4_INT32 );
4696 pC = p->apCsr[pOp->p1];
4697 assert( pC!=0 );
4698 #ifdef SQLITE_DEBUG
4699 pC->seekOp = pOp->opcode;
4700 #endif
4701 pIn3 = &aMem[pOp->p3];
4702 assert( pC->eCurType==CURTYPE_BTREE );
4703 assert( pC->uc.pCursor!=0 );
4704 assert( pC->isTable==0 );
4705 if( pOp->p4.i>0 ){
4706 r.pKeyInfo = pC->pKeyInfo;
4707 r.nField = (u16)pOp->p4.i;
4708 r.aMem = pIn3;
4709 #ifdef SQLITE_DEBUG
4710 for(ii=0; ii<r.nField; ii++){
4711 assert( memIsValid(&r.aMem[ii]) );
4712 assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
4713 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
4714 }
4715 #endif
4716 pIdxKey = &r;
4717 pFree = 0;
4718 }else{
4719 assert( pIn3->flags & MEM_Blob );
4720 rc = ExpandBlob(pIn3);
4721 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
4722 if( rc ) goto no_mem;
4723 pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
4724 if( pIdxKey==0 ) goto no_mem;
4725 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
4726 }
4727 pIdxKey->default_rc = 0;
4728 takeJump = 0;
4729 if( pOp->opcode==OP_NoConflict ){
4730 /* For the OP_NoConflict opcode, take the jump if any of the
4731 ** input fields are NULL, since any key with a NULL will not
4732 ** conflict */
4733 for(ii=0; ii<pIdxKey->nField; ii++){
4734 if( pIdxKey->aMem[ii].flags & MEM_Null ){
4735 takeJump = 1;
4736 break;
4737 }
4738 }
4739 }
4740 rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
4741 if( pFree ) sqlite3DbFreeNN(db, pFree);
4742 if( rc!=SQLITE_OK ){
4743 goto abort_due_to_error;
4744 }
4745 pC->seekResult = res;
4746 alreadyExists = (res==0);
4747 pC->nullRow = 1-alreadyExists;
4748 pC->deferredMoveto = 0;
4749 pC->cacheStatus = CACHE_STALE;
4750 if( pOp->opcode==OP_Found ){
4751 VdbeBranchTaken(alreadyExists!=0,2);
4752 if( alreadyExists ) goto jump_to_p2;
4753 }else{
4754 VdbeBranchTaken(takeJump||alreadyExists==0,2);
4755 if( takeJump || !alreadyExists ) goto jump_to_p2;
4756 if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
4757 }
4758 break;
4759 }
4760
4761 /* Opcode: SeekRowid P1 P2 P3 * *
4762 ** Synopsis: intkey=r[P3]
4763 **
4764 ** P1 is the index of a cursor open on an SQL table btree (with integer
4765 ** keys). If register P3 does not contain an integer or if P1 does not
4766 ** contain a record with rowid P3 then jump immediately to P2.
4767 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
4768 ** a record with rowid P3 then
4769 ** leave the cursor pointing at that record and fall through to the next
4770 ** instruction.
4771 **
4772 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
4773 ** the P3 register must be guaranteed to contain an integer value. With this
4774 ** opcode, register P3 might not contain an integer.
4775 **
4776 ** The OP_NotFound opcode performs the same operation on index btrees
4777 ** (with arbitrary multi-value keys).
4778 **
4779 ** This opcode leaves the cursor in a state where it cannot be advanced
4780 ** in either direction. In other words, the Next and Prev opcodes will
4781 ** not work following this opcode.
4782 **
4783 ** See also: Found, NotFound, NoConflict, SeekRowid
4784 */
4785 /* Opcode: NotExists P1 P2 P3 * *
4786 ** Synopsis: intkey=r[P3]
4787 **
4788 ** P1 is the index of a cursor open on an SQL table btree (with integer
4789 ** keys). P3 is an integer rowid. If P1 does not contain a record with
4790 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
4791 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
4792 ** leave the cursor pointing at that record and fall through to the next
4793 ** instruction.
4794 **
4795 ** The OP_SeekRowid opcode performs the same operation but also allows the
4796 ** P3 register to contain a non-integer value, in which case the jump is
4797 ** always taken. This opcode requires that P3 always contain an integer.
4798 **
4799 ** The OP_NotFound opcode performs the same operation on index btrees
4800 ** (with arbitrary multi-value keys).
4801 **
4802 ** This opcode leaves the cursor in a state where it cannot be advanced
4803 ** in either direction. In other words, the Next and Prev opcodes will
4804 ** not work following this opcode.
4805 **
4806 ** See also: Found, NotFound, NoConflict, SeekRowid
4807 */
4808 case OP_SeekRowid: { /* jump, in3 */
4809 VdbeCursor *pC;
4810 BtCursor *pCrsr;
4811 int res;
4812 u64 iKey;
4813
4814 pIn3 = &aMem[pOp->p3];
4815 testcase( pIn3->flags & MEM_Int );
4816 testcase( pIn3->flags & MEM_IntReal );
4817 testcase( pIn3->flags & MEM_Real );
4818 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
4819 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
4820 /* If pIn3->u.i does not contain an integer, compute iKey as the
4821 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
4822 ** into an integer without loss of information. Take care to avoid
4823 ** changing the datatype of pIn3, however, as it is used by other
4824 ** parts of the prepared statement. */
4825 Mem x = pIn3[0];
4826 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
4827 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
4828 iKey = x.u.i;
4829 goto notExistsWithKey;
4830 }
4831 /* Fall through into OP_NotExists */
4832 /* no break */ deliberate_fall_through
4833 case OP_NotExists: /* jump, in3 */
4834 pIn3 = &aMem[pOp->p3];
4835 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
4836 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4837 iKey = pIn3->u.i;
4838 notExistsWithKey:
4839 pC = p->apCsr[pOp->p1];
4840 assert( pC!=0 );
4841 #ifdef SQLITE_DEBUG
4842 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
4843 #endif
4844 assert( pC->isTable );
4845 assert( pC->eCurType==CURTYPE_BTREE );
4846 pCrsr = pC->uc.pCursor;
4847 assert( pCrsr!=0 );
4848 res = 0;
4849 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
4850 assert( rc==SQLITE_OK || res==0 );
4851 pC->movetoTarget = iKey; /* Used by OP_Delete */
4852 pC->nullRow = 0;
4853 pC->cacheStatus = CACHE_STALE;
4854 pC->deferredMoveto = 0;
4855 VdbeBranchTaken(res!=0,2);
4856 pC->seekResult = res;
4857 if( res!=0 ){
4858 assert( rc==SQLITE_OK );
4859 if( pOp->p2==0 ){
4860 rc = SQLITE_CORRUPT_BKPT;
4861 }else{
4862 goto jump_to_p2;
4863 }
4864 }
4865 if( rc ) goto abort_due_to_error;
4866 break;
4867 }
4868
4869 /* Opcode: Sequence P1 P2 * * *
4870 ** Synopsis: r[P2]=cursor[P1].ctr++
4871 **
4872 ** Find the next available sequence number for cursor P1.
4873 ** Write the sequence number into register P2.
4874 ** The sequence number on the cursor is incremented after this
4875 ** instruction.
4876 */
4877 case OP_Sequence: { /* out2 */
4878 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4879 assert( p->apCsr[pOp->p1]!=0 );
4880 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
4881 pOut = out2Prerelease(p, pOp);
4882 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
4883 break;
4884 }
4885
4886
4887 /* Opcode: NewRowid P1 P2 P3 * *
4888 ** Synopsis: r[P2]=rowid
4889 **
4890 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
4891 ** The record number is not previously used as a key in the database
4892 ** table that cursor P1 points to. The new record number is written
4893 ** written to register P2.
4894 **
4895 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
4896 ** the largest previously generated record number. No new record numbers are
4897 ** allowed to be less than this value. When this value reaches its maximum,
4898 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
4899 ** generated record number. This P3 mechanism is used to help implement the
4900 ** AUTOINCREMENT feature.
4901 */
4902 case OP_NewRowid: { /* out2 */
4903 i64 v; /* The new rowid */
4904 VdbeCursor *pC; /* Cursor of table to get the new rowid */
4905 int res; /* Result of an sqlite3BtreeLast() */
4906 int cnt; /* Counter to limit the number of searches */
4907 #ifndef SQLITE_OMIT_AUTOINCREMENT
4908 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
4909 VdbeFrame *pFrame; /* Root frame of VDBE */
4910 #endif
4911
4912 v = 0;
4913 res = 0;
4914 pOut = out2Prerelease(p, pOp);
4915 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4916 pC = p->apCsr[pOp->p1];
4917 assert( pC!=0 );
4918 assert( pC->isTable );
4919 assert( pC->eCurType==CURTYPE_BTREE );
4920 assert( pC->uc.pCursor!=0 );
4921 {
4922 /* The next rowid or record number (different terms for the same
4923 ** thing) is obtained in a two-step algorithm.
4924 **
4925 ** First we attempt to find the largest existing rowid and add one
4926 ** to that. But if the largest existing rowid is already the maximum
4927 ** positive integer, we have to fall through to the second
4928 ** probabilistic algorithm
4929 **
4930 ** The second algorithm is to select a rowid at random and see if
4931 ** it already exists in the table. If it does not exist, we have
4932 ** succeeded. If the random rowid does exist, we select a new one
4933 ** and try again, up to 100 times.
4934 */
4935 assert( pC->isTable );
4936
4937 #ifdef SQLITE_32BIT_ROWID
4938 # define MAX_ROWID 0x7fffffff
4939 #else
4940 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
4941 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
4942 ** to provide the constant while making all compilers happy.
4943 */
4944 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
4945 #endif
4946
4947 if( !pC->useRandomRowid ){
4948 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
4949 if( rc!=SQLITE_OK ){
4950 goto abort_due_to_error;
4951 }
4952 if( res ){
4953 v = 1; /* IMP: R-61914-48074 */
4954 }else{
4955 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
4956 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
4957 if( v>=MAX_ROWID ){
4958 pC->useRandomRowid = 1;
4959 }else{
4960 v++; /* IMP: R-29538-34987 */
4961 }
4962 }
4963 }
4964
4965 #ifndef SQLITE_OMIT_AUTOINCREMENT
4966 if( pOp->p3 ){
4967 /* Assert that P3 is a valid memory cell. */
4968 assert( pOp->p3>0 );
4969 if( p->pFrame ){
4970 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
4971 /* Assert that P3 is a valid memory cell. */
4972 assert( pOp->p3<=pFrame->nMem );
4973 pMem = &pFrame->aMem[pOp->p3];
4974 }else{
4975 /* Assert that P3 is a valid memory cell. */
4976 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
4977 pMem = &aMem[pOp->p3];
4978 memAboutToChange(p, pMem);
4979 }
4980 assert( memIsValid(pMem) );
4981
4982 REGISTER_TRACE(pOp->p3, pMem);
4983 sqlite3VdbeMemIntegerify(pMem);
4984 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
4985 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
4986 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
4987 goto abort_due_to_error;
4988 }
4989 if( v<pMem->u.i+1 ){
4990 v = pMem->u.i + 1;
4991 }
4992 pMem->u.i = v;
4993 }
4994 #endif
4995 if( pC->useRandomRowid ){
4996 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
4997 ** largest possible integer (9223372036854775807) then the database
4998 ** engine starts picking positive candidate ROWIDs at random until
4999 ** it finds one that is not previously used. */
5000 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
5001 ** an AUTOINCREMENT table. */
5002 cnt = 0;
5003 do{
5004 sqlite3_randomness(sizeof(v), &v);
5005 v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
5006 }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
5007 0, &res))==SQLITE_OK)
5008 && (res==0)
5009 && (++cnt<100));
5010 if( rc ) goto abort_due_to_error;
5011 if( res==0 ){
5012 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
5013 goto abort_due_to_error;
5014 }
5015 assert( v>0 ); /* EV: R-40812-03570 */
5016 }
5017 pC->deferredMoveto = 0;
5018 pC->cacheStatus = CACHE_STALE;
5019 }
5020 pOut->u.i = v;
5021 break;
5022 }
5023
5024 /* Opcode: Insert P1 P2 P3 P4 P5
5025 ** Synopsis: intkey=r[P3] data=r[P2]
5026 **
5027 ** Write an entry into the table of cursor P1. A new entry is
5028 ** created if it doesn't already exist or the data for an existing
5029 ** entry is overwritten. The data is the value MEM_Blob stored in register
5030 ** number P2. The key is stored in register P3. The key must
5031 ** be a MEM_Int.
5032 **
5033 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
5034 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
5035 ** then rowid is stored for subsequent return by the
5036 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
5037 **
5038 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5039 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5040 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5041 ** seeks on the cursor or if the most recent seek used a key equal to P3.
5042 **
5043 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
5044 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
5045 ** is part of an INSERT operation. The difference is only important to
5046 ** the update hook.
5047 **
5048 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
5049 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
5050 ** following a successful insert.
5051 **
5052 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
5053 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
5054 ** and register P2 becomes ephemeral. If the cursor is changed, the
5055 ** value of register P2 will then change. Make sure this does not
5056 ** cause any problems.)
5057 **
5058 ** This instruction only works on tables. The equivalent instruction
5059 ** for indices is OP_IdxInsert.
5060 */
5061 case OP_Insert: {
5062 Mem *pData; /* MEM cell holding data for the record to be inserted */
5063 Mem *pKey; /* MEM cell holding key for the record */
5064 VdbeCursor *pC; /* Cursor to table into which insert is written */
5065 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
5066 const char *zDb; /* database name - used by the update hook */
5067 Table *pTab; /* Table structure - used by update and pre-update hooks */
5068 BtreePayload x; /* Payload to be inserted */
5069
5070 pData = &aMem[pOp->p2];
5071 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5072 assert( memIsValid(pData) );
5073 pC = p->apCsr[pOp->p1];
5074 assert( pC!=0 );
5075 assert( pC->eCurType==CURTYPE_BTREE );
5076 assert( pC->deferredMoveto==0 );
5077 assert( pC->uc.pCursor!=0 );
5078 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
5079 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
5080 REGISTER_TRACE(pOp->p2, pData);
5081 sqlite3VdbeIncrWriteCounter(p, pC);
5082
5083 pKey = &aMem[pOp->p3];
5084 assert( pKey->flags & MEM_Int );
5085 assert( memIsValid(pKey) );
5086 REGISTER_TRACE(pOp->p3, pKey);
5087 x.nKey = pKey->u.i;
5088
5089 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5090 assert( pC->iDb>=0 );
5091 zDb = db->aDb[pC->iDb].zDbSName;
5092 pTab = pOp->p4.pTab;
5093 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
5094 }else{
5095 pTab = 0;
5096 zDb = 0; /* Not needed. Silence a compiler warning. */
5097 }
5098
5099 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5100 /* Invoke the pre-update hook, if any */
5101 if( pTab ){
5102 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
5103 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
5104 }
5105 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
5106 /* Prevent post-update hook from running in cases when it should not */
5107 pTab = 0;
5108 }
5109 }
5110 if( pOp->p5 & OPFLAG_ISNOOP ) break;
5111 #endif
5112
5113 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5114 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
5115 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
5116 x.pData = pData->z;
5117 x.nData = pData->n;
5118 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5119 if( pData->flags & MEM_Zero ){
5120 x.nZero = pData->u.nZero;
5121 }else{
5122 x.nZero = 0;
5123 }
5124 x.pKey = 0;
5125 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5126 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5127 seekResult
5128 );
5129 pC->deferredMoveto = 0;
5130 pC->cacheStatus = CACHE_STALE;
5131
5132 /* Invoke the update-hook if required. */
5133 if( rc ) goto abort_due_to_error;
5134 if( pTab ){
5135 assert( db->xUpdateCallback!=0 );
5136 assert( pTab->aCol!=0 );
5137 db->xUpdateCallback(db->pUpdateArg,
5138 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
5139 zDb, pTab->zName, x.nKey);
5140 }
5141 break;
5142 }
5143
5144 /* Opcode: RowCell P1 P2 P3 * *
5145 **
5146 ** P1 and P2 are both open cursors. Both must be opened on the same type
5147 ** of table - intkey or index. This opcode is used as part of copying
5148 ** the current row from P2 into P1. If the cursors are opened on intkey
5149 ** tables, register P3 contains the rowid to use with the new record in
5150 ** P1. If they are opened on index tables, P3 is not used.
5151 **
5152 ** This opcode must be followed by either an Insert or InsertIdx opcode
5153 ** with the OPFLAG_PREFORMAT flag set to complete the insert operation.
5154 */
5155 case OP_RowCell: {
5156 VdbeCursor *pDest; /* Cursor to write to */
5157 VdbeCursor *pSrc; /* Cursor to read from */
5158 i64 iKey; /* Rowid value to insert with */
5159 assert( pOp[1].opcode==OP_Insert || pOp[1].opcode==OP_IdxInsert );
5160 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
5161 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
5162 assert( pOp[1].p5 & OPFLAG_PREFORMAT );
5163 pDest = p->apCsr[pOp->p1];
5164 pSrc = p->apCsr[pOp->p2];
5165 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
5166 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
5167 if( rc!=SQLITE_OK ) goto abort_due_to_error;
5168 break;
5169 };
5170
5171 /* Opcode: Delete P1 P2 P3 P4 P5
5172 **
5173 ** Delete the record at which the P1 cursor is currently pointing.
5174 **
5175 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
5176 ** the cursor will be left pointing at either the next or the previous
5177 ** record in the table. If it is left pointing at the next record, then
5178 ** the next Next instruction will be a no-op. As a result, in this case
5179 ** it is ok to delete a record from within a Next loop. If
5180 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
5181 ** left in an undefined state.
5182 **
5183 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
5184 ** delete one of several associated with deleting a table row and all its
5185 ** associated index entries. Exactly one of those deletes is the "primary"
5186 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
5187 ** marked with the AUXDELETE flag.
5188 **
5189 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
5190 ** change count is incremented (otherwise not).
5191 **
5192 ** P1 must not be pseudo-table. It has to be a real table with
5193 ** multiple rows.
5194 **
5195 ** If P4 is not NULL then it points to a Table object. In this case either
5196 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
5197 ** have been positioned using OP_NotFound prior to invoking this opcode in
5198 ** this case. Specifically, if one is configured, the pre-update hook is
5199 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
5200 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
5201 **
5202 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
5203 ** of the memory cell that contains the value that the rowid of the row will
5204 ** be set to by the update.
5205 */
5206 case OP_Delete: {
5207 VdbeCursor *pC;
5208 const char *zDb;
5209 Table *pTab;
5210 int opflags;
5211
5212 opflags = pOp->p2;
5213 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5214 pC = p->apCsr[pOp->p1];
5215 assert( pC!=0 );
5216 assert( pC->eCurType==CURTYPE_BTREE );
5217 assert( pC->uc.pCursor!=0 );
5218 assert( pC->deferredMoveto==0 );
5219 sqlite3VdbeIncrWriteCounter(p, pC);
5220
5221 #ifdef SQLITE_DEBUG
5222 if( pOp->p4type==P4_TABLE
5223 && HasRowid(pOp->p4.pTab)
5224 && pOp->p5==0
5225 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
5226 ){
5227 /* If p5 is zero, the seek operation that positioned the cursor prior to
5228 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
5229 ** the row that is being deleted */
5230 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5231 assert( CORRUPT_DB || pC->movetoTarget==iKey );
5232 }
5233 #endif
5234
5235 /* If the update-hook or pre-update-hook will be invoked, set zDb to
5236 ** the name of the db to pass as to it. Also set local pTab to a copy
5237 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
5238 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
5239 ** VdbeCursor.movetoTarget to the current rowid. */
5240 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
5241 assert( pC->iDb>=0 );
5242 assert( pOp->p4.pTab!=0 );
5243 zDb = db->aDb[pC->iDb].zDbSName;
5244 pTab = pOp->p4.pTab;
5245 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
5246 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5247 }
5248 }else{
5249 zDb = 0; /* Not needed. Silence a compiler warning. */
5250 pTab = 0; /* Not needed. Silence a compiler warning. */
5251 }
5252
5253 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
5254 /* Invoke the pre-update-hook if required. */
5255 if( db->xPreUpdateCallback && pOp->p4.pTab ){
5256 assert( !(opflags & OPFLAG_ISUPDATE)
5257 || HasRowid(pTab)==0
5258 || (aMem[pOp->p3].flags & MEM_Int)
5259 );
5260 sqlite3VdbePreUpdateHook(p, pC,
5261 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
5262 zDb, pTab, pC->movetoTarget,
5263 pOp->p3
5264 );
5265 }
5266 if( opflags & OPFLAG_ISNOOP ) break;
5267 #endif
5268
5269 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
5270 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
5271 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
5272 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
5273
5274 #ifdef SQLITE_DEBUG
5275 if( p->pFrame==0 ){
5276 if( pC->isEphemeral==0
5277 && (pOp->p5 & OPFLAG_AUXDELETE)==0
5278 && (pC->wrFlag & OPFLAG_FORDELETE)==0
5279 ){
5280 nExtraDelete++;
5281 }
5282 if( pOp->p2 & OPFLAG_NCHANGE ){
5283 nExtraDelete--;
5284 }
5285 }
5286 #endif
5287
5288 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
5289 pC->cacheStatus = CACHE_STALE;
5290 pC->seekResult = 0;
5291 if( rc ) goto abort_due_to_error;
5292
5293 /* Invoke the update-hook if required. */
5294 if( opflags & OPFLAG_NCHANGE ){
5295 p->nChange++;
5296 if( db->xUpdateCallback && HasRowid(pTab) ){
5297 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
5298 pC->movetoTarget);
5299 assert( pC->iDb>=0 );
5300 }
5301 }
5302
5303 break;
5304 }
5305 /* Opcode: ResetCount * * * * *
5306 **
5307 ** The value of the change counter is copied to the database handle
5308 ** change counter (returned by subsequent calls to sqlite3_changes()).
5309 ** Then the VMs internal change counter resets to 0.
5310 ** This is used by trigger programs.
5311 */
5312 case OP_ResetCount: {
5313 sqlite3VdbeSetChanges(db, p->nChange);
5314 p->nChange = 0;
5315 break;
5316 }
5317
5318 /* Opcode: SorterCompare P1 P2 P3 P4
5319 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
5320 **
5321 ** P1 is a sorter cursor. This instruction compares a prefix of the
5322 ** record blob in register P3 against a prefix of the entry that
5323 ** the sorter cursor currently points to. Only the first P4 fields
5324 ** of r[P3] and the sorter record are compared.
5325 **
5326 ** If either P3 or the sorter contains a NULL in one of their significant
5327 ** fields (not counting the P4 fields at the end which are ignored) then
5328 ** the comparison is assumed to be equal.
5329 **
5330 ** Fall through to next instruction if the two records compare equal to
5331 ** each other. Jump to P2 if they are different.
5332 */
5333 case OP_SorterCompare: {
5334 VdbeCursor *pC;
5335 int res;
5336 int nKeyCol;
5337
5338 pC = p->apCsr[pOp->p1];
5339 assert( isSorter(pC) );
5340 assert( pOp->p4type==P4_INT32 );
5341 pIn3 = &aMem[pOp->p3];
5342 nKeyCol = pOp->p4.i;
5343 res = 0;
5344 rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
5345 VdbeBranchTaken(res!=0,2);
5346 if( rc ) goto abort_due_to_error;
5347 if( res ) goto jump_to_p2;
5348 break;
5349 };
5350
5351 /* Opcode: SorterData P1 P2 P3 * *
5352 ** Synopsis: r[P2]=data
5353 **
5354 ** Write into register P2 the current sorter data for sorter cursor P1.
5355 ** Then clear the column header cache on cursor P3.
5356 **
5357 ** This opcode is normally use to move a record out of the sorter and into
5358 ** a register that is the source for a pseudo-table cursor created using
5359 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
5360 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
5361 ** us from having to issue a separate NullRow instruction to clear that cache.
5362 */
5363 case OP_SorterData: {
5364 VdbeCursor *pC;
5365
5366 pOut = &aMem[pOp->p2];
5367 pC = p->apCsr[pOp->p1];
5368 assert( isSorter(pC) );
5369 rc = sqlite3VdbeSorterRowkey(pC, pOut);
5370 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
5371 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5372 if( rc ) goto abort_due_to_error;
5373 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
5374 break;
5375 }
5376
5377 /* Opcode: RowData P1 P2 P3 * *
5378 ** Synopsis: r[P2]=data
5379 **
5380 ** Write into register P2 the complete row content for the row at
5381 ** which cursor P1 is currently pointing.
5382 ** There is no interpretation of the data.
5383 ** It is just copied onto the P2 register exactly as
5384 ** it is found in the database file.
5385 **
5386 ** If cursor P1 is an index, then the content is the key of the row.
5387 ** If cursor P2 is a table, then the content extracted is the data.
5388 **
5389 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
5390 ** of a real table, not a pseudo-table.
5391 **
5392 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
5393 ** into the database page. That means that the content of the output
5394 ** register will be invalidated as soon as the cursor moves - including
5395 ** moves caused by other cursors that "save" the current cursors
5396 ** position in order that they can write to the same table. If P3==0
5397 ** then a copy of the data is made into memory. P3!=0 is faster, but
5398 ** P3==0 is safer.
5399 **
5400 ** If P3!=0 then the content of the P2 register is unsuitable for use
5401 ** in OP_Result and any OP_Result will invalidate the P2 register content.
5402 ** The P2 register content is invalidated by opcodes like OP_Function or
5403 ** by any use of another cursor pointing to the same table.
5404 */
5405 case OP_RowData: {
5406 VdbeCursor *pC;
5407 BtCursor *pCrsr;
5408 u32 n;
5409
5410 pOut = out2Prerelease(p, pOp);
5411
5412 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5413 pC = p->apCsr[pOp->p1];
5414 assert( pC!=0 );
5415 assert( pC->eCurType==CURTYPE_BTREE );
5416 assert( isSorter(pC)==0 );
5417 assert( pC->nullRow==0 );
5418 assert( pC->uc.pCursor!=0 );
5419 pCrsr = pC->uc.pCursor;
5420
5421 /* The OP_RowData opcodes always follow OP_NotExists or
5422 ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
5423 ** that might invalidate the cursor.
5424 ** If this where not the case, on of the following assert()s
5425 ** would fail. Should this ever change (because of changes in the code
5426 ** generator) then the fix would be to insert a call to
5427 ** sqlite3VdbeCursorMoveto().
5428 */
5429 assert( pC->deferredMoveto==0 );
5430 assert( sqlite3BtreeCursorIsValid(pCrsr) );
5431
5432 n = sqlite3BtreePayloadSize(pCrsr);
5433 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
5434 goto too_big;
5435 }
5436 testcase( n==0 );
5437 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
5438 if( rc ) goto abort_due_to_error;
5439 if( !pOp->p3 ) Deephemeralize(pOut);
5440 UPDATE_MAX_BLOBSIZE(pOut);
5441 REGISTER_TRACE(pOp->p2, pOut);
5442 break;
5443 }
5444
5445 /* Opcode: Rowid P1 P2 * * *
5446 ** Synopsis: r[P2]=rowid
5447 **
5448 ** Store in register P2 an integer which is the key of the table entry that
5449 ** P1 is currently point to.
5450 **
5451 ** P1 can be either an ordinary table or a virtual table. There used to
5452 ** be a separate OP_VRowid opcode for use with virtual tables, but this
5453 ** one opcode now works for both table types.
5454 */
5455 case OP_Rowid: { /* out2 */
5456 VdbeCursor *pC;
5457 i64 v;
5458 sqlite3_vtab *pVtab;
5459 const sqlite3_module *pModule;
5460
5461 pOut = out2Prerelease(p, pOp);
5462 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5463 pC = p->apCsr[pOp->p1];
5464 assert( pC!=0 );
5465 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
5466 if( pC->nullRow ){
5467 pOut->flags = MEM_Null;
5468 break;
5469 }else if( pC->deferredMoveto ){
5470 v = pC->movetoTarget;
5471 #ifndef SQLITE_OMIT_VIRTUALTABLE
5472 }else if( pC->eCurType==CURTYPE_VTAB ){
5473 assert( pC->uc.pVCur!=0 );
5474 pVtab = pC->uc.pVCur->pVtab;
5475 pModule = pVtab->pModule;
5476 assert( pModule->xRowid );
5477 rc = pModule->xRowid(pC->uc.pVCur, &v);
5478 sqlite3VtabImportErrmsg(p, pVtab);
5479 if( rc ) goto abort_due_to_error;
5480 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5481 }else{
5482 assert( pC->eCurType==CURTYPE_BTREE );
5483 assert( pC->uc.pCursor!=0 );
5484 rc = sqlite3VdbeCursorRestore(pC);
5485 if( rc ) goto abort_due_to_error;
5486 if( pC->nullRow ){
5487 pOut->flags = MEM_Null;
5488 break;
5489 }
5490 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
5491 }
5492 pOut->u.i = v;
5493 break;
5494 }
5495
5496 /* Opcode: NullRow P1 * * * *
5497 **
5498 ** Move the cursor P1 to a null row. Any OP_Column operations
5499 ** that occur while the cursor is on the null row will always
5500 ** write a NULL.
5501 */
5502 case OP_NullRow: {
5503 VdbeCursor *pC;
5504
5505 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5506 pC = p->apCsr[pOp->p1];
5507 assert( pC!=0 );
5508 pC->nullRow = 1;
5509 pC->cacheStatus = CACHE_STALE;
5510 if( pC->eCurType==CURTYPE_BTREE ){
5511 assert( pC->uc.pCursor!=0 );
5512 sqlite3BtreeClearCursor(pC->uc.pCursor);
5513 }
5514 #ifdef SQLITE_DEBUG
5515 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
5516 #endif
5517 break;
5518 }
5519
5520 /* Opcode: SeekEnd P1 * * * *
5521 **
5522 ** Position cursor P1 at the end of the btree for the purpose of
5523 ** appending a new entry onto the btree.
5524 **
5525 ** It is assumed that the cursor is used only for appending and so
5526 ** if the cursor is valid, then the cursor must already be pointing
5527 ** at the end of the btree and so no changes are made to
5528 ** the cursor.
5529 */
5530 /* Opcode: Last P1 P2 * * *
5531 **
5532 ** The next use of the Rowid or Column or Prev instruction for P1
5533 ** will refer to the last entry in the database table or index.
5534 ** If the table or index is empty and P2>0, then jump immediately to P2.
5535 ** If P2 is 0 or if the table or index is not empty, fall through
5536 ** to the following instruction.
5537 **
5538 ** This opcode leaves the cursor configured to move in reverse order,
5539 ** from the end toward the beginning. In other words, the cursor is
5540 ** configured to use Prev, not Next.
5541 */
5542 case OP_SeekEnd:
5543 case OP_Last: { /* jump */
5544 VdbeCursor *pC;
5545 BtCursor *pCrsr;
5546 int res;
5547
5548 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5549 pC = p->apCsr[pOp->p1];
5550 assert( pC!=0 );
5551 assert( pC->eCurType==CURTYPE_BTREE );
5552 pCrsr = pC->uc.pCursor;
5553 res = 0;
5554 assert( pCrsr!=0 );
5555 #ifdef SQLITE_DEBUG
5556 pC->seekOp = pOp->opcode;
5557 #endif
5558 if( pOp->opcode==OP_SeekEnd ){
5559 assert( pOp->p2==0 );
5560 pC->seekResult = -1;
5561 if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
5562 break;
5563 }
5564 }
5565 rc = sqlite3BtreeLast(pCrsr, &res);
5566 pC->nullRow = (u8)res;
5567 pC->deferredMoveto = 0;
5568 pC->cacheStatus = CACHE_STALE;
5569 if( rc ) goto abort_due_to_error;
5570 if( pOp->p2>0 ){
5571 VdbeBranchTaken(res!=0,2);
5572 if( res ) goto jump_to_p2;
5573 }
5574 break;
5575 }
5576
5577 /* Opcode: IfSmaller P1 P2 P3 * *
5578 **
5579 ** Estimate the number of rows in the table P1. Jump to P2 if that
5580 ** estimate is less than approximately 2**(0.1*P3).
5581 */
5582 case OP_IfSmaller: { /* jump */
5583 VdbeCursor *pC;
5584 BtCursor *pCrsr;
5585 int res;
5586 i64 sz;
5587
5588 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5589 pC = p->apCsr[pOp->p1];
5590 assert( pC!=0 );
5591 pCrsr = pC->uc.pCursor;
5592 assert( pCrsr );
5593 rc = sqlite3BtreeFirst(pCrsr, &res);
5594 if( rc ) goto abort_due_to_error;
5595 if( res==0 ){
5596 sz = sqlite3BtreeRowCountEst(pCrsr);
5597 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
5598 }
5599 VdbeBranchTaken(res!=0,2);
5600 if( res ) goto jump_to_p2;
5601 break;
5602 }
5603
5604
5605 /* Opcode: SorterSort P1 P2 * * *
5606 **
5607 ** After all records have been inserted into the Sorter object
5608 ** identified by P1, invoke this opcode to actually do the sorting.
5609 ** Jump to P2 if there are no records to be sorted.
5610 **
5611 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
5612 ** for Sorter objects.
5613 */
5614 /* Opcode: Sort P1 P2 * * *
5615 **
5616 ** This opcode does exactly the same thing as OP_Rewind except that
5617 ** it increments an undocumented global variable used for testing.
5618 **
5619 ** Sorting is accomplished by writing records into a sorting index,
5620 ** then rewinding that index and playing it back from beginning to
5621 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
5622 ** rewinding so that the global variable will be incremented and
5623 ** regression tests can determine whether or not the optimizer is
5624 ** correctly optimizing out sorts.
5625 */
5626 case OP_SorterSort: /* jump */
5627 case OP_Sort: { /* jump */
5628 #ifdef SQLITE_TEST
5629 sqlite3_sort_count++;
5630 sqlite3_search_count--;
5631 #endif
5632 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
5633 /* Fall through into OP_Rewind */
5634 /* no break */ deliberate_fall_through
5635 }
5636 /* Opcode: Rewind P1 P2 * * *
5637 **
5638 ** The next use of the Rowid or Column or Next instruction for P1
5639 ** will refer to the first entry in the database table or index.
5640 ** If the table or index is empty, jump immediately to P2.
5641 ** If the table or index is not empty, fall through to the following
5642 ** instruction.
5643 **
5644 ** This opcode leaves the cursor configured to move in forward order,
5645 ** from the beginning toward the end. In other words, the cursor is
5646 ** configured to use Next, not Prev.
5647 */
5648 case OP_Rewind: { /* jump */
5649 VdbeCursor *pC;
5650 BtCursor *pCrsr;
5651 int res;
5652
5653 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5654 assert( pOp->p5==0 );
5655 pC = p->apCsr[pOp->p1];
5656 assert( pC!=0 );
5657 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
5658 res = 1;
5659 #ifdef SQLITE_DEBUG
5660 pC->seekOp = OP_Rewind;
5661 #endif
5662 if( isSorter(pC) ){
5663 rc = sqlite3VdbeSorterRewind(pC, &res);
5664 }else{
5665 assert( pC->eCurType==CURTYPE_BTREE );
5666 pCrsr = pC->uc.pCursor;
5667 assert( pCrsr );
5668 rc = sqlite3BtreeFirst(pCrsr, &res);
5669 pC->deferredMoveto = 0;
5670 pC->cacheStatus = CACHE_STALE;
5671 }
5672 if( rc ) goto abort_due_to_error;
5673 pC->nullRow = (u8)res;
5674 assert( pOp->p2>0 && pOp->p2<p->nOp );
5675 VdbeBranchTaken(res!=0,2);
5676 if( res ) goto jump_to_p2;
5677 break;
5678 }
5679
5680 /* Opcode: Next P1 P2 P3 P4 P5
5681 **
5682 ** Advance cursor P1 so that it points to the next key/data pair in its
5683 ** table or index. If there are no more key/value pairs then fall through
5684 ** to the following instruction. But if the cursor advance was successful,
5685 ** jump immediately to P2.
5686 **
5687 ** The Next opcode is only valid following an SeekGT, SeekGE, or
5688 ** OP_Rewind opcode used to position the cursor. Next is not allowed
5689 ** to follow SeekLT, SeekLE, or OP_Last.
5690 **
5691 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
5692 ** been opened prior to this opcode or the program will segfault.
5693 **
5694 ** The P3 value is a hint to the btree implementation. If P3==1, that
5695 ** means P1 is an SQL index and that this instruction could have been
5696 ** omitted if that index had been unique. P3 is usually 0. P3 is
5697 ** always either 0 or 1.
5698 **
5699 ** P4 is always of type P4_ADVANCE. The function pointer points to
5700 ** sqlite3BtreeNext().
5701 **
5702 ** If P5 is positive and the jump is taken, then event counter
5703 ** number P5-1 in the prepared statement is incremented.
5704 **
5705 ** See also: Prev
5706 */
5707 /* Opcode: Prev P1 P2 P3 P4 P5
5708 **
5709 ** Back up cursor P1 so that it points to the previous key/data pair in its
5710 ** table or index. If there is no previous key/value pairs then fall through
5711 ** to the following instruction. But if the cursor backup was successful,
5712 ** jump immediately to P2.
5713 **
5714 **
5715 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
5716 ** OP_Last opcode used to position the cursor. Prev is not allowed
5717 ** to follow SeekGT, SeekGE, or OP_Rewind.
5718 **
5719 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
5720 ** not open then the behavior is undefined.
5721 **
5722 ** The P3 value is a hint to the btree implementation. If P3==1, that
5723 ** means P1 is an SQL index and that this instruction could have been
5724 ** omitted if that index had been unique. P3 is usually 0. P3 is
5725 ** always either 0 or 1.
5726 **
5727 ** P4 is always of type P4_ADVANCE. The function pointer points to
5728 ** sqlite3BtreePrevious().
5729 **
5730 ** If P5 is positive and the jump is taken, then event counter
5731 ** number P5-1 in the prepared statement is incremented.
5732 */
5733 /* Opcode: SorterNext P1 P2 * * P5
5734 **
5735 ** This opcode works just like OP_Next except that P1 must be a
5736 ** sorter object for which the OP_SorterSort opcode has been
5737 ** invoked. This opcode advances the cursor to the next sorted
5738 ** record, or jumps to P2 if there are no more sorted records.
5739 */
5740 case OP_SorterNext: { /* jump */
5741 VdbeCursor *pC;
5742
5743 pC = p->apCsr[pOp->p1];
5744 assert( isSorter(pC) );
5745 rc = sqlite3VdbeSorterNext(db, pC);
5746 goto next_tail;
5747 case OP_Prev: /* jump */
5748 case OP_Next: /* jump */
5749 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5750 assert( pOp->p5<ArraySize(p->aCounter) );
5751 pC = p->apCsr[pOp->p1];
5752 assert( pC!=0 );
5753 assert( pC->deferredMoveto==0 );
5754 assert( pC->eCurType==CURTYPE_BTREE );
5755 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
5756 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
5757
5758 /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
5759 ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
5760 assert( pOp->opcode!=OP_Next
5761 || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
5762 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
5763 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
5764 || pC->seekOp==OP_IfNoHope);
5765 assert( pOp->opcode!=OP_Prev
5766 || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
5767 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
5768 || pC->seekOp==OP_NullRow);
5769
5770 rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
5771 next_tail:
5772 pC->cacheStatus = CACHE_STALE;
5773 VdbeBranchTaken(rc==SQLITE_OK,2);
5774 if( rc==SQLITE_OK ){
5775 pC->nullRow = 0;
5776 p->aCounter[pOp->p5]++;
5777 #ifdef SQLITE_TEST
5778 sqlite3_search_count++;
5779 #endif
5780 goto jump_to_p2_and_check_for_interrupt;
5781 }
5782 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
5783 rc = SQLITE_OK;
5784 pC->nullRow = 1;
5785 goto check_for_interrupt;
5786 }
5787
5788 /* Opcode: IdxInsert P1 P2 P3 P4 P5
5789 ** Synopsis: key=r[P2]
5790 **
5791 ** Register P2 holds an SQL index key made using the
5792 ** MakeRecord instructions. This opcode writes that key
5793 ** into the index P1. Data for the entry is nil.
5794 **
5795 ** If P4 is not zero, then it is the number of values in the unpacked
5796 ** key of reg(P2). In that case, P3 is the index of the first register
5797 ** for the unpacked key. The availability of the unpacked key can sometimes
5798 ** be an optimization.
5799 **
5800 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
5801 ** that this insert is likely to be an append.
5802 **
5803 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
5804 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
5805 ** then the change counter is unchanged.
5806 **
5807 ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
5808 ** run faster by avoiding an unnecessary seek on cursor P1. However,
5809 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
5810 ** seeks on the cursor or if the most recent seek used a key equivalent
5811 ** to P2.
5812 **
5813 ** This instruction only works for indices. The equivalent instruction
5814 ** for tables is OP_Insert.
5815 */
5816 case OP_IdxInsert: { /* in2 */
5817 VdbeCursor *pC;
5818 BtreePayload x;
5819
5820 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5821 pC = p->apCsr[pOp->p1];
5822 sqlite3VdbeIncrWriteCounter(p, pC);
5823 assert( pC!=0 );
5824 assert( !isSorter(pC) );
5825 pIn2 = &aMem[pOp->p2];
5826 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
5827 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
5828 assert( pC->eCurType==CURTYPE_BTREE );
5829 assert( pC->isTable==0 );
5830 rc = ExpandBlob(pIn2);
5831 if( rc ) goto abort_due_to_error;
5832 x.nKey = pIn2->n;
5833 x.pKey = pIn2->z;
5834 x.aMem = aMem + pOp->p3;
5835 x.nMem = (u16)pOp->p4.i;
5836 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
5837 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
5838 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
5839 );
5840 assert( pC->deferredMoveto==0 );
5841 pC->cacheStatus = CACHE_STALE;
5842 if( rc) goto abort_due_to_error;
5843 break;
5844 }
5845
5846 /* Opcode: SorterInsert P1 P2 * * *
5847 ** Synopsis: key=r[P2]
5848 **
5849 ** Register P2 holds an SQL index key made using the
5850 ** MakeRecord instructions. This opcode writes that key
5851 ** into the sorter P1. Data for the entry is nil.
5852 */
5853 case OP_SorterInsert: { /* in2 */
5854 VdbeCursor *pC;
5855
5856 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5857 pC = p->apCsr[pOp->p1];
5858 sqlite3VdbeIncrWriteCounter(p, pC);
5859 assert( pC!=0 );
5860 assert( isSorter(pC) );
5861 pIn2 = &aMem[pOp->p2];
5862 assert( pIn2->flags & MEM_Blob );
5863 assert( pC->isTable==0 );
5864 rc = ExpandBlob(pIn2);
5865 if( rc ) goto abort_due_to_error;
5866 rc = sqlite3VdbeSorterWrite(pC, pIn2);
5867 if( rc) goto abort_due_to_error;
5868 break;
5869 }
5870
5871 /* Opcode: IdxDelete P1 P2 P3 * P5
5872 ** Synopsis: key=r[P2@P3]
5873 **
5874 ** The content of P3 registers starting at register P2 form
5875 ** an unpacked index key. This opcode removes that entry from the
5876 ** index opened by cursor P1.
5877 **
5878 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
5879 ** if no matching index entry is found. This happens when running
5880 ** an UPDATE or DELETE statement and the index entry to be updated
5881 ** or deleted is not found. For some uses of IdxDelete
5882 ** (example: the EXCEPT operator) it does not matter that no matching
5883 ** entry is found. For those cases, P5 is zero.
5884 */
5885 case OP_IdxDelete: {
5886 VdbeCursor *pC;
5887 BtCursor *pCrsr;
5888 int res;
5889 UnpackedRecord r;
5890
5891 assert( pOp->p3>0 );
5892 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
5893 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5894 pC = p->apCsr[pOp->p1];
5895 assert( pC!=0 );
5896 assert( pC->eCurType==CURTYPE_BTREE );
5897 sqlite3VdbeIncrWriteCounter(p, pC);
5898 pCrsr = pC->uc.pCursor;
5899 assert( pCrsr!=0 );
5900 r.pKeyInfo = pC->pKeyInfo;
5901 r.nField = (u16)pOp->p3;
5902 r.default_rc = 0;
5903 r.aMem = &aMem[pOp->p2];
5904 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
5905 if( rc ) goto abort_due_to_error;
5906 if( res==0 ){
5907 rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
5908 if( rc ) goto abort_due_to_error;
5909 }else if( pOp->p5 ){
5910 rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption");
5911 goto abort_due_to_error;
5912 }
5913 assert( pC->deferredMoveto==0 );
5914 pC->cacheStatus = CACHE_STALE;
5915 pC->seekResult = 0;
5916 break;
5917 }
5918
5919 /* Opcode: DeferredSeek P1 * P3 P4 *
5920 ** Synopsis: Move P3 to P1.rowid if needed
5921 **
5922 ** P1 is an open index cursor and P3 is a cursor on the corresponding
5923 ** table. This opcode does a deferred seek of the P3 table cursor
5924 ** to the row that corresponds to the current row of P1.
5925 **
5926 ** This is a deferred seek. Nothing actually happens until
5927 ** the cursor is used to read a record. That way, if no reads
5928 ** occur, no unnecessary I/O happens.
5929 **
5930 ** P4 may be an array of integers (type P4_INTARRAY) containing
5931 ** one entry for each column in the P3 table. If array entry a(i)
5932 ** is non-zero, then reading column a(i)-1 from cursor P3 is
5933 ** equivalent to performing the deferred seek and then reading column i
5934 ** from P1. This information is stored in P3 and used to redirect
5935 ** reads against P3 over to P1, thus possibly avoiding the need to
5936 ** seek and read cursor P3.
5937 */
5938 /* Opcode: IdxRowid P1 P2 * * *
5939 ** Synopsis: r[P2]=rowid
5940 **
5941 ** Write into register P2 an integer which is the last entry in the record at
5942 ** the end of the index key pointed to by cursor P1. This integer should be
5943 ** the rowid of the table entry to which this index entry points.
5944 **
5945 ** See also: Rowid, MakeRecord.
5946 */
5947 case OP_DeferredSeek:
5948 case OP_IdxRowid: { /* out2 */
5949 VdbeCursor *pC; /* The P1 index cursor */
5950 VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
5951 i64 rowid; /* Rowid that P1 current points to */
5952
5953 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
5954 pC = p->apCsr[pOp->p1];
5955 assert( pC!=0 );
5956 assert( pC->eCurType==CURTYPE_BTREE );
5957 assert( pC->uc.pCursor!=0 );
5958 assert( pC->isTable==0 );
5959 assert( pC->deferredMoveto==0 );
5960 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
5961
5962 /* The IdxRowid and Seek opcodes are combined because of the commonality
5963 ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
5964 rc = sqlite3VdbeCursorRestore(pC);
5965
5966 /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
5967 ** out from under the cursor. That will never happens for an IdxRowid
5968 ** or Seek opcode */
5969 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
5970
5971 if( !pC->nullRow ){
5972 rowid = 0; /* Not needed. Only used to silence a warning. */
5973 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
5974 if( rc!=SQLITE_OK ){
5975 goto abort_due_to_error;
5976 }
5977 if( pOp->opcode==OP_DeferredSeek ){
5978 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
5979 pTabCur = p->apCsr[pOp->p3];
5980 assert( pTabCur!=0 );
5981 assert( pTabCur->eCurType==CURTYPE_BTREE );
5982 assert( pTabCur->uc.pCursor!=0 );
5983 assert( pTabCur->isTable );
5984 pTabCur->nullRow = 0;
5985 pTabCur->movetoTarget = rowid;
5986 pTabCur->deferredMoveto = 1;
5987 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
5988 pTabCur->aAltMap = pOp->p4.ai;
5989 assert( !pC->isEphemeral );
5990 assert( !pTabCur->isEphemeral );
5991 pTabCur->pAltCursor = pC;
5992 }else{
5993 pOut = out2Prerelease(p, pOp);
5994 pOut->u.i = rowid;
5995 }
5996 }else{
5997 assert( pOp->opcode==OP_IdxRowid );
5998 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
5999 }
6000 break;
6001 }
6002
6003 /* Opcode: FinishSeek P1 * * * *
6004 **
6005 ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
6006 ** seek operation now, without further delay. If the cursor seek has
6007 ** already occurred, this instruction is a no-op.
6008 */
6009 case OP_FinishSeek: {
6010 VdbeCursor *pC; /* The P1 index cursor */
6011
6012 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6013 pC = p->apCsr[pOp->p1];
6014 if( pC->deferredMoveto ){
6015 rc = sqlite3VdbeFinishMoveto(pC);
6016 if( rc ) goto abort_due_to_error;
6017 }
6018 break;
6019 }
6020
6021 /* Opcode: IdxGE P1 P2 P3 P4 *
6022 ** Synopsis: key=r[P3@P4]
6023 **
6024 ** The P4 register values beginning with P3 form an unpacked index
6025 ** key that omits the PRIMARY KEY. Compare this key value against the index
6026 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6027 ** fields at the end.
6028 **
6029 ** If the P1 index entry is greater than or equal to the key value
6030 ** then jump to P2. Otherwise fall through to the next instruction.
6031 */
6032 /* Opcode: IdxGT P1 P2 P3 P4 *
6033 ** Synopsis: key=r[P3@P4]
6034 **
6035 ** The P4 register values beginning with P3 form an unpacked index
6036 ** key that omits the PRIMARY KEY. Compare this key value against the index
6037 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
6038 ** fields at the end.
6039 **
6040 ** If the P1 index entry is greater than the key value
6041 ** then jump to P2. Otherwise fall through to the next instruction.
6042 */
6043 /* Opcode: IdxLT P1 P2 P3 P4 *
6044 ** Synopsis: key=r[P3@P4]
6045 **
6046 ** The P4 register values beginning with P3 form an unpacked index
6047 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6048 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6049 ** ROWID on the P1 index.
6050 **
6051 ** If the P1 index entry is less than the key value then jump to P2.
6052 ** Otherwise fall through to the next instruction.
6053 */
6054 /* Opcode: IdxLE P1 P2 P3 P4 *
6055 ** Synopsis: key=r[P3@P4]
6056 **
6057 ** The P4 register values beginning with P3 form an unpacked index
6058 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
6059 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
6060 ** ROWID on the P1 index.
6061 **
6062 ** If the P1 index entry is less than or equal to the key value then jump
6063 ** to P2. Otherwise fall through to the next instruction.
6064 */
6065 case OP_IdxLE: /* jump */
6066 case OP_IdxGT: /* jump */
6067 case OP_IdxLT: /* jump */
6068 case OP_IdxGE: { /* jump */
6069 VdbeCursor *pC;
6070 int res;
6071 UnpackedRecord r;
6072
6073 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6074 pC = p->apCsr[pOp->p1];
6075 assert( pC!=0 );
6076 assert( pC->isOrdered );
6077 assert( pC->eCurType==CURTYPE_BTREE );
6078 assert( pC->uc.pCursor!=0);
6079 assert( pC->deferredMoveto==0 );
6080 assert( pOp->p4type==P4_INT32 );
6081 r.pKeyInfo = pC->pKeyInfo;
6082 r.nField = (u16)pOp->p4.i;
6083 if( pOp->opcode<OP_IdxLT ){
6084 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
6085 r.default_rc = -1;
6086 }else{
6087 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
6088 r.default_rc = 0;
6089 }
6090 r.aMem = &aMem[pOp->p3];
6091 #ifdef SQLITE_DEBUG
6092 {
6093 int i;
6094 for(i=0; i<r.nField; i++){
6095 assert( memIsValid(&r.aMem[i]) );
6096 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
6097 }
6098 }
6099 #endif
6100
6101 /* Inlined version of sqlite3VdbeIdxKeyCompare() */
6102 {
6103 i64 nCellKey = 0;
6104 BtCursor *pCur;
6105 Mem m;
6106
6107 assert( pC->eCurType==CURTYPE_BTREE );
6108 pCur = pC->uc.pCursor;
6109 assert( sqlite3BtreeCursorIsValid(pCur) );
6110 nCellKey = sqlite3BtreePayloadSize(pCur);
6111 /* nCellKey will always be between 0 and 0xffffffff because of the way
6112 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
6113 if( nCellKey<=0 || nCellKey>0x7fffffff ){
6114 rc = SQLITE_CORRUPT_BKPT;
6115 goto abort_due_to_error;
6116 }
6117 sqlite3VdbeMemInit(&m, db, 0);
6118 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
6119 if( rc ) goto abort_due_to_error;
6120 res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
6121 sqlite3VdbeMemRelease(&m);
6122 }
6123 /* End of inlined sqlite3VdbeIdxKeyCompare() */
6124
6125 assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
6126 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
6127 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
6128 res = -res;
6129 }else{
6130 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
6131 res++;
6132 }
6133 VdbeBranchTaken(res>0,2);
6134 assert( rc==SQLITE_OK );
6135 if( res>0 ) goto jump_to_p2;
6136 break;
6137 }
6138
6139 /* Opcode: Destroy P1 P2 P3 * *
6140 **
6141 ** Delete an entire database table or index whose root page in the database
6142 ** file is given by P1.
6143 **
6144 ** The table being destroyed is in the main database file if P3==0. If
6145 ** P3==1 then the table to be clear is in the auxiliary database file
6146 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6147 **
6148 ** If AUTOVACUUM is enabled then it is possible that another root page
6149 ** might be moved into the newly deleted root page in order to keep all
6150 ** root pages contiguous at the beginning of the database. The former
6151 ** value of the root page that moved - its value before the move occurred -
6152 ** is stored in register P2. If no page movement was required (because the
6153 ** table being dropped was already the last one in the database) then a
6154 ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
6155 ** is stored in register P2.
6156 **
6157 ** This opcode throws an error if there are any active reader VMs when
6158 ** it is invoked. This is done to avoid the difficulty associated with
6159 ** updating existing cursors when a root page is moved in an AUTOVACUUM
6160 ** database. This error is thrown even if the database is not an AUTOVACUUM
6161 ** db in order to avoid introducing an incompatibility between autovacuum
6162 ** and non-autovacuum modes.
6163 **
6164 ** See also: Clear
6165 */
6166 case OP_Destroy: { /* out2 */
6167 int iMoved;
6168 int iDb;
6169
6170 sqlite3VdbeIncrWriteCounter(p, 0);
6171 assert( p->readOnly==0 );
6172 assert( pOp->p1>1 );
6173 pOut = out2Prerelease(p, pOp);
6174 pOut->flags = MEM_Null;
6175 if( db->nVdbeRead > db->nVDestroy+1 ){
6176 rc = SQLITE_LOCKED;
6177 p->errorAction = OE_Abort;
6178 goto abort_due_to_error;
6179 }else{
6180 iDb = pOp->p3;
6181 assert( DbMaskTest(p->btreeMask, iDb) );
6182 iMoved = 0; /* Not needed. Only to silence a warning. */
6183 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
6184 pOut->flags = MEM_Int;
6185 pOut->u.i = iMoved;
6186 if( rc ) goto abort_due_to_error;
6187 #ifndef SQLITE_OMIT_AUTOVACUUM
6188 if( iMoved!=0 ){
6189 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
6190 /* All OP_Destroy operations occur on the same btree */
6191 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
6192 resetSchemaOnFault = iDb+1;
6193 }
6194 #endif
6195 }
6196 break;
6197 }
6198
6199 /* Opcode: Clear P1 P2 P3
6200 **
6201 ** Delete all contents of the database table or index whose root page
6202 ** in the database file is given by P1. But, unlike Destroy, do not
6203 ** remove the table or index from the database file.
6204 **
6205 ** The table being clear is in the main database file if P2==0. If
6206 ** P2==1 then the table to be clear is in the auxiliary database file
6207 ** that is used to store tables create using CREATE TEMPORARY TABLE.
6208 **
6209 ** If the P3 value is non-zero, then the table referred to must be an
6210 ** intkey table (an SQL table, not an index). In this case the row change
6211 ** count is incremented by the number of rows in the table being cleared.
6212 ** If P3 is greater than zero, then the value stored in register P3 is
6213 ** also incremented by the number of rows in the table being cleared.
6214 **
6215 ** See also: Destroy
6216 */
6217 case OP_Clear: {
6218 int nChange;
6219
6220 sqlite3VdbeIncrWriteCounter(p, 0);
6221 nChange = 0;
6222 assert( p->readOnly==0 );
6223 assert( DbMaskTest(p->btreeMask, pOp->p2) );
6224 rc = sqlite3BtreeClearTable(
6225 db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0)
6226 );
6227 if( pOp->p3 ){
6228 p->nChange += nChange;
6229 if( pOp->p3>0 ){
6230 assert( memIsValid(&aMem[pOp->p3]) );
6231 memAboutToChange(p, &aMem[pOp->p3]);
6232 aMem[pOp->p3].u.i += nChange;
6233 }
6234 }
6235 if( rc ) goto abort_due_to_error;
6236 break;
6237 }
6238
6239 /* Opcode: ResetSorter P1 * * * *
6240 **
6241 ** Delete all contents from the ephemeral table or sorter
6242 ** that is open on cursor P1.
6243 **
6244 ** This opcode only works for cursors used for sorting and
6245 ** opened with OP_OpenEphemeral or OP_SorterOpen.
6246 */
6247 case OP_ResetSorter: {
6248 VdbeCursor *pC;
6249
6250 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6251 pC = p->apCsr[pOp->p1];
6252 assert( pC!=0 );
6253 if( isSorter(pC) ){
6254 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
6255 }else{
6256 assert( pC->eCurType==CURTYPE_BTREE );
6257 assert( pC->isEphemeral );
6258 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
6259 if( rc ) goto abort_due_to_error;
6260 }
6261 break;
6262 }
6263
6264 /* Opcode: CreateBtree P1 P2 P3 * *
6265 ** Synopsis: r[P2]=root iDb=P1 flags=P3
6266 **
6267 ** Allocate a new b-tree in the main database file if P1==0 or in the
6268 ** TEMP database file if P1==1 or in an attached database if
6269 ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
6270 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
6271 ** The root page number of the new b-tree is stored in register P2.
6272 */
6273 case OP_CreateBtree: { /* out2 */
6274 Pgno pgno;
6275 Db *pDb;
6276
6277 sqlite3VdbeIncrWriteCounter(p, 0);
6278 pOut = out2Prerelease(p, pOp);
6279 pgno = 0;
6280 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
6281 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6282 assert( DbMaskTest(p->btreeMask, pOp->p1) );
6283 assert( p->readOnly==0 );
6284 pDb = &db->aDb[pOp->p1];
6285 assert( pDb->pBt!=0 );
6286 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
6287 if( rc ) goto abort_due_to_error;
6288 pOut->u.i = pgno;
6289 break;
6290 }
6291
6292 /* Opcode: SqlExec * * * P4 *
6293 **
6294 ** Run the SQL statement or statements specified in the P4 string.
6295 */
6296 case OP_SqlExec: {
6297 sqlite3VdbeIncrWriteCounter(p, 0);
6298 db->nSqlExec++;
6299 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
6300 db->nSqlExec--;
6301 if( rc ) goto abort_due_to_error;
6302 break;
6303 }
6304
6305 /* Opcode: ParseSchema P1 * * P4 *
6306 **
6307 ** Read and parse all entries from the schema table of database P1
6308 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
6309 ** entire schema for P1 is reparsed.
6310 **
6311 ** This opcode invokes the parser to create a new virtual machine,
6312 ** then runs the new virtual machine. It is thus a re-entrant opcode.
6313 */
6314 case OP_ParseSchema: {
6315 int iDb;
6316 const char *zSchema;
6317 char *zSql;
6318 InitData initData;
6319
6320 /* Any prepared statement that invokes this opcode will hold mutexes
6321 ** on every btree. This is a prerequisite for invoking
6322 ** sqlite3InitCallback().
6323 */
6324 #ifdef SQLITE_DEBUG
6325 for(iDb=0; iDb<db->nDb; iDb++){
6326 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
6327 }
6328 #endif
6329
6330 iDb = pOp->p1;
6331 assert( iDb>=0 && iDb<db->nDb );
6332 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
6333
6334 #ifndef SQLITE_OMIT_ALTERTABLE
6335 if( pOp->p4.z==0 ){
6336 sqlite3SchemaClear(db->aDb[iDb].pSchema);
6337 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
6338 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
6339 db->mDbFlags |= DBFLAG_SchemaChange;
6340 p->expired = 0;
6341 }else
6342 #endif
6343 {
6344 zSchema = DFLT_SCHEMA_TABLE;
6345 initData.db = db;
6346 initData.iDb = iDb;
6347 initData.pzErrMsg = &p->zErrMsg;
6348 initData.mInitFlags = 0;
6349 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
6350 zSql = sqlite3MPrintf(db,
6351 "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
6352 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
6353 if( zSql==0 ){
6354 rc = SQLITE_NOMEM_BKPT;
6355 }else{
6356 assert( db->init.busy==0 );
6357 db->init.busy = 1;
6358 initData.rc = SQLITE_OK;
6359 initData.nInitRow = 0;
6360 assert( !db->mallocFailed );
6361 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
6362 if( rc==SQLITE_OK ) rc = initData.rc;
6363 if( rc==SQLITE_OK && initData.nInitRow==0 ){
6364 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
6365 ** at least one SQL statement. Any less than that indicates that
6366 ** the sqlite_schema table is corrupt. */
6367 rc = SQLITE_CORRUPT_BKPT;
6368 }
6369 sqlite3DbFreeNN(db, zSql);
6370 db->init.busy = 0;
6371 }
6372 }
6373 if( rc ){
6374 sqlite3ResetAllSchemasOfConnection(db);
6375 if( rc==SQLITE_NOMEM ){
6376 goto no_mem;
6377 }
6378 goto abort_due_to_error;
6379 }
6380 break;
6381 }
6382
6383 #if !defined(SQLITE_OMIT_ANALYZE)
6384 /* Opcode: LoadAnalysis P1 * * * *
6385 **
6386 ** Read the sqlite_stat1 table for database P1 and load the content
6387 ** of that table into the internal index hash table. This will cause
6388 ** the analysis to be used when preparing all subsequent queries.
6389 */
6390 case OP_LoadAnalysis: {
6391 assert( pOp->p1>=0 && pOp->p1<db->nDb );
6392 rc = sqlite3AnalysisLoad(db, pOp->p1);
6393 if( rc ) goto abort_due_to_error;
6394 break;
6395 }
6396 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
6397
6398 /* Opcode: DropTable P1 * * P4 *
6399 **
6400 ** Remove the internal (in-memory) data structures that describe
6401 ** the table named P4 in database P1. This is called after a table
6402 ** is dropped from disk (using the Destroy opcode) in order to keep
6403 ** the internal representation of the
6404 ** schema consistent with what is on disk.
6405 */
6406 case OP_DropTable: {
6407 sqlite3VdbeIncrWriteCounter(p, 0);
6408 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
6409 break;
6410 }
6411
6412 /* Opcode: DropIndex P1 * * P4 *
6413 **
6414 ** Remove the internal (in-memory) data structures that describe
6415 ** the index named P4 in database P1. This is called after an index
6416 ** is dropped from disk (using the Destroy opcode)
6417 ** in order to keep the internal representation of the
6418 ** schema consistent with what is on disk.
6419 */
6420 case OP_DropIndex: {
6421 sqlite3VdbeIncrWriteCounter(p, 0);
6422 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
6423 break;
6424 }
6425
6426 /* Opcode: DropTrigger P1 * * P4 *
6427 **
6428 ** Remove the internal (in-memory) data structures that describe
6429 ** the trigger named P4 in database P1. This is called after a trigger
6430 ** is dropped from disk (using the Destroy opcode) in order to keep
6431 ** the internal representation of the
6432 ** schema consistent with what is on disk.
6433 */
6434 case OP_DropTrigger: {
6435 sqlite3VdbeIncrWriteCounter(p, 0);
6436 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
6437 break;
6438 }
6439
6440
6441 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
6442 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
6443 **
6444 ** Do an analysis of the currently open database. Store in
6445 ** register P1 the text of an error message describing any problems.
6446 ** If no problems are found, store a NULL in register P1.
6447 **
6448 ** The register P3 contains one less than the maximum number of allowed errors.
6449 ** At most reg(P3) errors will be reported.
6450 ** In other words, the analysis stops as soon as reg(P1) errors are
6451 ** seen. Reg(P1) is updated with the number of errors remaining.
6452 **
6453 ** The root page numbers of all tables in the database are integers
6454 ** stored in P4_INTARRAY argument.
6455 **
6456 ** If P5 is not zero, the check is done on the auxiliary database
6457 ** file, not the main database file.
6458 **
6459 ** This opcode is used to implement the integrity_check pragma.
6460 */
6461 case OP_IntegrityCk: {
6462 int nRoot; /* Number of tables to check. (Number of root pages.) */
6463 Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */
6464 int nErr; /* Number of errors reported */
6465 char *z; /* Text of the error report */
6466 Mem *pnErr; /* Register keeping track of errors remaining */
6467
6468 assert( p->bIsReader );
6469 nRoot = pOp->p2;
6470 aRoot = pOp->p4.ai;
6471 assert( nRoot>0 );
6472 assert( aRoot[0]==(Pgno)nRoot );
6473 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6474 pnErr = &aMem[pOp->p3];
6475 assert( (pnErr->flags & MEM_Int)!=0 );
6476 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
6477 pIn1 = &aMem[pOp->p1];
6478 assert( pOp->p5<db->nDb );
6479 assert( DbMaskTest(p->btreeMask, pOp->p5) );
6480 z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
6481 (int)pnErr->u.i+1, &nErr);
6482 sqlite3VdbeMemSetNull(pIn1);
6483 if( nErr==0 ){
6484 assert( z==0 );
6485 }else if( z==0 ){
6486 goto no_mem;
6487 }else{
6488 pnErr->u.i -= nErr-1;
6489 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
6490 }
6491 UPDATE_MAX_BLOBSIZE(pIn1);
6492 sqlite3VdbeChangeEncoding(pIn1, encoding);
6493 goto check_for_interrupt;
6494 }
6495 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
6496
6497 /* Opcode: RowSetAdd P1 P2 * * *
6498 ** Synopsis: rowset(P1)=r[P2]
6499 **
6500 ** Insert the integer value held by register P2 into a RowSet object
6501 ** held in register P1.
6502 **
6503 ** An assertion fails if P2 is not an integer.
6504 */
6505 case OP_RowSetAdd: { /* in1, in2 */
6506 pIn1 = &aMem[pOp->p1];
6507 pIn2 = &aMem[pOp->p2];
6508 assert( (pIn2->flags & MEM_Int)!=0 );
6509 if( (pIn1->flags & MEM_Blob)==0 ){
6510 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6511 }
6512 assert( sqlite3VdbeMemIsRowSet(pIn1) );
6513 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
6514 break;
6515 }
6516
6517 /* Opcode: RowSetRead P1 P2 P3 * *
6518 ** Synopsis: r[P3]=rowset(P1)
6519 **
6520 ** Extract the smallest value from the RowSet object in P1
6521 ** and put that value into register P3.
6522 ** Or, if RowSet object P1 is initially empty, leave P3
6523 ** unchanged and jump to instruction P2.
6524 */
6525 case OP_RowSetRead: { /* jump, in1, out3 */
6526 i64 val;
6527
6528 pIn1 = &aMem[pOp->p1];
6529 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
6530 if( (pIn1->flags & MEM_Blob)==0
6531 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
6532 ){
6533 /* The boolean index is empty */
6534 sqlite3VdbeMemSetNull(pIn1);
6535 VdbeBranchTaken(1,2);
6536 goto jump_to_p2_and_check_for_interrupt;
6537 }else{
6538 /* A value was pulled from the index */
6539 VdbeBranchTaken(0,2);
6540 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
6541 }
6542 goto check_for_interrupt;
6543 }
6544
6545 /* Opcode: RowSetTest P1 P2 P3 P4
6546 ** Synopsis: if r[P3] in rowset(P1) goto P2
6547 **
6548 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
6549 ** contains a RowSet object and that RowSet object contains
6550 ** the value held in P3, jump to register P2. Otherwise, insert the
6551 ** integer in P3 into the RowSet and continue on to the
6552 ** next opcode.
6553 **
6554 ** The RowSet object is optimized for the case where sets of integers
6555 ** are inserted in distinct phases, which each set contains no duplicates.
6556 ** Each set is identified by a unique P4 value. The first set
6557 ** must have P4==0, the final set must have P4==-1, and for all other sets
6558 ** must have P4>0.
6559 **
6560 ** This allows optimizations: (a) when P4==0 there is no need to test
6561 ** the RowSet object for P3, as it is guaranteed not to contain it,
6562 ** (b) when P4==-1 there is no need to insert the value, as it will
6563 ** never be tested for, and (c) when a value that is part of set X is
6564 ** inserted, there is no need to search to see if the same value was
6565 ** previously inserted as part of set X (only if it was previously
6566 ** inserted as part of some other set).
6567 */
6568 case OP_RowSetTest: { /* jump, in1, in3 */
6569 int iSet;
6570 int exists;
6571
6572 pIn1 = &aMem[pOp->p1];
6573 pIn3 = &aMem[pOp->p3];
6574 iSet = pOp->p4.i;
6575 assert( pIn3->flags&MEM_Int );
6576
6577 /* If there is anything other than a rowset object in memory cell P1,
6578 ** delete it now and initialize P1 with an empty rowset
6579 */
6580 if( (pIn1->flags & MEM_Blob)==0 ){
6581 if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
6582 }
6583 assert( sqlite3VdbeMemIsRowSet(pIn1) );
6584 assert( pOp->p4type==P4_INT32 );
6585 assert( iSet==-1 || iSet>=0 );
6586 if( iSet ){
6587 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
6588 VdbeBranchTaken(exists!=0,2);
6589 if( exists ) goto jump_to_p2;
6590 }
6591 if( iSet>=0 ){
6592 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
6593 }
6594 break;
6595 }
6596
6597
6598 #ifndef SQLITE_OMIT_TRIGGER
6599
6600 /* Opcode: Program P1 P2 P3 P4 P5
6601 **
6602 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
6603 **
6604 ** P1 contains the address of the memory cell that contains the first memory
6605 ** cell in an array of values used as arguments to the sub-program. P2
6606 ** contains the address to jump to if the sub-program throws an IGNORE
6607 ** exception using the RAISE() function. Register P3 contains the address
6608 ** of a memory cell in this (the parent) VM that is used to allocate the
6609 ** memory required by the sub-vdbe at runtime.
6610 **
6611 ** P4 is a pointer to the VM containing the trigger program.
6612 **
6613 ** If P5 is non-zero, then recursive program invocation is enabled.
6614 */
6615 case OP_Program: { /* jump */
6616 int nMem; /* Number of memory registers for sub-program */
6617 int nByte; /* Bytes of runtime space required for sub-program */
6618 Mem *pRt; /* Register to allocate runtime space */
6619 Mem *pMem; /* Used to iterate through memory cells */
6620 Mem *pEnd; /* Last memory cell in new array */
6621 VdbeFrame *pFrame; /* New vdbe frame to execute in */
6622 SubProgram *pProgram; /* Sub-program to execute */
6623 void *t; /* Token identifying trigger */
6624
6625 pProgram = pOp->p4.pProgram;
6626 pRt = &aMem[pOp->p3];
6627 assert( pProgram->nOp>0 );
6628
6629 /* If the p5 flag is clear, then recursive invocation of triggers is
6630 ** disabled for backwards compatibility (p5 is set if this sub-program
6631 ** is really a trigger, not a foreign key action, and the flag set
6632 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
6633 **
6634 ** It is recursive invocation of triggers, at the SQL level, that is
6635 ** disabled. In some cases a single trigger may generate more than one
6636 ** SubProgram (if the trigger may be executed with more than one different
6637 ** ON CONFLICT algorithm). SubProgram structures associated with a
6638 ** single trigger all have the same value for the SubProgram.token
6639 ** variable. */
6640 if( pOp->p5 ){
6641 t = pProgram->token;
6642 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
6643 if( pFrame ) break;
6644 }
6645
6646 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
6647 rc = SQLITE_ERROR;
6648 sqlite3VdbeError(p, "too many levels of trigger recursion");
6649 goto abort_due_to_error;
6650 }
6651
6652 /* Register pRt is used to store the memory required to save the state
6653 ** of the current program, and the memory required at runtime to execute
6654 ** the trigger program. If this trigger has been fired before, then pRt
6655 ** is already allocated. Otherwise, it must be initialized. */
6656 if( (pRt->flags&MEM_Blob)==0 ){
6657 /* SubProgram.nMem is set to the number of memory cells used by the
6658 ** program stored in SubProgram.aOp. As well as these, one memory
6659 ** cell is required for each cursor used by the program. Set local
6660 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
6661 */
6662 nMem = pProgram->nMem + pProgram->nCsr;
6663 assert( nMem>0 );
6664 if( pProgram->nCsr==0 ) nMem++;
6665 nByte = ROUND8(sizeof(VdbeFrame))
6666 + nMem * sizeof(Mem)
6667 + pProgram->nCsr * sizeof(VdbeCursor*)
6668 + (pProgram->nOp + 7)/8;
6669 pFrame = sqlite3DbMallocZero(db, nByte);
6670 if( !pFrame ){
6671 goto no_mem;
6672 }
6673 sqlite3VdbeMemRelease(pRt);
6674 pRt->flags = MEM_Blob|MEM_Dyn;
6675 pRt->z = (char*)pFrame;
6676 pRt->n = nByte;
6677 pRt->xDel = sqlite3VdbeFrameMemDel;
6678
6679 pFrame->v = p;
6680 pFrame->nChildMem = nMem;
6681 pFrame->nChildCsr = pProgram->nCsr;
6682 pFrame->pc = (int)(pOp - aOp);
6683 pFrame->aMem = p->aMem;
6684 pFrame->nMem = p->nMem;
6685 pFrame->apCsr = p->apCsr;
6686 pFrame->nCursor = p->nCursor;
6687 pFrame->aOp = p->aOp;
6688 pFrame->nOp = p->nOp;
6689 pFrame->token = pProgram->token;
6690 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6691 pFrame->anExec = p->anExec;
6692 #endif
6693 #ifdef SQLITE_DEBUG
6694 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
6695 #endif
6696
6697 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
6698 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
6699 pMem->flags = MEM_Undefined;
6700 pMem->db = db;
6701 }
6702 }else{
6703 pFrame = (VdbeFrame*)pRt->z;
6704 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
6705 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
6706 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
6707 assert( pProgram->nCsr==pFrame->nChildCsr );
6708 assert( (int)(pOp - aOp)==pFrame->pc );
6709 }
6710
6711 p->nFrame++;
6712 pFrame->pParent = p->pFrame;
6713 pFrame->lastRowid = db->lastRowid;
6714 pFrame->nChange = p->nChange;
6715 pFrame->nDbChange = p->db->nChange;
6716 assert( pFrame->pAuxData==0 );
6717 pFrame->pAuxData = p->pAuxData;
6718 p->pAuxData = 0;
6719 p->nChange = 0;
6720 p->pFrame = pFrame;
6721 p->aMem = aMem = VdbeFrameMem(pFrame);
6722 p->nMem = pFrame->nChildMem;
6723 p->nCursor = (u16)pFrame->nChildCsr;
6724 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
6725 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
6726 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
6727 p->aOp = aOp = pProgram->aOp;
6728 p->nOp = pProgram->nOp;
6729 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
6730 p->anExec = 0;
6731 #endif
6732 #ifdef SQLITE_DEBUG
6733 /* Verify that second and subsequent executions of the same trigger do not
6734 ** try to reuse register values from the first use. */
6735 {
6736 int i;
6737 for(i=0; i<p->nMem; i++){
6738 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
6739 MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
6740 }
6741 }
6742 #endif
6743 pOp = &aOp[-1];
6744 goto check_for_interrupt;
6745 }
6746
6747 /* Opcode: Param P1 P2 * * *
6748 **
6749 ** This opcode is only ever present in sub-programs called via the
6750 ** OP_Program instruction. Copy a value currently stored in a memory
6751 ** cell of the calling (parent) frame to cell P2 in the current frames
6752 ** address space. This is used by trigger programs to access the new.*
6753 ** and old.* values.
6754 **
6755 ** The address of the cell in the parent frame is determined by adding
6756 ** the value of the P1 argument to the value of the P1 argument to the
6757 ** calling OP_Program instruction.
6758 */
6759 case OP_Param: { /* out2 */
6760 VdbeFrame *pFrame;
6761 Mem *pIn;
6762 pOut = out2Prerelease(p, pOp);
6763 pFrame = p->pFrame;
6764 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
6765 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
6766 break;
6767 }
6768
6769 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
6770
6771 #ifndef SQLITE_OMIT_FOREIGN_KEY
6772 /* Opcode: FkCounter P1 P2 * * *
6773 ** Synopsis: fkctr[P1]+=P2
6774 **
6775 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
6776 ** If P1 is non-zero, the database constraint counter is incremented
6777 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
6778 ** statement counter is incremented (immediate foreign key constraints).
6779 */
6780 case OP_FkCounter: {
6781 if( db->flags & SQLITE_DeferFKs ){
6782 db->nDeferredImmCons += pOp->p2;
6783 }else if( pOp->p1 ){
6784 db->nDeferredCons += pOp->p2;
6785 }else{
6786 p->nFkConstraint += pOp->p2;
6787 }
6788 break;
6789 }
6790
6791 /* Opcode: FkIfZero P1 P2 * * *
6792 ** Synopsis: if fkctr[P1]==0 goto P2
6793 **
6794 ** This opcode tests if a foreign key constraint-counter is currently zero.
6795 ** If so, jump to instruction P2. Otherwise, fall through to the next
6796 ** instruction.
6797 **
6798 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
6799 ** is zero (the one that counts deferred constraint violations). If P1 is
6800 ** zero, the jump is taken if the statement constraint-counter is zero
6801 ** (immediate foreign key constraint violations).
6802 */
6803 case OP_FkIfZero: { /* jump */
6804 if( pOp->p1 ){
6805 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
6806 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6807 }else{
6808 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
6809 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
6810 }
6811 break;
6812 }
6813 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
6814
6815 #ifndef SQLITE_OMIT_AUTOINCREMENT
6816 /* Opcode: MemMax P1 P2 * * *
6817 ** Synopsis: r[P1]=max(r[P1],r[P2])
6818 **
6819 ** P1 is a register in the root frame of this VM (the root frame is
6820 ** different from the current frame if this instruction is being executed
6821 ** within a sub-program). Set the value of register P1 to the maximum of
6822 ** its current value and the value in register P2.
6823 **
6824 ** This instruction throws an error if the memory cell is not initially
6825 ** an integer.
6826 */
6827 case OP_MemMax: { /* in2 */
6828 VdbeFrame *pFrame;
6829 if( p->pFrame ){
6830 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
6831 pIn1 = &pFrame->aMem[pOp->p1];
6832 }else{
6833 pIn1 = &aMem[pOp->p1];
6834 }
6835 assert( memIsValid(pIn1) );
6836 sqlite3VdbeMemIntegerify(pIn1);
6837 pIn2 = &aMem[pOp->p2];
6838 sqlite3VdbeMemIntegerify(pIn2);
6839 if( pIn1->u.i<pIn2->u.i){
6840 pIn1->u.i = pIn2->u.i;
6841 }
6842 break;
6843 }
6844 #endif /* SQLITE_OMIT_AUTOINCREMENT */
6845
6846 /* Opcode: IfPos P1 P2 P3 * *
6847 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
6848 **
6849 ** Register P1 must contain an integer.
6850 ** If the value of register P1 is 1 or greater, subtract P3 from the
6851 ** value in P1 and jump to P2.
6852 **
6853 ** If the initial value of register P1 is less than 1, then the
6854 ** value is unchanged and control passes through to the next instruction.
6855 */
6856 case OP_IfPos: { /* jump, in1 */
6857 pIn1 = &aMem[pOp->p1];
6858 assert( pIn1->flags&MEM_Int );
6859 VdbeBranchTaken( pIn1->u.i>0, 2);
6860 if( pIn1->u.i>0 ){
6861 pIn1->u.i -= pOp->p3;
6862 goto jump_to_p2;
6863 }
6864 break;
6865 }
6866
6867 /* Opcode: OffsetLimit P1 P2 P3 * *
6868 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
6869 **
6870 ** This opcode performs a commonly used computation associated with
6871 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
6872 ** holds the offset counter. The opcode computes the combined value
6873 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
6874 ** value computed is the total number of rows that will need to be
6875 ** visited in order to complete the query.
6876 **
6877 ** If r[P3] is zero or negative, that means there is no OFFSET
6878 ** and r[P2] is set to be the value of the LIMIT, r[P1].
6879 **
6880 ** if r[P1] is zero or negative, that means there is no LIMIT
6881 ** and r[P2] is set to -1.
6882 **
6883 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
6884 */
6885 case OP_OffsetLimit: { /* in1, out2, in3 */
6886 i64 x;
6887 pIn1 = &aMem[pOp->p1];
6888 pIn3 = &aMem[pOp->p3];
6889 pOut = out2Prerelease(p, pOp);
6890 assert( pIn1->flags & MEM_Int );
6891 assert( pIn3->flags & MEM_Int );
6892 x = pIn1->u.i;
6893 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
6894 /* If the LIMIT is less than or equal to zero, loop forever. This
6895 ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
6896 ** also loop forever. This is undocumented. In fact, one could argue
6897 ** that the loop should terminate. But assuming 1 billion iterations
6898 ** per second (far exceeding the capabilities of any current hardware)
6899 ** it would take nearly 300 years to actually reach the limit. So
6900 ** looping forever is a reasonable approximation. */
6901 pOut->u.i = -1;
6902 }else{
6903 pOut->u.i = x;
6904 }
6905 break;
6906 }
6907
6908 /* Opcode: IfNotZero P1 P2 * * *
6909 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
6910 **
6911 ** Register P1 must contain an integer. If the content of register P1 is
6912 ** initially greater than zero, then decrement the value in register P1.
6913 ** If it is non-zero (negative or positive) and then also jump to P2.
6914 ** If register P1 is initially zero, leave it unchanged and fall through.
6915 */
6916 case OP_IfNotZero: { /* jump, in1 */
6917 pIn1 = &aMem[pOp->p1];
6918 assert( pIn1->flags&MEM_Int );
6919 VdbeBranchTaken(pIn1->u.i<0, 2);
6920 if( pIn1->u.i ){
6921 if( pIn1->u.i>0 ) pIn1->u.i--;
6922 goto jump_to_p2;
6923 }
6924 break;
6925 }
6926
6927 /* Opcode: DecrJumpZero P1 P2 * * *
6928 ** Synopsis: if (--r[P1])==0 goto P2
6929 **
6930 ** Register P1 must hold an integer. Decrement the value in P1
6931 ** and jump to P2 if the new value is exactly zero.
6932 */
6933 case OP_DecrJumpZero: { /* jump, in1 */
6934 pIn1 = &aMem[pOp->p1];
6935 assert( pIn1->flags&MEM_Int );
6936 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
6937 VdbeBranchTaken(pIn1->u.i==0, 2);
6938 if( pIn1->u.i==0 ) goto jump_to_p2;
6939 break;
6940 }
6941
6942
6943 /* Opcode: AggStep * P2 P3 P4 P5
6944 ** Synopsis: accum=r[P3] step(r[P2@P5])
6945 **
6946 ** Execute the xStep function for an aggregate.
6947 ** The function has P5 arguments. P4 is a pointer to the
6948 ** FuncDef structure that specifies the function. Register P3 is the
6949 ** accumulator.
6950 **
6951 ** The P5 arguments are taken from register P2 and its
6952 ** successors.
6953 */
6954 /* Opcode: AggInverse * P2 P3 P4 P5
6955 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
6956 **
6957 ** Execute the xInverse function for an aggregate.
6958 ** The function has P5 arguments. P4 is a pointer to the
6959 ** FuncDef structure that specifies the function. Register P3 is the
6960 ** accumulator.
6961 **
6962 ** The P5 arguments are taken from register P2 and its
6963 ** successors.
6964 */
6965 /* Opcode: AggStep1 P1 P2 P3 P4 P5
6966 ** Synopsis: accum=r[P3] step(r[P2@P5])
6967 **
6968 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
6969 ** aggregate. The function has P5 arguments. P4 is a pointer to the
6970 ** FuncDef structure that specifies the function. Register P3 is the
6971 ** accumulator.
6972 **
6973 ** The P5 arguments are taken from register P2 and its
6974 ** successors.
6975 **
6976 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
6977 ** the FuncDef stored in P4 is converted into an sqlite3_context and
6978 ** the opcode is changed. In this way, the initialization of the
6979 ** sqlite3_context only happens once, instead of on each call to the
6980 ** step function.
6981 */
6982 case OP_AggInverse:
6983 case OP_AggStep: {
6984 int n;
6985 sqlite3_context *pCtx;
6986
6987 assert( pOp->p4type==P4_FUNCDEF );
6988 n = pOp->p5;
6989 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
6990 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
6991 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
6992 pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
6993 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
6994 if( pCtx==0 ) goto no_mem;
6995 pCtx->pMem = 0;
6996 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
6997 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
6998 pCtx->pFunc = pOp->p4.pFunc;
6999 pCtx->iOp = (int)(pOp - aOp);
7000 pCtx->pVdbe = p;
7001 pCtx->skipFlag = 0;
7002 pCtx->isError = 0;
7003 pCtx->argc = n;
7004 pOp->p4type = P4_FUNCCTX;
7005 pOp->p4.pCtx = pCtx;
7006
7007 /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
7008 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
7009
7010 pOp->opcode = OP_AggStep1;
7011 /* Fall through into OP_AggStep */
7012 /* no break */ deliberate_fall_through
7013 }
7014 case OP_AggStep1: {
7015 int i;
7016 sqlite3_context *pCtx;
7017 Mem *pMem;
7018
7019 assert( pOp->p4type==P4_FUNCCTX );
7020 pCtx = pOp->p4.pCtx;
7021 pMem = &aMem[pOp->p3];
7022
7023 #ifdef SQLITE_DEBUG
7024 if( pOp->p1 ){
7025 /* This is an OP_AggInverse call. Verify that xStep has always
7026 ** been called at least once prior to any xInverse call. */
7027 assert( pMem->uTemp==0x1122e0e3 );
7028 }else{
7029 /* This is an OP_AggStep call. Mark it as such. */
7030 pMem->uTemp = 0x1122e0e3;
7031 }
7032 #endif
7033
7034 /* If this function is inside of a trigger, the register array in aMem[]
7035 ** might change from one evaluation to the next. The next block of code
7036 ** checks to see if the register array has changed, and if so it
7037 ** reinitializes the relavant parts of the sqlite3_context object */
7038 if( pCtx->pMem != pMem ){
7039 pCtx->pMem = pMem;
7040 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7041 }
7042
7043 #ifdef SQLITE_DEBUG
7044 for(i=0; i<pCtx->argc; i++){
7045 assert( memIsValid(pCtx->argv[i]) );
7046 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7047 }
7048 #endif
7049
7050 pMem->n++;
7051 assert( pCtx->pOut->flags==MEM_Null );
7052 assert( pCtx->isError==0 );
7053 assert( pCtx->skipFlag==0 );
7054 #ifndef SQLITE_OMIT_WINDOWFUNC
7055 if( pOp->p1 ){
7056 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
7057 }else
7058 #endif
7059 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
7060
7061 if( pCtx->isError ){
7062 if( pCtx->isError>0 ){
7063 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
7064 rc = pCtx->isError;
7065 }
7066 if( pCtx->skipFlag ){
7067 assert( pOp[-1].opcode==OP_CollSeq );
7068 i = pOp[-1].p1;
7069 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
7070 pCtx->skipFlag = 0;
7071 }
7072 sqlite3VdbeMemRelease(pCtx->pOut);
7073 pCtx->pOut->flags = MEM_Null;
7074 pCtx->isError = 0;
7075 if( rc ) goto abort_due_to_error;
7076 }
7077 assert( pCtx->pOut->flags==MEM_Null );
7078 assert( pCtx->skipFlag==0 );
7079 break;
7080 }
7081
7082 /* Opcode: AggFinal P1 P2 * P4 *
7083 ** Synopsis: accum=r[P1] N=P2
7084 **
7085 ** P1 is the memory location that is the accumulator for an aggregate
7086 ** or window function. Execute the finalizer function
7087 ** for an aggregate and store the result in P1.
7088 **
7089 ** P2 is the number of arguments that the step function takes and
7090 ** P4 is a pointer to the FuncDef for this function. The P2
7091 ** argument is not used by this opcode. It is only there to disambiguate
7092 ** functions that can take varying numbers of arguments. The
7093 ** P4 argument is only needed for the case where
7094 ** the step function was not previously called.
7095 */
7096 /* Opcode: AggValue * P2 P3 P4 *
7097 ** Synopsis: r[P3]=value N=P2
7098 **
7099 ** Invoke the xValue() function and store the result in register P3.
7100 **
7101 ** P2 is the number of arguments that the step function takes and
7102 ** P4 is a pointer to the FuncDef for this function. The P2
7103 ** argument is not used by this opcode. It is only there to disambiguate
7104 ** functions that can take varying numbers of arguments. The
7105 ** P4 argument is only needed for the case where
7106 ** the step function was not previously called.
7107 */
7108 case OP_AggValue:
7109 case OP_AggFinal: {
7110 Mem *pMem;
7111 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
7112 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
7113 pMem = &aMem[pOp->p1];
7114 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
7115 #ifndef SQLITE_OMIT_WINDOWFUNC
7116 if( pOp->p3 ){
7117 memAboutToChange(p, &aMem[pOp->p3]);
7118 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
7119 pMem = &aMem[pOp->p3];
7120 }else
7121 #endif
7122 {
7123 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
7124 }
7125
7126 if( rc ){
7127 sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
7128 goto abort_due_to_error;
7129 }
7130 sqlite3VdbeChangeEncoding(pMem, encoding);
7131 UPDATE_MAX_BLOBSIZE(pMem);
7132 if( sqlite3VdbeMemTooBig(pMem) ){
7133 goto too_big;
7134 }
7135 break;
7136 }
7137
7138 #ifndef SQLITE_OMIT_WAL
7139 /* Opcode: Checkpoint P1 P2 P3 * *
7140 **
7141 ** Checkpoint database P1. This is a no-op if P1 is not currently in
7142 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
7143 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
7144 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
7145 ** WAL after the checkpoint into mem[P3+1] and the number of pages
7146 ** in the WAL that have been checkpointed after the checkpoint
7147 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
7148 ** mem[P3+2] are initialized to -1.
7149 */
7150 case OP_Checkpoint: {
7151 int i; /* Loop counter */
7152 int aRes[3]; /* Results */
7153 Mem *pMem; /* Write results here */
7154
7155 assert( p->readOnly==0 );
7156 aRes[0] = 0;
7157 aRes[1] = aRes[2] = -1;
7158 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
7159 || pOp->p2==SQLITE_CHECKPOINT_FULL
7160 || pOp->p2==SQLITE_CHECKPOINT_RESTART
7161 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
7162 );
7163 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
7164 if( rc ){
7165 if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
7166 rc = SQLITE_OK;
7167 aRes[0] = 1;
7168 }
7169 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
7170 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
7171 }
7172 break;
7173 };
7174 #endif
7175
7176 #ifndef SQLITE_OMIT_PRAGMA
7177 /* Opcode: JournalMode P1 P2 P3 * *
7178 **
7179 ** Change the journal mode of database P1 to P3. P3 must be one of the
7180 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
7181 ** modes (delete, truncate, persist, off and memory), this is a simple
7182 ** operation. No IO is required.
7183 **
7184 ** If changing into or out of WAL mode the procedure is more complicated.
7185 **
7186 ** Write a string containing the final journal-mode to register P2.
7187 */
7188 case OP_JournalMode: { /* out2 */
7189 Btree *pBt; /* Btree to change journal mode of */
7190 Pager *pPager; /* Pager associated with pBt */
7191 int eNew; /* New journal mode */
7192 int eOld; /* The old journal mode */
7193 #ifndef SQLITE_OMIT_WAL
7194 const char *zFilename; /* Name of database file for pPager */
7195 #endif
7196
7197 pOut = out2Prerelease(p, pOp);
7198 eNew = pOp->p3;
7199 assert( eNew==PAGER_JOURNALMODE_DELETE
7200 || eNew==PAGER_JOURNALMODE_TRUNCATE
7201 || eNew==PAGER_JOURNALMODE_PERSIST
7202 || eNew==PAGER_JOURNALMODE_OFF
7203 || eNew==PAGER_JOURNALMODE_MEMORY
7204 || eNew==PAGER_JOURNALMODE_WAL
7205 || eNew==PAGER_JOURNALMODE_QUERY
7206 );
7207 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7208 assert( p->readOnly==0 );
7209
7210 pBt = db->aDb[pOp->p1].pBt;
7211 pPager = sqlite3BtreePager(pBt);
7212 eOld = sqlite3PagerGetJournalMode(pPager);
7213 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
7214 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
7215
7216 #ifndef SQLITE_OMIT_WAL
7217 zFilename = sqlite3PagerFilename(pPager, 1);
7218
7219 /* Do not allow a transition to journal_mode=WAL for a database
7220 ** in temporary storage or if the VFS does not support shared memory
7221 */
7222 if( eNew==PAGER_JOURNALMODE_WAL
7223 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
7224 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
7225 ){
7226 eNew = eOld;
7227 }
7228
7229 if( (eNew!=eOld)
7230 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
7231 ){
7232 if( !db->autoCommit || db->nVdbeRead>1 ){
7233 rc = SQLITE_ERROR;
7234 sqlite3VdbeError(p,
7235 "cannot change %s wal mode from within a transaction",
7236 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
7237 );
7238 goto abort_due_to_error;
7239 }else{
7240
7241 if( eOld==PAGER_JOURNALMODE_WAL ){
7242 /* If leaving WAL mode, close the log file. If successful, the call
7243 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
7244 ** file. An EXCLUSIVE lock may still be held on the database file
7245 ** after a successful return.
7246 */
7247 rc = sqlite3PagerCloseWal(pPager, db);
7248 if( rc==SQLITE_OK ){
7249 sqlite3PagerSetJournalMode(pPager, eNew);
7250 }
7251 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
7252 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
7253 ** as an intermediate */
7254 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
7255 }
7256
7257 /* Open a transaction on the database file. Regardless of the journal
7258 ** mode, this transaction always uses a rollback journal.
7259 */
7260 assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
7261 if( rc==SQLITE_OK ){
7262 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
7263 }
7264 }
7265 }
7266 #endif /* ifndef SQLITE_OMIT_WAL */
7267
7268 if( rc ) eNew = eOld;
7269 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
7270
7271 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
7272 pOut->z = (char *)sqlite3JournalModename(eNew);
7273 pOut->n = sqlite3Strlen30(pOut->z);
7274 pOut->enc = SQLITE_UTF8;
7275 sqlite3VdbeChangeEncoding(pOut, encoding);
7276 if( rc ) goto abort_due_to_error;
7277 break;
7278 };
7279 #endif /* SQLITE_OMIT_PRAGMA */
7280
7281 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7282 /* Opcode: Vacuum P1 P2 * * *
7283 **
7284 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
7285 ** for an attached database. The "temp" database may not be vacuumed.
7286 **
7287 ** If P2 is not zero, then it is a register holding a string which is
7288 ** the file into which the result of vacuum should be written. When
7289 ** P2 is zero, the vacuum overwrites the original database.
7290 */
7291 case OP_Vacuum: {
7292 assert( p->readOnly==0 );
7293 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
7294 pOp->p2 ? &aMem[pOp->p2] : 0);
7295 if( rc ) goto abort_due_to_error;
7296 break;
7297 }
7298 #endif
7299
7300 #if !defined(SQLITE_OMIT_AUTOVACUUM)
7301 /* Opcode: IncrVacuum P1 P2 * * *
7302 **
7303 ** Perform a single step of the incremental vacuum procedure on
7304 ** the P1 database. If the vacuum has finished, jump to instruction
7305 ** P2. Otherwise, fall through to the next instruction.
7306 */
7307 case OP_IncrVacuum: { /* jump */
7308 Btree *pBt;
7309
7310 assert( pOp->p1>=0 && pOp->p1<db->nDb );
7311 assert( DbMaskTest(p->btreeMask, pOp->p1) );
7312 assert( p->readOnly==0 );
7313 pBt = db->aDb[pOp->p1].pBt;
7314 rc = sqlite3BtreeIncrVacuum(pBt);
7315 VdbeBranchTaken(rc==SQLITE_DONE,2);
7316 if( rc ){
7317 if( rc!=SQLITE_DONE ) goto abort_due_to_error;
7318 rc = SQLITE_OK;
7319 goto jump_to_p2;
7320 }
7321 break;
7322 }
7323 #endif
7324
7325 /* Opcode: Expire P1 P2 * * *
7326 **
7327 ** Cause precompiled statements to expire. When an expired statement
7328 ** is executed using sqlite3_step() it will either automatically
7329 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
7330 ** or it will fail with SQLITE_SCHEMA.
7331 **
7332 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
7333 ** then only the currently executing statement is expired.
7334 **
7335 ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
7336 ** then running SQL statements are allowed to continue to run to completion.
7337 ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
7338 ** that might help the statement run faster but which does not affect the
7339 ** correctness of operation.
7340 */
7341 case OP_Expire: {
7342 assert( pOp->p2==0 || pOp->p2==1 );
7343 if( !pOp->p1 ){
7344 sqlite3ExpirePreparedStatements(db, pOp->p2);
7345 }else{
7346 p->expired = pOp->p2+1;
7347 }
7348 break;
7349 }
7350
7351 /* Opcode: CursorLock P1 * * * *
7352 **
7353 ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
7354 ** written by an other cursor.
7355 */
7356 case OP_CursorLock: {
7357 VdbeCursor *pC;
7358 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7359 pC = p->apCsr[pOp->p1];
7360 assert( pC!=0 );
7361 assert( pC->eCurType==CURTYPE_BTREE );
7362 sqlite3BtreeCursorPin(pC->uc.pCursor);
7363 break;
7364 }
7365
7366 /* Opcode: CursorUnlock P1 * * * *
7367 **
7368 ** Unlock the btree to which cursor P1 is pointing so that it can be
7369 ** written by other cursors.
7370 */
7371 case OP_CursorUnlock: {
7372 VdbeCursor *pC;
7373 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7374 pC = p->apCsr[pOp->p1];
7375 assert( pC!=0 );
7376 assert( pC->eCurType==CURTYPE_BTREE );
7377 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
7378 break;
7379 }
7380
7381 #ifndef SQLITE_OMIT_SHARED_CACHE
7382 /* Opcode: TableLock P1 P2 P3 P4 *
7383 ** Synopsis: iDb=P1 root=P2 write=P3
7384 **
7385 ** Obtain a lock on a particular table. This instruction is only used when
7386 ** the shared-cache feature is enabled.
7387 **
7388 ** P1 is the index of the database in sqlite3.aDb[] of the database
7389 ** on which the lock is acquired. A readlock is obtained if P3==0 or
7390 ** a write lock if P3==1.
7391 **
7392 ** P2 contains the root-page of the table to lock.
7393 **
7394 ** P4 contains a pointer to the name of the table being locked. This is only
7395 ** used to generate an error message if the lock cannot be obtained.
7396 */
7397 case OP_TableLock: {
7398 u8 isWriteLock = (u8)pOp->p3;
7399 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
7400 int p1 = pOp->p1;
7401 assert( p1>=0 && p1<db->nDb );
7402 assert( DbMaskTest(p->btreeMask, p1) );
7403 assert( isWriteLock==0 || isWriteLock==1 );
7404 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
7405 if( rc ){
7406 if( (rc&0xFF)==SQLITE_LOCKED ){
7407 const char *z = pOp->p4.z;
7408 sqlite3VdbeError(p, "database table is locked: %s", z);
7409 }
7410 goto abort_due_to_error;
7411 }
7412 }
7413 break;
7414 }
7415 #endif /* SQLITE_OMIT_SHARED_CACHE */
7416
7417 #ifndef SQLITE_OMIT_VIRTUALTABLE
7418 /* Opcode: VBegin * * * P4 *
7419 **
7420 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
7421 ** xBegin method for that table.
7422 **
7423 ** Also, whether or not P4 is set, check that this is not being called from
7424 ** within a callback to a virtual table xSync() method. If it is, the error
7425 ** code will be set to SQLITE_LOCKED.
7426 */
7427 case OP_VBegin: {
7428 VTable *pVTab;
7429 pVTab = pOp->p4.pVtab;
7430 rc = sqlite3VtabBegin(db, pVTab);
7431 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
7432 if( rc ) goto abort_due_to_error;
7433 break;
7434 }
7435 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7436
7437 #ifndef SQLITE_OMIT_VIRTUALTABLE
7438 /* Opcode: VCreate P1 P2 * * *
7439 **
7440 ** P2 is a register that holds the name of a virtual table in database
7441 ** P1. Call the xCreate method for that table.
7442 */
7443 case OP_VCreate: {
7444 Mem sMem; /* For storing the record being decoded */
7445 const char *zTab; /* Name of the virtual table */
7446
7447 memset(&sMem, 0, sizeof(sMem));
7448 sMem.db = db;
7449 /* Because P2 is always a static string, it is impossible for the
7450 ** sqlite3VdbeMemCopy() to fail */
7451 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
7452 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
7453 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
7454 assert( rc==SQLITE_OK );
7455 zTab = (const char*)sqlite3_value_text(&sMem);
7456 assert( zTab || db->mallocFailed );
7457 if( zTab ){
7458 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
7459 }
7460 sqlite3VdbeMemRelease(&sMem);
7461 if( rc ) goto abort_due_to_error;
7462 break;
7463 }
7464 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7465
7466 #ifndef SQLITE_OMIT_VIRTUALTABLE
7467 /* Opcode: VDestroy P1 * * P4 *
7468 **
7469 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
7470 ** of that table.
7471 */
7472 case OP_VDestroy: {
7473 db->nVDestroy++;
7474 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
7475 db->nVDestroy--;
7476 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
7477 if( rc ) goto abort_due_to_error;
7478 break;
7479 }
7480 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7481
7482 #ifndef SQLITE_OMIT_VIRTUALTABLE
7483 /* Opcode: VOpen P1 * * P4 *
7484 **
7485 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7486 ** P1 is a cursor number. This opcode opens a cursor to the virtual
7487 ** table and stores that cursor in P1.
7488 */
7489 case OP_VOpen: {
7490 VdbeCursor *pCur;
7491 sqlite3_vtab_cursor *pVCur;
7492 sqlite3_vtab *pVtab;
7493 const sqlite3_module *pModule;
7494
7495 assert( p->bIsReader );
7496 pCur = 0;
7497 pVCur = 0;
7498 pVtab = pOp->p4.pVtab->pVtab;
7499 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7500 rc = SQLITE_LOCKED;
7501 goto abort_due_to_error;
7502 }
7503 pModule = pVtab->pModule;
7504 rc = pModule->xOpen(pVtab, &pVCur);
7505 sqlite3VtabImportErrmsg(p, pVtab);
7506 if( rc ) goto abort_due_to_error;
7507
7508 /* Initialize sqlite3_vtab_cursor base class */
7509 pVCur->pVtab = pVtab;
7510
7511 /* Initialize vdbe cursor object */
7512 pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
7513 if( pCur ){
7514 pCur->uc.pVCur = pVCur;
7515 pVtab->nRef++;
7516 }else{
7517 assert( db->mallocFailed );
7518 pModule->xClose(pVCur);
7519 goto no_mem;
7520 }
7521 break;
7522 }
7523 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7524
7525 #ifndef SQLITE_OMIT_VIRTUALTABLE
7526 /* Opcode: VFilter P1 P2 P3 P4 *
7527 ** Synopsis: iplan=r[P3] zplan='P4'
7528 **
7529 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
7530 ** the filtered result set is empty.
7531 **
7532 ** P4 is either NULL or a string that was generated by the xBestIndex
7533 ** method of the module. The interpretation of the P4 string is left
7534 ** to the module implementation.
7535 **
7536 ** This opcode invokes the xFilter method on the virtual table specified
7537 ** by P1. The integer query plan parameter to xFilter is stored in register
7538 ** P3. Register P3+1 stores the argc parameter to be passed to the
7539 ** xFilter method. Registers P3+2..P3+1+argc are the argc
7540 ** additional parameters which are passed to
7541 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
7542 **
7543 ** A jump is made to P2 if the result set after filtering would be empty.
7544 */
7545 case OP_VFilter: { /* jump */
7546 int nArg;
7547 int iQuery;
7548 const sqlite3_module *pModule;
7549 Mem *pQuery;
7550 Mem *pArgc;
7551 sqlite3_vtab_cursor *pVCur;
7552 sqlite3_vtab *pVtab;
7553 VdbeCursor *pCur;
7554 int res;
7555 int i;
7556 Mem **apArg;
7557
7558 pQuery = &aMem[pOp->p3];
7559 pArgc = &pQuery[1];
7560 pCur = p->apCsr[pOp->p1];
7561 assert( memIsValid(pQuery) );
7562 REGISTER_TRACE(pOp->p3, pQuery);
7563 assert( pCur->eCurType==CURTYPE_VTAB );
7564 pVCur = pCur->uc.pVCur;
7565 pVtab = pVCur->pVtab;
7566 pModule = pVtab->pModule;
7567
7568 /* Grab the index number and argc parameters */
7569 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
7570 nArg = (int)pArgc->u.i;
7571 iQuery = (int)pQuery->u.i;
7572
7573 /* Invoke the xFilter method */
7574 res = 0;
7575 apArg = p->apArg;
7576 for(i = 0; i<nArg; i++){
7577 apArg[i] = &pArgc[i+1];
7578 }
7579 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
7580 sqlite3VtabImportErrmsg(p, pVtab);
7581 if( rc ) goto abort_due_to_error;
7582 res = pModule->xEof(pVCur);
7583 pCur->nullRow = 0;
7584 VdbeBranchTaken(res!=0,2);
7585 if( res ) goto jump_to_p2;
7586 break;
7587 }
7588 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7589
7590 #ifndef SQLITE_OMIT_VIRTUALTABLE
7591 /* Opcode: VColumn P1 P2 P3 * P5
7592 ** Synopsis: r[P3]=vcolumn(P2)
7593 **
7594 ** Store in register P3 the value of the P2-th column of
7595 ** the current row of the virtual-table of cursor P1.
7596 **
7597 ** If the VColumn opcode is being used to fetch the value of
7598 ** an unchanging column during an UPDATE operation, then the P5
7599 ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
7600 ** function to return true inside the xColumn method of the virtual
7601 ** table implementation. The P5 column might also contain other
7602 ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
7603 ** unused by OP_VColumn.
7604 */
7605 case OP_VColumn: {
7606 sqlite3_vtab *pVtab;
7607 const sqlite3_module *pModule;
7608 Mem *pDest;
7609 sqlite3_context sContext;
7610
7611 VdbeCursor *pCur = p->apCsr[pOp->p1];
7612 assert( pCur->eCurType==CURTYPE_VTAB );
7613 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
7614 pDest = &aMem[pOp->p3];
7615 memAboutToChange(p, pDest);
7616 if( pCur->nullRow ){
7617 sqlite3VdbeMemSetNull(pDest);
7618 break;
7619 }
7620 pVtab = pCur->uc.pVCur->pVtab;
7621 pModule = pVtab->pModule;
7622 assert( pModule->xColumn );
7623 memset(&sContext, 0, sizeof(sContext));
7624 sContext.pOut = pDest;
7625 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
7626 if( pOp->p5 & OPFLAG_NOCHNG ){
7627 sqlite3VdbeMemSetNull(pDest);
7628 pDest->flags = MEM_Null|MEM_Zero;
7629 pDest->u.nZero = 0;
7630 }else{
7631 MemSetTypeFlag(pDest, MEM_Null);
7632 }
7633 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
7634 sqlite3VtabImportErrmsg(p, pVtab);
7635 if( sContext.isError>0 ){
7636 sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
7637 rc = sContext.isError;
7638 }
7639 sqlite3VdbeChangeEncoding(pDest, encoding);
7640 REGISTER_TRACE(pOp->p3, pDest);
7641 UPDATE_MAX_BLOBSIZE(pDest);
7642
7643 if( sqlite3VdbeMemTooBig(pDest) ){
7644 goto too_big;
7645 }
7646 if( rc ) goto abort_due_to_error;
7647 break;
7648 }
7649 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7650
7651 #ifndef SQLITE_OMIT_VIRTUALTABLE
7652 /* Opcode: VNext P1 P2 * * *
7653 **
7654 ** Advance virtual table P1 to the next row in its result set and
7655 ** jump to instruction P2. Or, if the virtual table has reached
7656 ** the end of its result set, then fall through to the next instruction.
7657 */
7658 case OP_VNext: { /* jump */
7659 sqlite3_vtab *pVtab;
7660 const sqlite3_module *pModule;
7661 int res;
7662 VdbeCursor *pCur;
7663
7664 res = 0;
7665 pCur = p->apCsr[pOp->p1];
7666 assert( pCur->eCurType==CURTYPE_VTAB );
7667 if( pCur->nullRow ){
7668 break;
7669 }
7670 pVtab = pCur->uc.pVCur->pVtab;
7671 pModule = pVtab->pModule;
7672 assert( pModule->xNext );
7673
7674 /* Invoke the xNext() method of the module. There is no way for the
7675 ** underlying implementation to return an error if one occurs during
7676 ** xNext(). Instead, if an error occurs, true is returned (indicating that
7677 ** data is available) and the error code returned when xColumn or
7678 ** some other method is next invoked on the save virtual table cursor.
7679 */
7680 rc = pModule->xNext(pCur->uc.pVCur);
7681 sqlite3VtabImportErrmsg(p, pVtab);
7682 if( rc ) goto abort_due_to_error;
7683 res = pModule->xEof(pCur->uc.pVCur);
7684 VdbeBranchTaken(!res,2);
7685 if( !res ){
7686 /* If there is data, jump to P2 */
7687 goto jump_to_p2_and_check_for_interrupt;
7688 }
7689 goto check_for_interrupt;
7690 }
7691 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7692
7693 #ifndef SQLITE_OMIT_VIRTUALTABLE
7694 /* Opcode: VRename P1 * * P4 *
7695 **
7696 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7697 ** This opcode invokes the corresponding xRename method. The value
7698 ** in register P1 is passed as the zName argument to the xRename method.
7699 */
7700 case OP_VRename: {
7701 sqlite3_vtab *pVtab;
7702 Mem *pName;
7703 int isLegacy;
7704
7705 isLegacy = (db->flags & SQLITE_LegacyAlter);
7706 db->flags |= SQLITE_LegacyAlter;
7707 pVtab = pOp->p4.pVtab->pVtab;
7708 pName = &aMem[pOp->p1];
7709 assert( pVtab->pModule->xRename );
7710 assert( memIsValid(pName) );
7711 assert( p->readOnly==0 );
7712 REGISTER_TRACE(pOp->p1, pName);
7713 assert( pName->flags & MEM_Str );
7714 testcase( pName->enc==SQLITE_UTF8 );
7715 testcase( pName->enc==SQLITE_UTF16BE );
7716 testcase( pName->enc==SQLITE_UTF16LE );
7717 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
7718 if( rc ) goto abort_due_to_error;
7719 rc = pVtab->pModule->xRename(pVtab, pName->z);
7720 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
7721 sqlite3VtabImportErrmsg(p, pVtab);
7722 p->expired = 0;
7723 if( rc ) goto abort_due_to_error;
7724 break;
7725 }
7726 #endif
7727
7728 #ifndef SQLITE_OMIT_VIRTUALTABLE
7729 /* Opcode: VUpdate P1 P2 P3 P4 P5
7730 ** Synopsis: data=r[P3@P2]
7731 **
7732 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
7733 ** This opcode invokes the corresponding xUpdate method. P2 values
7734 ** are contiguous memory cells starting at P3 to pass to the xUpdate
7735 ** invocation. The value in register (P3+P2-1) corresponds to the
7736 ** p2th element of the argv array passed to xUpdate.
7737 **
7738 ** The xUpdate method will do a DELETE or an INSERT or both.
7739 ** The argv[0] element (which corresponds to memory cell P3)
7740 ** is the rowid of a row to delete. If argv[0] is NULL then no
7741 ** deletion occurs. The argv[1] element is the rowid of the new
7742 ** row. This can be NULL to have the virtual table select the new
7743 ** rowid for itself. The subsequent elements in the array are
7744 ** the values of columns in the new row.
7745 **
7746 ** If P2==1 then no insert is performed. argv[0] is the rowid of
7747 ** a row to delete.
7748 **
7749 ** P1 is a boolean flag. If it is set to true and the xUpdate call
7750 ** is successful, then the value returned by sqlite3_last_insert_rowid()
7751 ** is set to the value of the rowid for the row just inserted.
7752 **
7753 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
7754 ** apply in the case of a constraint failure on an insert or update.
7755 */
7756 case OP_VUpdate: {
7757 sqlite3_vtab *pVtab;
7758 const sqlite3_module *pModule;
7759 int nArg;
7760 int i;
7761 sqlite_int64 rowid;
7762 Mem **apArg;
7763 Mem *pX;
7764
7765 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
7766 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
7767 );
7768 assert( p->readOnly==0 );
7769 if( db->mallocFailed ) goto no_mem;
7770 sqlite3VdbeIncrWriteCounter(p, 0);
7771 pVtab = pOp->p4.pVtab->pVtab;
7772 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
7773 rc = SQLITE_LOCKED;
7774 goto abort_due_to_error;
7775 }
7776 pModule = pVtab->pModule;
7777 nArg = pOp->p2;
7778 assert( pOp->p4type==P4_VTAB );
7779 if( ALWAYS(pModule->xUpdate) ){
7780 u8 vtabOnConflict = db->vtabOnConflict;
7781 apArg = p->apArg;
7782 pX = &aMem[pOp->p3];
7783 for(i=0; i<nArg; i++){
7784 assert( memIsValid(pX) );
7785 memAboutToChange(p, pX);
7786 apArg[i] = pX;
7787 pX++;
7788 }
7789 db->vtabOnConflict = pOp->p5;
7790 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
7791 db->vtabOnConflict = vtabOnConflict;
7792 sqlite3VtabImportErrmsg(p, pVtab);
7793 if( rc==SQLITE_OK && pOp->p1 ){
7794 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
7795 db->lastRowid = rowid;
7796 }
7797 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
7798 if( pOp->p5==OE_Ignore ){
7799 rc = SQLITE_OK;
7800 }else{
7801 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
7802 }
7803 }else{
7804 p->nChange++;
7805 }
7806 if( rc ) goto abort_due_to_error;
7807 }
7808 break;
7809 }
7810 #endif /* SQLITE_OMIT_VIRTUALTABLE */
7811
7812 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7813 /* Opcode: Pagecount P1 P2 * * *
7814 **
7815 ** Write the current number of pages in database P1 to memory cell P2.
7816 */
7817 case OP_Pagecount: { /* out2 */
7818 pOut = out2Prerelease(p, pOp);
7819 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
7820 break;
7821 }
7822 #endif
7823
7824
7825 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
7826 /* Opcode: MaxPgcnt P1 P2 P3 * *
7827 **
7828 ** Try to set the maximum page count for database P1 to the value in P3.
7829 ** Do not let the maximum page count fall below the current page count and
7830 ** do not change the maximum page count value if P3==0.
7831 **
7832 ** Store the maximum page count after the change in register P2.
7833 */
7834 case OP_MaxPgcnt: { /* out2 */
7835 unsigned int newMax;
7836 Btree *pBt;
7837
7838 pOut = out2Prerelease(p, pOp);
7839 pBt = db->aDb[pOp->p1].pBt;
7840 newMax = 0;
7841 if( pOp->p3 ){
7842 newMax = sqlite3BtreeLastPage(pBt);
7843 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
7844 }
7845 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
7846 break;
7847 }
7848 #endif
7849
7850 /* Opcode: Function P1 P2 P3 P4 *
7851 ** Synopsis: r[P3]=func(r[P2@NP])
7852 **
7853 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7854 ** contains a pointer to the function to be run) with arguments taken
7855 ** from register P2 and successors. The number of arguments is in
7856 ** the sqlite3_context object that P4 points to.
7857 ** The result of the function is stored
7858 ** in register P3. Register P3 must not be one of the function inputs.
7859 **
7860 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7861 ** function was determined to be constant at compile time. If the first
7862 ** argument was constant then bit 0 of P1 is set. This is used to determine
7863 ** whether meta data associated with a user function argument using the
7864 ** sqlite3_set_auxdata() API may be safely retained until the next
7865 ** invocation of this opcode.
7866 **
7867 ** See also: AggStep, AggFinal, PureFunc
7868 */
7869 /* Opcode: PureFunc P1 P2 P3 P4 *
7870 ** Synopsis: r[P3]=func(r[P2@NP])
7871 **
7872 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
7873 ** contains a pointer to the function to be run) with arguments taken
7874 ** from register P2 and successors. The number of arguments is in
7875 ** the sqlite3_context object that P4 points to.
7876 ** The result of the function is stored
7877 ** in register P3. Register P3 must not be one of the function inputs.
7878 **
7879 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
7880 ** function was determined to be constant at compile time. If the first
7881 ** argument was constant then bit 0 of P1 is set. This is used to determine
7882 ** whether meta data associated with a user function argument using the
7883 ** sqlite3_set_auxdata() API may be safely retained until the next
7884 ** invocation of this opcode.
7885 **
7886 ** This opcode works exactly like OP_Function. The only difference is in
7887 ** its name. This opcode is used in places where the function must be
7888 ** purely non-deterministic. Some built-in date/time functions can be
7889 ** either determinitic of non-deterministic, depending on their arguments.
7890 ** When those function are used in a non-deterministic way, they will check
7891 ** to see if they were called using OP_PureFunc instead of OP_Function, and
7892 ** if they were, they throw an error.
7893 **
7894 ** See also: AggStep, AggFinal, Function
7895 */
7896 case OP_PureFunc: /* group */
7897 case OP_Function: { /* group */
7898 int i;
7899 sqlite3_context *pCtx;
7900
7901 assert( pOp->p4type==P4_FUNCCTX );
7902 pCtx = pOp->p4.pCtx;
7903
7904 /* If this function is inside of a trigger, the register array in aMem[]
7905 ** might change from one evaluation to the next. The next block of code
7906 ** checks to see if the register array has changed, and if so it
7907 ** reinitializes the relavant parts of the sqlite3_context object */
7908 pOut = &aMem[pOp->p3];
7909 if( pCtx->pOut != pOut ){
7910 pCtx->pVdbe = p;
7911 pCtx->pOut = pOut;
7912 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
7913 }
7914 assert( pCtx->pVdbe==p );
7915
7916 memAboutToChange(p, pOut);
7917 #ifdef SQLITE_DEBUG
7918 for(i=0; i<pCtx->argc; i++){
7919 assert( memIsValid(pCtx->argv[i]) );
7920 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
7921 }
7922 #endif
7923 MemSetTypeFlag(pOut, MEM_Null);
7924 assert( pCtx->isError==0 );
7925 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
7926
7927 /* If the function returned an error, throw an exception */
7928 if( pCtx->isError ){
7929 if( pCtx->isError>0 ){
7930 sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
7931 rc = pCtx->isError;
7932 }
7933 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
7934 pCtx->isError = 0;
7935 if( rc ) goto abort_due_to_error;
7936 }
7937
7938 /* Copy the result of the function into register P3 */
7939 if( pOut->flags & (MEM_Str|MEM_Blob) ){
7940 sqlite3VdbeChangeEncoding(pOut, encoding);
7941 if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
7942 }
7943
7944 REGISTER_TRACE(pOp->p3, pOut);
7945 UPDATE_MAX_BLOBSIZE(pOut);
7946 break;
7947 }
7948
7949 /* Opcode: Trace P1 P2 * P4 *
7950 **
7951 ** Write P4 on the statement trace output if statement tracing is
7952 ** enabled.
7953 **
7954 ** Operand P1 must be 0x7fffffff and P2 must positive.
7955 */
7956 /* Opcode: Init P1 P2 P3 P4 *
7957 ** Synopsis: Start at P2
7958 **
7959 ** Programs contain a single instance of this opcode as the very first
7960 ** opcode.
7961 **
7962 ** If tracing is enabled (by the sqlite3_trace()) interface, then
7963 ** the UTF-8 string contained in P4 is emitted on the trace callback.
7964 ** Or if P4 is blank, use the string returned by sqlite3_sql().
7965 **
7966 ** If P2 is not zero, jump to instruction P2.
7967 **
7968 ** Increment the value of P1 so that OP_Once opcodes will jump the
7969 ** first time they are evaluated for this run.
7970 **
7971 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
7972 ** error is encountered.
7973 */
7974 case OP_Trace:
7975 case OP_Init: { /* jump */
7976 int i;
7977 #ifndef SQLITE_OMIT_TRACE
7978 char *zTrace;
7979 #endif
7980
7981 /* If the P4 argument is not NULL, then it must be an SQL comment string.
7982 ** The "--" string is broken up to prevent false-positives with srcck1.c.
7983 **
7984 ** This assert() provides evidence for:
7985 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
7986 ** would have been returned by the legacy sqlite3_trace() interface by
7987 ** using the X argument when X begins with "--" and invoking
7988 ** sqlite3_expanded_sql(P) otherwise.
7989 */
7990 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
7991
7992 /* OP_Init is always instruction 0 */
7993 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
7994
7995 #ifndef SQLITE_OMIT_TRACE
7996 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
7997 && !p->doingRerun
7998 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
7999 ){
8000 #ifndef SQLITE_OMIT_DEPRECATED
8001 if( db->mTrace & SQLITE_TRACE_LEGACY ){
8002 char *z = sqlite3VdbeExpandSql(p, zTrace);
8003 db->trace.xLegacy(db->pTraceArg, z);
8004 sqlite3_free(z);
8005 }else
8006 #endif
8007 if( db->nVdbeExec>1 ){
8008 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
8009 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
8010 sqlite3DbFree(db, z);
8011 }else{
8012 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
8013 }
8014 }
8015 #ifdef SQLITE_USE_FCNTL_TRACE
8016 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
8017 if( zTrace ){
8018 int j;
8019 for(j=0; j<db->nDb; j++){
8020 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
8021 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
8022 }
8023 }
8024 #endif /* SQLITE_USE_FCNTL_TRACE */
8025 #ifdef SQLITE_DEBUG
8026 if( (db->flags & SQLITE_SqlTrace)!=0
8027 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
8028 ){
8029 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
8030 }
8031 #endif /* SQLITE_DEBUG */
8032 #endif /* SQLITE_OMIT_TRACE */
8033 assert( pOp->p2>0 );
8034 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
8035 if( pOp->opcode==OP_Trace ) break;
8036 for(i=1; i<p->nOp; i++){
8037 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
8038 }
8039 pOp->p1 = 0;
8040 }
8041 pOp->p1++;
8042 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
8043 goto jump_to_p2;
8044 }
8045
8046 #ifdef SQLITE_ENABLE_CURSOR_HINTS
8047 /* Opcode: CursorHint P1 * * P4 *
8048 **
8049 ** Provide a hint to cursor P1 that it only needs to return rows that
8050 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
8051 ** to values currently held in registers. TK_COLUMN terms in the P4
8052 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
8053 */
8054 case OP_CursorHint: {
8055 VdbeCursor *pC;
8056
8057 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
8058 assert( pOp->p4type==P4_EXPR );
8059 pC = p->apCsr[pOp->p1];
8060 if( pC ){
8061 assert( pC->eCurType==CURTYPE_BTREE );
8062 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
8063 pOp->p4.pExpr, aMem);
8064 }
8065 break;
8066 }
8067 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
8068
8069 #ifdef SQLITE_DEBUG
8070 /* Opcode: Abortable * * * * *
8071 **
8072 ** Verify that an Abort can happen. Assert if an Abort at this point
8073 ** might cause database corruption. This opcode only appears in debugging
8074 ** builds.
8075 **
8076 ** An Abort is safe if either there have been no writes, or if there is
8077 ** an active statement journal.
8078 */
8079 case OP_Abortable: {
8080 sqlite3VdbeAssertAbortable(p);
8081 break;
8082 }
8083 #endif
8084
8085 #ifdef SQLITE_DEBUG
8086 /* Opcode: ReleaseReg P1 P2 P3 * P5
8087 ** Synopsis: release r[P1@P2] mask P3
8088 **
8089 ** Release registers from service. Any content that was in the
8090 ** the registers is unreliable after this opcode completes.
8091 **
8092 ** The registers released will be the P2 registers starting at P1,
8093 ** except if bit ii of P3 set, then do not release register P1+ii.
8094 ** In other words, P3 is a mask of registers to preserve.
8095 **
8096 ** Releasing a register clears the Mem.pScopyFrom pointer. That means
8097 ** that if the content of the released register was set using OP_SCopy,
8098 ** a change to the value of the source register for the OP_SCopy will no longer
8099 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
8100 **
8101 ** If P5 is set, then all released registers have their type set
8102 ** to MEM_Undefined so that any subsequent attempt to read the released
8103 ** register (before it is reinitialized) will generate an assertion fault.
8104 **
8105 ** P5 ought to be set on every call to this opcode.
8106 ** However, there are places in the code generator will release registers
8107 ** before their are used, under the (valid) assumption that the registers
8108 ** will not be reallocated for some other purpose before they are used and
8109 ** hence are safe to release.
8110 **
8111 ** This opcode is only available in testing and debugging builds. It is
8112 ** not generated for release builds. The purpose of this opcode is to help
8113 ** validate the generated bytecode. This opcode does not actually contribute
8114 ** to computing an answer.
8115 */
8116 case OP_ReleaseReg: {
8117 Mem *pMem;
8118 int i;
8119 u32 constMask;
8120 assert( pOp->p1>0 );
8121 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
8122 pMem = &aMem[pOp->p1];
8123 constMask = pOp->p3;
8124 for(i=0; i<pOp->p2; i++, pMem++){
8125 if( i>=32 || (constMask & MASKBIT32(i))==0 ){
8126 pMem->pScopyFrom = 0;
8127 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
8128 }
8129 }
8130 break;
8131 }
8132 #endif
8133
8134 /* Opcode: Noop * * * * *
8135 **
8136 ** Do nothing. This instruction is often useful as a jump
8137 ** destination.
8138 */
8139 /*
8140 ** The magic Explain opcode are only inserted when explain==2 (which
8141 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
8142 ** This opcode records information from the optimizer. It is the
8143 ** the same as a no-op. This opcodesnever appears in a real VM program.
8144 */
8145 default: { /* This is really OP_Noop, OP_Explain */
8146 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
8147
8148 break;
8149 }
8150
8151 /*****************************************************************************
8152 ** The cases of the switch statement above this line should all be indented
8153 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
8154 ** readability. From this point on down, the normal indentation rules are
8155 ** restored.
8156 *****************************************************************************/
8157 }
8158
8159 #ifdef VDBE_PROFILE
8160 {
8161 u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
8162 if( endTime>start ) pOrigOp->cycles += endTime - start;
8163 pOrigOp->cnt++;
8164 }
8165 #endif
8166
8167 /* The following code adds nothing to the actual functionality
8168 ** of the program. It is only here for testing and debugging.
8169 ** On the other hand, it does burn CPU cycles every time through
8170 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
8171 */
8172 #ifndef NDEBUG
8173 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8174
8175 #ifdef SQLITE_DEBUG
8176 if( db->flags & SQLITE_VdbeTrace ){
8177 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8178 if( rc!=0 ) printf("rc=%d\n",rc);
8179 if( opProperty & (OPFLG_OUT2) ){
8180 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8181 }
8182 if( opProperty & OPFLG_OUT3 ){
8183 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8184 }
8185 if( opProperty==0xff ){
8186 /* Never happens. This code exists to avoid a harmless linkage
8187 ** warning aboud sqlite3VdbeRegisterDump() being defined but not
8188 ** used. */
8189 sqlite3VdbeRegisterDump(p);
8190 }
8191 }
8192 #endif /* SQLITE_DEBUG */
8193 #endif /* NDEBUG */
8194 } /* The end of the for(;;) loop the loops through opcodes */
8195
8196 /* If we reach this point, it means that execution is finished with
8197 ** an error of some kind.
8198 */
8199 abort_due_to_error:
8200 if( db->mallocFailed ){
8201 rc = SQLITE_NOMEM_BKPT;
8202 }else if( rc==SQLITE_IOERR_CORRUPTFS ){
8203 rc = SQLITE_CORRUPT_BKPT;
8204 }
8205 assert( rc );
8206 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
8207 sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
8208 }
8209 p->rc = rc;
8210 sqlite3SystemError(db, rc);
8211 testcase( sqlite3GlobalConfig.xLog!=0 );
8212 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
8213 (int)(pOp - aOp), p->zSql, p->zErrMsg);
8214 sqlite3VdbeHalt(p);
8215 if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
8216 rc = SQLITE_ERROR;
8217 if( resetSchemaOnFault>0 ){
8218 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
8219 }
8220
8221 /* This is the only way out of this procedure. We have to
8222 ** release the mutexes on btrees that were acquired at the
8223 ** top. */
8224 vdbe_return:
8225 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8226 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
8227 nProgressLimit += db->nProgressOps;
8228 if( db->xProgress(db->pProgressArg) ){
8229 nProgressLimit = LARGEST_UINT64;
8230 rc = SQLITE_INTERRUPT;
8231 goto abort_due_to_error;
8232 }
8233 }
8234 #endif
8235 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
8236 sqlite3VdbeLeave(p);
8237 assert( rc!=SQLITE_OK || nExtraDelete==0
8238 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
8239 );
8240 return rc;
8241
8242 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
8243 ** is encountered.
8244 */
8245 too_big:
8246 sqlite3VdbeError(p, "string or blob too big");
8247 rc = SQLITE_TOOBIG;
8248 goto abort_due_to_error;
8249
8250 /* Jump to here if a malloc() fails.
8251 */
8252 no_mem:
8253 sqlite3OomFault(db);
8254 sqlite3VdbeError(p, "out of memory");
8255 rc = SQLITE_NOMEM_BKPT;
8256 goto abort_due_to_error;
8257
8258 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
8259 ** flag.
8260 */
8261 abort_due_to_interrupt:
8262 assert( AtomicLoad(&db->u1.isInterrupted) );
8263 rc = SQLITE_INTERRUPT;
8264 goto abort_due_to_error;
8265 }
8266