Bumped all versions.
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** The code in this file implements execution method of the
13 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
14 ** handles housekeeping details such as creating and deleting
15 ** VDBE instances. This file is solely interested in executing
18 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
21 ** The SQL parser generates a program which is then executed by
22 ** the VDBE to do the work of the SQL statement. VDBE programs are
23 ** similar in form to assembly language. The program consists of
24 ** a linear sequence of operations. Each operation has an opcode
25 ** and 3 operands. Operands P1 and P2 are integers. Operand P3
26 ** is a null-terminated string. The P2 operand must be non-negative.
27 ** Opcodes will typically ignore one or more operands. Many opcodes
28 ** ignore all three operands.
30 ** Computation results are stored on a stack. Each entry on the
31 ** stack is either an integer, a null-terminated string, a floating point
32 ** number, or the SQL "NULL" value. An inplicit conversion from one
33 ** type to the other occurs as necessary.
35 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
36 ** function which does the work of interpreting a VDBE program.
37 ** But other routines are also provided to help in building up
38 ** a program instruction by instruction.
40 ** Various scripts scan this source file in order to generate HTML
41 ** documentation, headers files, or other derived files. The formatting
42 ** of the code in this file is, therefore, important. See other comments
43 ** in this file for details. If in doubt, do not deviate from existing
44 ** commenting and indentation practices when changing or adding code.
48 #include "sqliteInt.h"
54 ** The following global variable is incremented every time a cursor
55 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
56 ** procedures use this information to make sure that indices are
57 ** working correctly. This variable has no function other than to
58 ** help verify the correct operation of the library.
61 int sqlite3_search_count = 0;
65 ** When this global variable is positive, it gets decremented once before
66 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
67 ** field of the sqlite3 structure is set in order to simulate and interrupt.
69 ** This facility is used for testing purposes only. It does not function
70 ** in an ordinary build.
73 int sqlite3_interrupt_count = 0;
77 ** The next global variable is incremented each type the OP_Sort opcode
78 ** is executed. The test procedures use this information to make sure that
79 ** sorting is occurring or not occuring at appropriate times. This variable
80 ** has no function other than to help verify the correct operation of the
84 int sqlite3_sort_count = 0;
88 ** The next global variable records the size of the largest MEM_Blob
89 ** or MEM_Str that has appeared on the VDBE stack. The test procedures
90 ** use this information to make sure that the zero-blob functionality
91 ** is working correctly. This variable has no function other than to
92 ** help verify the correct operation of the library.
95 int sqlite3_max_blobsize = 0;
99 ** Release the memory associated with the given stack level. This
100 ** leaves the Mem.flags field in an inconsistent state.
102 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
105 ** Convert the given stack entity into a string if it isn't one
106 ** already. Return non-zero if a malloc() fails.
108 #define Stringify(P, enc) \
109 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
113 ** The header of a record consists of a sequence variable-length integers.
114 ** These integers are almost always small and are encoded as a single byte.
115 ** The following macro takes advantage this fact to provide a fast decode
116 ** of the integers in a record header. It is faster for the common case
117 ** where the integer is a single byte. It is a little slower when the
118 ** integer is two or more bytes. But overall it is faster.
120 ** The following expressions are equivalent:
122 ** x = sqlite3GetVarint32( A, &B );
124 ** x = GetVarint( A, B );
127 #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
130 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
131 ** a pointer to a dynamically allocated string where some other entity
132 ** is responsible for deallocating that string. Because the stack entry
133 ** does not control the string, it might be deleted without the stack
136 ** This routine converts an ephemeral string into a dynamically allocated
137 ** string that the stack entry itself controls. In other words, it
138 ** converts an MEM_Ephem string into an MEM_Dyn string.
140 #define Deephemeralize(P) \
141 if( ((P)->flags&MEM_Ephem)!=0 \
142 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
145 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
148 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
151 ** Argument pMem points at a memory cell that will be passed to a
152 ** user-defined function or returned to the user as the result of a query.
153 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
154 ** stack variables. This routine sets the pMem->enc and pMem->type
155 ** variables used by the sqlite3_value_*() routines.
157 #define storeTypeInfo(A,B) _storeTypeInfo(A)
158 static void _storeTypeInfo(Mem *pMem){
159 int flags = pMem->flags;
160 if( flags & MEM_Null ){
161 pMem->type = SQLITE_NULL;
163 else if( flags & MEM_Int ){
164 pMem->type = SQLITE_INTEGER;
166 else if( flags & MEM_Real ){
167 pMem->type = SQLITE_FLOAT;
169 else if( flags & MEM_Str ){
170 pMem->type = SQLITE_TEXT;
172 pMem->type = SQLITE_BLOB;
177 ** Pop the stack N times.
179 static void popStack(Mem **ppTos, int N){
190 ** Allocate cursor number iCur. Return a pointer to it. Return NULL
191 ** if we run out of memory.
193 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
195 assert( iCur<p->nCursor );
196 if( p->apCsr[iCur] ){
197 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
199 p->apCsr[iCur] = pCx = sqlite3MallocZero( sizeof(Cursor) );
207 ** Try to convert a value into a numeric representation if we can
208 ** do so without loss of information. In other words, if the string
209 ** looks like a number, convert it into a number. If it does not
210 ** look like a number, leave it alone.
212 static void applyNumericAffinity(Mem *pRec){
213 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
215 sqlite3VdbeMemNulTerminate(pRec);
216 if( (pRec->flags&MEM_Str)
217 && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
219 sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
220 if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
221 sqlite3VdbeMemRelease(pRec);
223 pRec->flags = MEM_Int;
225 sqlite3VdbeMemRealify(pRec);
232 ** Processing is determine by the affinity parameter:
234 ** SQLITE_AFF_INTEGER:
236 ** SQLITE_AFF_NUMERIC:
237 ** Try to convert pRec to an integer representation or a
238 ** floating-point representation if an integer representation
239 ** is not possible. Note that the integer representation is
240 ** always preferred, even if the affinity is REAL, because
241 ** an integer representation is more space efficient on disk.
244 ** Convert pRec to a text representation.
247 ** No-op. pRec is unchanged.
249 static void applyAffinity(
250 Mem *pRec, /* The value to apply affinity to */
251 char affinity, /* The affinity to be applied */
252 u8 enc /* Use this text encoding */
254 if( affinity==SQLITE_AFF_TEXT ){
255 /* Only attempt the conversion to TEXT if there is an integer or real
256 ** representation (blob and NULL do not get converted) but no string
259 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
260 sqlite3VdbeMemStringify(pRec, enc);
262 pRec->flags &= ~(MEM_Real|MEM_Int);
263 }else if( affinity!=SQLITE_AFF_NONE ){
264 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
265 || affinity==SQLITE_AFF_NUMERIC );
266 applyNumericAffinity(pRec);
267 if( pRec->flags & MEM_Real ){
268 sqlite3VdbeIntegerAffinity(pRec);
274 ** Try to convert the type of a function argument or a result column
275 ** into a numeric representation. Use either INTEGER or REAL whichever
276 ** is appropriate. But only do the conversion if it is possible without
277 ** loss of information and return the revised type of the argument.
279 ** This is an EXPERIMENTAL api and is subject to change or removal.
281 int sqlite3_value_numeric_type(sqlite3_value *pVal){
282 Mem *pMem = (Mem*)pVal;
283 applyNumericAffinity(pMem);
284 storeTypeInfo(pMem, 0);
289 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
290 ** not the internal Mem* type.
292 void sqlite3ValueApplyAffinity(
297 applyAffinity((Mem *)pVal, affinity, enc);
302 ** Write a nice string representation of the contents of cell pMem
303 ** into buffer zBuf, length nBuf.
305 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
309 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
316 assert( (f & (MEM_Static|MEM_Ephem))==0 );
317 }else if( f & MEM_Static ){
319 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
320 }else if( f & MEM_Ephem ){
322 assert( (f & (MEM_Static|MEM_Dyn))==0 );
327 sqlite3_snprintf(100, zCsr, "%c", c);
328 zCsr += strlen(zCsr);
329 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
330 zCsr += strlen(zCsr);
331 for(i=0; i<16 && i<pMem->n; i++){
332 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
333 zCsr += strlen(zCsr);
335 for(i=0; i<16 && i<pMem->n; i++){
337 if( z<32 || z>126 ) *zCsr++ = '.';
341 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
342 zCsr += strlen(zCsr);
344 sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
345 zCsr += strlen(zCsr);
348 }else if( f & MEM_Str ){
353 assert( (f & (MEM_Static|MEM_Ephem))==0 );
354 }else if( f & MEM_Static ){
356 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
357 }else if( f & MEM_Ephem ){
359 assert( (f & (MEM_Static|MEM_Dyn))==0 );
364 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
365 k += strlen(&zBuf[k]);
367 for(j=0; j<15 && j<pMem->n; j++){
369 if( c>=0x20 && c<0x7f ){
376 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
377 k += strlen(&zBuf[k]);
386 ** The following routine only works on pentium-class processors.
387 ** It uses the RDTSC opcode to read the cycle count value out of the
388 ** processor and returns that value. This can be used for high-res
391 __inline__ unsigned long long int hwtime(void){
392 unsigned long long int x;
394 "mov %%edx, %%ecx\n\t"
401 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
402 ** sqlite3_interrupt() routine has been called. If it has been, then
403 ** processing of the VDBE program is interrupted.
405 ** This macro added to every instruction that does a jump in order to
406 ** implement a loop. This test used to be on every single instruction,
407 ** but that meant we more testing that we needed. By only testing the
408 ** flag on jump instructions, we get a (small) speed improvement.
410 #define CHECK_FOR_INTERRUPT \
411 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
415 ** Execute as much of a VDBE program as we can then return.
417 ** sqlite3VdbeMakeReady() must be called before this routine in order to
418 ** close the program with a final OP_Halt and to set up the callbacks
419 ** and the error message pointer.
421 ** Whenever a row or result data is available, this routine will either
422 ** invoke the result callback (if there is one) or return with
425 ** If an attempt is made to open a locked database, then this routine
426 ** will either invoke the busy callback (if there is one) or it will
427 ** return SQLITE_BUSY.
429 ** If an error occurs, an error message is written to memory obtained
430 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
431 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
433 ** If the callback ever returns non-zero, then the program exits
434 ** immediately. There will be no error message but the p->rc field is
435 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
437 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
438 ** routine to return SQLITE_ERROR.
440 ** Other fatal errors return SQLITE_ERROR.
442 ** After this routine has finished, sqlite3VdbeFinalize() should be
443 ** used to clean up the mess that was left behind.
446 Vdbe *p /* The VDBE */
448 int pc; /* The program counter */
449 Op *pOp; /* Current operation */
450 int rc = SQLITE_OK; /* Value to return */
451 sqlite3 *db = p->db; /* The database */
452 u8 encoding = ENC(db); /* The database encoding */
453 Mem *pTos; /* Top entry in the operand stack */
455 unsigned long long start; /* CPU clock count at start of opcode */
456 int origPc; /* Program counter at start of opcode */
458 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
459 int nProgressOps = 0; /* Opcodes executed since progress callback. */
465 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
466 assert( db->magic==SQLITE_MAGIC_BUSY );
468 sqlite3BtreeMutexArrayEnter(&p->aMutex);
469 if( p->rc==SQLITE_NOMEM ){
470 /* This happens if a malloc() inside a call to sqlite3_column_text() or
471 ** sqlite3_column_text16() failed. */
474 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
476 assert( p->explain==0 );
478 popStack(&pTos, p->popStack);
482 db->busyHandler.nBusy = 0;
484 sqlite3VdbeIOTraceSql(p);
486 if( (p->db->flags & SQLITE_VdbeListing)!=0
487 || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS)
490 printf("VDBE Program Listing:\n");
491 sqlite3VdbePrintSql(p);
492 for(i=0; i<p->nOp; i++){
493 sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
496 if( sqlite3OsAccess(db->pVfs, "vdbe_trace", SQLITE_ACCESS_EXISTS) ){
500 for(pc=p->pc; rc==SQLITE_OK; pc++){
501 assert( pc>=0 && pc<p->nOp );
502 assert( pTos<=&p->aStack[pc] );
503 if( db->mallocFailed ) goto no_mem;
510 /* Only allow tracing if SQLITE_DEBUG is defined.
515 printf("VDBE Execution Trace:\n");
516 sqlite3VdbePrintSql(p);
518 sqlite3VdbePrintOp(p->trace, pc, pOp);
520 if( p->trace==0 && pc==0
521 && sqlite3OsAccess(db->pVfs, "vdbe_sqltrace", SQLITE_ACCESS_EXISTS) ){
522 sqlite3VdbePrintSql(p);
527 /* Check to see if we need to simulate an interrupt. This only happens
528 ** if we have a special test build.
531 if( sqlite3_interrupt_count>0 ){
532 sqlite3_interrupt_count--;
533 if( sqlite3_interrupt_count==0 ){
534 sqlite3_interrupt(db);
539 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
540 /* Call the progress callback if it is configured and the required number
541 ** of VDBE ops have been executed (either since this invocation of
542 ** sqlite3VdbeExec() or since last time the progress callback was called).
543 ** If the progress callback returns non-zero, exit the virtual machine with
544 ** a return code SQLITE_ABORT.
547 if( db->nProgressOps==nProgressOps ){
549 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
550 prc =db->xProgress(db->pProgressArg);
551 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
553 rc = SQLITE_INTERRUPT;
563 /* This is to check that the return value of static function
564 ** opcodeNoPush() (see vdbeaux.c) returns values that match the
565 ** implementation of the virtual machine in this file. If
566 ** opcodeNoPush() returns non-zero, then the stack is guarenteed
567 ** not to grow when the opcode is executed. If it returns zero, then
568 ** the stack may grow by at most 1.
570 ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
571 ** available if NDEBUG is defined at build time.
574 if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
579 switch( pOp->opcode ){
581 /*****************************************************************************
582 ** What follows is a massive switch statement where each case implements a
583 ** separate instruction in the virtual machine. If we follow the usual
584 ** indentation conventions, each case should be indented by 6 spaces. But
585 ** that is a lot of wasted space on the left margin. So the code within
586 ** the switch statement will break with convention and be flush-left. Another
587 ** big comment (similar to this one) will mark the point in the code where
588 ** we transition back to normal indentation.
590 ** The formatting of each case is important. The makefile for SQLite
591 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
592 ** file looking for lines that begin with "case OP_". The opcodes.h files
593 ** will be filled with #defines that give unique integer values to each
594 ** opcode and the opcodes.c file is filled with an array of strings where
595 ** each string is the symbolic name for the corresponding opcode. If the
596 ** case statement is followed by a comment of the form "/# same as ... #/"
597 ** that comment is used to determine the particular value of the opcode.
599 ** If a comment on the same line as the "case OP_" construction contains
600 ** the word "no-push", then the opcode is guarenteed not to grow the
601 ** vdbe stack when it is executed. See function opcode() in
602 ** vdbeaux.c for details.
604 ** Documentation about VDBE opcodes is generated by scanning this file
605 ** for lines of that contain "Opcode:". That line and all subsequent
606 ** comment lines are used in the generation of the opcode.html documentation
611 ** Formatting is important to scripts that scan this file.
612 ** Do not deviate from the formatting style currently in use.
614 *****************************************************************************/
616 /* Opcode: Goto * P2 *
618 ** An unconditional jump to address P2.
619 ** The next instruction executed will be
620 ** the one at index P2 from the beginning of
623 case OP_Goto: { /* no-push */
629 /* Opcode: Gosub * P2 *
631 ** Push the current address plus 1 onto the return address stack
632 ** and then jump to address P2.
634 ** The return address stack is of limited depth. If too many
635 ** OP_Gosub operations occur without intervening OP_Returns, then
636 ** the return address stack will fill up and processing will abort
637 ** with a fatal error.
639 case OP_Gosub: { /* no-push */
640 assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
641 p->returnStack[p->returnDepth++] = pc+1;
646 /* Opcode: Return * * *
648 ** Jump immediately to the next instruction after the last unreturned
649 ** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
650 ** processing aborts with a fatal error.
652 case OP_Return: { /* no-push */
653 assert( p->returnDepth>0 );
655 pc = p->returnStack[p->returnDepth] - 1;
659 /* Opcode: Halt P1 P2 P3
661 ** Exit immediately. All open cursors, Fifos, etc are closed
664 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
665 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
666 ** For errors, it can be some other value. If P1!=0 then P2 will determine
667 ** whether or not to rollback the current transaction. Do not rollback
668 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
669 ** then back out all changes that have occurred during this execution of the
670 ** VDBE, but do not rollback the transaction.
672 ** If P3 is not null then it is an error message string.
674 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
675 ** every program. So a jump past the last instruction of the program
676 ** is the same as executing Halt.
678 case OP_Halt: { /* no-push */
682 p->errorAction = pOp->p2;
684 sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
686 rc = sqlite3VdbeHalt(p);
687 assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
688 if( rc==SQLITE_BUSY ){
689 p->rc = rc = SQLITE_BUSY;
691 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
696 /* Opcode: Integer P1 * *
698 ** The 32-bit integer value P1 is pushed onto the stack.
702 pTos->flags = MEM_Int;
707 /* Opcode: Int64 * * P3
709 ** P3 is a string representation of an integer. Convert that integer
710 ** to a 64-bit value and push it onto the stack.
714 assert( pOp->p3!=0 );
715 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
717 pTos->n = strlen(pTos->z);
718 pTos->enc = SQLITE_UTF8;
719 pTos->u.i = sqlite3VdbeIntValue(pTos);
720 pTos->flags |= MEM_Int;
724 /* Opcode: Real * * P3
726 ** The string value P3 is converted to a real and pushed on to the stack.
728 case OP_Real: { /* same as TK_FLOAT, */
730 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
732 pTos->n = strlen(pTos->z);
733 pTos->enc = SQLITE_UTF8;
734 pTos->r = sqlite3VdbeRealValue(pTos);
735 pTos->flags |= MEM_Real;
736 sqlite3VdbeChangeEncoding(pTos, encoding);
740 /* Opcode: String8 * * P3
742 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed
743 ** into an OP_String before it is executed for the first time.
745 case OP_String8: { /* same as TK_STRING */
746 assert( pOp->p3!=0 );
747 pOp->opcode = OP_String;
748 pOp->p1 = strlen(pOp->p3);
749 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
750 assert( pOp->p1 < SQLITE_MAX_LENGTH );
752 #ifndef SQLITE_OMIT_UTF16
753 if( encoding!=SQLITE_UTF8 ){
755 sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
756 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
757 if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
758 pTos->flags &= ~(MEM_Dyn);
759 pTos->flags |= MEM_Static;
760 if( pOp->p3type==P3_DYNAMIC ){
761 sqlite3_free(pOp->p3);
763 pOp->p3type = P3_DYNAMIC;
766 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
770 /* Otherwise fall through to the next case, OP_String */
773 /* Opcode: String P1 * P3
775 ** The string value P3 of length P1 (bytes) is pushed onto the stack.
778 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
780 assert( pOp->p3!=0 );
781 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
784 pTos->enc = encoding;
788 /* Opcode: Null * * *
790 ** Push a NULL onto the stack.
794 pTos->flags = MEM_Null;
800 #ifndef SQLITE_OMIT_BLOB_LITERAL
801 /* Opcode: HexBlob * * P3
803 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
806 ** The first time this instruction executes, in transforms itself into a
807 ** 'Blob' opcode with a binary blob as P3.
809 case OP_HexBlob: { /* same as TK_BLOB */
810 pOp->opcode = OP_Blob;
811 pOp->p1 = strlen(pOp->p3)/2;
812 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
813 assert( pOp->p1 < SQLITE_MAX_LENGTH );
815 char *zBlob = sqlite3HexToBlob(db, pOp->p3);
816 if( !zBlob ) goto no_mem;
817 if( pOp->p3type==P3_DYNAMIC ){
818 sqlite3_free(pOp->p3);
821 pOp->p3type = P3_DYNAMIC;
823 if( pOp->p3type==P3_DYNAMIC ){
824 sqlite3_free(pOp->p3);
826 pOp->p3type = P3_STATIC;
830 /* Fall through to the next case, OP_Blob. */
833 /* Opcode: Blob P1 * P3
835 ** P3 points to a blob of data P1 bytes long. Push this
836 ** value onto the stack. This instruction is not coded directly
837 ** by the compiler. Instead, the compiler layer specifies
838 ** an OP_HexBlob opcode, with the hex string representation of
839 ** the blob as P3. This opcode is transformed to an OP_Blob
840 ** the first time it is executed.
844 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
845 sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
846 pTos->enc = encoding;
849 #endif /* SQLITE_OMIT_BLOB_LITERAL */
851 /* Opcode: Variable P1 * *
853 ** Push the value of variable P1 onto the stack. A variable is
854 ** an unknown in the original SQL string as handed to sqlite3_compile().
855 ** Any occurance of the '?' character in the original SQL is considered
856 ** a variable. Variables in the SQL string are number from left to
857 ** right beginning with 1. The values of variables are set using the
858 ** sqlite3_bind() API.
863 assert( j>=0 && j<p->nVar );
866 if( sqlite3VdbeMemTooBig(pVar) ){
870 sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
874 /* Opcode: Pop P1 * *
876 ** P1 elements are popped off of the top of stack and discarded.
878 case OP_Pop: { /* no-push */
879 assert( pOp->p1>=0 );
880 popStack(&pTos, pOp->p1);
881 assert( pTos>=&p->aStack[-1] );
885 /* Opcode: Dup P1 P2 *
887 ** A copy of the P1-th element of the stack
888 ** is made and pushed onto the top of the stack.
889 ** The top of the stack is element 0. So the
890 ** instruction "Dup 0 0 0" will make a copy of the
893 ** If the content of the P1-th element is a dynamically
894 ** allocated string, then a new copy of that string
895 ** is made if P2==0. If P2!=0, then just a pointer
896 ** to the string is copied.
898 ** Also see the Pull instruction.
901 Mem *pFrom = &pTos[-pOp->p1];
902 assert( pFrom<=pTos && pFrom>=p->aStack );
904 sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
906 Deephemeralize(pTos);
911 /* Opcode: Pull P1 * *
913 ** The P1-th element is removed from its current location on
914 ** the stack and pushed back on top of the stack. The
915 ** top of the stack is element 0, so "Pull 0 0 0" is
916 ** a no-op. "Pull 1 0 0" swaps the top two elements of
919 ** See also the Dup instruction.
921 case OP_Pull: { /* no-push */
922 Mem *pFrom = &pTos[-pOp->p1];
927 Deephemeralize(pTos);
928 for(i=0; i<pOp->p1; i++, pFrom++){
929 Deephemeralize(&pFrom[1]);
930 assert( (pFrom[1].flags & MEM_Ephem)==0 );
932 if( pFrom->flags & MEM_Short ){
933 assert( pFrom->flags & (MEM_Str|MEM_Blob) );
934 assert( pFrom->z==pFrom[1].zShort );
935 pFrom->z = pFrom->zShort;
939 if( pTos->flags & MEM_Short ){
940 assert( pTos->flags & (MEM_Str|MEM_Blob) );
941 assert( pTos->z==pTos[-pOp->p1].zShort );
942 pTos->z = pTos->zShort;
947 /* Opcode: Push P1 * *
949 ** Overwrite the value of the P1-th element down on the
950 ** stack (P1==0 is the top of the stack) with the value
951 ** of the top of the stack. Then pop the top of the stack.
953 case OP_Push: { /* no-push */
954 Mem *pTo = &pTos[-pOp->p1];
956 assert( pTo>=p->aStack );
957 sqlite3VdbeMemMove(pTo, pTos);
962 /* Opcode: Callback P1 * *
964 ** The top P1 values on the stack represent a single result row from
965 ** a query. This opcode causes the sqlite3_step() call to terminate
966 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
967 ** structure to provide access to the top P1 values as the result
968 ** row. When the sqlite3_step() function is run again, the top P1
969 ** values will be automatically popped from the stack before the next
970 ** instruction executes.
972 case OP_Callback: { /* no-push */
975 assert( p->nResColumn==pOp->p1 );
977 /* Data in the pager might be moved or changed out from under us
978 ** in between the return from this sqlite3_step() call and the
979 ** next call to sqlite3_step(). So deephermeralize everything on
980 ** the stack. Note that ephemeral data is never stored in memory
981 ** cells so we do not have to worry about them.
983 pFirstColumn = &pTos[0-pOp->p1];
984 for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
985 Deephemeralize(pMem);
988 /* Invalidate all ephemeral cursor row caches */
989 p->cacheCtr = (p->cacheCtr + 2)|1;
991 /* Make sure the results of the current row are \000 terminated
992 ** and have an assigned type. The results are deephemeralized as
995 for(; pMem<=pTos; pMem++ ){
996 sqlite3VdbeMemNulTerminate(pMem);
997 storeTypeInfo(pMem, encoding);
1000 /* Set up the statement structure so that it will pop the current
1001 ** results from the stack when the statement returns.
1005 p->popStack = pOp->p1;
1012 /* Opcode: Concat P1 P2 *
1014 ** Look at the first P1+2 elements of the stack. Append them all
1015 ** together with the lowest element first. The original P1+2 elements
1016 ** are popped from the stack if P2==0 and retained if P2==1. If
1017 ** any element of the stack is NULL, then the result is NULL.
1019 ** When P1==1, this routine makes a copy of the top stack element
1020 ** into memory obtained from sqlite3_malloc().
1022 case OP_Concat: { /* same as TK_CONCAT */
1029 /* Loop through the stack elements to see how long the result will be. */
1030 nField = pOp->p1 + 2;
1031 pTerm = &pTos[1-nField];
1033 for(i=0; i<nField; i++, pTerm++){
1034 assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
1035 if( pTerm->flags&MEM_Null ){
1040 Stringify(pTerm, encoding);
1045 /* If nByte is less than zero, then there is a NULL value on the stack.
1046 ** In this case just pop the values off the stack (if required) and
1050 popStack(&pTos, nField);
1053 pTos->flags = MEM_Null;
1055 /* Otherwise malloc() space for the result and concatenate all the
1058 if( nByte+2>SQLITE_MAX_LENGTH ){
1061 zNew = sqlite3DbMallocRaw(db, nByte+2 );
1062 if( zNew==0 ) goto no_mem;
1064 pTerm = &pTos[1-nField];
1065 for(i=j=0; i<nField; i++, pTerm++){
1067 assert( pTerm->flags & (MEM_Str|MEM_Blob) );
1068 memcpy(&zNew[j], pTerm->z, n);
1076 popStack(&pTos, nField);
1080 pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
1082 pTos->enc = encoding;
1088 /* Opcode: Add * * *
1090 ** Pop the top two elements from the stack, add them together,
1091 ** and push the result back onto the stack. If either element
1092 ** is a string then it is converted to a double using the atof()
1093 ** function before the addition.
1094 ** If either operand is NULL, the result is NULL.
1096 /* Opcode: Multiply * * *
1098 ** Pop the top two elements from the stack, multiply them together,
1099 ** and push the result back onto the stack. If either element
1100 ** is a string then it is converted to a double using the atof()
1101 ** function before the multiplication.
1102 ** If either operand is NULL, the result is NULL.
1104 /* Opcode: Subtract * * *
1106 ** Pop the top two elements from the stack, subtract the
1107 ** first (what was on top of the stack) from the second (the
1109 ** and push the result back onto the stack. If either element
1110 ** is a string then it is converted to a double using the atof()
1111 ** function before the subtraction.
1112 ** If either operand is NULL, the result is NULL.
1114 /* Opcode: Divide * * *
1116 ** Pop the top two elements from the stack, divide the
1117 ** first (what was on top of the stack) from the second (the
1119 ** and push the result back onto the stack. If either element
1120 ** is a string then it is converted to a double using the atof()
1121 ** function before the division. Division by zero returns NULL.
1122 ** If either operand is NULL, the result is NULL.
1124 /* Opcode: Remainder * * *
1126 ** Pop the top two elements from the stack, divide the
1127 ** first (what was on top of the stack) from the second (the
1129 ** and push the remainder after division onto the stack. If either element
1130 ** is a string then it is converted to a double using the atof()
1131 ** function before the division. Division by zero returns NULL.
1132 ** If either operand is NULL, the result is NULL.
1134 case OP_Add: /* same as TK_PLUS, no-push */
1135 case OP_Subtract: /* same as TK_MINUS, no-push */
1136 case OP_Multiply: /* same as TK_STAR, no-push */
1137 case OP_Divide: /* same as TK_SLASH, no-push */
1138 case OP_Remainder: { /* same as TK_REM, no-push */
1139 Mem *pNos = &pTos[-1];
1141 assert( pNos>=p->aStack );
1142 flags = pTos->flags | pNos->flags;
1143 if( (flags & MEM_Null)!=0 ){
1147 pTos->flags = MEM_Null;
1148 }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
1152 switch( pOp->opcode ){
1153 case OP_Add: b += a; break;
1154 case OP_Subtract: b -= a; break;
1155 case OP_Multiply: b *= a; break;
1157 if( a==0 ) goto divide_by_zero;
1158 /* Dividing the largest possible negative 64-bit integer (1<<63) by
1159 ** -1 returns an integer to large to store in a 64-bit data-type. On
1160 ** some architectures, the value overflows to (1<<63). On others,
1161 ** a SIGFPE is issued. The following statement normalizes this
1162 ** behaviour so that all architectures behave as if integer
1163 ** overflow occured.
1165 if( a==-1 && b==(((i64)1)<<63) ) a = 1;
1170 if( a==0 ) goto divide_by_zero;
1180 pTos->flags = MEM_Int;
1183 a = sqlite3VdbeRealValue(pTos);
1184 b = sqlite3VdbeRealValue(pNos);
1185 switch( pOp->opcode ){
1186 case OP_Add: b += a; break;
1187 case OP_Subtract: b -= a; break;
1188 case OP_Multiply: b *= a; break;
1190 if( a==0.0 ) goto divide_by_zero;
1197 if( ia==0 ) goto divide_by_zero;
1198 if( ia==-1 ) ia = 1;
1203 if( sqlite3_isnan(b) ){
1204 goto divide_by_zero;
1210 pTos->flags = MEM_Real;
1211 if( (flags & MEM_Real)==0 ){
1212 sqlite3VdbeIntegerAffinity(pTos);
1221 pTos->flags = MEM_Null;
1225 /* Opcode: CollSeq * * P3
1227 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
1228 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1229 ** be returned. This is used by the built-in min(), max() and nullif()
1232 ** The interface used by the implementation of the aforementioned functions
1233 ** to retrieve the collation sequence set by this opcode is not available
1234 ** publicly, only to user functions defined in func.c.
1236 case OP_CollSeq: { /* no-push */
1237 assert( pOp->p3type==P3_COLLSEQ );
1241 /* Opcode: Function P1 P2 P3
1243 ** Invoke a user function (P3 is a pointer to a Function structure that
1244 ** defines the function) with P2 arguments taken from the stack. Pop all
1245 ** arguments from the stack and push back the result.
1247 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
1248 ** function was determined to be constant at compile time. If the first
1249 ** argument was constant then bit 0 of P1 is set. This is used to determine
1250 ** whether meta data associated with a user function argument using the
1251 ** sqlite3_set_auxdata() API may be safely retained until the next
1252 ** invocation of this opcode.
1254 ** See also: AggStep and AggFinal
1259 sqlite3_context ctx;
1260 sqlite3_value **apVal;
1264 assert( apVal || n==0 );
1267 for(i=0; i<n; i++, pArg++){
1269 storeTypeInfo(pArg, encoding);
1272 assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
1273 if( pOp->p3type==P3_FUNCDEF ){
1274 ctx.pFunc = (FuncDef*)pOp->p3;
1277 ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
1278 ctx.pFunc = ctx.pVdbeFunc->pFunc;
1281 ctx.s.flags = MEM_Null;
1286 if( ctx.pFunc->needCollSeq ){
1287 assert( pOp>p->aOp );
1288 assert( pOp[-1].p3type==P3_COLLSEQ );
1289 assert( pOp[-1].opcode==OP_CollSeq );
1290 ctx.pColl = (CollSeq *)pOp[-1].p3;
1292 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1293 (*ctx.pFunc->xFunc)(&ctx, n, apVal);
1294 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
1295 if( db->mallocFailed ){
1296 /* Even though a malloc() has failed, the implementation of the
1297 ** user function may have called an sqlite3_result_XXX() function
1298 ** to return a value. The following call releases any resources
1299 ** associated with such a value.
1301 ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
1302 ** fails also (the if(...) statement above). But if people are
1303 ** misusing sqlite, they have bigger problems than a leaked value.
1305 sqlite3VdbeMemRelease(&ctx.s);
1310 /* If any auxilary data functions have been called by this user function,
1311 ** immediately call the destructor for any non-static values.
1313 if( ctx.pVdbeFunc ){
1314 sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1315 pOp->p3 = (char *)ctx.pVdbeFunc;
1316 pOp->p3type = P3_VDBEFUNC;
1319 /* If the function returned an error, throw an exception */
1321 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
1325 /* Copy the result of the function to the top of the stack */
1326 sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1329 sqlite3VdbeMemMove(pTos, &ctx.s);
1330 if( sqlite3VdbeMemTooBig(pTos) ){
1336 /* Opcode: BitAnd * * *
1338 ** Pop the top two elements from the stack. Convert both elements
1339 ** to integers. Push back onto the stack the bit-wise AND of the
1341 ** If either operand is NULL, the result is NULL.
1343 /* Opcode: BitOr * * *
1345 ** Pop the top two elements from the stack. Convert both elements
1346 ** to integers. Push back onto the stack the bit-wise OR of the
1348 ** If either operand is NULL, the result is NULL.
1350 /* Opcode: ShiftLeft * * *
1352 ** Pop the top two elements from the stack. Convert both elements
1353 ** to integers. Push back onto the stack the second element shifted
1354 ** left by N bits where N is the top element on the stack.
1355 ** If either operand is NULL, the result is NULL.
1357 /* Opcode: ShiftRight * * *
1359 ** Pop the top two elements from the stack. Convert both elements
1360 ** to integers. Push back onto the stack the second element shifted
1361 ** right by N bits where N is the top element on the stack.
1362 ** If either operand is NULL, the result is NULL.
1364 case OP_BitAnd: /* same as TK_BITAND, no-push */
1365 case OP_BitOr: /* same as TK_BITOR, no-push */
1366 case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
1367 case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
1368 Mem *pNos = &pTos[-1];
1371 assert( pNos>=p->aStack );
1372 if( (pTos->flags | pNos->flags) & MEM_Null ){
1375 pTos->flags = MEM_Null;
1378 a = sqlite3VdbeIntValue(pNos);
1379 b = sqlite3VdbeIntValue(pTos);
1380 switch( pOp->opcode ){
1381 case OP_BitAnd: a &= b; break;
1382 case OP_BitOr: a |= b; break;
1383 case OP_ShiftLeft: a <<= b; break;
1384 case OP_ShiftRight: a >>= b; break;
1385 default: /* CANT HAPPEN */ break;
1391 pTos->flags = MEM_Int;
1395 /* Opcode: AddImm P1 * *
1397 ** Add the value P1 to whatever is on top of the stack. The result
1398 ** is always an integer.
1400 ** To force the top of the stack to be an integer, just add 0.
1402 case OP_AddImm: { /* no-push */
1403 assert( pTos>=p->aStack );
1404 sqlite3VdbeMemIntegerify(pTos);
1405 pTos->u.i += pOp->p1;
1409 /* Opcode: ForceInt P1 P2 *
1411 ** Convert the top of the stack into an integer. If the current top of
1412 ** the stack is not numeric (meaning that is is a NULL or a string that
1413 ** does not look like an integer or floating point number) then pop the
1414 ** stack and jump to P2. If the top of the stack is numeric then
1415 ** convert it into the least integer that is greater than or equal to its
1416 ** current value if P1==0, or to the least integer that is strictly
1417 ** greater than its current value if P1==1.
1419 case OP_ForceInt: { /* no-push */
1421 assert( pTos>=p->aStack );
1422 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1423 if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
1429 if( pTos->flags & MEM_Int ){
1430 v = pTos->u.i + (pOp->p1!=0);
1432 /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */
1433 sqlite3VdbeMemRealify(pTos);
1435 if( pTos->r>(double)v ) v++;
1436 if( pOp->p1 && pTos->r==(double)v ) v++;
1440 pTos->flags = MEM_Int;
1444 /* Opcode: MustBeInt P1 P2 *
1446 ** Force the top of the stack to be an integer. If the top of the
1447 ** stack is not an integer and cannot be converted into an integer
1448 ** with out data loss, then jump immediately to P2, or if P2==0
1449 ** raise an SQLITE_MISMATCH exception.
1451 ** If the top of the stack is not an integer and P2 is not zero and
1452 ** P1 is 1, then the stack is popped. In all other cases, the depth
1453 ** of the stack is unchanged.
1455 case OP_MustBeInt: { /* no-push */
1456 assert( pTos>=p->aStack );
1457 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1458 if( (pTos->flags & MEM_Int)==0 ){
1460 rc = SQLITE_MISMATCH;
1461 goto abort_due_to_error;
1463 if( pOp->p1 ) popStack(&pTos, 1);
1468 pTos->flags = MEM_Int;
1473 /* Opcode: RealAffinity * * *
1475 ** If the top of the stack is an integer, convert it to a real value.
1477 ** This opcode is used when extracting information from a column that
1478 ** has REAL affinity. Such column values may still be stored as
1479 ** integers, for space efficiency, but after extraction we want them
1480 ** to have only a real value.
1482 case OP_RealAffinity: { /* no-push */
1483 assert( pTos>=p->aStack );
1484 if( pTos->flags & MEM_Int ){
1485 sqlite3VdbeMemRealify(pTos);
1490 #ifndef SQLITE_OMIT_CAST
1491 /* Opcode: ToText * * *
1493 ** Force the value on the top of the stack to be text.
1494 ** If the value is numeric, convert it to a string using the
1495 ** equivalent of printf(). Blob values are unchanged and
1496 ** are afterwards simply interpreted as text.
1498 ** A NULL value is not changed by this routine. It remains NULL.
1500 case OP_ToText: { /* same as TK_TO_TEXT, no-push */
1501 assert( pTos>=p->aStack );
1502 if( pTos->flags & MEM_Null ) break;
1503 assert( MEM_Str==(MEM_Blob>>3) );
1504 pTos->flags |= (pTos->flags&MEM_Blob)>>3;
1505 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1506 rc = ExpandBlob(pTos);
1507 assert( pTos->flags & MEM_Str );
1508 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
1512 /* Opcode: ToBlob * * *
1514 ** Force the value on the top of the stack to be a BLOB.
1515 ** If the value is numeric, convert it to a string first.
1516 ** Strings are simply reinterpreted as blobs with no change
1517 ** to the underlying data.
1519 ** A NULL value is not changed by this routine. It remains NULL.
1521 case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */
1522 assert( pTos>=p->aStack );
1523 if( pTos->flags & MEM_Null ) break;
1524 if( (pTos->flags & MEM_Blob)==0 ){
1525 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1526 assert( pTos->flags & MEM_Str );
1527 pTos->flags |= MEM_Blob;
1529 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
1533 /* Opcode: ToNumeric * * *
1535 ** Force the value on the top of the stack to be numeric (either an
1536 ** integer or a floating-point number.)
1537 ** If the value is text or blob, try to convert it to an using the
1538 ** equivalent of atoi() or atof() and store 0 if no such conversion
1541 ** A NULL value is not changed by this routine. It remains NULL.
1543 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */
1544 assert( pTos>=p->aStack );
1545 if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
1546 sqlite3VdbeMemNumerify(pTos);
1550 #endif /* SQLITE_OMIT_CAST */
1552 /* Opcode: ToInt * * *
1554 ** Force the value on the top of the stack to be an integer. If
1555 ** The value is currently a real number, drop its fractional part.
1556 ** If the value is text or blob, try to convert it to an integer using the
1557 ** equivalent of atoi() and store 0 if no such conversion is possible.
1559 ** A NULL value is not changed by this routine. It remains NULL.
1561 case OP_ToInt: { /* same as TK_TO_INT, no-push */
1562 assert( pTos>=p->aStack );
1563 if( (pTos->flags & MEM_Null)==0 ){
1564 sqlite3VdbeMemIntegerify(pTos);
1569 #ifndef SQLITE_OMIT_CAST
1570 /* Opcode: ToReal * * *
1572 ** Force the value on the top of the stack to be a floating point number.
1573 ** If The value is currently an integer, convert it.
1574 ** If the value is text or blob, try to convert it to an integer using the
1575 ** equivalent of atoi() and store 0 if no such conversion is possible.
1577 ** A NULL value is not changed by this routine. It remains NULL.
1579 case OP_ToReal: { /* same as TK_TO_REAL, no-push */
1580 assert( pTos>=p->aStack );
1581 if( (pTos->flags & MEM_Null)==0 ){
1582 sqlite3VdbeMemRealify(pTos);
1586 #endif /* SQLITE_OMIT_CAST */
1588 /* Opcode: Eq P1 P2 P3
1590 ** Pop the top two elements from the stack. If they are equal, then
1591 ** jump to instruction P2. Otherwise, continue to the next instruction.
1593 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
1594 ** jump. If the 0x100 bit of P1 is clear then fall thru if either operand
1597 ** If the 0x200 bit of P1 is set and either operand is NULL then
1598 ** both operands are converted to integers prior to comparison.
1599 ** NULL operands are converted to zero and non-NULL operands are
1600 ** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true
1601 ** whereas it would normally be NULL. Similarly, NULL==123 is false when
1602 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
1604 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
1605 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1606 ** to coerce both values
1607 ** according to the affinity before the comparison is made. If the byte is
1608 ** 0x00, then numeric affinity is used.
1610 ** Once any conversions have taken place, and neither value is NULL,
1611 ** the values are compared. If both values are blobs, or both are text,
1612 ** then memcmp() is used to determine the results of the comparison. If
1613 ** both values are numeric, then a numeric comparison is used. If the
1614 ** two values are of different types, then they are inequal.
1616 ** If P2 is zero, do not jump. Instead, push an integer 1 onto the
1617 ** stack if the jump would have been taken, or a 0 if not. Push a
1618 ** NULL if either operand was NULL.
1620 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
1621 ** structure) that defines how to compare text.
1623 /* Opcode: Ne P1 P2 P3
1625 ** This works just like the Eq opcode except that the jump is taken if
1626 ** the operands from the stack are not equal. See the Eq opcode for
1627 ** additional information.
1629 /* Opcode: Lt P1 P2 P3
1631 ** This works just like the Eq opcode except that the jump is taken if
1632 ** the 2nd element down on the stack is less than the top of the stack.
1633 ** See the Eq opcode for additional information.
1635 /* Opcode: Le P1 P2 P3
1637 ** This works just like the Eq opcode except that the jump is taken if
1638 ** the 2nd element down on the stack is less than or equal to the
1639 ** top of the stack. See the Eq opcode for additional information.
1641 /* Opcode: Gt P1 P2 P3
1643 ** This works just like the Eq opcode except that the jump is taken if
1644 ** the 2nd element down on the stack is greater than the top of the stack.
1645 ** See the Eq opcode for additional information.
1647 /* Opcode: Ge P1 P2 P3
1649 ** This works just like the Eq opcode except that the jump is taken if
1650 ** the 2nd element down on the stack is greater than or equal to the
1651 ** top of the stack. See the Eq opcode for additional information.
1653 case OP_Eq: /* same as TK_EQ, no-push */
1654 case OP_Ne: /* same as TK_NE, no-push */
1655 case OP_Lt: /* same as TK_LT, no-push */
1656 case OP_Le: /* same as TK_LE, no-push */
1657 case OP_Gt: /* same as TK_GT, no-push */
1658 case OP_Ge: { /* same as TK_GE, no-push */
1665 flags = pTos->flags|pNos->flags;
1667 /* If either value is a NULL P2 is not zero, take the jump if the least
1668 ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
1671 if( flags&MEM_Null ){
1672 if( (pOp->p1 & 0x200)!=0 ){
1673 /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
1674 ** magic SQL value it normally is - treat it as if it were another
1677 ** With 0x200 set, if either operand is NULL then both operands
1678 ** are converted to integers prior to being passed down into the
1679 ** normal comparison logic below. NULL operands are converted to
1680 ** zero and non-NULL operands are converted to 1. Thus, for example,
1681 ** with 0x200 set, NULL==NULL is true whereas it would normally
1682 ** be NULL. Similarly, NULL!=123 is true.
1684 sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
1685 sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
1687 /* If the 0x200 bit of P1 is clear and either operand is NULL then
1688 ** the result is always NULL. The jump is taken if the 0x100 bit
1693 if( pOp->p1 & 0x100 ){
1698 pTos->flags = MEM_Null;
1704 affinity = pOp->p1 & 0xFF;
1706 applyAffinity(pNos, affinity, encoding);
1707 applyAffinity(pTos, affinity, encoding);
1710 assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
1713 res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
1714 switch( pOp->opcode ){
1715 case OP_Eq: res = res==0; break;
1716 case OP_Ne: res = res!=0; break;
1717 case OP_Lt: res = res<0; break;
1718 case OP_Le: res = res<=0; break;
1719 case OP_Gt: res = res>0; break;
1720 default: res = res>=0; break;
1730 pTos->flags = MEM_Int;
1736 /* Opcode: And * * *
1738 ** Pop two values off the stack. Take the logical AND of the
1739 ** two values and push the resulting boolean value back onto the
1744 ** Pop two values off the stack. Take the logical OR of the
1745 ** two values and push the resulting boolean value back onto the
1748 case OP_And: /* same as TK_AND, no-push */
1749 case OP_Or: { /* same as TK_OR, no-push */
1750 Mem *pNos = &pTos[-1];
1751 int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
1753 assert( pNos>=p->aStack );
1754 if( pTos->flags & MEM_Null ){
1757 sqlite3VdbeMemIntegerify(pTos);
1760 if( pNos->flags & MEM_Null ){
1763 sqlite3VdbeMemIntegerify(pNos);
1766 if( pOp->opcode==OP_And ){
1767 static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1768 v1 = and_logic[v1*3+v2];
1770 static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1771 v1 = or_logic[v1*3+v2];
1776 pTos->flags = MEM_Null;
1779 pTos->flags = MEM_Int;
1784 /* Opcode: Negative * * *
1786 ** Treat the top of the stack as a numeric quantity. Replace it
1787 ** with its additive inverse. If the top of the stack is NULL
1788 ** its value is unchanged.
1790 /* Opcode: AbsValue * * *
1792 ** Treat the top of the stack as a numeric quantity. Replace it
1793 ** with its absolute value. If the top of the stack is NULL
1794 ** its value is unchanged.
1796 case OP_Negative: /* same as TK_UMINUS, no-push */
1798 assert( pTos>=p->aStack );
1799 if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
1800 sqlite3VdbeMemNumerify(pTos);
1802 if( pTos->flags & MEM_Real ){
1804 if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1807 pTos->flags = MEM_Real;
1808 }else if( pTos->flags & MEM_Int ){
1810 if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
1811 pTos->u.i = -pTos->u.i;
1813 pTos->flags = MEM_Int;
1818 /* Opcode: Not * * *
1820 ** Interpret the top of the stack as a boolean value. Replace it
1821 ** with its complement. If the top of the stack is NULL its value
1824 case OP_Not: { /* same as TK_NOT, no-push */
1825 assert( pTos>=p->aStack );
1826 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1827 sqlite3VdbeMemIntegerify(pTos);
1828 assert( (pTos->flags & MEM_Dyn)==0 );
1829 pTos->u.i = !pTos->u.i;
1830 pTos->flags = MEM_Int;
1834 /* Opcode: BitNot * * *
1836 ** Interpret the top of the stack as an value. Replace it
1837 ** with its ones-complement. If the top of the stack is NULL its
1838 ** value is unchanged.
1840 case OP_BitNot: { /* same as TK_BITNOT, no-push */
1841 assert( pTos>=p->aStack );
1842 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1843 sqlite3VdbeMemIntegerify(pTos);
1844 assert( (pTos->flags & MEM_Dyn)==0 );
1845 pTos->u.i = ~pTos->u.i;
1846 pTos->flags = MEM_Int;
1850 /* Opcode: Noop * * *
1852 ** Do nothing. This instruction is often useful as a jump
1856 ** The magic Explain opcode are only inserted when explain==2 (which
1857 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
1858 ** This opcode records information from the optimizer. It is the
1859 ** the same as a no-op. This opcodesnever appears in a real VM program.
1862 case OP_Noop: { /* no-push */
1866 /* Opcode: If P1 P2 *
1868 ** Pop a single boolean from the stack. If the boolean popped is
1869 ** true, then jump to p2. Otherwise continue to the next instruction.
1870 ** An integer is false if zero and true otherwise. A string is
1871 ** false if it has zero length and true otherwise.
1873 ** If the value popped of the stack is NULL, then take the jump if P1
1874 ** is true and fall through if P1 is false.
1876 /* Opcode: IfNot P1 P2 *
1878 ** Pop a single boolean from the stack. If the boolean popped is
1879 ** false, then jump to p2. Otherwise continue to the next instruction.
1880 ** An integer is false if zero and true otherwise. A string is
1881 ** false if it has zero length and true otherwise.
1883 ** If the value popped of the stack is NULL, then take the jump if P1
1884 ** is true and fall through if P1 is false.
1886 case OP_If: /* no-push */
1887 case OP_IfNot: { /* no-push */
1889 assert( pTos>=p->aStack );
1890 if( pTos->flags & MEM_Null ){
1893 #ifdef SQLITE_OMIT_FLOATING_POINT
1894 c = sqlite3VdbeIntValue(pTos);
1896 c = sqlite3VdbeRealValue(pTos)!=0.0;
1898 if( pOp->opcode==OP_IfNot ) c = !c;
1902 if( c ) pc = pOp->p2-1;
1906 /* Opcode: IsNull P1 P2 *
1908 ** Check the top of the stack and jump to P2 if the top of the stack
1909 ** is NULL. If P1 is positive, then pop P1 elements from the stack
1910 ** regardless of whether or not the jump is taken. If P1 is negative,
1911 ** pop -P1 elements from the stack only if the jump is taken and leave
1912 ** the stack unchanged if the jump is not taken.
1914 case OP_IsNull: { /* same as TK_ISNULL, no-push */
1915 if( pTos->flags & MEM_Null ){
1918 popStack(&pTos, -pOp->p1);
1922 popStack(&pTos, pOp->p1);
1927 /* Opcode: NotNull P1 P2 *
1929 ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
1930 ** Regardless of whether or not the jump is taken, pop the stack
1931 ** P1 times if P1 is greater than zero. But if P1 is negative,
1932 ** leave the stack unchanged.
1934 case OP_NotNull: { /* same as TK_NOTNULL, no-push */
1937 if( cnt<0 ) cnt = -cnt;
1938 assert( &pTos[1-cnt] >= p->aStack );
1939 for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
1940 if( i>=cnt ) pc = pOp->p2-1;
1941 if( pOp->p1>0 ) popStack(&pTos, cnt);
1945 /* Opcode: SetNumColumns P1 P2 *
1947 ** Before the OP_Column opcode can be executed on a cursor, this
1948 ** opcode must be called to set the number of fields in the table.
1950 ** This opcode sets the number of columns for cursor P1 to P2.
1952 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
1953 ** before this op-code.
1955 case OP_SetNumColumns: { /* no-push */
1957 assert( (pOp->p1)<p->nCursor );
1958 assert( p->apCsr[pOp->p1]!=0 );
1959 pC = p->apCsr[pOp->p1];
1960 pC->nField = pOp->p2;
1964 /* Opcode: Column P1 P2 P3
1966 ** Interpret the data that cursor P1 points to as a structure built using
1967 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
1968 ** information about the format of the data.) Push onto the stack the value
1969 ** of the P2-th column contained in the data. If there are less that (P2+1)
1970 ** values in the record, push a NULL onto the stack.
1972 ** If the KeyAsData opcode has previously executed on this cursor, then the
1973 ** field might be extracted from the key rather than the data.
1975 ** If the column contains fewer than P2 fields, then push a NULL. Or
1976 ** if P3 is of type P3_MEM, then push the P3 value. The P3 value will
1977 ** be default value for a column that has been added using the ALTER TABLE
1978 ** ADD COLUMN command. If P3 is an ordinary string, just push a NULL.
1979 ** When P3 is a string it is really just a comment describing the value
1980 ** to be pushed, not a default value.
1983 u32 payloadSize; /* Number of bytes in the record */
1984 int p1 = pOp->p1; /* P1 value of the opcode */
1985 int p2 = pOp->p2; /* column number to retrieve */
1986 Cursor *pC = 0; /* The VDBE cursor */
1987 char *zRec; /* Pointer to complete record-data */
1988 BtCursor *pCrsr; /* The BTree cursor */
1989 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
1990 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
1991 u32 nField; /* number of fields in the record */
1992 int len; /* The length of the serialized data for the column */
1993 int i; /* Loop counter */
1994 char *zData; /* Part of the record being decoded */
1995 Mem sMem; /* For storing the record being decoded */
1998 assert( p1<p->nCursor );
2000 pTos->flags = MEM_Null;
2002 /* This block sets the variable payloadSize to be the total number of
2003 ** bytes in the record.
2005 ** zRec is set to be the complete text of the record if it is available.
2006 ** The complete record text is always available for pseudo-tables
2007 ** If the record is stored in a cursor, the complete record text
2008 ** might be available in the pC->aRow cache. Or it might not be.
2009 ** If the data is unavailable, zRec is set to NULL.
2011 ** We also compute the number of columns in the record. For cursors,
2012 ** the number of columns is stored in the Cursor.nField element. For
2013 ** records on the stack, the next entry down on the stack is an integer
2014 ** which is the number of records.
2017 #ifndef SQLITE_OMIT_VIRTUALTABLE
2018 assert( pC->pVtabCursor==0 );
2021 if( pC->pCursor!=0 ){
2022 /* The record is stored in a B-Tree */
2023 rc = sqlite3VdbeCursorMoveto(pC);
2024 if( rc ) goto abort_due_to_error;
2026 pCrsr = pC->pCursor;
2029 }else if( pC->cacheStatus==p->cacheCtr ){
2030 payloadSize = pC->payloadSize;
2031 zRec = (char*)pC->aRow;
2032 }else if( pC->isIndex ){
2034 sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2035 payloadSize = payloadSize64;
2037 sqlite3BtreeDataSize(pCrsr, &payloadSize);
2039 nField = pC->nField;
2040 }else if( pC->pseudoTable ){
2041 /* The record is the sole entry of a pseudo-table */
2042 payloadSize = pC->nData;
2044 pC->cacheStatus = CACHE_STALE;
2045 assert( payloadSize==0 || zRec!=0 );
2046 nField = pC->nField;
2055 /* If payloadSize is 0, then just push a NULL onto the stack. */
2056 if( payloadSize==0 ){
2057 assert( pTos->flags==MEM_Null );
2060 if( payloadSize>SQLITE_MAX_LENGTH ){
2064 assert( p2<nField );
2066 /* Read and parse the table header. Store the results of the parse
2067 ** into the record header cache fields of the cursor.
2069 if( pC && pC->cacheStatus==p->cacheCtr ){
2071 aOffset = pC->aOffset;
2073 u8 *zIdx; /* Index into header */
2074 u8 *zEndHdr; /* Pointer to first byte after the header */
2075 u32 offset; /* Offset into the data */
2076 int szHdrSz; /* Size of the header size field at start of record */
2077 int avail; /* Number of bytes of available data */
2081 pC->aType = aType = sqlite3DbMallocRaw(db, 2*nField*sizeof(aType) );
2086 pC->aOffset = aOffset = &aType[nField];
2087 pC->payloadSize = payloadSize;
2088 pC->cacheStatus = p->cacheCtr;
2090 /* Figure out how many bytes are in the header */
2095 zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2097 zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
2099 /* If KeyFetch()/DataFetch() managed to get the entire payload,
2100 ** save the payload in the pC->aRow cache. That will save us from
2101 ** having to make additional calls to fetch the content portion of
2104 if( avail>=payloadSize ){
2106 pC->aRow = (u8*)zData;
2111 /* The following assert is true in all cases accept when
2112 ** the database file has been corrupted externally.
2113 ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
2114 szHdrSz = GetVarint((u8*)zData, offset);
2116 /* The KeyFetch() or DataFetch() above are fast and will get the entire
2117 ** record header in most cases. But they will fail to get the complete
2118 ** record header if the record header does not fit on a single page
2119 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
2120 ** acquire the complete header text.
2122 if( !zRec && avail<offset ){
2123 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
2124 if( rc!=SQLITE_OK ){
2129 zEndHdr = (u8 *)&zData[offset];
2130 zIdx = (u8 *)&zData[szHdrSz];
2132 /* Scan the header and use it to fill in the aType[] and aOffset[]
2133 ** arrays. aType[i] will contain the type integer for the i-th
2134 ** column and aOffset[i] will contain the offset from the beginning
2135 ** of the record to the start of the data for the i-th column
2137 for(i=0; i<nField; i++){
2139 aOffset[i] = offset;
2140 zIdx += GetVarint(zIdx, aType[i]);
2141 offset += sqlite3VdbeSerialTypeLen(aType[i]);
2143 /* If i is less that nField, then there are less fields in this
2144 ** record than SetNumColumns indicated there are columns in the
2145 ** table. Set the offset for any extra columns not present in
2146 ** the record to 0. This tells code below to push a NULL onto the
2147 ** stack instead of deserializing a value from the record.
2153 sMem.flags = MEM_Null;
2155 /* If we have read more header data than was contained in the header,
2156 ** or if the end of the last field appears to be past the end of the
2157 ** record, then we must be dealing with a corrupt database.
2159 if( zIdx>zEndHdr || offset>payloadSize ){
2160 rc = SQLITE_CORRUPT_BKPT;
2165 /* Get the column information. If aOffset[p2] is non-zero, then
2166 ** deserialize the value from the record. If aOffset[p2] is zero,
2167 ** then there are not enough fields in the record to satisfy the
2168 ** request. In this case, set the value NULL or to P3 if P3 is
2169 ** a pointer to a Mem object.
2172 assert( rc==SQLITE_OK );
2174 zData = &zRec[aOffset[p2]];
2176 len = sqlite3VdbeSerialTypeLen(aType[p2]);
2177 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
2178 if( rc!=SQLITE_OK ){
2183 sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
2184 pTos->enc = encoding;
2186 if( pOp->p3type==P3_MEM ){
2187 sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
2189 pTos->flags = MEM_Null;
2193 /* If we dynamically allocated space to hold the data (in the
2194 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2195 ** dynamically allocated space over to the pTos structure.
2196 ** This prevents a memory copy.
2198 if( (sMem.flags & MEM_Dyn)!=0 ){
2199 assert( pTos->flags & MEM_Ephem );
2200 assert( pTos->flags & (MEM_Str|MEM_Blob) );
2201 assert( pTos->z==sMem.z );
2202 assert( sMem.flags & MEM_Term );
2203 pTos->flags &= ~MEM_Ephem;
2204 pTos->flags |= MEM_Dyn|MEM_Term;
2207 /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
2208 ** can abandon sMem */
2209 rc = sqlite3VdbeMemMakeWriteable(pTos);
2215 /* Opcode: MakeRecord P1 P2 P3
2217 ** Convert the top abs(P1) entries of the stack into a single entry
2218 ** suitable for use as a data record in a database table or as a key
2219 ** in an index. The details of the format are irrelavant as long as
2220 ** the OP_Column opcode can decode the record later and as long as the
2221 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
2222 ** records. Refer to source code comments for the details of the record
2225 ** The original stack entries are popped from the stack if P1>0 but
2226 ** remain on the stack if P1<0.
2228 ** If P2 is not zero and one or more of the entries are NULL, then jump
2229 ** to the address given by P2. This feature can be used to skip a
2230 ** uniqueness test on indices.
2232 ** P3 may be a string that is P1 characters long. The nth character of the
2233 ** string indicates the column affinity that should be used for the nth
2234 ** field of the index key (i.e. the first character of P3 corresponds to the
2235 ** lowest element on the stack).
2237 ** The mapping from character to affinity is given by the SQLITE_AFF_
2238 ** macros defined in sqliteInt.h.
2240 ** If P3 is NULL then all index fields have the affinity NONE.
2242 ** See also OP_MakeIdxRec
2244 /* Opcode: MakeIdxRec P1 P2 P3
2246 ** This opcode works just OP_MakeRecord except that it reads an extra
2247 ** integer from the stack (thus reading a total of abs(P1+1) entries)
2248 ** and appends that extra integer to the end of the record as a varint.
2249 ** This results in an index key.
2252 case OP_MakeRecord: {
2253 /* Assuming the record contains N fields, the record format looks
2256 ** ------------------------------------------------------------------------
2257 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2258 ** ------------------------------------------------------------------------
2260 ** Data(0) is taken from the lowest element of the stack and data(N-1) is
2261 ** the top of the stack.
2263 ** Each type field is a varint representing the serial type of the
2264 ** corresponding data element (see sqlite3VdbeSerialType()). The
2265 ** hdr-size field is also a varint which is the offset from the beginning
2266 ** of the record to data0.
2268 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2269 Mem *pRec; /* The new record */
2270 Mem *pRowid = 0; /* Rowid appended to the new record */
2271 u64 nData = 0; /* Number of bytes of data space */
2272 int nHdr = 0; /* Number of bytes of header space */
2273 u64 nByte = 0; /* Data space required for this record */
2274 int nZero = 0; /* Number of zero bytes at the end of the record */
2275 int nVarint; /* Number of bytes in a varint */
2276 u32 serial_type; /* Type field */
2277 int containsNull = 0; /* True if any of the data fields are NULL */
2278 Mem *pData0; /* Bottom of the stack */
2279 int leaveOnStack; /* If true, leave the entries on the stack */
2280 int nField; /* Number of fields in the record */
2281 int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
2282 int addRowid; /* True to append a rowid column at the end */
2283 char *zAffinity; /* The affinity string for the record */
2284 int file_format; /* File format to use for encoding */
2285 int i; /* Space used in zNewRecord[] */
2286 char zTemp[NBFS]; /* Space to hold small records */
2288 leaveOnStack = ((pOp->p1<0)?1:0);
2289 nField = pOp->p1 * (leaveOnStack?-1:1);
2290 jumpIfNull = pOp->p2;
2291 addRowid = pOp->opcode==OP_MakeIdxRec;
2292 zAffinity = pOp->p3;
2294 pData0 = &pTos[1-nField];
2295 assert( pData0>=p->aStack );
2297 file_format = p->minWriteFileFormat;
2299 /* Loop through the elements that will make up the record to figure
2300 ** out how much space is required for the new record.
2302 for(pRec=pData0; pRec<=pTos; pRec++){
2305 applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2307 if( pRec->flags&MEM_Null ){
2310 if( pRec->flags&MEM_Zero && pRec->n>0 ){
2313 serial_type = sqlite3VdbeSerialType(pRec, file_format);
2314 len = sqlite3VdbeSerialTypeLen(serial_type);
2316 nHdr += sqlite3VarintLen(serial_type);
2317 if( pRec->flags & MEM_Zero ){
2318 /* Only pure zero-filled BLOBs can be input to this Opcode.
2319 ** We do not allow blobs with a prefix and a zero-filled tail. */
2326 /* If we have to append a varint rowid to this record, set pRowid
2327 ** to the value of the rowid and increase nByte by the amount of space
2328 ** required to store it.
2331 pRowid = &pTos[0-nField];
2332 assert( pRowid>=p->aStack );
2333 sqlite3VdbeMemIntegerify(pRowid);
2334 serial_type = sqlite3VdbeSerialType(pRowid, 0);
2335 nData += sqlite3VdbeSerialTypeLen(serial_type);
2336 nHdr += sqlite3VarintLen(serial_type);
2340 /* Add the initial header varint and total the size */
2341 nHdr += nVarint = sqlite3VarintLen(nHdr);
2342 if( nVarint<sqlite3VarintLen(nHdr) ){
2345 nByte = nHdr+nData-nZero;
2346 if( nByte>SQLITE_MAX_LENGTH ){
2350 /* Allocate space for the new record. */
2351 if( nByte>sizeof(zTemp) ){
2352 zNewRecord = sqlite3DbMallocRaw(db, nByte);
2357 zNewRecord = (u8*)zTemp;
2360 /* Write the record */
2361 i = sqlite3PutVarint(zNewRecord, nHdr);
2362 for(pRec=pData0; pRec<=pTos; pRec++){
2363 serial_type = sqlite3VdbeSerialType(pRec, file_format);
2364 i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */
2367 i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
2369 for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */
2370 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
2373 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
2377 /* Pop entries off the stack if required. Push the new record on. */
2378 if( !leaveOnStack ){
2379 popStack(&pTos, nField+addRowid);
2383 if( nByte<=sizeof(zTemp) ){
2384 assert( zNewRecord==(unsigned char *)zTemp );
2385 pTos->z = pTos->zShort;
2386 memcpy(pTos->zShort, zTemp, nByte);
2387 pTos->flags = MEM_Blob | MEM_Short;
2389 assert( zNewRecord!=(unsigned char *)zTemp );
2390 pTos->z = (char*)zNewRecord;
2391 pTos->flags = MEM_Blob | MEM_Dyn;
2396 pTos->flags |= MEM_Zero;
2398 pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
2400 /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
2401 if( jumpIfNull && containsNull ){
2402 pc = jumpIfNull - 1;
2407 /* Opcode: Statement P1 * *
2409 ** Begin an individual statement transaction which is part of a larger
2410 ** BEGIN..COMMIT transaction. This is needed so that the statement
2411 ** can be rolled back after an error without having to roll back the
2412 ** entire transaction. The statement transaction will automatically
2413 ** commit when the VDBE halts.
2415 ** The statement is begun on the database file with index P1. The main
2416 ** database file has an index of 0 and the file used for temporary tables
2417 ** has an index of 1.
2419 case OP_Statement: { /* no-push */
2422 if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
2423 assert( sqlite3BtreeIsInTrans(pBt) );
2424 assert( (p->btreeMask & (1<<i))!=0 );
2425 if( !sqlite3BtreeIsInStmt(pBt) ){
2426 rc = sqlite3BtreeBeginStmt(pBt);
2427 p->openedStatement = 1;
2433 /* Opcode: AutoCommit P1 P2 *
2435 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2436 ** back any currently active btree transactions. If there are any active
2437 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2439 ** This instruction causes the VM to halt.
2441 case OP_AutoCommit: { /* no-push */
2443 u8 rollback = pOp->p2;
2445 assert( i==1 || i==0 );
2446 assert( i==1 || rollback==0 );
2448 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
2450 if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2451 /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2452 ** still running, and a transaction is active, return an error indicating
2453 ** that the other VMs must complete first.
2455 sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2456 " transaction - SQL statements in progress", (char*)0);
2458 }else if( i!=db->autoCommit ){
2461 sqlite3RollbackAll(db);
2465 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2468 db->autoCommit = 1-i;
2469 p->rc = rc = SQLITE_BUSY;
2473 if( p->rc==SQLITE_OK ){
2480 sqlite3SetString(&p->zErrMsg,
2481 (!i)?"cannot start a transaction within a transaction":(
2482 (rollback)?"cannot rollback - no transaction is active":
2483 "cannot commit - no transaction is active"), (char*)0);
2490 /* Opcode: Transaction P1 P2 *
2492 ** Begin a transaction. The transaction ends when a Commit or Rollback
2493 ** opcode is encountered. Depending on the ON CONFLICT setting, the
2494 ** transaction might also be rolled back if an error is encountered.
2496 ** P1 is the index of the database file on which the transaction is
2497 ** started. Index 0 is the main database file and index 1 is the
2498 ** file used for temporary tables.
2500 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
2501 ** obtained on the database file when a write-transaction is started. No
2502 ** other process can start another write transaction while this transaction is
2503 ** underway. Starting a write transaction also creates a rollback journal. A
2504 ** write transaction must be started before any changes can be made to the
2505 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2508 ** If P2 is zero, then a read-lock is obtained on the database file.
2510 case OP_Transaction: { /* no-push */
2514 assert( i>=0 && i<db->nDb );
2515 assert( (p->btreeMask & (1<<i))!=0 );
2516 pBt = db->aDb[i].pBt;
2519 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2520 if( rc==SQLITE_BUSY ){
2522 p->rc = rc = SQLITE_BUSY;
2526 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2527 goto abort_due_to_error;
2533 /* Opcode: ReadCookie P1 P2 *
2535 ** Read cookie number P2 from database P1 and push it onto the stack.
2536 ** P2==0 is the schema version. P2==1 is the database format.
2537 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2538 ** the main database file and P1==1 is the database file used to store
2539 ** temporary tables.
2541 ** If P1 is negative, then this is a request to read the size of a
2542 ** databases free-list. P2 must be set to 1 in this case. The actual
2543 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
2544 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
2546 ** There must be a read-lock on the database (either a transaction
2547 ** must be started or there must be an open cursor) before
2548 ** executing this instruction.
2550 case OP_ReadCookie: {
2553 int iCookie = pOp->p2;
2555 assert( pOp->p2<SQLITE_N_BTREE_META );
2560 assert( iDb>=0 && iDb<db->nDb );
2561 assert( db->aDb[iDb].pBt!=0 );
2562 assert( (p->btreeMask & (1<<iDb))!=0 );
2563 /* The indexing of meta values at the schema layer is off by one from
2564 ** the indexing in the btree layer. The btree considers meta[0] to
2565 ** be the number of free pages in the database (a read-only value)
2566 ** and meta[1] to be the schema cookie. The schema layer considers
2567 ** meta[1] to be the schema cookie. So we have to shift the index
2568 ** by one in the following statement.
2570 rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
2573 pTos->flags = MEM_Int;
2577 /* Opcode: SetCookie P1 P2 *
2579 ** Write the top of the stack into cookie number P2 of database P1.
2580 ** P2==0 is the schema version. P2==1 is the database format.
2581 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2582 ** the main database file and P1==1 is the database file used to store
2583 ** temporary tables.
2585 ** A transaction must be started before executing this opcode.
2587 case OP_SetCookie: { /* no-push */
2589 assert( pOp->p2<SQLITE_N_BTREE_META );
2590 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2591 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
2592 pDb = &db->aDb[pOp->p1];
2593 assert( pDb->pBt!=0 );
2594 assert( pTos>=p->aStack );
2595 sqlite3VdbeMemIntegerify(pTos);
2596 /* See note about index shifting on OP_ReadCookie */
2597 rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
2599 /* When the schema cookie changes, record the new cookie internally */
2600 pDb->pSchema->schema_cookie = pTos->u.i;
2601 db->flags |= SQLITE_InternChanges;
2602 }else if( pOp->p2==1 ){
2603 /* Record changes in the file format */
2604 pDb->pSchema->file_format = pTos->u.i;
2606 assert( (pTos->flags & MEM_Dyn)==0 );
2609 /* Invalidate all prepared statements whenever the TEMP database
2610 ** schema is changed. Ticket #1644 */
2611 sqlite3ExpirePreparedStatements(db);
2616 /* Opcode: VerifyCookie P1 P2 *
2618 ** Check the value of global database parameter number 0 (the
2619 ** schema version) and make sure it is equal to P2.
2620 ** P1 is the database number which is 0 for the main database file
2621 ** and 1 for the file holding temporary tables and some higher number
2622 ** for auxiliary databases.
2624 ** The cookie changes its value whenever the database schema changes.
2625 ** This operation is used to detect when that the cookie has changed
2626 ** and that the current process needs to reread the schema.
2628 ** Either a transaction needs to have been started or an OP_Open needs
2629 ** to be executed (to establish a read lock) before this opcode is
2632 case OP_VerifyCookie: { /* no-push */
2635 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2636 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
2637 pBt = db->aDb[pOp->p1].pBt;
2639 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2644 if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2645 sqlite3_free(p->zErrMsg);
2646 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
2647 /* If the schema-cookie from the database file matches the cookie
2648 ** stored with the in-memory representation of the schema, do
2649 ** not reload the schema from the database file.
2651 ** If virtual-tables are in use, this is not just an optimisation.
2652 ** Often, v-tables store their data in other SQLite tables, which
2653 ** are queried from within xNext() and other v-table methods using
2654 ** prepared queries. If such a query is out-of-date, we do not want to
2655 ** discard the database schema, as the user code implementing the
2656 ** v-table would have to be ready for the sqlite3_vtab structure itself
2657 ** to be invalidated whenever sqlite3_step() is called from within
2658 ** a v-table method.
2660 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2661 sqlite3ResetInternalSchema(db, pOp->p1);
2664 sqlite3ExpirePreparedStatements(db);
2670 /* Opcode: OpenRead P1 P2 P3
2672 ** Open a read-only cursor for the database table whose root page is
2673 ** P2 in a database file. The database file is determined by an
2674 ** integer from the top of the stack. 0 means the main database and
2675 ** 1 means the database used for temporary tables. Give the new
2676 ** cursor an identifier of P1. The P1 values need not be contiguous
2677 ** but all P1 values should be small integers. It is an error for
2678 ** P1 to be negative.
2680 ** If P2==0 then take the root page number from the next of the stack.
2682 ** There will be a read lock on the database whenever there is an
2683 ** open cursor. If the database was unlocked prior to this instruction
2684 ** then a read lock is acquired as part of this instruction. A read
2685 ** lock allows other processes to read the database but prohibits
2686 ** any other process from modifying the database. The read lock is
2687 ** released when all cursors are closed. If this instruction attempts
2688 ** to get a read lock but fails, the script terminates with an
2689 ** SQLITE_BUSY error code.
2691 ** The P3 value is a pointer to a KeyInfo structure that defines the
2692 ** content and collating sequence of indices. P3 is NULL for cursors
2693 ** that are not pointing to indices.
2695 ** See also OpenWrite.
2697 /* Opcode: OpenWrite P1 P2 P3
2699 ** Open a read/write cursor named P1 on the table or index whose root
2700 ** page is P2. If P2==0 then take the root page number from the stack.
2702 ** The P3 value is a pointer to a KeyInfo structure that defines the
2703 ** content and collating sequence of indices. P3 is NULL for cursors
2704 ** that are not pointing to indices.
2706 ** This instruction works just like OpenRead except that it opens the cursor
2707 ** in read/write mode. For a given table, there can be one or more read-only
2708 ** cursors or a single read/write cursor but not both.
2710 ** See also OpenRead.
2712 case OP_OpenRead: /* no-push */
2713 case OP_OpenWrite: { /* no-push */
2722 assert( pTos>=p->aStack );
2723 sqlite3VdbeMemIntegerify(pTos);
2725 assert( (pTos->flags & MEM_Dyn)==0 );
2727 assert( iDb>=0 && iDb<db->nDb );
2728 assert( (p->btreeMask & (1<<iDb))!=0 );
2729 pDb = &db->aDb[iDb];
2732 if( pOp->opcode==OP_OpenWrite ){
2734 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
2735 p->minWriteFileFormat = pDb->pSchema->file_format;
2741 assert( pTos>=p->aStack );
2742 sqlite3VdbeMemIntegerify(pTos);
2744 assert( (pTos->flags & MEM_Dyn)==0 );
2749 pCur = allocateCursor(p, i, iDb);
2750 if( pCur==0 ) goto no_mem;
2753 /* We always provide a key comparison function. If the table being
2754 ** opened is of type INTKEY, the comparision function will be ignored. */
2755 rc = sqlite3BtreeCursor(pX, p2, wrFlag,
2756 sqlite3VdbeRecordCompare, pOp->p3,
2758 if( pOp->p3type==P3_KEYINFO ){
2759 pCur->pKeyInfo = (KeyInfo*)pOp->p3;
2760 pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2761 pCur->pKeyInfo->enc = ENC(p->db);
2764 pCur->pIncrKey = &pCur->bogusIncrKey;
2769 p->rc = rc = SQLITE_BUSY;
2770 p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
2774 int flags = sqlite3BtreeFlags(pCur->pCursor);
2775 /* Sanity checking. Only the lower four bits of the flags byte should
2776 ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
2777 ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2778 ** 2 (zerodata for indices). If these conditions are not met it can
2779 ** only mean that we are dealing with a corrupt database file
2781 if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2782 rc = SQLITE_CORRUPT_BKPT;
2783 goto abort_due_to_error;
2785 pCur->isTable = (flags & BTREE_INTKEY)!=0;
2786 pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2787 /* If P3==0 it means we are expected to open a table. If P3!=0 then
2788 ** we expect to be opening an index. If this is not what happened,
2789 ** then the database is corrupt
2791 if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
2792 || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
2793 rc = SQLITE_CORRUPT_BKPT;
2794 goto abort_due_to_error;
2798 case SQLITE_EMPTY: {
2799 pCur->isTable = pOp->p3type!=P3_KEYINFO;
2800 pCur->isIndex = !pCur->isTable;
2805 goto abort_due_to_error;
2811 /* Opcode: OpenEphemeral P1 P2 P3
2813 ** Open a new cursor P1 to a transient table.
2814 ** The cursor is always opened read/write even if
2815 ** the main database is read-only. The transient or virtual
2816 ** table is deleted automatically when the cursor is closed.
2818 ** P2 is the number of columns in the virtual table.
2819 ** The cursor points to a BTree table if P3==0 and to a BTree index
2820 ** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
2821 ** that defines the format of keys in the index.
2823 ** This opcode was once called OpenTemp. But that created
2824 ** confusion because the term "temp table", might refer either
2825 ** to a TEMP table at the SQL level, or to a table opened by
2826 ** this opcode. Then this opcode was call OpenVirtual. But
2827 ** that created confusion with the whole virtual-table idea.
2829 case OP_OpenEphemeral: { /* no-push */
2832 static const int openFlags =
2833 SQLITE_OPEN_READWRITE |
2834 SQLITE_OPEN_CREATE |
2835 SQLITE_OPEN_EXCLUSIVE |
2836 SQLITE_OPEN_DELETEONCLOSE |
2837 SQLITE_OPEN_TRANSIENT_DB;
2840 pCx = allocateCursor(p, i, -1);
2841 if( pCx==0 ) goto no_mem;
2843 rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
2845 if( rc==SQLITE_OK ){
2846 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2848 if( rc==SQLITE_OK ){
2849 /* If a transient index is required, create it by calling
2850 ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2851 ** opening it. If a transient table is required, just use the
2852 ** automatically created table with root-page 1 (an INTKEY table).
2856 assert( pOp->p3type==P3_KEYINFO );
2857 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2858 if( rc==SQLITE_OK ){
2859 assert( pgno==MASTER_ROOT+1 );
2860 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
2861 pOp->p3, &pCx->pCursor);
2862 pCx->pKeyInfo = (KeyInfo*)pOp->p3;
2863 pCx->pKeyInfo->enc = ENC(p->db);
2864 pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2868 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
2870 pCx->pIncrKey = &pCx->bogusIncrKey;
2873 pCx->nField = pOp->p2;
2874 pCx->isIndex = !pCx->isTable;
2878 /* Opcode: OpenPseudo P1 * *
2880 ** Open a new cursor that points to a fake table that contains a single
2881 ** row of data. Any attempt to write a second row of data causes the
2882 ** first row to be deleted. All data is deleted when the cursor is
2885 ** A pseudo-table created by this opcode is useful for holding the
2886 ** NEW or OLD tables in a trigger. Also used to hold the a single
2887 ** row output from the sorter so that the row can be decomposed into
2888 ** individual columns using the OP_Column opcode.
2890 case OP_OpenPseudo: { /* no-push */
2894 pCx = allocateCursor(p, i, -1);
2895 if( pCx==0 ) goto no_mem;
2897 pCx->pseudoTable = 1;
2898 pCx->pIncrKey = &pCx->bogusIncrKey;
2904 /* Opcode: Close P1 * *
2906 ** Close a cursor previously opened as P1. If P1 is not
2907 ** currently open, this instruction is a no-op.
2909 case OP_Close: { /* no-push */
2911 if( i>=0 && i<p->nCursor ){
2912 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
2918 /* Opcode: MoveGe P1 P2 *
2920 ** Pop the top of the stack and use its value as a key. Reposition
2921 ** cursor P1 so that it points to the smallest entry that is greater
2922 ** than or equal to the key that was popped ffrom the stack.
2923 ** If there are no records greater than or equal to the key and P2
2924 ** is not zero, then jump to P2.
2926 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2928 /* Opcode: MoveGt P1 P2 *
2930 ** Pop the top of the stack and use its value as a key. Reposition
2931 ** cursor P1 so that it points to the smallest entry that is greater
2932 ** than the key from the stack.
2933 ** If there are no records greater than the key and P2 is not zero,
2936 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2938 /* Opcode: MoveLt P1 P2 *
2940 ** Pop the top of the stack and use its value as a key. Reposition
2941 ** cursor P1 so that it points to the largest entry that is less
2942 ** than the key from the stack.
2943 ** If there are no records less than the key and P2 is not zero,
2946 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2948 /* Opcode: MoveLe P1 P2 *
2950 ** Pop the top of the stack and use its value as a key. Reposition
2951 ** cursor P1 so that it points to the largest entry that is less than
2952 ** or equal to the key that was popped from the stack.
2953 ** If there are no records less than or eqal to the key and P2 is not zero,
2956 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2958 case OP_MoveLt: /* no-push */
2959 case OP_MoveLe: /* no-push */
2960 case OP_MoveGe: /* no-push */
2961 case OP_MoveGt: { /* no-push */
2965 assert( pTos>=p->aStack );
2966 assert( i>=0 && i<p->nCursor );
2969 if( pC->pCursor!=0 ){
2973 *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2976 sqlite3VdbeMemIntegerify(pTos);
2977 iKey = intToKey(pTos->u.i);
2978 if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
2979 pC->movetoTarget = iKey;
2980 pC->deferredMoveto = 1;
2981 assert( (pTos->flags & MEM_Dyn)==0 );
2985 rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
2986 if( rc!=SQLITE_OK ){
2987 goto abort_due_to_error;
2989 pC->lastRowid = pTos->u.i;
2990 pC->rowidIsValid = res==0;
2992 assert( pTos->flags & MEM_Blob );
2994 rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
2995 if( rc!=SQLITE_OK ){
2996 goto abort_due_to_error;
2998 pC->rowidIsValid = 0;
3000 pC->deferredMoveto = 0;
3001 pC->cacheStatus = CACHE_STALE;
3004 sqlite3_search_count++;
3006 if( oc==OP_MoveGe || oc==OP_MoveGt ){
3008 rc = sqlite3BtreeNext(pC->pCursor, &res);
3009 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3010 pC->rowidIsValid = 0;
3015 assert( oc==OP_MoveLt || oc==OP_MoveLe );
3017 rc = sqlite3BtreePrevious(pC->pCursor, &res);
3018 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3019 pC->rowidIsValid = 0;
3021 /* res might be negative because the table is empty. Check to
3022 ** see if this is the case.
3024 res = sqlite3BtreeEof(pC->pCursor);
3040 /* Opcode: Distinct P1 P2 *
3042 ** Use the top of the stack as a record created using MakeRecord. P1 is a
3043 ** cursor on a table that declared as an index. If that table contains an
3044 ** entry that matches the top of the stack fall thru. If the top of the stack
3045 ** matches no entry in P1 then jump to P2.
3047 ** The cursor is left pointing at the matching entry if it exists. The
3048 ** record on the top of the stack is not popped.
3050 ** This instruction is similar to NotFound except that this operation
3051 ** does not pop the key from the stack.
3053 ** The instruction is used to implement the DISTINCT operator on SELECT
3054 ** statements. The P1 table is not a true index but rather a record of
3055 ** all results that have produced so far.
3057 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
3059 /* Opcode: Found P1 P2 *
3061 ** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
3062 ** If an entry that matches the top of the stack exists in P1 then
3063 ** jump to P2. If the top of the stack does not match any entry in P1
3064 ** then fall thru. The P1 cursor is left pointing at the matching entry
3065 ** if it exists. The blob is popped off the top of the stack.
3067 ** This instruction is used to implement the IN operator where the
3068 ** left-hand side is a SELECT statement. P1 is not a true index but
3069 ** is instead a temporary index that holds the results of the SELECT
3070 ** statement. This instruction just checks to see if the left-hand side
3071 ** of the IN operator (stored on the top of the stack) exists in the
3072 ** result of the SELECT statement.
3074 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
3076 /* Opcode: NotFound P1 P2 *
3078 ** The top of the stack holds a blob constructed by MakeRecord. P1 is
3079 ** an index. If no entry exists in P1 that matches the blob then jump
3080 ** to P2. If an entry does existing, fall through. The cursor is left
3081 ** pointing to the entry that matches. The blob is popped from the stack.
3083 ** The difference between this operation and Distinct is that
3084 ** Distinct does not pop the key from the stack.
3086 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
3088 case OP_Distinct: /* no-push */
3089 case OP_NotFound: /* no-push */
3090 case OP_Found: { /* no-push */
3092 int alreadyExists = 0;
3094 assert( pTos>=p->aStack );
3095 assert( i>=0 && i<p->nCursor );
3096 assert( p->apCsr[i]!=0 );
3097 if( (pC = p->apCsr[i])->pCursor!=0 ){
3099 assert( pC->isTable==0 );
3100 assert( pTos->flags & MEM_Blob );
3101 Stringify(pTos, encoding);
3102 rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
3103 if( rc!=SQLITE_OK ){
3106 alreadyExists = (res==0);
3107 pC->deferredMoveto = 0;
3108 pC->cacheStatus = CACHE_STALE;
3110 if( pOp->opcode==OP_Found ){
3111 if( alreadyExists ) pc = pOp->p2 - 1;
3113 if( !alreadyExists ) pc = pOp->p2 - 1;
3115 if( pOp->opcode!=OP_Distinct ){
3122 /* Opcode: IsUnique P1 P2 *
3124 ** The top of the stack is an integer record number. Call this
3125 ** record number R. The next on the stack is an index key created
3126 ** using MakeIdxRec. Call it K. This instruction pops R from the
3127 ** stack but it leaves K unchanged.
3129 ** P1 is an index. So it has no data and its key consists of a
3130 ** record generated by OP_MakeRecord where the last field is the
3131 ** rowid of the entry that the index refers to.
3133 ** This instruction asks if there is an entry in P1 where the
3134 ** fields matches K but the rowid is different from R.
3135 ** If there is no such entry, then there is an immediate
3136 ** jump to P2. If any entry does exist where the index string
3137 ** matches K but the record number is not R, then the record
3138 ** number for that entry is pushed onto the stack and control
3139 ** falls through to the next instruction.
3141 ** See also: Distinct, NotFound, NotExists, Found
3143 case OP_IsUnique: { /* no-push */
3145 Mem *pNos = &pTos[-1];
3150 /* Pop the value R off the top of the stack
3152 assert( pNos>=p->aStack );
3153 sqlite3VdbeMemIntegerify(pTos);
3155 assert( (pTos->flags & MEM_Dyn)==0 );
3157 assert( i>=0 && i<p->nCursor );
3160 pCrsr = pCx->pCursor;
3163 i64 v; /* The record number on the P1 entry that matches K */
3164 char *zKey; /* The value of K */
3165 int nKey; /* Number of bytes in K */
3166 int len; /* Number of bytes in K without the rowid at the end */
3167 int szRowid; /* Size of the rowid column at the end of zKey */
3169 /* Make sure K is a string and make zKey point to K
3171 assert( pNos->flags & MEM_Blob );
3172 Stringify(pNos, encoding);
3176 szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
3179 /* Search for an entry in P1 where all but the last four bytes match K.
3180 ** If there is no such entry, jump immediately to P2.
3182 assert( pCx->deferredMoveto==0 );
3183 pCx->cacheStatus = CACHE_STALE;
3184 rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
3185 if( rc!=SQLITE_OK ){
3186 goto abort_due_to_error;
3189 rc = sqlite3BtreeNext(pCrsr, &res);
3195 rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
3196 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3202 /* At this point, pCrsr is pointing to an entry in P1 where all but
3203 ** the final entry (the rowid) matches K. Check to see if the
3204 ** final rowid column is different from R. If it equals R then jump
3205 ** immediately to P2.
3207 rc = sqlite3VdbeIdxRowid(pCrsr, &v);
3208 if( rc!=SQLITE_OK ){
3209 goto abort_due_to_error;
3216 /* The final varint of the key is different from R. Push it onto
3217 ** the stack. (The record number of an entry that violates a UNIQUE
3222 pTos->flags = MEM_Int;
3227 /* Opcode: NotExists P1 P2 *
3229 ** Use the top of the stack as a integer key. If a record with that key
3230 ** does not exist in table of P1, then jump to P2. If the record
3231 ** does exist, then fall thru. The cursor is left pointing to the
3232 ** record if it exists. The integer key is popped from the stack.
3234 ** The difference between this operation and NotFound is that this
3235 ** operation assumes the key is an integer and that P1 is a table whereas
3236 ** NotFound assumes key is a blob constructed from MakeRecord and
3239 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
3241 case OP_NotExists: { /* no-push */
3245 assert( pTos>=p->aStack );
3246 assert( i>=0 && i<p->nCursor );
3247 assert( p->apCsr[i]!=0 );
3248 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3251 assert( pTos->flags & MEM_Int );
3252 assert( p->apCsr[i]->isTable );
3253 iKey = intToKey(pTos->u.i);
3254 rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
3255 pC->lastRowid = pTos->u.i;
3256 pC->rowidIsValid = res==0;
3258 pC->cacheStatus = CACHE_STALE;
3259 /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
3260 ** processing is about to abort so we really do not care whether or not
3261 ** the following jump is taken. (In other words, do not stress over
3262 ** the error that valgrind sometimes shows on the next statement when
3263 ** running ioerr.test and similar failure-recovery test scripts.) */
3266 pC->rowidIsValid = 0;
3274 /* Opcode: Sequence P1 * *
3276 ** Push an integer onto the stack which is the next available
3277 ** sequence number for cursor P1. The sequence number on the
3278 ** cursor is incremented after the push.
3282 assert( pTos>=p->aStack );
3283 assert( i>=0 && i<p->nCursor );
3284 assert( p->apCsr[i]!=0 );
3286 pTos->u.i = p->apCsr[i]->seqCount++;
3287 pTos->flags = MEM_Int;
3292 /* Opcode: NewRowid P1 P2 *
3294 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3295 ** The record number is not previously used as a key in the database
3296 ** table that cursor P1 points to. The new record number is pushed
3299 ** If P2>0 then P2 is a memory cell that holds the largest previously
3300 ** generated record number. No new record numbers are allowed to be less
3301 ** than this value. When this value reaches its maximum, a SQLITE_FULL
3302 ** error is generated. The P2 memory cell is updated with the generated
3303 ** record number. This P2 mechanism is used to help implement the
3304 ** AUTOINCREMENT feature.
3310 assert( i>=0 && i<p->nCursor );
3311 assert( p->apCsr[i]!=0 );
3312 if( (pC = p->apCsr[i])->pCursor==0 ){
3313 /* The zero initialization above is all that is needed */
3315 /* The next rowid or record number (different terms for the same
3316 ** thing) is obtained in a two-step algorithm.
3318 ** First we attempt to find the largest existing rowid and add one
3319 ** to that. But if the largest existing rowid is already the maximum
3320 ** positive integer, we have to fall through to the second
3321 ** probabilistic algorithm
3323 ** The second algorithm is to select a rowid at random and see if
3324 ** it already exists in the table. If it does not exist, we have
3325 ** succeeded. If the random rowid does exist, we select a new one
3326 ** and try again, up to 1000 times.
3328 ** For a table with less than 2 billion entries, the probability
3329 ** of not finding a unused rowid is about 1.0e-300. This is a
3330 ** non-zero probability, but it is still vanishingly small and should
3331 ** never cause a problem. You are much, much more likely to have a
3332 ** hardware failure than for this algorithm to fail.
3334 ** The analysis in the previous paragraph assumes that you have a good
3335 ** source of random numbers. Is a library function like lrand48()
3336 ** good enough? Maybe. Maybe not. It's hard to know whether there
3337 ** might be subtle bugs is some implementations of lrand48() that
3338 ** could cause problems. To avoid uncertainty, SQLite uses its own
3339 ** random number generator based on the RC4 algorithm.
3341 ** To promote locality of reference for repetitive inserts, the
3342 ** first few attempts at chosing a random rowid pick values just a little
3343 ** larger than the previous rowid. This has been shown experimentally
3344 ** to double the speed of the COPY operation.
3346 int res, rx=SQLITE_OK, cnt;
3349 if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
3351 rc = SQLITE_CORRUPT_BKPT;
3352 goto abort_due_to_error;
3354 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3355 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3357 #ifdef SQLITE_32BIT_ROWID
3358 # define MAX_ROWID 0x7fffffff
3360 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3361 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
3362 ** to provide the constant while making all compilers happy.
3364 # define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3367 if( !pC->useRandomRowid ){
3368 if( pC->nextRowidValid ){
3371 rc = sqlite3BtreeLast(pC->pCursor, &res);
3372 if( rc!=SQLITE_OK ){
3373 goto abort_due_to_error;
3378 sqlite3BtreeKeySize(pC->pCursor, &v);
3381 pC->useRandomRowid = 1;
3388 #ifndef SQLITE_OMIT_AUTOINCREMENT
3391 assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
3392 pMem = &p->aMem[pOp->p2];
3393 sqlite3VdbeMemIntegerify(pMem);
3394 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
3395 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3397 goto abort_due_to_error;
3399 if( v<pMem->u.i+1 ){
3407 pC->nextRowidValid = 1;
3408 pC->nextRowid = v+1;
3410 pC->nextRowidValid = 0;
3413 if( pC->useRandomRowid ){
3414 assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
3415 v = db->priorNewRowid;
3418 if( v==0 || cnt>2 ){
3419 sqlite3Randomness(sizeof(v), &v);
3420 if( cnt<5 ) v &= 0xffffff;
3423 sqlite3Randomness(1, &r);
3426 if( v==0 ) continue;
3428 rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
3430 }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3431 db->priorNewRowid = v;
3432 if( rx==SQLITE_OK && res==0 ){
3434 goto abort_due_to_error;
3437 pC->rowidIsValid = 0;
3438 pC->deferredMoveto = 0;
3439 pC->cacheStatus = CACHE_STALE;
3443 pTos->flags = MEM_Int;
3447 /* Opcode: Insert P1 P2 P3
3449 ** Write an entry into the table of cursor P1. A new entry is
3450 ** created if it doesn't already exist or the data for an existing
3451 ** entry is overwritten. The data is the value on the top of the
3452 ** stack. The key is the next value down on the stack. The key must
3453 ** be an integer. The stack is popped twice by this instruction.
3455 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3456 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
3457 ** then rowid is stored for subsequent return by the
3458 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
3460 ** Parameter P3 may point to a string containing the table-name, or
3461 ** may be NULL. If it is not NULL, then the update-hook
3462 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
3464 ** This instruction only works on tables. The equivalent instruction
3465 ** for indices is OP_IdxInsert.
3467 case OP_Insert: { /* no-push */
3468 Mem *pNos = &pTos[-1];
3471 assert( pNos>=p->aStack );
3472 assert( i>=0 && i<p->nCursor );
3473 assert( p->apCsr[i]!=0 );
3474 if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3475 i64 iKey; /* The integer ROWID or key for the record to be inserted */
3477 assert( pNos->flags & MEM_Int );
3478 assert( pC->isTable );
3479 iKey = intToKey(pNos->u.i);
3481 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3482 if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
3483 if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
3484 pC->nextRowidValid = 0;
3486 if( pTos->flags & MEM_Null ){
3490 assert( pTos->flags & (MEM_Blob|MEM_Str) );
3492 if( pC->pseudoTable ){
3493 sqlite3_free(pC->pData);
3495 pC->nData = pTos->n;
3496 if( pTos->flags & MEM_Dyn ){
3497 pC->pData = pTos->z;
3498 pTos->flags = MEM_Null;
3500 pC->pData = sqlite3_malloc( pC->nData+2 );
3501 if( !pC->pData ) goto no_mem;
3502 memcpy(pC->pData, pTos->z, pC->nData);
3503 pC->pData[pC->nData] = 0;
3504 pC->pData[pC->nData+1] = 0;
3509 if( pTos->flags & MEM_Zero ){
3514 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3515 pTos->z, pTos->n, nZero,
3516 pOp->p2 & OPFLAG_APPEND);
3519 pC->rowidIsValid = 0;
3520 pC->deferredMoveto = 0;
3521 pC->cacheStatus = CACHE_STALE;
3523 /* Invoke the update-hook if required. */
3524 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3525 const char *zDb = db->aDb[pC->iDb].zName;
3526 const char *zTbl = pOp->p3;
3527 int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3528 assert( pC->isTable );
3529 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3530 assert( pC->iDb>=0 );
3538 /* Opcode: Delete P1 P2 P3
3540 ** Delete the record at which the P1 cursor is currently pointing.
3542 ** The cursor will be left pointing at either the next or the previous
3543 ** record in the table. If it is left pointing at the next record, then
3544 ** the next Next instruction will be a no-op. Hence it is OK to delete
3545 ** a record from within an Next loop.
3547 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3548 ** incremented (otherwise not).
3550 ** If P1 is a pseudo-table, then this instruction is a no-op.
3552 case OP_Delete: { /* no-push */
3555 assert( i>=0 && i<p->nCursor );
3558 if( pC->pCursor!=0 ){
3561 /* If the update-hook will be invoked, set iKey to the rowid of the
3562 ** row being deleted.
3564 if( db->xUpdateCallback && pOp->p3 ){
3565 assert( pC->isTable );
3566 if( pC->rowidIsValid ){
3567 iKey = pC->lastRowid;
3569 rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
3571 goto abort_due_to_error;
3573 iKey = keyToInt(iKey);
3577 rc = sqlite3VdbeCursorMoveto(pC);
3578 if( rc ) goto abort_due_to_error;
3579 rc = sqlite3BtreeDelete(pC->pCursor);
3580 pC->nextRowidValid = 0;
3581 pC->cacheStatus = CACHE_STALE;
3583 /* Invoke the update-hook if required. */
3584 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3585 const char *zDb = db->aDb[pC->iDb].zName;
3586 const char *zTbl = pOp->p3;
3587 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3588 assert( pC->iDb>=0 );
3591 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3595 /* Opcode: ResetCount P1 * *
3597 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
3598 ** then the value of the change counter is copied to the database handle
3599 ** change counter (returned by subsequent calls to sqlite3_changes())
3600 ** before it is reset. This is used by trigger programs.
3602 case OP_ResetCount: { /* no-push */
3604 sqlite3VdbeSetChanges(db, p->nChange);
3610 /* Opcode: RowData P1 * *
3612 ** Push onto the stack the complete row data for cursor P1.
3613 ** There is no interpretation of the data. It is just copied
3614 ** onto the stack exactly as it is found in the database file.
3616 ** If the cursor is not pointing to a valid row, a NULL is pushed
3619 /* Opcode: RowKey P1 * *
3621 ** Push onto the stack the complete row key for cursor P1.
3622 ** There is no interpretation of the key. It is just copied
3623 ** onto the stack exactly as it is found in the database file.
3625 ** If the cursor is not pointing to a valid row, a NULL is pushed
3634 /* Note that RowKey and RowData are really exactly the same instruction */
3636 assert( i>=0 && i<p->nCursor );
3638 assert( pC->isTable || pOp->opcode==OP_RowKey );
3639 assert( pC->isIndex || pOp->opcode==OP_RowData );
3642 pTos->flags = MEM_Null;
3643 }else if( pC->pCursor!=0 ){
3644 BtCursor *pCrsr = pC->pCursor;
3645 rc = sqlite3VdbeCursorMoveto(pC);
3646 if( rc ) goto abort_due_to_error;
3648 pTos->flags = MEM_Null;
3650 }else if( pC->isIndex ){
3652 assert( !pC->isTable );
3653 sqlite3BtreeKeySize(pCrsr, &n64);
3654 if( n64>SQLITE_MAX_LENGTH ){
3659 sqlite3BtreeDataSize(pCrsr, &n);
3661 if( n>SQLITE_MAX_LENGTH ){
3666 pTos->flags = MEM_Blob | MEM_Short;
3667 pTos->z = pTos->zShort;
3669 char *z = sqlite3_malloc( n );
3670 if( z==0 ) goto no_mem;
3671 pTos->flags = MEM_Blob | MEM_Dyn;
3676 rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
3678 rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
3680 }else if( pC->pseudoTable ){
3681 pTos->n = pC->nData;
3682 assert( pC->nData<=SQLITE_MAX_LENGTH );
3683 pTos->z = pC->pData;
3684 pTos->flags = MEM_Blob|MEM_Ephem;
3686 pTos->flags = MEM_Null;
3688 pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
3692 /* Opcode: Rowid P1 * *
3694 ** Push onto the stack an integer which is the key of the table entry that
3695 ** P1 is currently point to.
3702 assert( i>=0 && i<p->nCursor );
3705 rc = sqlite3VdbeCursorMoveto(pC);
3706 if( rc ) goto abort_due_to_error;
3708 if( pC->rowidIsValid ){
3710 }else if( pC->pseudoTable ){
3711 v = keyToInt(pC->iKey);
3712 }else if( pC->nullRow || pC->pCursor==0 ){
3713 pTos->flags = MEM_Null;
3716 assert( pC->pCursor!=0 );
3717 sqlite3BtreeKeySize(pC->pCursor, &v);
3721 pTos->flags = MEM_Int;
3725 /* Opcode: NullRow P1 * *
3727 ** Move the cursor P1 to a null row. Any OP_Column operations
3728 ** that occur while the cursor is on the null row will always push
3729 ** a NULL onto the stack.
3731 case OP_NullRow: { /* no-push */
3735 assert( i>=0 && i<p->nCursor );
3739 pC->rowidIsValid = 0;
3743 /* Opcode: Last P1 P2 *
3745 ** The next use of the Rowid or Column or Next instruction for P1
3746 ** will refer to the last entry in the database table or index.
3747 ** If the table or index is empty and P2>0, then jump immediately to P2.
3748 ** If P2 is 0 or if the table or index is not empty, fall through
3749 ** to the following instruction.
3751 case OP_Last: { /* no-push */
3756 assert( i>=0 && i<p->nCursor );
3759 if( (pCrsr = pC->pCursor)!=0 ){
3761 rc = sqlite3BtreeLast(pCrsr, &res);
3763 pC->deferredMoveto = 0;
3764 pC->cacheStatus = CACHE_STALE;
3765 if( res && pOp->p2>0 ){
3775 /* Opcode: Sort P1 P2 *
3777 ** This opcode does exactly the same thing as OP_Rewind except that
3778 ** it increments an undocumented global variable used for testing.
3780 ** Sorting is accomplished by writing records into a sorting index,
3781 ** then rewinding that index and playing it back from beginning to
3782 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
3783 ** rewinding so that the global variable will be incremented and
3784 ** regression tests can determine whether or not the optimizer is
3785 ** correctly optimizing out sorts.
3787 case OP_Sort: { /* no-push */
3789 sqlite3_sort_count++;
3790 sqlite3_search_count--;
3792 /* Fall through into OP_Rewind */
3794 /* Opcode: Rewind P1 P2 *
3796 ** The next use of the Rowid or Column or Next instruction for P1
3797 ** will refer to the first entry in the database table or index.
3798 ** If the table or index is empty and P2>0, then jump immediately to P2.
3799 ** If P2 is 0 or if the table or index is not empty, fall through
3800 ** to the following instruction.
3802 case OP_Rewind: { /* no-push */
3808 assert( i>=0 && i<p->nCursor );
3811 if( (pCrsr = pC->pCursor)!=0 ){
3812 rc = sqlite3BtreeFirst(pCrsr, &res);
3813 pC->atFirst = res==0;
3814 pC->deferredMoveto = 0;
3815 pC->cacheStatus = CACHE_STALE;
3820 if( res && pOp->p2>0 ){
3826 /* Opcode: Next P1 P2 *
3828 ** Advance cursor P1 so that it points to the next key/data pair in its
3829 ** table or index. If there are no more key/value pairs then fall through
3830 ** to the following instruction. But if the cursor advance was successful,
3831 ** jump immediately to P2.
3835 /* Opcode: Prev P1 P2 *
3837 ** Back up cursor P1 so that it points to the previous key/data pair in its
3838 ** table or index. If there is no previous key/value pairs then fall through
3839 ** to the following instruction. But if the cursor backup was successful,
3840 ** jump immediately to P2.
3842 case OP_Prev: /* no-push */
3843 case OP_Next: { /* no-push */
3847 CHECK_FOR_INTERRUPT;
3848 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3849 pC = p->apCsr[pOp->p1];
3851 break; /* See ticket #2273 */
3853 if( (pCrsr = pC->pCursor)!=0 ){
3858 assert( pC->deferredMoveto==0 );
3859 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3860 sqlite3BtreePrevious(pCrsr, &res);
3862 pC->cacheStatus = CACHE_STALE;
3867 sqlite3_search_count++;
3873 pC->rowidIsValid = 0;
3877 /* Opcode: IdxInsert P1 P2 *
3879 ** The top of the stack holds a SQL index key made using either the
3880 ** MakeIdxRec or MakeRecord instructions. This opcode writes that key
3881 ** into the index P1. Data for the entry is nil.
3883 ** P2 is a flag that provides a hint to the b-tree layer that this
3884 ** insert is likely to be an append.
3886 ** This instruction only works for indices. The equivalent instruction
3887 ** for tables is OP_Insert.
3889 case OP_IdxInsert: { /* no-push */
3893 assert( pTos>=p->aStack );
3894 assert( i>=0 && i<p->nCursor );
3895 assert( p->apCsr[i]!=0 );
3896 assert( pTos->flags & MEM_Blob );
3897 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3898 assert( pC->isTable==0 );
3899 rc = ExpandBlob(pTos);
3900 if( rc==SQLITE_OK ){
3902 const char *zKey = pTos->z;
3903 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
3904 assert( pC->deferredMoveto==0 );
3905 pC->cacheStatus = CACHE_STALE;
3913 /* Opcode: IdxDelete P1 * *
3915 ** The top of the stack is an index key built using the either the
3916 ** MakeIdxRec or MakeRecord opcodes.
3917 ** This opcode removes that entry from the index.
3919 case OP_IdxDelete: { /* no-push */
3923 assert( pTos>=p->aStack );
3924 assert( pTos->flags & MEM_Blob );
3925 assert( i>=0 && i<p->nCursor );
3926 assert( p->apCsr[i]!=0 );
3927 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3929 rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
3930 if( rc==SQLITE_OK && res==0 ){
3931 rc = sqlite3BtreeDelete(pCrsr);
3933 assert( pC->deferredMoveto==0 );
3934 pC->cacheStatus = CACHE_STALE;
3941 /* Opcode: IdxRowid P1 * *
3943 ** Push onto the stack an integer which is the last entry in the record at
3944 ** the end of the index key pointed to by cursor P1. This integer should be
3945 ** the rowid of the table entry to which this index entry points.
3947 ** See also: Rowid, MakeIdxRec.
3954 assert( i>=0 && i<p->nCursor );
3955 assert( p->apCsr[i]!=0 );
3957 pTos->flags = MEM_Null;
3958 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3961 assert( pC->deferredMoveto==0 );
3962 assert( pC->isTable==0 );
3964 pTos->flags = MEM_Null;
3966 rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3967 if( rc!=SQLITE_OK ){
3968 goto abort_due_to_error;
3970 pTos->flags = MEM_Int;
3977 /* Opcode: IdxGT P1 P2 *
3979 ** The top of the stack is an index entry that omits the ROWID. Compare
3980 ** the top of stack against the index that P1 is currently pointing to.
3981 ** Ignore the ROWID on the P1 index.
3983 ** The top of the stack might have fewer columns that P1.
3985 ** If the P1 index entry is greater than the top of the stack
3986 ** then jump to P2. Otherwise fall through to the next instruction.
3987 ** In either case, the stack is popped once.
3989 /* Opcode: IdxGE P1 P2 P3
3991 ** The top of the stack is an index entry that omits the ROWID. Compare
3992 ** the top of stack against the index that P1 is currently pointing to.
3993 ** Ignore the ROWID on the P1 index.
3995 ** If the P1 index entry is greater than or equal to the top of the stack
3996 ** then jump to P2. Otherwise fall through to the next instruction.
3997 ** In either case, the stack is popped once.
3999 ** If P3 is the "+" string (or any other non-NULL string) then the
4000 ** index taken from the top of the stack is temporarily increased by
4001 ** an epsilon prior to the comparison. This make the opcode work
4002 ** like IdxGT except that if the key from the stack is a prefix of
4003 ** the key in the cursor, the result is false whereas it would be
4006 /* Opcode: IdxLT P1 P2 P3
4008 ** The top of the stack is an index entry that omits the ROWID. Compare
4009 ** the top of stack against the index that P1 is currently pointing to.
4010 ** Ignore the ROWID on the P1 index.
4012 ** If the P1 index entry is less than the top of the stack
4013 ** then jump to P2. Otherwise fall through to the next instruction.
4014 ** In either case, the stack is popped once.
4016 ** If P3 is the "+" string (or any other non-NULL string) then the
4017 ** index taken from the top of the stack is temporarily increased by
4018 ** an epsilon prior to the comparison. This makes the opcode work
4021 case OP_IdxLT: /* no-push */
4022 case OP_IdxGT: /* no-push */
4023 case OP_IdxGE: { /* no-push */
4027 assert( i>=0 && i<p->nCursor );
4028 assert( p->apCsr[i]!=0 );
4029 assert( pTos>=p->aStack );
4030 if( (pC = p->apCsr[i])->pCursor!=0 ){
4033 assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */
4034 assert( pC->deferredMoveto==0 );
4036 *pC->pIncrKey = pOp->p3!=0;
4037 assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
4038 rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
4040 if( rc!=SQLITE_OK ){
4043 if( pOp->opcode==OP_IdxLT ){
4045 }else if( pOp->opcode==OP_IdxGE ){
4057 /* Opcode: Destroy P1 P2 *
4059 ** Delete an entire database table or index whose root page in the database
4060 ** file is given by P1.
4062 ** The table being destroyed is in the main database file if P2==0. If
4063 ** P2==1 then the table to be clear is in the auxiliary database file
4064 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4066 ** If AUTOVACUUM is enabled then it is possible that another root page
4067 ** might be moved into the newly deleted root page in order to keep all
4068 ** root pages contiguous at the beginning of the database. The former
4069 ** value of the root page that moved - its value before the move occurred -
4070 ** is pushed onto the stack. If no page movement was required (because
4071 ** the table being dropped was already the last one in the database) then
4072 ** a zero is pushed onto the stack. If AUTOVACUUM is disabled
4073 ** then a zero is pushed onto the stack.
4080 #ifndef SQLITE_OMIT_VIRTUALTABLE
4083 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
4084 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
4089 iCnt = db->activeVdbeCnt;
4095 assert( (p->btreeMask & (1<<pOp->p2))!=0 );
4096 rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
4098 pTos->flags = MEM_Int;
4100 #ifndef SQLITE_OMIT_AUTOVACUUM
4101 if( rc==SQLITE_OK && iMoved!=0 ){
4102 sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
4109 /* Opcode: Clear P1 P2 *
4111 ** Delete all contents of the database table or index whose root page
4112 ** in the database file is given by P1. But, unlike Destroy, do not
4113 ** remove the table or index from the database file.
4115 ** The table being clear is in the main database file if P2==0. If
4116 ** P2==1 then the table to be clear is in the auxiliary database file
4117 ** that is used to store tables create using CREATE TEMPORARY TABLE.
4119 ** See also: Destroy
4121 case OP_Clear: { /* no-push */
4123 /* For consistency with the way other features of SQLite operate
4124 ** with a truncate, we will also skip the update callback.
4127 Btree *pBt = db->aDb[pOp->p2].pBt;
4128 if( db->xUpdateCallback && pOp->p3 ){
4129 const char *zDb = db->aDb[pOp->p2].zName;
4130 const char *zTbl = pOp->p3;
4134 rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
4135 if( rc!=SQLITE_OK ){
4136 goto abort_due_to_error;
4139 rc=sqlite3BtreeFirst(pCur, &fin);
4140 rc==SQLITE_OK && !fin;
4141 rc=sqlite3BtreeNext(pCur, &fin)
4144 rc = sqlite3BtreeKeySize(pCur, &iKey);
4148 iKey = keyToInt(iKey);
4149 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
4151 sqlite3BtreeCloseCursor(pCur);
4152 if( rc!=SQLITE_OK ){
4153 goto abort_due_to_error;
4157 assert( (p->btreeMask & (1<<pOp->p2))!=0 );
4158 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4162 /* Opcode: CreateTable P1 * *
4164 ** Allocate a new table in the main database file if P2==0 or in the
4165 ** auxiliary database file if P2==1. Push the page number
4166 ** for the root page of the new table onto the stack.
4168 ** The difference between a table and an index is this: A table must
4169 ** have a 4-byte integer key and can have arbitrary data. An index
4170 ** has an arbitrary key but no data.
4172 ** See also: CreateIndex
4174 /* Opcode: CreateIndex P1 * *
4176 ** Allocate a new index in the main database file if P2==0 or in the
4177 ** auxiliary database file if P2==1. Push the page number of the
4178 ** root page of the new index onto the stack.
4180 ** See documentation on OP_CreateTable for additional information.
4182 case OP_CreateIndex:
4183 case OP_CreateTable: {
4187 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4188 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
4189 pDb = &db->aDb[pOp->p1];
4190 assert( pDb->pBt!=0 );
4191 if( pOp->opcode==OP_CreateTable ){
4192 /* flags = BTREE_INTKEY; */
4193 flags = BTREE_LEAFDATA|BTREE_INTKEY;
4195 flags = BTREE_ZERODATA;
4197 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4199 if( rc==SQLITE_OK ){
4201 pTos->flags = MEM_Int;
4203 pTos->flags = MEM_Null;
4208 /* Opcode: ParseSchema P1 P2 P3
4210 ** Read and parse all entries from the SQLITE_MASTER table of database P1
4211 ** that match the WHERE clause P3. P2 is the "force" flag. Always do
4212 ** the parsing if P2 is true. If P2 is false, then this routine is a
4213 ** no-op if the schema is not currently loaded. In other words, if P2
4214 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
4215 ** schema is already loaded into the symbol table.
4217 ** This opcode invokes the parser to create a new virtual machine,
4218 ** then runs the new virtual machine. It is thus a reentrant opcode.
4220 case OP_ParseSchema: { /* no-push */
4223 const char *zMaster;
4226 assert( iDb>=0 && iDb<db->nDb );
4227 if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
4230 zMaster = SCHEMA_TABLE(iDb);
4232 initData.iDb = pOp->p1;
4233 initData.pzErrMsg = &p->zErrMsg;
4234 zSql = sqlite3MPrintf(db,
4235 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
4236 db->aDb[iDb].zName, zMaster, pOp->p3);
4237 if( zSql==0 ) goto no_mem;
4238 sqlite3SafetyOff(db);
4239 assert( db->init.busy==0 );
4241 assert( !db->mallocFailed );
4242 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4243 if( rc==SQLITE_ABORT ) rc = initData.rc;
4246 sqlite3SafetyOn(db);
4247 if( rc==SQLITE_NOMEM ){
4253 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
4254 /* Opcode: LoadAnalysis P1 * *
4256 ** Read the sqlite_stat1 table for database P1 and load the content
4257 ** of that table into the internal index hash table. This will cause
4258 ** the analysis to be used when preparing all subsequent queries.
4260 case OP_LoadAnalysis: { /* no-push */
4262 assert( iDb>=0 && iDb<db->nDb );
4263 rc = sqlite3AnalysisLoad(db, iDb);
4266 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
4268 /* Opcode: DropTable P1 * P3
4270 ** Remove the internal (in-memory) data structures that describe
4271 ** the table named P3 in database P1. This is called after a table
4272 ** is dropped in order to keep the internal representation of the
4273 ** schema consistent with what is on disk.
4275 case OP_DropTable: { /* no-push */
4276 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
4280 /* Opcode: DropIndex P1 * P3
4282 ** Remove the internal (in-memory) data structures that describe
4283 ** the index named P3 in database P1. This is called after an index
4284 ** is dropped in order to keep the internal representation of the
4285 ** schema consistent with what is on disk.
4287 case OP_DropIndex: { /* no-push */
4288 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
4292 /* Opcode: DropTrigger P1 * P3
4294 ** Remove the internal (in-memory) data structures that describe
4295 ** the trigger named P3 in database P1. This is called after a trigger
4296 ** is dropped in order to keep the internal representation of the
4297 ** schema consistent with what is on disk.
4299 case OP_DropTrigger: { /* no-push */
4300 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
4305 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
4306 /* Opcode: IntegrityCk P1 P2 *
4308 ** Do an analysis of the currently open database. Push onto the
4309 ** stack the text of an error message describing any problems.
4310 ** If no problems are found, push a NULL onto the stack.
4312 ** P1 is the address of a memory cell that contains the maximum
4313 ** number of allowed errors. At most mem[P1] errors will be reported.
4314 ** In other words, the analysis stops as soon as mem[P1] errors are
4315 ** seen. Mem[P1] is updated with the number of errors remaining.
4317 ** The root page numbers of all tables in the database are integer
4318 ** values on the stack. This opcode pulls as many integers as it
4319 ** can off of the stack and uses those numbers as the root pages.
4321 ** If P2 is not zero, the check is done on the auxiliary database
4322 ** file, not the main database file.
4324 ** This opcode is used to implement the integrity_check pragma.
4326 case OP_IntegrityCk: {
4334 for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
4335 if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
4338 aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) );
4339 if( aRoot==0 ) goto no_mem;
4341 assert( j>=0 && j<p->nMem );
4342 pnErr = &p->aMem[j];
4343 assert( (pnErr->flags & MEM_Int)!=0 );
4344 for(j=0; j<nRoot; j++){
4345 aRoot[j] = (pTos-j)->u.i;
4348 popStack(&pTos, nRoot);
4350 assert( pOp->p2>=0 && pOp->p2<db->nDb );
4351 assert( (p->btreeMask & (1<<pOp->p2))!=0 );
4352 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
4357 pTos->flags = MEM_Null;
4360 pTos->n = strlen(z);
4361 pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
4364 pTos->enc = SQLITE_UTF8;
4365 sqlite3VdbeChangeEncoding(pTos, encoding);
4366 sqlite3_free(aRoot);
4369 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4371 /* Opcode: FifoWrite * * *
4373 ** Write the integer on the top of the stack
4376 case OP_FifoWrite: { /* no-push */
4377 assert( pTos>=p->aStack );
4378 sqlite3VdbeMemIntegerify(pTos);
4379 if( sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i)==SQLITE_NOMEM ){
4382 assert( (pTos->flags & MEM_Dyn)==0 );
4387 /* Opcode: FifoRead * P2 *
4389 ** Attempt to read a single integer from the Fifo
4390 ** and push it onto the stack. If the Fifo is empty
4391 ** push nothing but instead jump to P2.
4395 CHECK_FOR_INTERRUPT;
4396 if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
4401 pTos->flags = MEM_Int;
4406 #ifndef SQLITE_OMIT_TRIGGER
4407 /* Opcode: ContextPush * * *
4409 ** Save the current Vdbe context such that it can be restored by a ContextPop
4410 ** opcode. The context stores the last insert row id, the last statement change
4411 ** count, and the current statement change count.
4413 case OP_ContextPush: { /* no-push */
4414 int i = p->contextStackTop++;
4418 /* FIX ME: This should be allocated as part of the vdbe at compile-time */
4419 if( i>=p->contextStackDepth ){
4420 p->contextStackDepth = i+1;
4421 p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
4422 sizeof(Context)*(i+1));
4423 if( p->contextStack==0 ) goto no_mem;
4425 pContext = &p->contextStack[i];
4426 pContext->lastRowid = db->lastRowid;
4427 pContext->nChange = p->nChange;
4428 pContext->sFifo = p->sFifo;
4429 sqlite3VdbeFifoInit(&p->sFifo);
4433 /* Opcode: ContextPop * * *
4435 ** Restore the Vdbe context to the state it was in when contextPush was last
4436 ** executed. The context stores the last insert row id, the last statement
4437 ** change count, and the current statement change count.
4439 case OP_ContextPop: { /* no-push */
4440 Context *pContext = &p->contextStack[--p->contextStackTop];
4441 assert( p->contextStackTop>=0 );
4442 db->lastRowid = pContext->lastRowid;
4443 p->nChange = pContext->nChange;
4444 sqlite3VdbeFifoClear(&p->sFifo);
4445 p->sFifo = pContext->sFifo;
4448 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
4450 /* Opcode: MemStore P1 P2 *
4452 ** Write the top of the stack into memory location P1.
4453 ** P1 should be a small integer since space is allocated
4454 ** for all memory locations between 0 and P1 inclusive.
4456 ** After the data is stored in the memory location, the
4457 ** stack is popped once if P2 is 1. If P2 is zero, then
4458 ** the original data remains on the stack.
4460 case OP_MemStore: { /* no-push */
4461 assert( pTos>=p->aStack );
4462 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4463 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
4466 /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
4467 ** restore the top of the stack to its original value.
4473 /* Opcode: MemLoad P1 * *
4475 ** Push a copy of the value in memory location P1 onto the stack.
4477 ** If the value is a string, then the value pushed is a pointer to
4478 ** the string that is stored in the memory location. If the memory
4479 ** location is subsequently changed (using OP_MemStore) then the
4480 ** value pushed onto the stack will change too.
4484 assert( i>=0 && i<p->nMem );
4486 sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
4490 #ifndef SQLITE_OMIT_AUTOINCREMENT
4491 /* Opcode: MemMax P1 * *
4493 ** Set the value of memory cell P1 to the maximum of its current value
4494 ** and the value on the top of the stack. The stack is unchanged.
4496 ** This instruction throws an error if the memory cell is not initially
4499 case OP_MemMax: { /* no-push */
4502 assert( pTos>=p->aStack );
4503 assert( i>=0 && i<p->nMem );
4505 sqlite3VdbeMemIntegerify(pMem);
4506 sqlite3VdbeMemIntegerify(pTos);
4507 if( pMem->u.i<pTos->u.i){
4508 pMem->u.i = pTos->u.i;
4512 #endif /* SQLITE_OMIT_AUTOINCREMENT */
4514 /* Opcode: MemIncr P1 P2 *
4516 ** Increment the integer valued memory cell P2 by the value in P1.
4518 ** It is illegal to use this instruction on a memory cell that does
4519 ** not contain an integer. An assertion fault will result if you try.
4521 case OP_MemIncr: { /* no-push */
4524 assert( i>=0 && i<p->nMem );
4526 assert( pMem->flags==MEM_Int );
4527 pMem->u.i += pOp->p1;
4531 /* Opcode: IfMemPos P1 P2 *
4533 ** If the value of memory cell P1 is 1 or greater, jump to P2.
4535 ** It is illegal to use this instruction on a memory cell that does
4536 ** not contain an integer. An assertion fault will result if you try.
4538 case OP_IfMemPos: { /* no-push */
4541 assert( i>=0 && i<p->nMem );
4543 assert( pMem->flags==MEM_Int );
4550 /* Opcode: IfMemNeg P1 P2 *
4552 ** If the value of memory cell P1 is less than zero, jump to P2.
4554 ** It is illegal to use this instruction on a memory cell that does
4555 ** not contain an integer. An assertion fault will result if you try.
4557 case OP_IfMemNeg: { /* no-push */
4560 assert( i>=0 && i<p->nMem );
4562 assert( pMem->flags==MEM_Int );
4569 /* Opcode: IfMemZero P1 P2 *
4571 ** If the value of memory cell P1 is exactly 0, jump to P2.
4573 ** It is illegal to use this instruction on a memory cell that does
4574 ** not contain an integer. An assertion fault will result if you try.
4576 case OP_IfMemZero: { /* no-push */
4579 assert( i>=0 && i<p->nMem );
4581 assert( pMem->flags==MEM_Int );
4588 /* Opcode: MemNull P1 * *
4590 ** Store a NULL in memory cell P1
4593 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4594 sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
4598 /* Opcode: MemInt P1 P2 *
4600 ** Store the integer value P1 in memory cell P2.
4603 assert( pOp->p2>=0 && pOp->p2<p->nMem );
4604 sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
4608 /* Opcode: MemMove P1 P2 *
4610 ** Move the content of memory cell P2 over to memory cell P1.
4611 ** Any prior content of P1 is erased. Memory cell P2 is left
4612 ** containing a NULL.
4615 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4616 assert( pOp->p2>=0 && pOp->p2<p->nMem );
4617 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
4621 /* Opcode: AggStep P1 P2 P3
4623 ** Execute the step function for an aggregate. The
4624 ** function has P2 arguments. P3 is a pointer to the FuncDef
4625 ** structure that specifies the function. Use memory location
4626 ** P1 as the accumulator.
4628 ** The P2 arguments are popped from the stack.
4630 case OP_AggStep: { /* no-push */
4634 sqlite3_context ctx;
4635 sqlite3_value **apVal;
4639 assert( pRec>=p->aStack );
4641 assert( apVal || n==0 );
4642 for(i=0; i<n; i++, pRec++){
4644 storeTypeInfo(pRec, encoding);
4646 ctx.pFunc = (FuncDef*)pOp->p3;
4647 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4648 ctx.pMem = pMem = &p->aMem[pOp->p1];
4650 ctx.s.flags = MEM_Null;
4656 if( ctx.pFunc->needCollSeq ){
4657 assert( pOp>p->aOp );
4658 assert( pOp[-1].p3type==P3_COLLSEQ );
4659 assert( pOp[-1].opcode==OP_CollSeq );
4660 ctx.pColl = (CollSeq *)pOp[-1].p3;
4662 (ctx.pFunc->xStep)(&ctx, n, apVal);
4665 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
4668 sqlite3VdbeMemRelease(&ctx.s);
4672 /* Opcode: AggFinal P1 P2 P3
4674 ** Execute the finalizer function for an aggregate. P1 is
4675 ** the memory location that is the accumulator for the aggregate.
4677 ** P2 is the number of arguments that the step function takes and
4678 ** P3 is a pointer to the FuncDef for this function. The P2
4679 ** argument is not used by this opcode. It is only there to disambiguate
4680 ** functions that can take varying numbers of arguments. The
4681 ** P3 argument is only needed for the degenerate case where
4682 ** the step function was not previously called.
4684 case OP_AggFinal: { /* no-push */
4686 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4687 pMem = &p->aMem[pOp->p1];
4688 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
4689 rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
4690 if( rc==SQLITE_ERROR ){
4691 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
4693 if( sqlite3VdbeMemTooBig(pMem) ){
4700 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
4701 /* Opcode: Vacuum * * *
4703 ** Vacuum the entire database. This opcode will cause other virtual
4704 ** machines to be created and run. It may not be called from within
4707 case OP_Vacuum: { /* no-push */
4708 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4709 rc = sqlite3RunVacuum(&p->zErrMsg, db);
4710 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4715 #if !defined(SQLITE_OMIT_AUTOVACUUM)
4716 /* Opcode: IncrVacuum P1 P2 *
4718 ** Perform a single step of the incremental vacuum procedure on
4719 ** the P1 database. If the vacuum has finished, jump to instruction
4720 ** P2. Otherwise, fall through to the next instruction.
4722 case OP_IncrVacuum: { /* no-push */
4725 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4726 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
4727 pBt = db->aDb[pOp->p1].pBt;
4728 rc = sqlite3BtreeIncrVacuum(pBt);
4729 if( rc==SQLITE_DONE ){
4737 /* Opcode: Expire P1 * *
4739 ** Cause precompiled statements to become expired. An expired statement
4740 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
4741 ** (via sqlite3_step()).
4743 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4744 ** then only the currently executing statement is affected.
4746 case OP_Expire: { /* no-push */
4748 sqlite3ExpirePreparedStatements(db);
4755 #ifndef SQLITE_OMIT_SHARED_CACHE
4756 /* Opcode: TableLock P1 P2 P3
4758 ** Obtain a lock on a particular table. This instruction is only used when
4759 ** the shared-cache feature is enabled.
4761 ** If P1 is not negative, then it is the index of the database
4762 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
4763 ** write-lock is required. In this case the index of the database is the
4764 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
4767 ** P2 contains the root-page of the table to lock.
4769 ** P3 contains a pointer to the name of the table being locked. This is only
4770 ** used to generate an error message if the lock cannot be obtained.
4772 case OP_TableLock: { /* no-push */
4774 u8 isWriteLock = (p1<0);
4778 assert( p1>=0 && p1<db->nDb );
4779 assert( (p->btreeMask & (1<<p1))!=0 );
4780 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
4781 if( rc==SQLITE_LOCKED ){
4782 const char *z = (const char *)pOp->p3;
4783 sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
4787 #endif /* SQLITE_OMIT_SHARED_CACHE */
4789 #ifndef SQLITE_OMIT_VIRTUALTABLE
4790 /* Opcode: VBegin * * P3
4792 ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
4795 case OP_VBegin: { /* no-push */
4796 rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
4799 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4801 #ifndef SQLITE_OMIT_VIRTUALTABLE
4802 /* Opcode: VCreate P1 * P3
4804 ** P3 is the name of a virtual table in database P1. Call the xCreate method
4807 case OP_VCreate: { /* no-push */
4808 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
4811 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4813 #ifndef SQLITE_OMIT_VIRTUALTABLE
4814 /* Opcode: VDestroy P1 * P3
4816 ** P3 is the name of a virtual table in database P1. Call the xDestroy method
4819 case OP_VDestroy: { /* no-push */
4820 p->inVtabMethod = 2;
4821 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
4822 p->inVtabMethod = 0;
4825 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4827 #ifndef SQLITE_OMIT_VIRTUALTABLE
4828 /* Opcode: VOpen P1 * P3
4830 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4831 ** P1 is a cursor number. This opcode opens a cursor to the virtual
4832 ** table and stores that cursor in P1.
4834 case OP_VOpen: { /* no-push */
4836 sqlite3_vtab_cursor *pVtabCursor = 0;
4838 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
4839 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4841 assert(pVtab && pModule);
4842 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4843 rc = pModule->xOpen(pVtab, &pVtabCursor);
4844 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4845 if( SQLITE_OK==rc ){
4846 /* Initialise sqlite3_vtab_cursor base class */
4847 pVtabCursor->pVtab = pVtab;
4849 /* Initialise vdbe cursor object */
4850 pCur = allocateCursor(p, pOp->p1, -1);
4852 pCur->pVtabCursor = pVtabCursor;
4853 pCur->pModule = pVtabCursor->pVtab->pModule;
4855 db->mallocFailed = 1;
4856 pModule->xClose(pVtabCursor);
4861 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4863 #ifndef SQLITE_OMIT_VIRTUALTABLE
4864 /* Opcode: VFilter P1 P2 P3
4866 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
4867 ** the filtered result set is empty.
4869 ** P3 is either NULL or a string that was generated by the xBestIndex
4870 ** method of the module. The interpretation of the P3 string is left
4871 ** to the module implementation.
4873 ** This opcode invokes the xFilter method on the virtual table specified
4874 ** by P1. The integer query plan parameter to xFilter is the top of the
4875 ** stack. Next down on the stack is the argc parameter. Beneath the
4876 ** next of stack are argc additional parameters which are passed to
4877 ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
4878 ** the stack) becomes argv[argc-1] when passed to xFilter.
4880 ** The integer query plan parameter, argc, and all argv stack values
4881 ** are popped from the stack before this instruction completes.
4883 ** A jump is made to P2 if the result set after filtering would be
4886 case OP_VFilter: { /* no-push */
4889 const sqlite3_module *pModule;
4891 Cursor *pCur = p->apCsr[pOp->p1];
4892 assert( pCur->pVtabCursor );
4893 pModule = pCur->pVtabCursor->pVtab->pModule;
4895 /* Grab the index number and argc parameters off the top of the stack. */
4896 assert( (&pTos[-1])>=p->aStack );
4897 assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
4898 nArg = pTos[-1].u.i;
4900 /* Invoke the xFilter method */
4904 Mem **apArg = p->apArg;
4905 for(i = 0; i<nArg; i++){
4906 apArg[i] = &pTos[i+1-2-nArg];
4907 storeTypeInfo(apArg[i], 0);
4910 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4911 p->inVtabMethod = 1;
4912 rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
4913 p->inVtabMethod = 0;
4914 if( rc==SQLITE_OK ){
4915 res = pModule->xEof(pCur->pVtabCursor);
4917 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4924 /* Pop the index number, argc value and parameters off the stack */
4925 popStack(&pTos, 2+nArg);
4928 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4930 #ifndef SQLITE_OMIT_VIRTUALTABLE
4931 /* Opcode: VRowid P1 * *
4933 ** Push an integer onto the stack which is the rowid of
4934 ** the virtual-table that the P1 cursor is pointing to.
4937 const sqlite3_module *pModule;
4939 Cursor *pCur = p->apCsr[pOp->p1];
4940 assert( pCur->pVtabCursor );
4941 pModule = pCur->pVtabCursor->pVtab->pModule;
4942 if( pModule->xRowid==0 ){
4943 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
4948 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4949 rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
4950 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4953 pTos->flags = MEM_Int;
4959 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4961 #ifndef SQLITE_OMIT_VIRTUALTABLE
4962 /* Opcode: VColumn P1 P2 *
4964 ** Push onto the stack the value of the P2-th column of
4965 ** the row of the virtual-table that the P1 cursor is pointing to.
4968 const sqlite3_module *pModule;
4970 Cursor *pCur = p->apCsr[pOp->p1];
4971 assert( pCur->pVtabCursor );
4972 pModule = pCur->pVtabCursor->pVtab->pModule;
4973 if( pModule->xColumn==0 ){
4974 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
4977 sqlite3_context sContext;
4978 memset(&sContext, 0, sizeof(sContext));
4979 sContext.s.flags = MEM_Null;
4981 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4982 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
4984 /* Copy the result of the function to the top of the stack. We
4985 ** do this regardless of whether or not an error occured to ensure any
4986 ** dynamic allocation in sContext.s (a Mem struct) is released.
4988 sqlite3VdbeChangeEncoding(&sContext.s, encoding);
4991 sqlite3VdbeMemMove(pTos, &sContext.s);
4993 if( sqlite3SafetyOn(db) ){
4994 goto abort_due_to_misuse;
4996 if( sqlite3VdbeMemTooBig(pTos) ){
5003 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5005 #ifndef SQLITE_OMIT_VIRTUALTABLE
5006 /* Opcode: VNext P1 P2 *
5008 ** Advance virtual table P1 to the next row in its result set and
5009 ** jump to instruction P2. Or, if the virtual table has reached
5010 ** the end of its result set, then fall through to the next instruction.
5012 case OP_VNext: { /* no-push */
5013 const sqlite3_module *pModule;
5016 Cursor *pCur = p->apCsr[pOp->p1];
5017 assert( pCur->pVtabCursor );
5018 pModule = pCur->pVtabCursor->pVtab->pModule;
5019 if( pModule->xNext==0 ){
5020 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
5023 /* Invoke the xNext() method of the module. There is no way for the
5024 ** underlying implementation to return an error if one occurs during
5025 ** xNext(). Instead, if an error occurs, true is returned (indicating that
5026 ** data is available) and the error code returned when xColumn or
5027 ** some other method is next invoked on the save virtual table cursor.
5029 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5030 p->inVtabMethod = 1;
5031 rc = pModule->xNext(pCur->pVtabCursor);
5032 p->inVtabMethod = 0;
5033 if( rc==SQLITE_OK ){
5034 res = pModule->xEof(pCur->pVtabCursor);
5036 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5039 /* If there is data, jump to P2 */
5046 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5048 #ifndef SQLITE_OMIT_VIRTUALTABLE
5049 /* Opcode: VRename * * P3
5051 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
5052 ** This opcode invokes the corresponding xRename method. The value
5053 ** on the top of the stack is popped and passed as the zName argument
5054 ** to the xRename method.
5056 case OP_VRename: { /* no-push */
5057 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5058 assert( pVtab->pModule->xRename );
5060 Stringify(pTos, encoding);
5062 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5063 sqlite3VtabLock(pVtab);
5064 rc = pVtab->pModule->xRename(pVtab, pTos->z);
5065 sqlite3VtabUnlock(db, pVtab);
5066 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5073 #ifndef SQLITE_OMIT_VIRTUALTABLE
5074 /* Opcode: VUpdate P1 P2 P3
5076 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
5077 ** This opcode invokes the corresponding xUpdate method. P2 values
5078 ** are taken from the stack to pass to the xUpdate invocation. The
5079 ** value on the top of the stack corresponds to the p2th element
5080 ** of the argv array passed to xUpdate.
5082 ** The xUpdate method will do a DELETE or an INSERT or both.
5083 ** The argv[0] element (which corresponds to the P2-th element down
5084 ** on the stack) is the rowid of a row to delete. If argv[0] is
5085 ** NULL then no deletion occurs. The argv[1] element is the rowid
5086 ** of the new row. This can be NULL to have the virtual table
5087 ** select the new rowid for itself. The higher elements in the
5088 ** stack are the values of columns in the new row.
5090 ** If P2==1 then no insert is performed. argv[0] is the rowid of
5093 ** P1 is a boolean flag. If it is set to true and the xUpdate call
5094 ** is successful, then the value returned by sqlite3_last_insert_rowid()
5095 ** is set to the value of the rowid for the row just inserted.
5097 case OP_VUpdate: { /* no-push */
5098 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5099 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
5101 assert( pOp->p3type==P3_VTAB );
5102 if( pModule->xUpdate==0 ){
5103 sqlite3SetString(&p->zErrMsg, "read-only table", 0);
5108 Mem **apArg = p->apArg;
5109 Mem *pX = &pTos[1-nArg];
5110 for(i = 0; i<nArg; i++, pX++){
5111 storeTypeInfo(pX, 0);
5114 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5115 sqlite3VtabLock(pVtab);
5116 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
5117 sqlite3VtabUnlock(db, pVtab);
5118 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5119 if( pOp->p1 && rc==SQLITE_OK ){
5120 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
5121 db->lastRowid = rowid;
5124 popStack(&pTos, nArg);
5127 #endif /* SQLITE_OMIT_VIRTUALTABLE */
5129 /* An other opcode is illegal...
5136 /*****************************************************************************
5137 ** The cases of the switch statement above this line should all be indented
5138 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
5139 ** readability. From this point on down, the normal indentation rules are
5141 *****************************************************************************/
5144 /* Make sure the stack limit was not exceeded */
5145 assert( pTos<=pStackLimit );
5149 long long elapse = hwtime() - start;
5150 pOp->cycles += elapse;
5153 fprintf(stdout, "%10lld ", elapse);
5154 sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
5160 /* Keep track of the size of the largest BLOB or STR that has appeared
5161 ** on the top of the VDBE stack.
5163 if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
5164 && pTos->n>sqlite3_max_blobsize ){
5165 sqlite3_max_blobsize = pTos->n;
5169 /* The following code adds nothing to the actual functionality
5170 ** of the program. It is only here for testing and debugging.
5171 ** On the other hand, it does burn CPU cycles every time through
5172 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
5175 /* Sanity checking on the top element of the stack. If the previous
5176 ** instruction was VNoChange, then the flags field of the top
5177 ** of the stack is set to 0. This is technically invalid for a memory
5178 ** cell, so avoid calling MemSanity() in this case.
5180 if( pTos>=p->aStack && pTos->flags ){
5181 assert( pTos->db==db );
5182 sqlite3VdbeMemSanity(pTos);
5183 assert( !sqlite3VdbeMemTooBig(pTos) );
5185 assert( pc>=-1 && pc<p->nOp );
5188 /* Code for tracing the vdbe stack. */
5189 if( p->trace && pTos>=p->aStack ){
5191 fprintf(p->trace, "Stack:");
5192 for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
5193 if( pTos[i].flags & MEM_Null ){
5194 fprintf(p->trace, " NULL");
5195 }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
5196 fprintf(p->trace, " si:%lld", pTos[i].u.i);
5197 }else if( pTos[i].flags & MEM_Int ){
5198 fprintf(p->trace, " i:%lld", pTos[i].u.i);
5199 }else if( pTos[i].flags & MEM_Real ){
5200 fprintf(p->trace, " r:%g", pTos[i].r);
5203 sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
5204 fprintf(p->trace, " ");
5205 fprintf(p->trace, "%s", zBuf);
5208 if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
5209 fprintf(p->trace,"\n");
5211 #endif /* SQLITE_DEBUG */
5213 } /* The end of the for(;;) loop the loops through opcodes */
5215 /* If we reach this point, it means that execution is finished.
5227 /* This is the only way out of this procedure. We have to
5228 ** release the mutexes on btrees that were acquired at the
5231 sqlite3BtreeMutexArrayLeave(&p->aMutex);
5234 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
5238 sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
5242 /* Jump to here if a malloc() fails.
5245 db->mallocFailed = 1;
5246 sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
5250 /* Jump to here for an SQLITE_MISUSE error.
5252 abort_due_to_misuse:
5254 /* Fall thru into abort_due_to_error */
5256 /* Jump to here for any other kind of fatal error. The "rc" variable
5257 ** should hold the error number.
5260 if( p->zErrMsg==0 ){
5261 if( db->mallocFailed ) rc = SQLITE_NOMEM;
5262 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5266 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
5269 abort_due_to_interrupt:
5270 assert( db->u1.isInterrupted );
5271 if( db->magic!=SQLITE_MAGIC_BUSY ){
5274 rc = SQLITE_INTERRUPT;
5277 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);