disable the egl demos.
[AROS-Contrib.git] / sqlite3 / vdbe.c
blob8085428cb41a03175a7669328ce38695689008ae
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
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
16 ** the VDBE program.
18 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
19 ** to a VDBE.
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.
34 **
35 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
36 ** function which does the work of interpreting a VDBE program.
37 ** But other routines are also provided to help in building up
38 ** a program instruction by instruction.
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.
46 ** $Id$
48 #include "sqliteInt.h"
49 #include "os.h"
50 #include <ctype.h>
51 #include "vdbeInt.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.
60 int sqlite3_search_count = 0;
63 ** When this global variable is positive, it gets decremented once before
64 ** each instruction in the VDBE. When reaches zero, the SQLITE_Interrupt
65 ** of the db.flags field is set in order to simulate and interrupt.
67 ** This facility is used for testing purposes only. It does not function
68 ** in an ordinary build.
70 int sqlite3_interrupt_count = 0;
73 ** The next global variable is incremented each type the OP_Sort opcode
74 ** is executed. The test procedures use this information to make sure that
75 ** sorting is occurring or not occuring at appropriate times. This variable
76 ** has no function other than to help verify the correct operation of the
77 ** library.
79 int sqlite3_sort_count = 0;
82 ** Release the memory associated with the given stack level. This
83 ** leaves the Mem.flags field in an inconsistent state.
85 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
88 ** Convert the given stack entity into a string if it isn't one
89 ** already. Return non-zero if a malloc() fails.
91 #define Stringify(P, enc) \
92 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
93 { goto no_mem; }
96 ** Convert the given stack entity into a string that has been obtained
97 ** from sqliteMalloc(). This is different from Stringify() above in that
98 ** Stringify() will use the NBFS bytes of static string space if the string
99 ** will fit but this routine always mallocs for space.
100 ** Return non-zero if we run out of memory.
102 #define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
106 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
107 ** a pointer to a dynamically allocated string where some other entity
108 ** is responsible for deallocating that string. Because the stack entry
109 ** does not control the string, it might be deleted without the stack
110 ** entry knowing it.
112 ** This routine converts an ephemeral string into a dynamically allocated
113 ** string that the stack entry itself controls. In other words, it
114 ** converts an MEM_Ephem string into an MEM_Dyn string.
116 #define Deephemeralize(P) \
117 if( ((P)->flags&MEM_Ephem)!=0 \
118 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
121 ** Convert the given stack entity into a integer if it isn't one
122 ** already.
124 ** Any prior string or real representation is invalidated.
125 ** NULLs are converted into 0.
127 #define Integerify(P) sqlite3VdbeMemIntegerify(P)
130 ** Convert P so that it has type MEM_Real.
132 ** Any prior string or integer representation is invalidated.
133 ** NULLs are converted into 0.0.
135 #define Realify(P) sqlite3VdbeMemRealify(P)
138 ** Argument pMem points at a memory cell that will be passed to a
139 ** user-defined function or returned to the user as the result of a query.
140 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
141 ** stack variables. This routine sets the pMem->enc and pMem->type
142 ** variables used by the sqlite3_value_*() routines.
144 #define storeTypeInfo(A,B) _storeTypeInfo(A)
145 static void _storeTypeInfo(Mem *pMem){
146 int flags = pMem->flags;
147 if( flags & MEM_Null ){
148 pMem->type = SQLITE_NULL;
150 else if( flags & MEM_Int ){
151 pMem->type = SQLITE_INTEGER;
153 else if( flags & MEM_Real ){
154 pMem->type = SQLITE_FLOAT;
156 else if( flags & MEM_Str ){
157 pMem->type = SQLITE_TEXT;
158 }else{
159 pMem->type = SQLITE_BLOB;
164 ** Insert a new aggregate element and make it the element that
165 ** has focus.
167 ** Return 0 on success and 1 if memory is exhausted.
169 static int AggInsert(Agg *p, char *zKey, int nKey){
170 AggElem *pElem;
171 int i;
172 int rc;
173 pElem = sqliteMalloc( sizeof(AggElem) + nKey +
174 (p->nMem-1)*sizeof(pElem->aMem[0]) );
175 if( pElem==0 ) return SQLITE_NOMEM;
176 pElem->zKey = (char*)&pElem->aMem[p->nMem];
177 memcpy(pElem->zKey, zKey, nKey);
178 pElem->nKey = nKey;
180 if( p->pCsr ){
181 rc = sqlite3BtreeInsert(p->pCsr, zKey, nKey, &pElem, sizeof(AggElem*));
182 if( rc!=SQLITE_OK ){
183 sqliteFree(pElem);
184 return rc;
188 for(i=0; i<p->nMem; i++){
189 pElem->aMem[i].flags = MEM_Null;
191 p->pCurrent = pElem;
192 return 0;
196 ** Pop the stack N times.
198 static void popStack(Mem **ppTos, int N){
199 Mem *pTos = *ppTos;
200 while( N>0 ){
201 N--;
202 Release(pTos);
203 pTos--;
205 *ppTos = pTos;
209 ** The parameters are pointers to the head of two sorted lists
210 ** of Sorter structures. Merge these two lists together and return
211 ** a single sorted list. This routine forms the core of the merge-sort
212 ** algorithm.
214 ** In the case of a tie, left sorts in front of right.
216 static Sorter *Merge(Sorter *pLeft, Sorter *pRight, KeyInfo *pKeyInfo){
217 Sorter sHead;
218 Sorter *pTail;
219 pTail = &sHead;
220 pTail->pNext = 0;
221 while( pLeft && pRight ){
222 int c = sqlite3VdbeRecordCompare(pKeyInfo, pLeft->nKey, pLeft->zKey,
223 pRight->nKey, pRight->zKey);
224 if( c<=0 ){
225 pTail->pNext = pLeft;
226 pLeft = pLeft->pNext;
227 }else{
228 pTail->pNext = pRight;
229 pRight = pRight->pNext;
231 pTail = pTail->pNext;
233 if( pLeft ){
234 pTail->pNext = pLeft;
235 }else if( pRight ){
236 pTail->pNext = pRight;
238 return sHead.pNext;
242 ** Allocate cursor number iCur. Return a pointer to it. Return NULL
243 ** if we run out of memory.
245 static Cursor *allocateCursor(Vdbe *p, int iCur){
246 Cursor *pCx;
247 assert( iCur<p->nCursor );
248 if( p->apCsr[iCur] ){
249 sqlite3VdbeFreeCursor(p->apCsr[iCur]);
251 p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
252 return pCx;
256 ** Apply any conversion required by the supplied column affinity to
257 ** memory cell pRec. affinity may be one of:
259 ** SQLITE_AFF_NUMERIC
260 ** SQLITE_AFF_TEXT
261 ** SQLITE_AFF_NONE
262 ** SQLITE_AFF_INTEGER
265 static void applyAffinity(Mem *pRec, char affinity, u8 enc){
266 if( affinity==SQLITE_AFF_NONE ){
267 /* do nothing */
268 }else if( affinity==SQLITE_AFF_TEXT ){
269 /* Only attempt the conversion to TEXT if there is an integer or real
270 ** representation (blob and NULL do not get converted) but no string
271 ** representation.
273 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
274 sqlite3VdbeMemStringify(pRec, enc);
276 pRec->flags &= ~(MEM_Real|MEM_Int);
277 }else{
278 if( 0==(pRec->flags&(MEM_Real|MEM_Int)) ){
279 /* pRec does not have a valid integer or real representation.
280 ** Attempt a conversion if pRec has a string representation and
281 ** it looks like a number.
283 int realnum;
284 sqlite3VdbeMemNulTerminate(pRec);
285 if( pRec->flags&MEM_Str && sqlite3IsNumber(pRec->z, &realnum, enc) ){
286 if( realnum ){
287 Realify(pRec);
288 }else{
289 Integerify(pRec);
294 if( affinity==SQLITE_AFF_INTEGER ){
295 /* For INTEGER affinity, try to convert a real value to an int */
296 if( (pRec->flags&MEM_Real) && !(pRec->flags&MEM_Int) ){
297 pRec->i = pRec->r;
298 if( ((double)pRec->i)==pRec->r ){
299 pRec->flags |= MEM_Int;
307 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
308 ** not the internal Mem* type.
310 void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
311 applyAffinity((Mem *)pVal, affinity, enc);
314 #ifdef SQLITE_DEBUG
316 ** Write a nice string representation of the contents of cell pMem
317 ** into buffer zBuf, length nBuf.
319 void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf, int nBuf){
320 char *zCsr = zBuf;
321 int f = pMem->flags;
323 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
325 if( f&MEM_Blob ){
326 int i;
327 char c;
328 if( f & MEM_Dyn ){
329 c = 'z';
330 assert( (f & (MEM_Static|MEM_Ephem))==0 );
331 }else if( f & MEM_Static ){
332 c = 't';
333 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
334 }else if( f & MEM_Ephem ){
335 c = 'e';
336 assert( (f & (MEM_Static|MEM_Dyn))==0 );
337 }else{
338 c = 's';
341 zCsr += sprintf(zCsr, "%c", c);
342 zCsr += sprintf(zCsr, "%d[", pMem->n);
343 for(i=0; i<16 && i<pMem->n; i++){
344 zCsr += sprintf(zCsr, "%02X ", ((int)pMem->z[i] & 0xFF));
346 for(i=0; i<16 && i<pMem->n; i++){
347 char z = pMem->z[i];
348 if( z<32 || z>126 ) *zCsr++ = '.';
349 else *zCsr++ = z;
352 zCsr += sprintf(zCsr, "]");
353 *zCsr = '\0';
354 }else if( f & MEM_Str ){
355 int j, k;
356 zBuf[0] = ' ';
357 if( f & MEM_Dyn ){
358 zBuf[1] = 'z';
359 assert( (f & (MEM_Static|MEM_Ephem))==0 );
360 }else if( f & MEM_Static ){
361 zBuf[1] = 't';
362 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
363 }else if( f & MEM_Ephem ){
364 zBuf[1] = 'e';
365 assert( (f & (MEM_Static|MEM_Dyn))==0 );
366 }else{
367 zBuf[1] = 's';
369 k = 2;
370 k += sprintf(&zBuf[k], "%d", pMem->n);
371 zBuf[k++] = '[';
372 for(j=0; j<15 && j<pMem->n; j++){
373 u8 c = pMem->z[j];
374 if( c>=0x20 && c<0x7f ){
375 zBuf[k++] = c;
376 }else{
377 zBuf[k++] = '.';
380 zBuf[k++] = ']';
381 k += sprintf(&zBuf[k], encnames[pMem->enc]);
382 zBuf[k++] = 0;
385 #endif
388 #ifdef VDBE_PROFILE
390 ** The following routine only works on pentium-class processors.
391 ** It uses the RDTSC opcode to read the cycle count value out of the
392 ** processor and returns that value. This can be used for high-res
393 ** profiling.
395 __inline__ unsigned long long int hwtime(void){
396 unsigned long long int x;
397 __asm__("rdtsc\n\t"
398 "mov %%edx, %%ecx\n\t"
399 :"=A" (x));
400 return x;
402 #endif
405 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
406 ** sqlite3_interrupt() routine has been called. If it has been, then
407 ** processing of the VDBE program is interrupted.
409 ** This macro added to every instruction that does a jump in order to
410 ** implement a loop. This test used to be on every single instruction,
411 ** but that meant we more testing that we needed. By only testing the
412 ** flag on jump instructions, we get a (small) speed improvement.
414 #define CHECK_FOR_INTERRUPT \
415 if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
419 ** Execute as much of a VDBE program as we can then return.
421 ** sqlite3VdbeMakeReady() must be called before this routine in order to
422 ** close the program with a final OP_Halt and to set up the callbacks
423 ** and the error message pointer.
425 ** Whenever a row or result data is available, this routine will either
426 ** invoke the result callback (if there is one) or return with
427 ** SQLITE_ROW.
429 ** If an attempt is made to open a locked database, then this routine
430 ** will either invoke the busy callback (if there is one) or it will
431 ** return SQLITE_BUSY.
433 ** If an error occurs, an error message is written to memory obtained
434 ** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
435 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
437 ** If the callback ever returns non-zero, then the program exits
438 ** immediately. There will be no error message but the p->rc field is
439 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
441 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
442 ** routine to return SQLITE_ERROR.
444 ** Other fatal errors return SQLITE_ERROR.
446 ** After this routine has finished, sqlite3VdbeFinalize() should be
447 ** used to clean up the mess that was left behind.
449 int sqlite3VdbeExec(
450 Vdbe *p /* The VDBE */
452 int pc; /* The program counter */
453 Op *pOp; /* Current operation */
454 int rc = SQLITE_OK; /* Value to return */
455 sqlite3 *db = p->db; /* The database */
456 Mem *pTos; /* Top entry in the operand stack */
457 char zBuf[100]; /* Space to sprintf() an integer */
458 #ifdef VDBE_PROFILE
459 unsigned long long start; /* CPU clock count at start of opcode */
460 int origPc; /* Program counter at start of opcode */
461 #endif
462 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
463 int nProgressOps = 0; /* Opcodes executed since progress callback. */
464 #endif
465 #ifndef NDEBUG
466 Mem *pStackLimit;
467 #endif
469 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
470 assert( db->magic==SQLITE_MAGIC_BUSY );
471 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
472 p->rc = SQLITE_OK;
473 assert( p->explain==0 );
474 pTos = p->pTos;
475 if( sqlite3_malloc_failed ) goto no_mem;
476 if( p->popStack ){
477 popStack(&pTos, p->popStack);
478 p->popStack = 0;
480 p->resOnStack = 0;
481 CHECK_FOR_INTERRUPT;
482 for(pc=p->pc; rc==SQLITE_OK; pc++){
483 assert( pc>=0 && pc<p->nOp );
484 assert( pTos<=&p->aStack[pc] );
485 if( sqlite3_malloc_failed ) goto no_mem;
486 #ifdef VDBE_PROFILE
487 origPc = pc;
488 start = hwtime();
489 #endif
490 pOp = &p->aOp[pc];
492 /* Only allow tracing if SQLITE_DEBUG is defined.
494 #ifdef SQLITE_DEBUG
495 if( p->trace ){
496 if( pc==0 ){
497 printf("VDBE Execution Trace:\n");
498 sqlite3VdbePrintSql(p);
500 sqlite3VdbePrintOp(p->trace, pc, pOp);
502 if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
503 sqlite3VdbePrintSql(p);
505 #endif
508 /* Check to see if we need to simulate an interrupt. This only happens
509 ** if we have a special test build.
511 #ifdef SQLITE_TEST
512 if( sqlite3_interrupt_count>0 ){
513 sqlite3_interrupt_count--;
514 if( sqlite3_interrupt_count==0 ){
515 sqlite3_interrupt(db);
518 #endif
520 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
521 /* Call the progress callback if it is configured and the required number
522 ** of VDBE ops have been executed (either since this invocation of
523 ** sqlite3VdbeExec() or since last time the progress callback was called).
524 ** If the progress callback returns non-zero, exit the virtual machine with
525 ** a return code SQLITE_ABORT.
527 if( db->xProgress ){
528 if( db->nProgressOps==nProgressOps ){
529 if( db->xProgress(db->pProgressArg)!=0 ){
530 rc = SQLITE_ABORT;
531 continue; /* skip to the next iteration of the for loop */
533 nProgressOps = 0;
535 nProgressOps++;
537 #endif
539 #ifndef NDEBUG
540 /* This is to check that the return value of static function
541 ** opcodeNoPush() (see vdbeaux.c) returns values that match the
542 ** implementation of the virtual machine in this file. If
543 ** opcodeNoPush() returns non-zero, then the stack is guarenteed
544 ** not to grow when the opcode is executed. If it returns zero, then
545 ** the stack may grow by at most 1.
547 ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
548 ** available if NDEBUG is defined at build time.
550 pStackLimit = pTos;
551 if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
552 pStackLimit++;
554 #endif
556 switch( pOp->opcode ){
558 /*****************************************************************************
559 ** What follows is a massive switch statement where each case implements a
560 ** separate instruction in the virtual machine. If we follow the usual
561 ** indentation conventions, each case should be indented by 6 spaces. But
562 ** that is a lot of wasted space on the left margin. So the code within
563 ** the switch statement will break with convention and be flush-left. Another
564 ** big comment (similar to this one) will mark the point in the code where
565 ** we transition back to normal indentation.
567 ** The formatting of each case is important. The makefile for SQLite
568 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
569 ** file looking for lines that begin with "case OP_". The opcodes.h files
570 ** will be filled with #defines that give unique integer values to each
571 ** opcode and the opcodes.c file is filled with an array of strings where
572 ** each string is the symbolic name for the corresponding opcode. If the
573 ** case statement is followed by a comment of the form "/# same as ... #/"
574 ** that comment is used to determine the particular value of the opcode.
576 ** If a comment on the same line as the "case OP_" construction contains
577 ** the word "no-push", then the opcode is guarenteed not to grow the
578 ** vdbe stack when it is executed. See function opcode() in
579 ** vdbeaux.c for details.
581 ** Documentation about VDBE opcodes is generated by scanning this file
582 ** for lines of that contain "Opcode:". That line and all subsequent
583 ** comment lines are used in the generation of the opcode.html documentation
584 ** file.
586 ** SUMMARY:
588 ** Formatting is important to scripts that scan this file.
589 ** Do not deviate from the formatting style currently in use.
591 *****************************************************************************/
593 /* Opcode: Goto * P2 *
595 ** An unconditional jump to address P2.
596 ** The next instruction executed will be
597 ** the one at index P2 from the beginning of
598 ** the program.
600 case OP_Goto: { /* no-push */
601 CHECK_FOR_INTERRUPT;
602 pc = pOp->p2 - 1;
603 break;
606 /* Opcode: Gosub * P2 *
608 ** Push the current address plus 1 onto the return address stack
609 ** and then jump to address P2.
611 ** The return address stack is of limited depth. If too many
612 ** OP_Gosub operations occur without intervening OP_Returns, then
613 ** the return address stack will fill up and processing will abort
614 ** with a fatal error.
616 case OP_Gosub: { /* no-push */
617 assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
618 p->returnStack[p->returnDepth++] = pc+1;
619 pc = pOp->p2 - 1;
620 break;
623 /* Opcode: Return * * *
625 ** Jump immediately to the next instruction after the last unreturned
626 ** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
627 ** processing aborts with a fatal error.
629 case OP_Return: { /* no-push */
630 assert( p->returnDepth>0 );
631 p->returnDepth--;
632 pc = p->returnStack[p->returnDepth] - 1;
633 break;
636 /* Opcode: Halt P1 P2 *
638 ** Exit immediately. All open cursors, Lists, Sorts, etc are closed
639 ** automatically.
641 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
642 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
643 ** For errors, it can be some other value. If P1!=0 then P2 will determine
644 ** whether or not to rollback the current transaction. Do not rollback
645 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
646 ** then back out all changes that have occurred during this execution of the
647 ** VDBE, but do not rollback the transaction.
649 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
650 ** every program. So a jump past the last instruction of the program
651 ** is the same as executing Halt.
653 case OP_Halt: { /* no-push */
654 p->pTos = pTos;
655 p->rc = pOp->p1;
656 p->pc = pc;
657 p->errorAction = pOp->p2;
658 if( pOp->p3 ){
659 sqlite3SetString(&p->zErrMsg, pOp->p3, NULL);
661 rc = sqlite3VdbeHalt(p);
662 assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
663 if( rc==SQLITE_BUSY ){
664 p->rc = SQLITE_BUSY;
665 return SQLITE_BUSY;
667 return p->rc ? SQLITE_ERROR : SQLITE_DONE;
670 /* Opcode: Integer P1 * P3
672 ** The integer value P1 is pushed onto the stack. If P3 is not zero
673 ** then it is assumed to be a string representation of the same integer.
674 ** If P1 is zero and P3 is not zero, then the value is derived from P3.
676 ** If the value cannot be represented as a 32-bits then its value
677 ** will be in P3.
679 case OP_Integer: {
680 pTos++;
681 if( pOp->p3==0 ){
682 pTos->flags = MEM_Int;
683 pTos->i = pOp->p1;
684 }else{
685 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
686 pTos->z = pOp->p3;
687 pTos->n = strlen(pTos->z);
688 pTos->enc = SQLITE_UTF8;
689 pTos->i = sqlite3VdbeIntValue(pTos);
690 pTos->flags |= MEM_Int;
692 break;
695 /* Opcode: Real * * P3
697 ** The string value P3 is converted to a real and pushed on to the stack.
699 case OP_Real: { /* same as TK_FLOAT, */
700 pTos++;
701 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
702 pTos->z = pOp->p3;
703 pTos->n = strlen(pTos->z);
704 pTos->enc = SQLITE_UTF8;
705 pTos->r = sqlite3VdbeRealValue(pTos);
706 pTos->flags |= MEM_Real;
707 sqlite3VdbeChangeEncoding(pTos, db->enc);
708 break;
711 /* Opcode: String8 * * P3
713 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed
714 ** into an OP_String before it is executed for the first time.
716 case OP_String8: { /* same as TK_STRING */
717 #ifndef SQLITE_OMIT_UTF16
718 pOp->opcode = OP_String;
720 assert( pOp->p3!=0 );
721 if( db->enc!=SQLITE_UTF8 ){
722 pTos++;
723 sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
724 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, db->enc) ) goto no_mem;
725 if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
726 pTos->flags &= ~(MEM_Dyn);
727 pTos->flags |= MEM_Static;
728 if( pOp->p3type==P3_DYNAMIC ){
729 sqliteFree(pOp->p3);
731 pOp->p3type = P3_DYNAMIC;
732 pOp->p3 = pTos->z;
733 break;
735 #endif
736 /* Otherwise fall through to the next case, OP_String */
739 /* Opcode: String * * P3
741 ** The string value P3 is pushed onto the stack. If P3==0 then a
742 ** NULL is pushed onto the stack. P3 is assumed to be a nul terminated
743 ** string encoded with the database native encoding.
745 case OP_String: {
746 pTos++;
747 assert( pOp->p3!=0 );
748 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
749 pTos->z = pOp->p3;
750 #ifndef SQLITE_OMIT_UTF16
751 if( db->enc==SQLITE_UTF8 ){
752 pTos->n = strlen(pTos->z);
753 }else{
754 pTos->n = sqlite3utf16ByteLen(pTos->z, -1);
756 #else
757 assert( db->enc==SQLITE_UTF8 );
758 pTos->n = strlen(pTos->z);
759 #endif
760 pTos->enc = db->enc;
761 break;
764 /* Opcode: Null * * *
766 ** Push a NULL onto the stack.
768 case OP_Null: {
769 pTos++;
770 pTos->flags = MEM_Null;
771 break;
775 #ifndef SQLITE_OMIT_BLOB_LITERAL
776 /* Opcode: HexBlob * * P3
778 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
779 ** vdbe stack.
781 ** The first time this instruction executes, in transforms itself into a
782 ** 'Blob' opcode with a binary blob as P3.
784 case OP_HexBlob: { /* same as TK_BLOB */
785 pOp->opcode = OP_Blob;
786 pOp->p1 = strlen(pOp->p3)/2;
787 if( pOp->p1 ){
788 char *zBlob = sqlite3HexToBlob(pOp->p3);
789 if( !zBlob ) goto no_mem;
790 if( pOp->p3type==P3_DYNAMIC ){
791 sqliteFree(pOp->p3);
793 pOp->p3 = zBlob;
794 pOp->p3type = P3_DYNAMIC;
795 }else{
796 if( pOp->p3type==P3_DYNAMIC ){
797 sqliteFree(pOp->p3);
799 pOp->p3type = P3_STATIC;
800 pOp->p3 = "";
803 /* Fall through to the next case, OP_Blob. */
806 /* Opcode: Blob P1 * P3
808 ** P3 points to a blob of data P1 bytes long. Push this
809 ** value onto the stack. This instruction is not coded directly
810 ** by the compiler. Instead, the compiler layer specifies
811 ** an OP_HexBlob opcode, with the hex string representation of
812 ** the blob as P3. This opcode is transformed to an OP_Blob
813 ** the first time it is executed.
815 case OP_Blob: {
816 pTos++;
817 sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
818 break;
820 #endif /* SQLITE_OMIT_BLOB_LITERAL */
822 /* Opcode: Variable P1 * *
824 ** Push the value of variable P1 onto the stack. A variable is
825 ** an unknown in the original SQL string as handed to sqlite3_compile().
826 ** Any occurance of the '?' character in the original SQL is considered
827 ** a variable. Variables in the SQL string are number from left to
828 ** right beginning with 1. The values of variables are set using the
829 ** sqlite3_bind() API.
831 case OP_Variable: {
832 int j = pOp->p1 - 1;
833 assert( j>=0 && j<p->nVar );
835 pTos++;
836 sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
837 break;
840 /* Opcode: Pop P1 * *
842 ** P1 elements are popped off of the top of stack and discarded.
844 case OP_Pop: { /* no-push */
845 assert( pOp->p1>=0 );
846 popStack(&pTos, pOp->p1);
847 assert( pTos>=&p->aStack[-1] );
848 break;
851 /* Opcode: Dup P1 P2 *
853 ** A copy of the P1-th element of the stack
854 ** is made and pushed onto the top of the stack.
855 ** The top of the stack is element 0. So the
856 ** instruction "Dup 0 0 0" will make a copy of the
857 ** top of the stack.
859 ** If the content of the P1-th element is a dynamically
860 ** allocated string, then a new copy of that string
861 ** is made if P2==0. If P2!=0, then just a pointer
862 ** to the string is copied.
864 ** Also see the Pull instruction.
866 case OP_Dup: {
867 Mem *pFrom = &pTos[-pOp->p1];
868 assert( pFrom<=pTos && pFrom>=p->aStack );
869 pTos++;
870 sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
871 if( pOp->p2 ){
872 Deephemeralize(pTos);
874 break;
877 /* Opcode: Pull P1 * *
879 ** The P1-th element is removed from its current location on
880 ** the stack and pushed back on top of the stack. The
881 ** top of the stack is element 0, so "Pull 0 0 0" is
882 ** a no-op. "Pull 1 0 0" swaps the top two elements of
883 ** the stack.
885 ** See also the Dup instruction.
887 case OP_Pull: { /* no-push */
888 Mem *pFrom = &pTos[-pOp->p1];
889 int i;
890 Mem ts;
892 ts = *pFrom;
893 Deephemeralize(pTos);
894 for(i=0; i<pOp->p1; i++, pFrom++){
895 Deephemeralize(&pFrom[1]);
896 assert( (pFrom->flags & MEM_Ephem)==0 );
897 *pFrom = pFrom[1];
898 if( pFrom->flags & MEM_Short ){
899 assert( pFrom->flags & (MEM_Str|MEM_Blob) );
900 assert( pFrom->z==pFrom[1].zShort );
901 pFrom->z = pFrom->zShort;
904 *pTos = ts;
905 if( pTos->flags & MEM_Short ){
906 assert( pTos->flags & (MEM_Str|MEM_Blob) );
907 assert( pTos->z==pTos[-pOp->p1].zShort );
908 pTos->z = pTos->zShort;
910 break;
913 /* Opcode: Push P1 * *
915 ** Overwrite the value of the P1-th element down on the
916 ** stack (P1==0 is the top of the stack) with the value
917 ** of the top of the stack. Then pop the top of the stack.
919 case OP_Push: { /* no-push */
920 Mem *pTo = &pTos[-pOp->p1];
922 assert( pTo>=p->aStack );
923 sqlite3VdbeMemMove(pTo, pTos);
924 pTos--;
925 break;
928 /* Opcode: Callback P1 * *
930 ** Pop P1 values off the stack and form them into an array. Then
931 ** invoke the callback function using the newly formed array as the
932 ** 3rd parameter.
934 case OP_Callback: { /* no-push */
935 int i;
936 assert( p->nResColumn==pOp->p1 );
938 for(i=0; i<pOp->p1; i++){
939 Mem *pVal = &pTos[0-i];
940 sqlite3VdbeMemNulTerminate(pVal);
941 storeTypeInfo(pVal, db->enc);
944 p->resOnStack = 1;
945 p->nCallback++;
946 p->popStack = pOp->p1;
947 p->pc = pc + 1;
948 p->pTos = pTos;
949 return SQLITE_ROW;
952 /* Opcode: Concat P1 P2 *
954 ** Look at the first P1+2 elements of the stack. Append them all
955 ** together with the lowest element first. The original P1+2 elements
956 ** are popped from the stack if P2==0 and retained if P2==1. If
957 ** any element of the stack is NULL, then the result is NULL.
959 ** When P1==1, this routine makes a copy of the top stack element
960 ** into memory obtained from sqliteMalloc().
962 case OP_Concat: { /* same as TK_CONCAT */
963 char *zNew;
964 int nByte;
965 int nField;
966 int i, j;
967 Mem *pTerm;
969 /* Loop through the stack elements to see how long the result will be. */
970 nField = pOp->p1 + 2;
971 pTerm = &pTos[1-nField];
972 nByte = 0;
973 for(i=0; i<nField; i++, pTerm++){
974 assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
975 if( pTerm->flags&MEM_Null ){
976 nByte = -1;
977 break;
979 Stringify(pTerm, db->enc);
980 nByte += pTerm->n;
983 if( nByte<0 ){
984 /* If nByte is less than zero, then there is a NULL value on the stack.
985 ** In this case just pop the values off the stack (if required) and
986 ** push on a NULL.
988 if( pOp->p2==0 ){
989 popStack(&pTos, nField);
991 pTos++;
992 pTos->flags = MEM_Null;
993 }else{
994 /* Otherwise malloc() space for the result and concatenate all the
995 ** stack values.
997 zNew = sqliteMallocRaw( nByte+2 );
998 if( zNew==0 ) goto no_mem;
999 j = 0;
1000 pTerm = &pTos[1-nField];
1001 for(i=j=0; i<nField; i++, pTerm++){
1002 int n = pTerm->n;
1003 assert( pTerm->flags & MEM_Str );
1004 memcpy(&zNew[j], pTerm->z, n);
1005 j += n;
1007 zNew[j] = 0;
1008 zNew[j+1] = 0;
1009 assert( j==nByte );
1011 if( pOp->p2==0 ){
1012 popStack(&pTos, nField);
1014 pTos++;
1015 pTos->n = j;
1016 pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
1017 pTos->xDel = 0;
1018 pTos->enc = db->enc;
1019 pTos->z = zNew;
1021 break;
1024 /* Opcode: Add * * *
1026 ** Pop the top two elements from the stack, add them together,
1027 ** and push the result back onto the stack. If either element
1028 ** is a string then it is converted to a double using the atof()
1029 ** function before the addition.
1030 ** If either operand is NULL, the result is NULL.
1032 /* Opcode: Multiply * * *
1034 ** Pop the top two elements from the stack, multiply them together,
1035 ** and push the result back onto the stack. If either element
1036 ** is a string then it is converted to a double using the atof()
1037 ** function before the multiplication.
1038 ** If either operand is NULL, the result is NULL.
1040 /* Opcode: Subtract * * *
1042 ** Pop the top two elements from the stack, subtract the
1043 ** first (what was on top of the stack) from the second (the
1044 ** next on stack)
1045 ** and push the result back onto the stack. If either element
1046 ** is a string then it is converted to a double using the atof()
1047 ** function before the subtraction.
1048 ** If either operand is NULL, the result is NULL.
1050 /* Opcode: Divide * * *
1052 ** Pop the top two elements from the stack, divide the
1053 ** first (what was on top of the stack) from the second (the
1054 ** next on stack)
1055 ** and push the result back onto the stack. If either element
1056 ** is a string then it is converted to a double using the atof()
1057 ** function before the division. Division by zero returns NULL.
1058 ** If either operand is NULL, the result is NULL.
1060 /* Opcode: Remainder * * *
1062 ** Pop the top two elements from the stack, divide the
1063 ** first (what was on top of the stack) from the second (the
1064 ** next on stack)
1065 ** and push the remainder after division onto the stack. If either element
1066 ** is a string then it is converted to a double using the atof()
1067 ** function before the division. Division by zero returns NULL.
1068 ** If either operand is NULL, the result is NULL.
1070 case OP_Add: /* same as TK_PLUS, no-push */
1071 case OP_Subtract: /* same as TK_MINUS, no-push */
1072 case OP_Multiply: /* same as TK_STAR, no-push */
1073 case OP_Divide: /* same as TK_SLASH, no-push */
1074 case OP_Remainder: { /* same as TK_REM, no-push */
1075 Mem *pNos = &pTos[-1];
1076 assert( pNos>=p->aStack );
1077 if( ((pTos->flags | pNos->flags) & MEM_Null)!=0 ){
1078 Release(pTos);
1079 pTos--;
1080 Release(pTos);
1081 pTos->flags = MEM_Null;
1082 }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
1083 i64 a, b;
1084 a = pTos->i;
1085 b = pNos->i;
1086 switch( pOp->opcode ){
1087 case OP_Add: b += a; break;
1088 case OP_Subtract: b -= a; break;
1089 case OP_Multiply: b *= a; break;
1090 case OP_Divide: {
1091 if( a==0 ) goto divide_by_zero;
1092 b /= a;
1093 break;
1095 default: {
1096 if( a==0 ) goto divide_by_zero;
1097 b %= a;
1098 break;
1101 Release(pTos);
1102 pTos--;
1103 Release(pTos);
1104 pTos->i = b;
1105 pTos->flags = MEM_Int;
1106 }else{
1107 double a, b;
1108 a = sqlite3VdbeRealValue(pTos);
1109 b = sqlite3VdbeRealValue(pNos);
1110 switch( pOp->opcode ){
1111 case OP_Add: b += a; break;
1112 case OP_Subtract: b -= a; break;
1113 case OP_Multiply: b *= a; break;
1114 case OP_Divide: {
1115 if( a==0.0 ) goto divide_by_zero;
1116 b /= a;
1117 break;
1119 default: {
1120 int ia = (int)a;
1121 int ib = (int)b;
1122 if( ia==0.0 ) goto divide_by_zero;
1123 b = ib % ia;
1124 break;
1127 Release(pTos);
1128 pTos--;
1129 Release(pTos);
1130 pTos->r = b;
1131 pTos->flags = MEM_Real;
1133 break;
1135 divide_by_zero:
1136 Release(pTos);
1137 pTos--;
1138 Release(pTos);
1139 pTos->flags = MEM_Null;
1140 break;
1143 /* Opcode: CollSeq * * P3
1145 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
1146 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1147 ** be returned. This is used by the built-in min(), max() and nullif()
1148 ** functions.
1150 ** The interface used by the implementation of the aforementioned functions
1151 ** to retrieve the collation sequence set by this opcode is not available
1152 ** publicly, only to user functions defined in func.c.
1154 case OP_CollSeq: { /* no-push */
1155 assert( pOp->p3type==P3_COLLSEQ );
1156 break;
1159 /* Opcode: Function P1 P2 P3
1161 ** Invoke a user function (P3 is a pointer to a Function structure that
1162 ** defines the function) with P1 arguments taken from the stack. Pop all
1163 ** arguments from the stack and push back the result.
1165 ** P2 is a 32-bit bitmask indicating whether or not each argument to the
1166 ** function was determined to be constant at compile time. If the first
1167 ** argument was constant then bit 0 of P2 is set. This is used to determine
1168 ** whether meta data associated with a user function argument using the
1169 ** sqlite3_set_auxdata() API may be safely retained until the next
1170 ** invocation of this opcode.
1172 ** See also: AggFunc
1174 case OP_Function: {
1175 int i;
1176 Mem *pArg;
1177 sqlite3_context ctx;
1178 sqlite3_value **apVal;
1179 int n = pOp->p1;
1181 n = pOp->p1;
1182 apVal = p->apArg;
1183 assert( apVal || n==0 );
1185 pArg = &pTos[1-n];
1186 for(i=0; i<n; i++, pArg++){
1187 apVal[i] = pArg;
1188 storeTypeInfo(pArg, db->enc);
1191 assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
1192 if( pOp->p3type==P3_FUNCDEF ){
1193 ctx.pFunc = (FuncDef*)pOp->p3;
1194 ctx.pVdbeFunc = 0;
1195 }else{
1196 ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
1197 ctx.pFunc = ctx.pVdbeFunc->pFunc;
1200 ctx.s.flags = MEM_Null;
1201 ctx.s.z = 0;
1202 ctx.s.xDel = 0;
1203 ctx.isError = 0;
1204 if( ctx.pFunc->needCollSeq ){
1205 assert( pOp>p->aOp );
1206 assert( pOp[-1].p3type==P3_COLLSEQ );
1207 assert( pOp[-1].opcode==OP_CollSeq );
1208 ctx.pColl = (CollSeq *)pOp[-1].p3;
1210 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1211 (*ctx.pFunc->xFunc)(&ctx, n, apVal);
1212 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
1213 if( sqlite3_malloc_failed ) goto no_mem;
1214 popStack(&pTos, n);
1216 /* If any auxilary data functions have been called by this user function,
1217 ** immediately call the destructor for any non-static values.
1219 if( ctx.pVdbeFunc ){
1220 sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p2);
1221 pOp->p3 = (char *)ctx.pVdbeFunc;
1222 pOp->p3type = P3_VDBEFUNC;
1225 /* Copy the result of the function to the top of the stack */
1226 sqlite3VdbeChangeEncoding(&ctx.s, db->enc);
1227 pTos++;
1228 pTos->flags = 0;
1229 sqlite3VdbeMemMove(pTos, &ctx.s);
1231 /* If the function returned an error, throw an exception */
1232 if( ctx.isError ){
1233 if( !(pTos->flags&MEM_Str) ){
1234 sqlite3SetString(&p->zErrMsg, "user function error", NULL);
1235 }else{
1236 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pTos), NULL);
1237 sqlite3VdbeChangeEncoding(pTos, db->enc);
1239 rc = SQLITE_ERROR;
1241 break;
1244 /* Opcode: BitAnd * * *
1246 ** Pop the top two elements from the stack. Convert both elements
1247 ** to integers. Push back onto the stack the bit-wise AND of the
1248 ** two elements.
1249 ** If either operand is NULL, the result is NULL.
1251 /* Opcode: BitOr * * *
1253 ** Pop the top two elements from the stack. Convert both elements
1254 ** to integers. Push back onto the stack the bit-wise OR of the
1255 ** two elements.
1256 ** If either operand is NULL, the result is NULL.
1258 /* Opcode: ShiftLeft * * *
1260 ** Pop the top two elements from the stack. Convert both elements
1261 ** to integers. Push back onto the stack the second element shifted
1262 ** left by N bits where N is the top element on the stack.
1263 ** If either operand is NULL, the result is NULL.
1265 /* Opcode: ShiftRight * * *
1267 ** Pop the top two elements from the stack. Convert both elements
1268 ** to integers. Push back onto the stack the second element shifted
1269 ** right by N bits where N is the top element on the stack.
1270 ** If either operand is NULL, the result is NULL.
1272 case OP_BitAnd: /* same as TK_BITAND, no-push */
1273 case OP_BitOr: /* same as TK_BITOR, no-push */
1274 case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
1275 case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
1276 Mem *pNos = &pTos[-1];
1277 int a, b;
1279 assert( pNos>=p->aStack );
1280 if( (pTos->flags | pNos->flags) & MEM_Null ){
1281 popStack(&pTos, 2);
1282 pTos++;
1283 pTos->flags = MEM_Null;
1284 break;
1286 a = sqlite3VdbeIntValue(pNos);
1287 b = sqlite3VdbeIntValue(pTos);
1288 switch( pOp->opcode ){
1289 case OP_BitAnd: a &= b; break;
1290 case OP_BitOr: a |= b; break;
1291 case OP_ShiftLeft: a <<= b; break;
1292 case OP_ShiftRight: a >>= b; break;
1293 default: /* CANT HAPPEN */ break;
1295 Release(pTos);
1296 pTos--;
1297 Release(pTos);
1298 pTos->i = a;
1299 pTos->flags = MEM_Int;
1300 break;
1303 /* Opcode: AddImm P1 * *
1305 ** Add the value P1 to whatever is on top of the stack. The result
1306 ** is always an integer.
1308 ** To force the top of the stack to be an integer, just add 0.
1310 case OP_AddImm: { /* no-push */
1311 assert( pTos>=p->aStack );
1312 Integerify(pTos);
1313 pTos->i += pOp->p1;
1314 break;
1317 /* Opcode: ForceInt P1 P2 *
1319 ** Convert the top of the stack into an integer. If the current top of
1320 ** the stack is not numeric (meaning that is is a NULL or a string that
1321 ** does not look like an integer or floating point number) then pop the
1322 ** stack and jump to P2. If the top of the stack is numeric then
1323 ** convert it into the least integer that is greater than or equal to its
1324 ** current value if P1==0, or to the least integer that is strictly
1325 ** greater than its current value if P1==1.
1327 case OP_ForceInt: { /* no-push */
1328 i64 v;
1329 assert( pTos>=p->aStack );
1330 applyAffinity(pTos, SQLITE_AFF_INTEGER, db->enc);
1331 if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
1332 Release(pTos);
1333 pTos--;
1334 pc = pOp->p2 - 1;
1335 break;
1337 if( pTos->flags & MEM_Int ){
1338 v = pTos->i + (pOp->p1!=0);
1339 }else{
1340 Realify(pTos);
1341 v = (int)pTos->r;
1342 if( pTos->r>(double)v ) v++;
1343 if( pOp->p1 && pTos->r==(double)v ) v++;
1345 Release(pTos);
1346 pTos->i = v;
1347 pTos->flags = MEM_Int;
1348 break;
1351 /* Opcode: MustBeInt P1 P2 *
1353 ** Force the top of the stack to be an integer. If the top of the
1354 ** stack is not an integer and cannot be converted into an integer
1355 ** with out data loss, then jump immediately to P2, or if P2==0
1356 ** raise an SQLITE_MISMATCH exception.
1358 ** If the top of the stack is not an integer and P2 is not zero and
1359 ** P1 is 1, then the stack is popped. In all other cases, the depth
1360 ** of the stack is unchanged.
1362 case OP_MustBeInt: { /* no-push */
1363 assert( pTos>=p->aStack );
1364 applyAffinity(pTos, SQLITE_AFF_INTEGER, db->enc);
1365 if( (pTos->flags & MEM_Int)==0 ){
1366 if( pOp->p2==0 ){
1367 rc = SQLITE_MISMATCH;
1368 goto abort_due_to_error;
1369 }else{
1370 if( pOp->p1 ) popStack(&pTos, 1);
1371 pc = pOp->p2 - 1;
1373 }else{
1374 Release(pTos);
1375 pTos->flags = MEM_Int;
1377 break;
1380 /* Opcode: Eq P1 P2 P3
1382 ** Pop the top two elements from the stack. If they are equal, then
1383 ** jump to instruction P2. Otherwise, continue to the next instruction.
1385 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
1386 ** jump. If the 0x100 bit of P1 is false then fall thru if either operand
1387 ** is NULL.
1389 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
1390 ** 'n', 't', 'i' or 'o' - or 0x00. An attempt is made to coerce both values
1391 ** according to the affinity before the comparison is made. If the byte is
1392 ** 0x00, then numeric affinity is used.
1394 ** Once any conversions have taken place, and neither value is NULL,
1395 ** the values are compared. If both values are blobs, or both are text,
1396 ** then memcmp() is used to determine the results of the comparison. If
1397 ** both values are numeric, then a numeric comparison is used. If the
1398 ** two values are of different types, then they are inequal.
1400 ** If P2 is zero, do not jump. Instead, push an integer 1 onto the
1401 ** stack if the jump would have been taken, or a 0 if not. Push a
1402 ** NULL if either operand was NULL.
1404 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
1405 ** structure) that defines how to compare text.
1407 /* Opcode: Ne P1 P2 P3
1409 ** This works just like the Eq opcode except that the jump is taken if
1410 ** the operands from the stack are not equal. See the Eq opcode for
1411 ** additional information.
1413 /* Opcode: Lt P1 P2 P3
1415 ** This works just like the Eq opcode except that the jump is taken if
1416 ** the 2nd element down on the stack is less than the top of the stack.
1417 ** See the Eq opcode for additional information.
1419 /* Opcode: Le P1 P2 P3
1421 ** This works just like the Eq opcode except that the jump is taken if
1422 ** the 2nd element down on the stack is less than or equal to the
1423 ** top of the stack. See the Eq opcode for additional information.
1425 /* Opcode: Gt P1 P2 P3
1427 ** This works just like the Eq opcode except that the jump is taken if
1428 ** the 2nd element down on the stack is greater than the top of the stack.
1429 ** See the Eq opcode for additional information.
1431 /* Opcode: Ge P1 P2 P3
1433 ** This works just like the Eq opcode except that the jump is taken if
1434 ** the 2nd element down on the stack is greater than or equal to the
1435 ** top of the stack. See the Eq opcode for additional information.
1437 case OP_Eq: /* same as TK_EQ, no-push */
1438 case OP_Ne: /* same as TK_NE, no-push */
1439 case OP_Lt: /* same as TK_LT, no-push */
1440 case OP_Le: /* same as TK_LE, no-push */
1441 case OP_Gt: /* same as TK_GT, no-push */
1442 case OP_Ge: { /* same as TK_GE, no-push */
1443 Mem *pNos;
1444 int flags;
1445 int res;
1446 char affinity;
1448 pNos = &pTos[-1];
1449 flags = pTos->flags|pNos->flags;
1451 /* If either value is a NULL P2 is not zero, take the jump if the least
1452 ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
1453 ** the stack.
1455 if( flags&MEM_Null ){
1456 popStack(&pTos, 2);
1457 if( pOp->p2 ){
1458 if( pOp->p1 & 0x100 ) pc = pOp->p2-1;
1459 }else{
1460 pTos++;
1461 pTos->flags = MEM_Null;
1463 break;
1466 affinity = pOp->p1 & 0xFF;
1467 if( affinity ){
1468 applyAffinity(pNos, affinity, db->enc);
1469 applyAffinity(pTos, affinity, db->enc);
1472 assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
1473 res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
1474 switch( pOp->opcode ){
1475 case OP_Eq: res = res==0; break;
1476 case OP_Ne: res = res!=0; break;
1477 case OP_Lt: res = res<0; break;
1478 case OP_Le: res = res<=0; break;
1479 case OP_Gt: res = res>0; break;
1480 default: res = res>=0; break;
1483 popStack(&pTos, 2);
1484 if( pOp->p2 ){
1485 if( res ){
1486 pc = pOp->p2-1;
1488 }else{
1489 pTos++;
1490 pTos->flags = MEM_Int;
1491 pTos->i = res;
1493 break;
1496 /* Opcode: And * * *
1498 ** Pop two values off the stack. Take the logical AND of the
1499 ** two values and push the resulting boolean value back onto the
1500 ** stack.
1502 /* Opcode: Or * * *
1504 ** Pop two values off the stack. Take the logical OR of the
1505 ** two values and push the resulting boolean value back onto the
1506 ** stack.
1508 case OP_And: /* same as TK_AND, no-push */
1509 case OP_Or: { /* same as TK_OR, no-push */
1510 Mem *pNos = &pTos[-1];
1511 int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
1513 assert( pNos>=p->aStack );
1514 if( pTos->flags & MEM_Null ){
1515 v1 = 2;
1516 }else{
1517 Integerify(pTos);
1518 v1 = pTos->i==0;
1520 if( pNos->flags & MEM_Null ){
1521 v2 = 2;
1522 }else{
1523 Integerify(pNos);
1524 v2 = pNos->i==0;
1526 if( pOp->opcode==OP_And ){
1527 static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1528 v1 = and_logic[v1*3+v2];
1529 }else{
1530 static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1531 v1 = or_logic[v1*3+v2];
1533 popStack(&pTos, 2);
1534 pTos++;
1535 if( v1==2 ){
1536 pTos->flags = MEM_Null;
1537 }else{
1538 pTos->i = v1==0;
1539 pTos->flags = MEM_Int;
1541 break;
1544 /* Opcode: Negative * * *
1546 ** Treat the top of the stack as a numeric quantity. Replace it
1547 ** with its additive inverse. If the top of the stack is NULL
1548 ** its value is unchanged.
1550 /* Opcode: AbsValue * * *
1552 ** Treat the top of the stack as a numeric quantity. Replace it
1553 ** with its absolute value. If the top of the stack is NULL
1554 ** its value is unchanged.
1556 case OP_Negative: /* same as TK_UMINUS, no-push */
1557 case OP_AbsValue: {
1558 assert( pTos>=p->aStack );
1559 if( pTos->flags & MEM_Real ){
1560 Release(pTos);
1561 if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1562 pTos->r = -pTos->r;
1564 pTos->flags = MEM_Real;
1565 }else if( pTos->flags & MEM_Int ){
1566 Release(pTos);
1567 if( pOp->opcode==OP_Negative || pTos->i<0 ){
1568 pTos->i = -pTos->i;
1570 pTos->flags = MEM_Int;
1571 }else if( pTos->flags & MEM_Null ){
1572 /* Do nothing */
1573 }else{
1574 Realify(pTos);
1575 if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1576 pTos->r = -pTos->r;
1578 pTos->flags = MEM_Real;
1580 break;
1583 /* Opcode: Not * * *
1585 ** Interpret the top of the stack as a boolean value. Replace it
1586 ** with its complement. If the top of the stack is NULL its value
1587 ** is unchanged.
1589 case OP_Not: { /* same as TK_NOT, no-push */
1590 assert( pTos>=p->aStack );
1591 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1592 Integerify(pTos);
1593 assert( (pTos->flags & MEM_Dyn)==0 );
1594 pTos->i = !pTos->i;
1595 pTos->flags = MEM_Int;
1596 break;
1599 /* Opcode: BitNot * * *
1601 ** Interpret the top of the stack as an value. Replace it
1602 ** with its ones-complement. If the top of the stack is NULL its
1603 ** value is unchanged.
1605 case OP_BitNot: { /* same as TK_BITNOT, no-push */
1606 assert( pTos>=p->aStack );
1607 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1608 Integerify(pTos);
1609 assert( (pTos->flags & MEM_Dyn)==0 );
1610 pTos->i = ~pTos->i;
1611 pTos->flags = MEM_Int;
1612 break;
1615 /* Opcode: Noop * * *
1617 ** Do nothing. This instruction is often useful as a jump
1618 ** destination.
1620 case OP_Noop: { /* no-push */
1621 break;
1624 /* Opcode: If P1 P2 *
1626 ** Pop a single boolean from the stack. If the boolean popped is
1627 ** true, then jump to p2. Otherwise continue to the next instruction.
1628 ** An integer is false if zero and true otherwise. A string is
1629 ** false if it has zero length and true otherwise.
1631 ** If the value popped of the stack is NULL, then take the jump if P1
1632 ** is true and fall through if P1 is false.
1634 /* Opcode: IfNot P1 P2 *
1636 ** Pop a single boolean from the stack. If the boolean popped is
1637 ** false, then jump to p2. Otherwise continue to the next instruction.
1638 ** An integer is false if zero and true otherwise. A string is
1639 ** false if it has zero length and true otherwise.
1641 ** If the value popped of the stack is NULL, then take the jump if P1
1642 ** is true and fall through if P1 is false.
1644 case OP_If: /* no-push */
1645 case OP_IfNot: { /* no-push */
1646 int c;
1647 assert( pTos>=p->aStack );
1648 if( pTos->flags & MEM_Null ){
1649 c = pOp->p1;
1650 }else{
1651 #ifdef SQLITE_OMIT_FLOATING_POINT
1652 c = sqlite3VdbeIntValue(pTos);
1653 #else
1654 c = sqlite3VdbeRealValue(pTos)!=0.0;
1655 #endif
1656 if( pOp->opcode==OP_IfNot ) c = !c;
1658 Release(pTos);
1659 pTos--;
1660 if( c ) pc = pOp->p2-1;
1661 break;
1664 /* Opcode: IsNull P1 P2 *
1666 ** If any of the top abs(P1) values on the stack are NULL, then jump
1667 ** to P2. Pop the stack P1 times if P1>0. If P1<0 leave the stack
1668 ** unchanged.
1670 case OP_IsNull: { /* same as TK_ISNULL, no-push */
1671 int i, cnt;
1672 Mem *pTerm;
1673 cnt = pOp->p1;
1674 if( cnt<0 ) cnt = -cnt;
1675 pTerm = &pTos[1-cnt];
1676 assert( pTerm>=p->aStack );
1677 for(i=0; i<cnt; i++, pTerm++){
1678 if( pTerm->flags & MEM_Null ){
1679 pc = pOp->p2-1;
1680 break;
1683 if( pOp->p1>0 ) popStack(&pTos, cnt);
1684 break;
1687 /* Opcode: NotNull P1 P2 *
1689 ** Jump to P2 if the top P1 values on the stack are all not NULL. Pop the
1690 ** stack if P1 times if P1 is greater than zero. If P1 is less than
1691 ** zero then leave the stack unchanged.
1693 case OP_NotNull: { /* same as TK_NOTNULL, no-push */
1694 int i, cnt;
1695 cnt = pOp->p1;
1696 if( cnt<0 ) cnt = -cnt;
1697 assert( &pTos[1-cnt] >= p->aStack );
1698 for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
1699 if( i>=cnt ) pc = pOp->p2-1;
1700 if( pOp->p1>0 ) popStack(&pTos, cnt);
1701 break;
1704 /* Opcode: SetNumColumns P1 P2 *
1706 ** Before the OP_Column opcode can be executed on a cursor, this
1707 ** opcode must be called to set the number of fields in the table.
1709 ** This opcode sets the number of columns for cursor P1 to P2.
1711 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
1712 ** before this op-code.
1714 case OP_SetNumColumns: { /* no-push */
1715 Cursor *pC;
1716 assert( (pOp->p1)<p->nCursor );
1717 assert( p->apCsr[pOp->p1]!=0 );
1718 pC = p->apCsr[pOp->p1];
1719 pC->nField = pOp->p2;
1720 break;
1723 /* Opcode: Column P1 P2 P3
1725 ** Interpret the data that cursor P1 points to as a structure built using
1726 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
1727 ** information about the format of the data.) Push onto the stack the value
1728 ** of the P2-th column contained in the data. If there are less that (P2+1)
1729 ** values in the record, push a NULL onto the stack.
1731 ** If the KeyAsData opcode has previously executed on this cursor, then the
1732 ** field might be extracted from the key rather than the data.
1734 ** If P1 is negative, then the record is stored on the stack rather than in
1735 ** a table. For P1==-1, the top of the stack is used. For P1==-2, the
1736 ** next on the stack is used. And so forth. The value pushed is always
1737 ** just a pointer into the record which is stored further down on the
1738 ** stack. The column value is not copied. The number of columns in the
1739 ** record is stored on the stack just above the record itself.
1741 case OP_Column: {
1742 u32 payloadSize; /* Number of bytes in the record */
1743 int p1 = pOp->p1; /* P1 value of the opcode */
1744 int p2 = pOp->p2; /* column number to retrieve */
1745 Cursor *pC = 0; /* The VDBE cursor */
1746 char *zRec; /* Pointer to complete record-data */
1747 BtCursor *pCrsr; /* The BTree cursor */
1748 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
1749 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
1750 u32 nField; /* number of fields in the record */
1751 u32 szHdr; /* Number of bytes in the record header */
1752 int len; /* The length of the serialized data for the column */
1753 int offset = 0; /* Offset into the data */
1754 int idx; /* Index into the header */
1755 int i; /* Loop counter */
1756 char *zData; /* Part of the record being decoded */
1757 Mem sMem; /* For storing the record being decoded */
1759 sMem.flags = 0;
1760 assert( p1<p->nCursor );
1761 pTos++;
1762 pTos->flags = MEM_Null;
1764 /* This block sets the variable payloadSize to be the total number of
1765 ** bytes in the record.
1767 ** zRec is set to be the complete text of the record if it is available.
1768 ** The complete record text is always available for pseudo-tables and
1769 ** when we are decoded a record from the stack. If the record is stored
1770 ** in a cursor, the complete record text might be available in the
1771 ** pC->aRow cache. Or it might not be. If the data is unavailable,
1772 ** zRec is set to NULL.
1774 ** We also compute the number of columns in the record. For cursors,
1775 ** the number of columns is stored in the Cursor.nField element. For
1776 ** records on the stack, the next entry down on the stack is an integer
1777 ** which is the number of records.
1779 assert( p1<0 || p->apCsr[p1]!=0 );
1780 if( p1<0 ){
1781 /* Take the record off of the stack */
1782 Mem *pRec = &pTos[p1];
1783 Mem *pCnt = &pRec[-1];
1784 assert( pRec>=p->aStack );
1785 assert( pRec->flags & MEM_Blob );
1786 payloadSize = pRec->n;
1787 zRec = pRec->z;
1788 assert( pCnt>=p->aStack );
1789 assert( pCnt->flags & MEM_Int );
1790 nField = pCnt->i;
1791 pCrsr = 0;
1792 }else if( (pC = p->apCsr[p1])->pCursor!=0 ){
1793 /* The record is stored in a B-Tree */
1794 rc = sqlite3VdbeCursorMoveto(pC);
1795 if( rc ) goto abort_due_to_error;
1796 zRec = 0;
1797 pCrsr = pC->pCursor;
1798 if( pC->nullRow ){
1799 payloadSize = 0;
1800 }else if( pC->cacheValid ){
1801 payloadSize = pC->payloadSize;
1802 zRec = pC->aRow;
1803 }else if( pC->isIndex ){
1804 i64 payloadSize64;
1805 sqlite3BtreeKeySize(pCrsr, &payloadSize64);
1806 payloadSize = payloadSize64;
1807 }else{
1808 sqlite3BtreeDataSize(pCrsr, &payloadSize);
1810 nField = pC->nField;
1811 #ifndef SQLITE_OMIT_TRIGGER
1812 }else if( pC->pseudoTable ){
1813 /* The record is the sole entry of a pseudo-table */
1814 payloadSize = pC->nData;
1815 zRec = pC->pData;
1816 pC->cacheValid = 0;
1817 assert( payloadSize==0 || zRec!=0 );
1818 nField = pC->nField;
1819 pCrsr = 0;
1820 #endif
1821 }else{
1822 zRec = 0;
1823 payloadSize = 0;
1824 pCrsr = 0;
1825 nField = 0;
1828 /* If payloadSize is 0, then just push a NULL onto the stack. */
1829 if( payloadSize==0 ){
1830 pTos->flags = MEM_Null;
1831 break;
1834 assert( p2<nField );
1836 /* Read and parse the table header. Store the results of the parse
1837 ** into the record header cache fields of the cursor.
1839 if( pC && pC->cacheValid ){
1840 aType = pC->aType;
1841 aOffset = pC->aOffset;
1842 }else{
1843 int avail; /* Number of bytes of available data */
1844 if( pC && pC->aType ){
1845 aType = pC->aType;
1846 }else{
1847 aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
1849 aOffset = &aType[nField];
1850 if( aType==0 ){
1851 goto no_mem;
1854 /* Figure out how many bytes are in the header */
1855 if( zRec ){
1856 zData = zRec;
1857 }else{
1858 if( pC->isIndex ){
1859 zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
1860 }else{
1861 zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
1863 /* If KeyFetch()/DataFetch() managed to get the entire payload,
1864 ** save the payload in the pC->aRow cache. That will save us from
1865 ** having to make additional calls to fetch the content portion of
1866 ** the record.
1868 if( avail>=payloadSize ){
1869 zRec = pC->aRow = zData;
1870 }else{
1871 pC->aRow = 0;
1874 idx = sqlite3GetVarint32(zData, &szHdr);
1877 /* The KeyFetch() or DataFetch() above are fast and will get the entire
1878 ** record header in most cases. But they will fail to get the complete
1879 ** record header if the record header does not fit on a single page
1880 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
1881 ** acquire the complete header text.
1883 if( !zRec && avail<szHdr ){
1884 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, szHdr, pC->isIndex, &sMem);
1885 if( rc!=SQLITE_OK ){
1886 goto op_column_out;
1888 zData = sMem.z;
1891 /* Scan the header and use it to fill in the aType[] and aOffset[]
1892 ** arrays. aType[i] will contain the type integer for the i-th
1893 ** column and aOffset[i] will contain the offset from the beginning
1894 ** of the record to the start of the data for the i-th column
1896 offset = szHdr;
1897 assert( offset>0 );
1898 i = 0;
1899 while( idx<szHdr && i<nField && offset<=payloadSize ){
1900 aOffset[i] = offset;
1901 idx += sqlite3GetVarint32(&zData[idx], &aType[i]);
1902 offset += sqlite3VdbeSerialTypeLen(aType[i]);
1903 i++;
1905 Release(&sMem);
1906 sMem.flags = MEM_Null;
1908 /* If i is less that nField, then there are less fields in this
1909 ** record than SetNumColumns indicated there are columns in the
1910 ** table. Set the offset for any extra columns not present in
1911 ** the record to 0. This tells code below to push a NULL onto the
1912 ** stack instead of deserializing a value from the record.
1914 while( i<nField ){
1915 aOffset[i++] = 0;
1918 /* The header should end at the start of data and the data should
1919 ** end at last byte of the record. If this is not the case then
1920 ** we are dealing with a malformed record.
1922 if( idx!=szHdr || offset!=payloadSize ){
1923 rc = SQLITE_CORRUPT;
1924 goto op_column_out;
1927 /* Remember all aType and aColumn information if we have a cursor
1928 ** to remember it in. */
1929 if( pC ){
1930 pC->payloadSize = payloadSize;
1931 pC->aType = aType;
1932 pC->aOffset = aOffset;
1933 pC->cacheValid = 1;
1937 /* Get the column information. If aOffset[p2] is non-zero, then
1938 ** deserialize the value from the record. If aOffset[p2] is zero,
1939 ** then there are not enough fields in the record to satisfy the
1940 ** request. The value is NULL in this case.
1942 if( aOffset[p2] ){
1943 assert( rc==SQLITE_OK );
1944 if( zRec ){
1945 zData = &zRec[aOffset[p2]];
1946 }else{
1947 len = sqlite3VdbeSerialTypeLen(aType[p2]);
1948 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
1949 if( rc!=SQLITE_OK ){
1950 goto op_column_out;
1952 zData = sMem.z;
1954 sqlite3VdbeSerialGet(zData, aType[p2], pTos);
1955 pTos->enc = db->enc;
1956 }else{
1957 if( pOp->p3 ){
1958 sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
1959 }else{
1960 pTos->flags = MEM_Null;
1964 /* If we dynamically allocated space to hold the data (in the
1965 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
1966 ** dynamically allocated space over to the pTos structure rather.
1967 ** This prevents a memory copy.
1969 if( (sMem.flags & MEM_Dyn)!=0 ){
1970 assert( pTos->flags & MEM_Ephem );
1971 assert( pTos->flags & (MEM_Str|MEM_Blob) );
1972 assert( pTos->z==sMem.z );
1973 assert( sMem.flags & MEM_Term );
1974 pTos->flags &= ~MEM_Ephem;
1975 pTos->flags |= MEM_Dyn|MEM_Term;
1978 /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
1979 ** can abandon sMem */
1980 rc = sqlite3VdbeMemMakeWriteable(pTos);
1982 op_column_out:
1983 /* Release the aType[] memory if we are not dealing with cursor */
1984 if( !pC || !pC->aType ){
1985 sqliteFree(aType);
1987 break;
1990 /* Opcode: MakeRecord P1 P2 P3
1992 ** Convert the top abs(P1) entries of the stack into a single entry
1993 ** suitable for use as a data record in a database table or as a key
1994 ** in an index. The details of the format are irrelavant as long as
1995 ** the OP_Column opcode can decode the record later and as long as the
1996 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
1997 ** records. Refer to source code comments for the details of the record
1998 ** format.
2000 ** The original stack entries are popped from the stack if P1>0 but
2001 ** remain on the stack if P1<0.
2003 ** The P2 argument is divided into two 16-bit words before it is processed.
2004 ** If the hi-word is non-zero, then an extra integer is read from the stack
2005 ** and appended to the record as a varint. If the low-word of P2 is not
2006 ** zero and one or more of the entries are NULL, then jump to the value of
2007 ** the low-word of P2. This feature can be used to skip a uniqueness test
2008 ** on indices.
2010 ** P3 may be a string that is P1 characters long. The nth character of the
2011 ** string indicates the column affinity that should be used for the nth
2012 ** field of the index key (i.e. the first character of P3 corresponds to the
2013 ** lowest element on the stack).
2015 ** The mapping from character to affinity is as follows:
2016 ** 'n' = NUMERIC.
2017 ** 'i' = INTEGER.
2018 ** 't' = TEXT.
2019 ** 'o' = NONE.
2021 ** If P3 is NULL then all index fields have the affinity NONE.
2023 case OP_MakeRecord: {
2024 /* Assuming the record contains N fields, the record format looks
2025 ** like this:
2027 ** ------------------------------------------------------------------------
2028 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2029 ** ------------------------------------------------------------------------
2031 ** Data(0) is taken from the lowest element of the stack and data(N-1) is
2032 ** the top of the stack.
2034 ** Each type field is a varint representing the serial type of the
2035 ** corresponding data element (see sqlite3VdbeSerialType()). The
2036 ** hdr-size field is also a varint which is the offset from the beginning
2037 ** of the record to data0.
2039 unsigned char *zNewRecord;
2040 unsigned char *zCsr;
2041 Mem *pRec;
2042 Mem *pRowid = 0;
2043 int nData = 0; /* Number of bytes of data space */
2044 int nHdr = 0; /* Number of bytes of header space */
2045 int nByte = 0; /* Space required for this record */
2046 int nVarint; /* Number of bytes in a varint */
2047 u32 serial_type; /* Type field */
2048 int containsNull = 0; /* True if any of the data fields are NULL */
2049 char zTemp[NBFS]; /* Space to hold small records */
2050 Mem *pData0;
2052 int leaveOnStack; /* If true, leave the entries on the stack */
2053 int nField; /* Number of fields in the record */
2054 int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
2055 int addRowid; /* True to append a rowid column at the end */
2056 char *zAffinity; /* The affinity string for the record */
2058 leaveOnStack = ((pOp->p1<0)?1:0);
2059 nField = pOp->p1 * (leaveOnStack?-1:1);
2060 jumpIfNull = (pOp->p2 & 0x00FFFFFF);
2061 addRowid = ((pOp->p2>>24) & 0x0000FFFF)?1:0;
2062 zAffinity = pOp->p3;
2064 pData0 = &pTos[1-nField];
2065 assert( pData0>=p->aStack );
2066 containsNull = 0;
2068 /* Loop through the elements that will make up the record to figure
2069 ** out how much space is required for the new record.
2071 for(pRec=pData0; pRec<=pTos; pRec++){
2072 if( zAffinity ){
2073 applyAffinity(pRec, zAffinity[pRec-pData0], db->enc);
2075 if( pRec->flags&MEM_Null ){
2076 containsNull = 1;
2078 serial_type = sqlite3VdbeSerialType(pRec);
2079 nData += sqlite3VdbeSerialTypeLen(serial_type);
2080 nHdr += sqlite3VarintLen(serial_type);
2083 /* If we have to append a varint rowid to this record, set 'rowid'
2084 ** to the value of the rowid and increase nByte by the amount of space
2085 ** required to store it and the 0x00 seperator byte.
2087 if( addRowid ){
2088 pRowid = &pTos[0-nField];
2089 assert( pRowid>=p->aStack );
2090 Integerify(pRowid);
2091 serial_type = sqlite3VdbeSerialType(pRowid);
2092 nData += sqlite3VdbeSerialTypeLen(serial_type);
2093 nHdr += sqlite3VarintLen(serial_type);
2096 /* Add the initial header varint and total the size */
2097 nHdr += nVarint = sqlite3VarintLen(nHdr);
2098 if( nVarint<sqlite3VarintLen(nHdr) ){
2099 nHdr++;
2101 nByte = nHdr+nData;
2103 /* Allocate space for the new record. */
2104 if( nByte>sizeof(zTemp) ){
2105 zNewRecord = sqliteMallocRaw(nByte);
2106 if( !zNewRecord ){
2107 goto no_mem;
2109 }else{
2110 zNewRecord = zTemp;
2113 /* Write the record */
2114 zCsr = zNewRecord;
2115 zCsr += sqlite3PutVarint(zCsr, nHdr);
2116 for(pRec=pData0; pRec<=pTos; pRec++){
2117 serial_type = sqlite3VdbeSerialType(pRec);
2118 zCsr += sqlite3PutVarint(zCsr, serial_type); /* serial type */
2120 if( addRowid ){
2121 zCsr += sqlite3PutVarint(zCsr, sqlite3VdbeSerialType(pRowid));
2123 for(pRec=pData0; pRec<=pTos; pRec++){
2124 zCsr += sqlite3VdbeSerialPut(zCsr, pRec); /* serial data */
2126 if( addRowid ){
2127 zCsr += sqlite3VdbeSerialPut(zCsr, pRowid);
2129 assert( zCsr==(zNewRecord+nByte) );
2131 /* Pop entries off the stack if required. Push the new record on. */
2132 if( !leaveOnStack ){
2133 popStack(&pTos, nField+addRowid);
2135 pTos++;
2136 pTos->n = nByte;
2137 if( nByte<=sizeof(zTemp) ){
2138 assert( zNewRecord==(unsigned char *)zTemp );
2139 pTos->z = pTos->zShort;
2140 memcpy(pTos->zShort, zTemp, nByte);
2141 pTos->flags = MEM_Blob | MEM_Short;
2142 }else{
2143 assert( zNewRecord!=(unsigned char *)zTemp );
2144 pTos->z = zNewRecord;
2145 pTos->flags = MEM_Blob | MEM_Dyn;
2146 pTos->xDel = 0;
2149 /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
2150 if( jumpIfNull && containsNull ){
2151 pc = jumpIfNull - 1;
2153 break;
2156 /* Opcode: Statement P1 * *
2158 ** Begin an individual statement transaction which is part of a larger
2159 ** BEGIN..COMMIT transaction. This is needed so that the statement
2160 ** can be rolled back after an error without having to roll back the
2161 ** entire transaction. The statement transaction will automatically
2162 ** commit when the VDBE halts.
2164 ** The statement is begun on the database file with index P1. The main
2165 ** database file has an index of 0 and the file used for temporary tables
2166 ** has an index of 1.
2168 case OP_Statement: { /* no-push */
2169 int i = pOp->p1;
2170 Btree *pBt;
2171 if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt) && !(db->autoCommit) ){
2172 assert( sqlite3BtreeIsInTrans(pBt) );
2173 if( !sqlite3BtreeIsInStmt(pBt) ){
2174 rc = sqlite3BtreeBeginStmt(pBt);
2177 break;
2180 /* Opcode: AutoCommit P1 P2 *
2182 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2183 ** back any currently active btree transactions. If there are any active
2184 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2186 ** This instruction causes the VM to halt.
2188 case OP_AutoCommit: { /* no-push */
2189 u8 i = pOp->p1;
2190 u8 rollback = pOp->p2;
2192 assert( i==1 || i==0 );
2193 assert( i==1 || rollback==0 );
2195 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
2197 if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2198 /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2199 ** still running, and a transaction is active, return an error indicating
2200 ** that the other VMs must complete first.
2202 sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2203 " transaction - SQL statements in progress", 0);
2204 rc = SQLITE_ERROR;
2205 }else if( i!=db->autoCommit ){
2206 db->autoCommit = i;
2207 if( pOp->p2 ){
2208 assert( i==1 );
2209 sqlite3RollbackAll(db);
2210 }else if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2211 p->pTos = pTos;
2212 p->pc = pc;
2213 db->autoCommit = 1-i;
2214 p->rc = SQLITE_BUSY;
2215 return SQLITE_BUSY;
2217 return SQLITE_DONE;
2218 }else{
2219 sqlite3SetString(&p->zErrMsg,
2220 (!i)?"cannot start a transaction within a transaction":(
2221 (rollback)?"cannot rollback - no transaction is active":
2222 "cannot commit - no transaction is active"), 0);
2224 rc = SQLITE_ERROR;
2226 break;
2229 /* Opcode: Transaction P1 P2 *
2231 ** Begin a transaction. The transaction ends when a Commit or Rollback
2232 ** opcode is encountered. Depending on the ON CONFLICT setting, the
2233 ** transaction might also be rolled back if an error is encountered.
2235 ** P1 is the index of the database file on which the transaction is
2236 ** started. Index 0 is the main database file and index 1 is the
2237 ** file used for temporary tables.
2239 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
2240 ** obtained on the database file when a write-transaction is started. No
2241 ** other process can start another write transaction while this transaction is
2242 ** underway. Starting a write transaction also creates a rollback journal. A
2243 ** write transaction must be started before any changes can be made to the
2244 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2245 ** on the file.
2247 ** If P2 is zero, then a read-lock is obtained on the database file.
2249 case OP_Transaction: { /* no-push */
2250 int i = pOp->p1;
2251 Btree *pBt;
2253 assert( i>=0 && i<db->nDb );
2254 pBt = db->aDb[i].pBt;
2256 if( pBt ){
2257 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2258 if( rc==SQLITE_BUSY ){
2259 p->pc = pc;
2260 p->rc = SQLITE_BUSY;
2261 p->pTos = pTos;
2262 return SQLITE_BUSY;
2264 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2265 goto abort_due_to_error;
2268 break;
2271 /* Opcode: ReadCookie P1 P2 *
2273 ** Read cookie number P2 from database P1 and push it onto the stack.
2274 ** P2==0 is the schema version. P2==1 is the database format.
2275 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2276 ** the main database file and P1==1 is the database file used to store
2277 ** temporary tables.
2279 ** There must be a read-lock on the database (either a transaction
2280 ** must be started or there must be an open cursor) before
2281 ** executing this instruction.
2283 case OP_ReadCookie: {
2284 int iMeta;
2285 assert( pOp->p2<SQLITE_N_BTREE_META );
2286 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2287 assert( db->aDb[pOp->p1].pBt!=0 );
2288 /* The indexing of meta values at the schema layer is off by one from
2289 ** the indexing in the btree layer. The btree considers meta[0] to
2290 ** be the number of free pages in the database (a read-only value)
2291 ** and meta[1] to be the schema cookie. The schema layer considers
2292 ** meta[1] to be the schema cookie. So we have to shift the index
2293 ** by one in the following statement.
2295 rc = sqlite3BtreeGetMeta(db->aDb[pOp->p1].pBt, 1 + pOp->p2, (u32 *)&iMeta);
2296 pTos++;
2297 pTos->i = iMeta;
2298 pTos->flags = MEM_Int;
2299 break;
2302 /* Opcode: SetCookie P1 P2 *
2304 ** Write the top of the stack into cookie number P2 of database P1.
2305 ** P2==0 is the schema version. P2==1 is the database format.
2306 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2307 ** the main database file and P1==1 is the database file used to store
2308 ** temporary tables.
2310 ** A transaction must be started before executing this opcode.
2312 case OP_SetCookie: { /* no-push */
2313 Db *pDb;
2314 assert( pOp->p2<SQLITE_N_BTREE_META );
2315 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2316 pDb = &db->aDb[pOp->p1];
2317 assert( pDb->pBt!=0 );
2318 assert( pTos>=p->aStack );
2319 Integerify(pTos);
2320 /* See note about index shifting on OP_ReadCookie */
2321 rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->i);
2322 if( pOp->p2==0 ){
2323 /* When the schema cookie changes, record the new cookie internally */
2324 pDb->schema_cookie = pTos->i;
2325 db->flags |= SQLITE_InternChanges;
2327 assert( (pTos->flags & MEM_Dyn)==0 );
2328 pTos--;
2329 break;
2332 /* Opcode: VerifyCookie P1 P2 *
2334 ** Check the value of global database parameter number 0 (the
2335 ** schema version) and make sure it is equal to P2.
2336 ** P1 is the database number which is 0 for the main database file
2337 ** and 1 for the file holding temporary tables and some higher number
2338 ** for auxiliary databases.
2340 ** The cookie changes its value whenever the database schema changes.
2341 ** This operation is used to detect when that the cookie has changed
2342 ** and that the current process needs to reread the schema.
2344 ** Either a transaction needs to have been started or an OP_Open needs
2345 ** to be executed (to establish a read lock) before this opcode is
2346 ** invoked.
2348 case OP_VerifyCookie: { /* no-push */
2349 int iMeta;
2350 Btree *pBt;
2351 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2352 pBt = db->aDb[pOp->p1].pBt;
2353 if( pBt ){
2354 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2355 }else{
2356 rc = SQLITE_OK;
2357 iMeta = 0;
2359 if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2360 sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
2361 rc = SQLITE_SCHEMA;
2363 break;
2366 /* Opcode: OpenRead P1 P2 P3
2368 ** Open a read-only cursor for the database table whose root page is
2369 ** P2 in a database file. The database file is determined by an
2370 ** integer from the top of the stack. 0 means the main database and
2371 ** 1 means the database used for temporary tables. Give the new
2372 ** cursor an identifier of P1. The P1 values need not be contiguous
2373 ** but all P1 values should be small integers. It is an error for
2374 ** P1 to be negative.
2376 ** If P2==0 then take the root page number from the next of the stack.
2378 ** There will be a read lock on the database whenever there is an
2379 ** open cursor. If the database was unlocked prior to this instruction
2380 ** then a read lock is acquired as part of this instruction. A read
2381 ** lock allows other processes to read the database but prohibits
2382 ** any other process from modifying the database. The read lock is
2383 ** released when all cursors are closed. If this instruction attempts
2384 ** to get a read lock but fails, the script terminates with an
2385 ** SQLITE_BUSY error code.
2387 ** The P3 value is a pointer to a KeyInfo structure that defines the
2388 ** content and collating sequence of indices. P3 is NULL for cursors
2389 ** that are not pointing to indices.
2391 ** See also OpenWrite.
2393 /* Opcode: OpenWrite P1 P2 P3
2395 ** Open a read/write cursor named P1 on the table or index whose root
2396 ** page is P2. If P2==0 then take the root page number from the stack.
2398 ** The P3 value is a pointer to a KeyInfo structure that defines the
2399 ** content and collating sequence of indices. P3 is NULL for cursors
2400 ** that are not pointing to indices.
2402 ** This instruction works just like OpenRead except that it opens the cursor
2403 ** in read/write mode. For a given table, there can be one or more read-only
2404 ** cursors or a single read/write cursor but not both.
2406 ** See also OpenRead.
2408 case OP_OpenRead: /* no-push */
2409 case OP_OpenWrite: { /* no-push */
2410 int i = pOp->p1;
2411 int p2 = pOp->p2;
2412 int wrFlag;
2413 Btree *pX;
2414 int iDb;
2415 Cursor *pCur;
2417 assert( pTos>=p->aStack );
2418 Integerify(pTos);
2419 iDb = pTos->i;
2420 assert( (pTos->flags & MEM_Dyn)==0 );
2421 pTos--;
2422 assert( iDb>=0 && iDb<db->nDb );
2423 pX = db->aDb[iDb].pBt;
2424 assert( pX!=0 );
2425 wrFlag = pOp->opcode==OP_OpenWrite;
2426 if( p2<=0 ){
2427 assert( pTos>=p->aStack );
2428 Integerify(pTos);
2429 p2 = pTos->i;
2430 assert( (pTos->flags & MEM_Dyn)==0 );
2431 pTos--;
2432 if( p2<2 ){
2433 sqlite3SetString(&p->zErrMsg, "root page number less than 2", (char*)0);
2434 rc = SQLITE_INTERNAL;
2435 break;
2438 assert( i>=0 );
2439 pCur = allocateCursor(p, i);
2440 if( pCur==0 ) goto no_mem;
2441 pCur->nullRow = 1;
2442 if( pX==0 ) break;
2443 /* We always provide a key comparison function. If the table being
2444 ** opened is of type INTKEY, the comparision function will be ignored. */
2445 rc = sqlite3BtreeCursor(pX, p2, wrFlag,
2446 sqlite3VdbeRecordCompare, pOp->p3,
2447 &pCur->pCursor);
2448 if( pOp->p3type==P3_KEYINFO ){
2449 pCur->pKeyInfo = (KeyInfo*)pOp->p3;
2450 pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2451 pCur->pKeyInfo->enc = p->db->enc;
2452 }else{
2453 pCur->pKeyInfo = 0;
2454 pCur->pIncrKey = &pCur->bogusIncrKey;
2456 switch( rc ){
2457 case SQLITE_BUSY: {
2458 p->pc = pc;
2459 p->rc = SQLITE_BUSY;
2460 p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
2461 return SQLITE_BUSY;
2463 case SQLITE_OK: {
2464 int flags = sqlite3BtreeFlags(pCur->pCursor);
2465 /* Sanity checking. Only the lower four bits of the flags byte should
2466 ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
2467 ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2468 ** 2 (zerodata for indices). If these conditions are not met it can
2469 ** only mean that we are dealing with a corrupt database file
2471 if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2472 rc = SQLITE_CORRUPT;
2473 goto abort_due_to_error;
2475 pCur->isTable = (flags & BTREE_INTKEY)!=0;
2476 pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2477 /* If P3==0 it means we are expected to open a table. If P3!=0 then
2478 ** we expect to be opening an index. If this is not what happened,
2479 ** then the database is corrupt
2481 if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
2482 || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
2483 rc = SQLITE_CORRUPT;
2484 goto abort_due_to_error;
2486 break;
2488 case SQLITE_EMPTY: {
2489 pCur->isTable = pOp->p3type!=P3_KEYINFO;
2490 pCur->isIndex = !pCur->isTable;
2491 rc = SQLITE_OK;
2492 break;
2494 default: {
2495 goto abort_due_to_error;
2498 break;
2501 /* Opcode: OpenTemp P1 * P3
2503 ** Open a new cursor to a transient table.
2504 ** The transient cursor is always opened read/write even if
2505 ** the main database is read-only. The transient table is deleted
2506 ** automatically when the cursor is closed.
2508 ** The cursor points to a BTree table if P3==0 and to a BTree index
2509 ** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
2510 ** that defines the format of keys in the index.
2512 ** This opcode is used for tables that exist for the duration of a single
2513 ** SQL statement only. Tables created using CREATE TEMPORARY TABLE
2514 ** are opened using OP_OpenRead or OP_OpenWrite. "Temporary" in the
2515 ** context of this opcode means for the duration of a single SQL statement
2516 ** whereas "Temporary" in the context of CREATE TABLE means for the duration
2517 ** of the connection to the database. Same word; different meanings.
2519 case OP_OpenTemp: { /* no-push */
2520 int i = pOp->p1;
2521 Cursor *pCx;
2522 assert( i>=0 );
2523 pCx = allocateCursor(p, i);
2524 if( pCx==0 ) goto no_mem;
2525 pCx->nullRow = 1;
2526 rc = sqlite3BtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
2527 if( rc==SQLITE_OK ){
2528 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2530 if( rc==SQLITE_OK ){
2531 /* If a transient index is required, create it by calling
2532 ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2533 ** opening it. If a transient table is required, just use the
2534 ** automatically created table with root-page 1 (an INTKEY table).
2536 if( pOp->p3 ){
2537 int pgno;
2538 assert( pOp->p3type==P3_KEYINFO );
2539 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2540 if( rc==SQLITE_OK ){
2541 assert( pgno==MASTER_ROOT+1 );
2542 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
2543 pOp->p3, &pCx->pCursor);
2544 pCx->pKeyInfo = (KeyInfo*)pOp->p3;
2545 pCx->pKeyInfo->enc = p->db->enc;
2546 pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2548 pCx->isTable = 0;
2549 }else{
2550 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
2551 pCx->isTable = 1;
2552 pCx->pIncrKey = &pCx->bogusIncrKey;
2555 pCx->isIndex = !pCx->isTable;
2556 break;
2559 #ifndef SQLITE_OMIT_TRIGGER
2560 /* Opcode: OpenPseudo P1 * *
2562 ** Open a new cursor that points to a fake table that contains a single
2563 ** row of data. Any attempt to write a second row of data causes the
2564 ** first row to be deleted. All data is deleted when the cursor is
2565 ** closed.
2567 ** A pseudo-table created by this opcode is useful for holding the
2568 ** NEW or OLD tables in a trigger.
2570 case OP_OpenPseudo: { /* no-push */
2571 int i = pOp->p1;
2572 Cursor *pCx;
2573 assert( i>=0 );
2574 pCx = allocateCursor(p, i);
2575 if( pCx==0 ) goto no_mem;
2576 pCx->nullRow = 1;
2577 pCx->pseudoTable = 1;
2578 pCx->pIncrKey = &pCx->bogusIncrKey;
2579 pCx->isTable = 1;
2580 pCx->isIndex = 0;
2581 break;
2583 #endif
2585 /* Opcode: Close P1 * *
2587 ** Close a cursor previously opened as P1. If P1 is not
2588 ** currently open, this instruction is a no-op.
2590 case OP_Close: { /* no-push */
2591 int i = pOp->p1;
2592 if( i>=0 && i<p->nCursor ){
2593 sqlite3VdbeFreeCursor(p->apCsr[i]);
2594 p->apCsr[i] = 0;
2596 break;
2599 /* Opcode: MoveGe P1 P2 *
2601 ** Pop the top of the stack and use its value as a key. Reposition
2602 ** cursor P1 so that it points to the smallest entry that is greater
2603 ** than or equal to the key that was popped ffrom the stack.
2604 ** If there are no records greater than or equal to the key and P2
2605 ** is not zero, then jump to P2.
2607 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2609 /* Opcode: MoveGt P1 P2 *
2611 ** Pop the top of the stack and use its value as a key. Reposition
2612 ** cursor P1 so that it points to the smallest entry that is greater
2613 ** than the key from the stack.
2614 ** If there are no records greater than the key and P2 is not zero,
2615 ** then jump to P2.
2617 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2619 /* Opcode: MoveLt P1 P2 *
2621 ** Pop the top of the stack and use its value as a key. Reposition
2622 ** cursor P1 so that it points to the largest entry that is less
2623 ** than the key from the stack.
2624 ** If there are no records less than the key and P2 is not zero,
2625 ** then jump to P2.
2627 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2629 /* Opcode: MoveLe P1 P2 *
2631 ** Pop the top of the stack and use its value as a key. Reposition
2632 ** cursor P1 so that it points to the largest entry that is less than
2633 ** or equal to the key that was popped from the stack.
2634 ** If there are no records less than or eqal to the key and P2 is not zero,
2635 ** then jump to P2.
2637 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2639 case OP_MoveLt: /* no-push */
2640 case OP_MoveLe: /* no-push */
2641 case OP_MoveGe: /* no-push */
2642 case OP_MoveGt: { /* no-push */
2643 int i = pOp->p1;
2644 Cursor *pC;
2646 assert( pTos>=p->aStack );
2647 assert( i>=0 && i<p->nCursor );
2648 pC = p->apCsr[i];
2649 assert( pC!=0 );
2650 if( pC->pCursor!=0 ){
2651 int res, oc;
2652 oc = pOp->opcode;
2653 pC->nullRow = 0;
2654 *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2655 if( pC->isTable ){
2656 i64 iKey;
2657 Integerify(pTos);
2658 iKey = intToKey(pTos->i);
2659 if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
2660 pC->movetoTarget = iKey;
2661 pC->deferredMoveto = 1;
2662 assert( (pTos->flags & MEM_Dyn)==0 );
2663 pTos--;
2664 break;
2666 rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, &res);
2667 if( rc!=SQLITE_OK ){
2668 goto abort_due_to_error;
2670 pC->lastRowid = pTos->i;
2671 pC->rowidIsValid = res==0;
2672 }else{
2673 Stringify(pTos, db->enc);
2674 rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
2675 if( rc!=SQLITE_OK ){
2676 goto abort_due_to_error;
2678 pC->rowidIsValid = 0;
2680 pC->deferredMoveto = 0;
2681 pC->cacheValid = 0;
2682 *pC->pIncrKey = 0;
2683 sqlite3_search_count++;
2684 if( oc==OP_MoveGe || oc==OP_MoveGt ){
2685 if( res<0 ){
2686 rc = sqlite3BtreeNext(pC->pCursor, &res);
2687 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2688 pC->rowidIsValid = 0;
2689 }else{
2690 res = 0;
2692 }else{
2693 assert( oc==OP_MoveLt || oc==OP_MoveLe );
2694 if( res>=0 ){
2695 rc = sqlite3BtreePrevious(pC->pCursor, &res);
2696 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2697 pC->rowidIsValid = 0;
2698 }else{
2699 /* res might be negative because the table is empty. Check to
2700 ** see if this is the case.
2702 res = sqlite3BtreeEof(pC->pCursor);
2705 if( res ){
2706 if( pOp->p2>0 ){
2707 pc = pOp->p2 - 1;
2708 }else{
2709 pC->nullRow = 1;
2713 Release(pTos);
2714 pTos--;
2715 break;
2718 /* Opcode: Distinct P1 P2 *
2720 ** Use the top of the stack as a record created using MakeRecord. P1 is a
2721 ** cursor on a table that declared as an index. If that table contains an
2722 ** entry that matches the top of the stack fall thru. If the top of the stack
2723 ** matches no entry in P1 then jump to P2.
2725 ** The cursor is left pointing at the matching entry if it exists. The
2726 ** record on the top of the stack is not popped.
2728 ** This instruction is similar to NotFound except that this operation
2729 ** does not pop the key from the stack.
2731 ** The instruction is used to implement the DISTINCT operator on SELECT
2732 ** statements. The P1 table is not a true index but rather a record of
2733 ** all results that have produced so far.
2735 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
2737 /* Opcode: Found P1 P2 *
2739 ** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
2740 ** If an entry that matches the top of the stack exists in P1 then
2741 ** jump to P2. If the top of the stack does not match any entry in P1
2742 ** then fall thru. The P1 cursor is left pointing at the matching entry
2743 ** if it exists. The blob is popped off the top of the stack.
2745 ** This instruction is used to implement the IN operator where the
2746 ** left-hand side is a SELECT statement. P1 is not a true index but
2747 ** is instead a temporary index that holds the results of the SELECT
2748 ** statement. This instruction just checks to see if the left-hand side
2749 ** of the IN operator (stored on the top of the stack) exists in the
2750 ** result of the SELECT statement.
2752 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
2754 /* Opcode: NotFound P1 P2 *
2756 ** The top of the stack holds a blob constructed by MakeRecord. P1 is
2757 ** an index. If no entry exists in P1 that matches the blob then jump
2758 ** to P1. If an entry does existing, fall through. The cursor is left
2759 ** pointing to the entry that matches. The blob is popped from the stack.
2761 ** The difference between this operation and Distinct is that
2762 ** Distinct does not pop the key from the stack.
2764 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
2766 case OP_Distinct: /* no-push */
2767 case OP_NotFound: /* no-push */
2768 case OP_Found: { /* no-push */
2769 int i = pOp->p1;
2770 int alreadyExists = 0;
2771 Cursor *pC;
2772 assert( pTos>=p->aStack );
2773 assert( i>=0 && i<p->nCursor );
2774 assert( p->apCsr[i]!=0 );
2775 if( (pC = p->apCsr[i])->pCursor!=0 ){
2776 int res, rx;
2777 assert( pC->isTable==0 );
2778 Stringify(pTos, db->enc);
2779 rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
2780 alreadyExists = rx==SQLITE_OK && res==0;
2781 pC->deferredMoveto = 0;
2782 pC->cacheValid = 0;
2784 if( pOp->opcode==OP_Found ){
2785 if( alreadyExists ) pc = pOp->p2 - 1;
2786 }else{
2787 if( !alreadyExists ) pc = pOp->p2 - 1;
2789 if( pOp->opcode!=OP_Distinct ){
2790 Release(pTos);
2791 pTos--;
2793 break;
2796 /* Opcode: IsUnique P1 P2 *
2798 ** The top of the stack is an integer record number. Call this
2799 ** record number R. The next on the stack is an index key created
2800 ** using MakeIdxKey. Call it K. This instruction pops R from the
2801 ** stack but it leaves K unchanged.
2803 ** P1 is an index. So it has no data and its key consists of a
2804 ** record generated by OP_MakeRecord where the last field is the
2805 ** rowid of the entry that the index refers to.
2807 ** This instruction asks if there is an entry in P1 where the
2808 ** fields matches K but the rowid is different from R.
2809 ** If there is no such entry, then there is an immediate
2810 ** jump to P2. If any entry does exist where the index string
2811 ** matches K but the record number is not R, then the record
2812 ** number for that entry is pushed onto the stack and control
2813 ** falls through to the next instruction.
2815 ** See also: Distinct, NotFound, NotExists, Found
2817 case OP_IsUnique: { /* no-push */
2818 int i = pOp->p1;
2819 Mem *pNos = &pTos[-1];
2820 Cursor *pCx;
2821 BtCursor *pCrsr;
2822 i64 R;
2824 /* Pop the value R off the top of the stack
2826 assert( pNos>=p->aStack );
2827 Integerify(pTos);
2828 R = pTos->i;
2829 assert( (pTos->flags & MEM_Dyn)==0 );
2830 pTos--;
2831 assert( i>=0 && i<=p->nCursor );
2832 pCx = p->apCsr[i];
2833 assert( pCx!=0 );
2834 pCrsr = pCx->pCursor;
2835 if( pCrsr!=0 ){
2836 int res, rc;
2837 i64 v; /* The record number on the P1 entry that matches K */
2838 char *zKey; /* The value of K */
2839 int nKey; /* Number of bytes in K */
2840 int len; /* Number of bytes in K without the rowid at the end */
2841 int szRowid; /* Size of the rowid column at the end of zKey */
2843 /* Make sure K is a string and make zKey point to K
2845 Stringify(pNos, db->enc);
2846 zKey = pNos->z;
2847 nKey = pNos->n;
2849 szRowid = sqlite3VdbeIdxRowidLen(nKey, zKey);
2850 len = nKey-szRowid;
2852 /* Search for an entry in P1 where all but the last four bytes match K.
2853 ** If there is no such entry, jump immediately to P2.
2855 assert( pCx->deferredMoveto==0 );
2856 pCx->cacheValid = 0;
2857 rc = sqlite3BtreeMoveto(pCrsr, zKey, len, &res);
2858 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2859 if( res<0 ){
2860 rc = sqlite3BtreeNext(pCrsr, &res);
2861 if( res ){
2862 pc = pOp->p2 - 1;
2863 break;
2866 rc = sqlite3VdbeIdxKeyCompare(pCx, len, zKey, &res);
2867 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2868 if( res>0 ){
2869 pc = pOp->p2 - 1;
2870 break;
2873 /* At this point, pCrsr is pointing to an entry in P1 where all but
2874 ** the final entry (the rowid) matches K. Check to see if the
2875 ** final rowid column is different from R. If it equals R then jump
2876 ** immediately to P2.
2878 rc = sqlite3VdbeIdxRowid(pCrsr, &v);
2879 if( rc!=SQLITE_OK ){
2880 goto abort_due_to_error;
2882 if( v==R ){
2883 pc = pOp->p2 - 1;
2884 break;
2887 /* The final varint of the key is different from R. Push it onto
2888 ** the stack. (The record number of an entry that violates a UNIQUE
2889 ** constraint.)
2891 pTos++;
2892 pTos->i = v;
2893 pTos->flags = MEM_Int;
2895 break;
2898 /* Opcode: NotExists P1 P2 *
2900 ** Use the top of the stack as a integer key. If a record with that key
2901 ** does not exist in table of P1, then jump to P2. If the record
2902 ** does exist, then fall thru. The cursor is left pointing to the
2903 ** record if it exists. The integer key is popped from the stack.
2905 ** The difference between this operation and NotFound is that this
2906 ** operation assumes the key is an integer and that P1 is a table whereas
2907 ** NotFound assumes key is a blob constructed from MakeRecord and
2908 ** P1 is an index.
2910 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
2912 case OP_NotExists: { /* no-push */
2913 int i = pOp->p1;
2914 Cursor *pC;
2915 BtCursor *pCrsr;
2916 assert( pTos>=p->aStack );
2917 assert( i>=0 && i<p->nCursor );
2918 assert( p->apCsr[i]!=0 );
2919 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
2920 int res;
2921 u64 iKey;
2922 assert( pTos->flags & MEM_Int );
2923 assert( p->apCsr[i]->isTable );
2924 iKey = intToKey(pTos->i);
2925 rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, &res);
2926 pC->lastRowid = pTos->i;
2927 pC->rowidIsValid = res==0;
2928 pC->nullRow = 0;
2929 pC->cacheValid = 0;
2930 if( res!=0 ){
2931 pc = pOp->p2 - 1;
2932 pC->rowidIsValid = 0;
2935 Release(pTos);
2936 pTos--;
2937 break;
2940 /* Opcode: NewRowid P1 P2 *
2942 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
2943 ** The record number is not previously used as a key in the database
2944 ** table that cursor P1 points to. The new record number is pushed
2945 ** onto the stack.
2947 ** If P2>0 then P2 is a memory cell that holds the largest previously
2948 ** generated record number. No new record numbers are allowed to be less
2949 ** than this value. When this value reaches its maximum, a SQLITE_FULL
2950 ** error is generated. The P2 memory cell is updated with the generated
2951 ** record number. This P2 mechanism is used to help implement the
2952 ** AUTOINCREMENT feature.
2954 case OP_NewRowid: {
2955 int i = pOp->p1;
2956 i64 v = 0;
2957 Cursor *pC;
2958 assert( i>=0 && i<p->nCursor );
2959 assert( p->apCsr[i]!=0 );
2960 if( (pC = p->apCsr[i])->pCursor==0 ){
2961 /* The zero initialization above is all that is needed */
2962 }else{
2963 /* The next rowid or record number (different terms for the same
2964 ** thing) is obtained in a two-step algorithm.
2966 ** First we attempt to find the largest existing rowid and add one
2967 ** to that. But if the largest existing rowid is already the maximum
2968 ** positive integer, we have to fall through to the second
2969 ** probabilistic algorithm
2971 ** The second algorithm is to select a rowid at random and see if
2972 ** it already exists in the table. If it does not exist, we have
2973 ** succeeded. If the random rowid does exist, we select a new one
2974 ** and try again, up to 1000 times.
2976 ** For a table with less than 2 billion entries, the probability
2977 ** of not finding a unused rowid is about 1.0e-300. This is a
2978 ** non-zero probability, but it is still vanishingly small and should
2979 ** never cause a problem. You are much, much more likely to have a
2980 ** hardware failure than for this algorithm to fail.
2982 ** The analysis in the previous paragraph assumes that you have a good
2983 ** source of random numbers. Is a library function like lrand48()
2984 ** good enough? Maybe. Maybe not. It's hard to know whether there
2985 ** might be subtle bugs is some implementations of lrand48() that
2986 ** could cause problems. To avoid uncertainty, SQLite uses its own
2987 ** random number generator based on the RC4 algorithm.
2989 ** To promote locality of reference for repetitive inserts, the
2990 ** first few attempts at chosing a random rowid pick values just a little
2991 ** larger than the previous rowid. This has been shown experimentally
2992 ** to double the speed of the COPY operation.
2994 int res, rx=SQLITE_OK, cnt;
2995 i64 x;
2996 cnt = 0;
2997 if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
2998 BTREE_INTKEY ){
2999 rc = SQLITE_CORRUPT;
3000 goto abort_due_to_error;
3002 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3003 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3005 #ifdef SQLITE_32BIT_ROWID
3006 # define MAX_ROWID 0x7fffffff
3007 #else
3008 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3009 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
3010 ** to provide the constant while making all compilers happy.
3012 # define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3013 #endif
3015 if( !pC->useRandomRowid ){
3016 if( pC->nextRowidValid ){
3017 v = pC->nextRowid;
3018 }else{
3019 rx = sqlite3BtreeLast(pC->pCursor, &res);
3020 if( res ){
3021 v = 1;
3022 }else{
3023 sqlite3BtreeKeySize(pC->pCursor, &v);
3024 v = keyToInt(v);
3025 if( v==MAX_ROWID ){
3026 pC->useRandomRowid = 1;
3027 }else{
3028 v++;
3033 #ifndef SQLITE_OMIT_AUTOINCREMENT
3034 if( pOp->p2 ){
3035 Mem *pMem;
3036 assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
3037 pMem = &p->aMem[pOp->p2];
3038 Integerify(pMem);
3039 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
3040 if( pMem->i==MAX_ROWID || pC->useRandomRowid ){
3041 rc = SQLITE_FULL;
3042 goto abort_due_to_error;
3044 if( v<pMem->i+1 ){
3045 v = pMem->i + 1;
3047 pMem->i = v;
3049 #endif
3051 if( v<MAX_ROWID ){
3052 pC->nextRowidValid = 1;
3053 pC->nextRowid = v+1;
3054 }else{
3055 pC->nextRowidValid = 0;
3058 if( pC->useRandomRowid ){
3059 assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
3060 v = db->priorNewRowid;
3061 cnt = 0;
3063 if( v==0 || cnt>2 ){
3064 sqlite3Randomness(sizeof(v), &v);
3065 if( cnt<5 ) v &= 0xffffff;
3066 }else{
3067 unsigned char r;
3068 sqlite3Randomness(1, &r);
3069 v += r + 1;
3071 if( v==0 ) continue;
3072 x = intToKey(v);
3073 rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, &res);
3074 cnt++;
3075 }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3076 db->priorNewRowid = v;
3077 if( rx==SQLITE_OK && res==0 ){
3078 rc = SQLITE_FULL;
3079 goto abort_due_to_error;
3082 pC->rowidIsValid = 0;
3083 pC->deferredMoveto = 0;
3084 pC->cacheValid = 0;
3086 pTos++;
3087 pTos->i = v;
3088 pTos->flags = MEM_Int;
3089 break;
3092 /* Opcode: Insert P1 P2 *
3094 ** Write an entry into the table of cursor P1. A new entry is
3095 ** created if it doesn't already exist or the data for an existing
3096 ** entry is overwritten. The data is the value on the top of the
3097 ** stack. The key is the next value down on the stack. The key must
3098 ** be an integer. The stack is popped twice by this instruction.
3100 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3101 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
3102 ** then rowid is stored for subsequent return by the
3103 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
3105 ** This instruction only works on tables. The equivalent instruction
3106 ** for indices is OP_IdxInsert.
3108 case OP_Insert: { /* no-push */
3109 Mem *pNos = &pTos[-1];
3110 int i = pOp->p1;
3111 Cursor *pC;
3112 assert( pNos>=p->aStack );
3113 assert( i>=0 && i<p->nCursor );
3114 assert( p->apCsr[i]!=0 );
3115 if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3116 i64 iKey; /* The integer ROWID or key for the record to be inserted */
3118 assert( pNos->flags & MEM_Int );
3119 assert( pC->isTable );
3120 iKey = intToKey(pNos->i);
3122 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3123 if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->i;
3124 if( pC->nextRowidValid && pTos->i>=pC->nextRowid ){
3125 pC->nextRowidValid = 0;
3127 if( pTos->flags & MEM_Null ){
3128 pTos->z = 0;
3129 pTos->n = 0;
3130 }else{
3131 assert( pTos->flags & (MEM_Blob|MEM_Str) );
3133 #ifndef SQLITE_OMIT_TRIGGER
3134 if( pC->pseudoTable ){
3135 sqliteFree(pC->pData);
3136 pC->iKey = iKey;
3137 pC->nData = pTos->n;
3138 if( pTos->flags & MEM_Dyn ){
3139 pC->pData = pTos->z;
3140 pTos->flags = MEM_Null;
3141 }else{
3142 pC->pData = sqliteMallocRaw( pC->nData+2 );
3143 if( !pC->pData ) goto no_mem;
3144 memcpy(pC->pData, pTos->z, pC->nData);
3145 pC->pData[pC->nData] = 0;
3146 pC->pData[pC->nData+1] = 0;
3148 pC->nullRow = 0;
3149 }else{
3150 #endif
3151 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, pTos->z, pTos->n);
3152 #ifndef SQLITE_OMIT_TRIGGER
3154 #endif
3156 pC->rowidIsValid = 0;
3157 pC->deferredMoveto = 0;
3158 pC->cacheValid = 0;
3160 popStack(&pTos, 2);
3161 break;
3164 /* Opcode: Delete P1 P2 *
3166 ** Delete the record at which the P1 cursor is currently pointing.
3168 ** The cursor will be left pointing at either the next or the previous
3169 ** record in the table. If it is left pointing at the next record, then
3170 ** the next Next instruction will be a no-op. Hence it is OK to delete
3171 ** a record from within an Next loop.
3173 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3174 ** incremented (otherwise not).
3176 ** If P1 is a pseudo-table, then this instruction is a no-op.
3178 case OP_Delete: { /* no-push */
3179 int i = pOp->p1;
3180 Cursor *pC;
3181 assert( i>=0 && i<p->nCursor );
3182 pC = p->apCsr[i];
3183 assert( pC!=0 );
3184 if( pC->pCursor!=0 ){
3185 rc = sqlite3VdbeCursorMoveto(pC);
3186 if( rc ) goto abort_due_to_error;
3187 rc = sqlite3BtreeDelete(pC->pCursor);
3188 pC->nextRowidValid = 0;
3189 pC->cacheValid = 0;
3191 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3192 break;
3195 /* Opcode: ResetCount P1 * *
3197 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
3198 ** then the value of the change counter is copied to the database handle
3199 ** change counter (returned by subsequent calls to sqlite3_changes())
3200 ** before it is reset. This is used by trigger programs.
3202 case OP_ResetCount: { /* no-push */
3203 if( pOp->p1 ){
3204 sqlite3VdbeSetChanges(db, p->nChange);
3206 p->nChange = 0;
3207 break;
3210 /* Opcode: RowData P1 * *
3212 ** Push onto the stack the complete row data for cursor P1.
3213 ** There is no interpretation of the data. It is just copied
3214 ** onto the stack exactly as it is found in the database file.
3216 ** If the cursor is not pointing to a valid row, a NULL is pushed
3217 ** onto the stack.
3219 /* Opcode: RowKey P1 * *
3221 ** Push onto the stack the complete row key for cursor P1.
3222 ** There is no interpretation of the key. It is just copied
3223 ** onto the stack exactly as it is found in the database file.
3225 ** If the cursor is not pointing to a valid row, a NULL is pushed
3226 ** onto the stack.
3228 case OP_RowKey:
3229 case OP_RowData: {
3230 int i = pOp->p1;
3231 Cursor *pC;
3232 u32 n;
3234 /* Note that RowKey and RowData are really exactly the same instruction */
3235 pTos++;
3236 assert( i>=0 && i<p->nCursor );
3237 pC = p->apCsr[i];
3238 assert( pC->isTable || pOp->opcode==OP_RowKey );
3239 assert( pC->isIndex || pOp->opcode==OP_RowData );
3240 assert( pC!=0 );
3241 if( pC->nullRow ){
3242 pTos->flags = MEM_Null;
3243 }else if( pC->pCursor!=0 ){
3244 BtCursor *pCrsr = pC->pCursor;
3245 rc = sqlite3VdbeCursorMoveto(pC);
3246 if( rc ) goto abort_due_to_error;
3247 if( pC->nullRow ){
3248 pTos->flags = MEM_Null;
3249 break;
3250 }else if( pC->isIndex ){
3251 i64 n64;
3252 assert( !pC->isTable );
3253 sqlite3BtreeKeySize(pCrsr, &n64);
3254 n = n64;
3255 }else{
3256 sqlite3BtreeDataSize(pCrsr, &n);
3258 pTos->n = n;
3259 if( n<=NBFS ){
3260 pTos->flags = MEM_Blob | MEM_Short;
3261 pTos->z = pTos->zShort;
3262 }else{
3263 char *z = sqliteMallocRaw( n );
3264 if( z==0 ) goto no_mem;
3265 pTos->flags = MEM_Blob | MEM_Dyn;
3266 pTos->xDel = 0;
3267 pTos->z = z;
3269 if( pC->isIndex ){
3270 sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
3271 }else{
3272 sqlite3BtreeData(pCrsr, 0, n, pTos->z);
3274 #ifndef SQLITE_OMIT_TRIGGER
3275 }else if( pC->pseudoTable ){
3276 pTos->n = pC->nData;
3277 pTos->z = pC->pData;
3278 pTos->flags = MEM_Blob|MEM_Ephem;
3279 #endif
3280 }else{
3281 pTos->flags = MEM_Null;
3283 break;
3286 /* Opcode: Rowid P1 * *
3288 ** Push onto the stack an integer which is the key of the table entry that
3289 ** P1 is currently point to.
3291 case OP_Rowid: {
3292 int i = pOp->p1;
3293 Cursor *pC;
3294 i64 v;
3296 assert( i>=0 && i<p->nCursor );
3297 pC = p->apCsr[i];
3298 assert( pC!=0 );
3299 rc = sqlite3VdbeCursorMoveto(pC);
3300 if( rc ) goto abort_due_to_error;
3301 pTos++;
3302 if( pC->rowidIsValid ){
3303 v = pC->lastRowid;
3304 }else if( pC->pseudoTable ){
3305 v = keyToInt(pC->iKey);
3306 }else if( pC->nullRow || pC->pCursor==0 ){
3307 pTos->flags = MEM_Null;
3308 break;
3309 }else{
3310 assert( pC->pCursor!=0 );
3311 sqlite3BtreeKeySize(pC->pCursor, &v);
3312 v = keyToInt(v);
3314 pTos->i = v;
3315 pTos->flags = MEM_Int;
3316 break;
3319 /* Opcode: NullRow P1 * *
3321 ** Move the cursor P1 to a null row. Any OP_Column operations
3322 ** that occur while the cursor is on the null row will always push
3323 ** a NULL onto the stack.
3325 case OP_NullRow: { /* no-push */
3326 int i = pOp->p1;
3327 Cursor *pC;
3329 assert( i>=0 && i<p->nCursor );
3330 pC = p->apCsr[i];
3331 assert( pC!=0 );
3332 pC->nullRow = 1;
3333 pC->rowidIsValid = 0;
3334 break;
3337 /* Opcode: Last P1 P2 *
3339 ** The next use of the Rowid or Column or Next instruction for P1
3340 ** will refer to the last entry in the database table or index.
3341 ** If the table or index is empty and P2>0, then jump immediately to P2.
3342 ** If P2 is 0 or if the table or index is not empty, fall through
3343 ** to the following instruction.
3345 case OP_Last: { /* no-push */
3346 int i = pOp->p1;
3347 Cursor *pC;
3348 BtCursor *pCrsr;
3350 assert( i>=0 && i<p->nCursor );
3351 pC = p->apCsr[i];
3352 assert( pC!=0 );
3353 if( (pCrsr = pC->pCursor)!=0 ){
3354 int res;
3355 rc = sqlite3BtreeLast(pCrsr, &res);
3356 pC->nullRow = res;
3357 pC->deferredMoveto = 0;
3358 pC->cacheValid = 0;
3359 if( res && pOp->p2>0 ){
3360 pc = pOp->p2 - 1;
3362 }else{
3363 pC->nullRow = 0;
3365 break;
3368 /* Opcode: Rewind P1 P2 *
3370 ** The next use of the Rowid or Column or Next instruction for P1
3371 ** will refer to the first entry in the database table or index.
3372 ** If the table or index is empty and P2>0, then jump immediately to P2.
3373 ** If P2 is 0 or if the table or index is not empty, fall through
3374 ** to the following instruction.
3376 case OP_Rewind: { /* no-push */
3377 int i = pOp->p1;
3378 Cursor *pC;
3379 BtCursor *pCrsr;
3380 int res;
3382 assert( i>=0 && i<p->nCursor );
3383 pC = p->apCsr[i];
3384 assert( pC!=0 );
3385 if( (pCrsr = pC->pCursor)!=0 ){
3386 rc = sqlite3BtreeFirst(pCrsr, &res);
3387 pC->atFirst = res==0;
3388 pC->deferredMoveto = 0;
3389 pC->cacheValid = 0;
3390 }else{
3391 res = 1;
3393 pC->nullRow = res;
3394 if( res && pOp->p2>0 ){
3395 pc = pOp->p2 - 1;
3397 break;
3400 /* Opcode: Next P1 P2 *
3402 ** Advance cursor P1 so that it points to the next key/data pair in its
3403 ** table or index. If there are no more key/value pairs then fall through
3404 ** to the following instruction. But if the cursor advance was successful,
3405 ** jump immediately to P2.
3407 ** See also: Prev
3409 /* Opcode: Prev P1 P2 *
3411 ** Back up cursor P1 so that it points to the previous key/data pair in its
3412 ** table or index. If there is no previous key/value pairs then fall through
3413 ** to the following instruction. But if the cursor backup was successful,
3414 ** jump immediately to P2.
3416 case OP_Prev: /* no-push */
3417 case OP_Next: { /* no-push */
3418 Cursor *pC;
3419 BtCursor *pCrsr;
3421 CHECK_FOR_INTERRUPT;
3422 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3423 pC = p->apCsr[pOp->p1];
3424 assert( pC!=0 );
3425 if( (pCrsr = pC->pCursor)!=0 ){
3426 int res;
3427 if( pC->nullRow ){
3428 res = 1;
3429 }else{
3430 assert( pC->deferredMoveto==0 );
3431 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3432 sqlite3BtreePrevious(pCrsr, &res);
3433 pC->nullRow = res;
3434 pC->cacheValid = 0;
3436 if( res==0 ){
3437 pc = pOp->p2 - 1;
3438 sqlite3_search_count++;
3440 }else{
3441 pC->nullRow = 1;
3443 pC->rowidIsValid = 0;
3444 break;
3447 /* Opcode: IdxInsert P1 P2 P3
3449 ** The top of the stack holds a SQL index key made using the
3450 ** MakeIdxKey instruction. This opcode writes that key into the
3451 ** index P1. Data for the entry is nil.
3453 ** If P2==1, then the key must be unique. If the key is not unique,
3454 ** the program aborts with a SQLITE_CONSTRAINT error and the database
3455 ** is rolled back. If P3 is not null, then it becomes part of the
3456 ** error message returned with the SQLITE_CONSTRAINT.
3458 ** This instruction only works for indices. The equivalent instruction
3459 ** for tables is OP_Insert.
3461 case OP_IdxInsert: { /* no-push */
3462 int i = pOp->p1;
3463 Cursor *pC;
3464 BtCursor *pCrsr;
3465 assert( pTos>=p->aStack );
3466 assert( i>=0 && i<p->nCursor );
3467 assert( p->apCsr[i]!=0 );
3468 assert( pTos->flags & MEM_Blob );
3469 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3470 int nKey = pTos->n;
3471 const char *zKey = pTos->z;
3472 if( pOp->p2 ){
3473 int res;
3474 int len;
3476 /* 'len' is the length of the key minus the rowid at the end */
3477 len = nKey - sqlite3VdbeIdxRowidLen(nKey, zKey);
3479 rc = sqlite3BtreeMoveto(pCrsr, zKey, len, &res);
3480 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3481 while( res!=0 && !sqlite3BtreeEof(pCrsr) ){
3482 int c;
3483 if( sqlite3VdbeIdxKeyCompare(pC, len, zKey, &c)==SQLITE_OK && c==0 ){
3484 rc = SQLITE_CONSTRAINT;
3485 if( pOp->p3 && pOp->p3[0] ){
3486 sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
3488 goto abort_due_to_error;
3490 if( res<0 ){
3491 sqlite3BtreeNext(pCrsr, &res);
3492 res = +1;
3493 }else{
3494 break;
3498 assert( pC->isTable==0 );
3499 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0);
3500 assert( pC->deferredMoveto==0 );
3501 pC->cacheValid = 0;
3503 Release(pTos);
3504 pTos--;
3505 break;
3508 /* Opcode: IdxDelete P1 * *
3510 ** The top of the stack is an index key built using the MakeIdxKey opcode.
3511 ** This opcode removes that entry from the index.
3513 case OP_IdxDelete: { /* no-push */
3514 int i = pOp->p1;
3515 Cursor *pC;
3516 BtCursor *pCrsr;
3517 assert( pTos>=p->aStack );
3518 assert( pTos->flags & MEM_Blob );
3519 assert( i>=0 && i<p->nCursor );
3520 assert( p->apCsr[i]!=0 );
3521 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3522 int rx, res;
3523 rx = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, &res);
3524 if( rx==SQLITE_OK && res==0 ){
3525 rc = sqlite3BtreeDelete(pCrsr);
3527 assert( pC->deferredMoveto==0 );
3528 pC->cacheValid = 0;
3530 Release(pTos);
3531 pTos--;
3532 break;
3535 /* Opcode: IdxRowid P1 * *
3537 ** Push onto the stack an integer which is the last entry in the record at
3538 ** the end of the index key pointed to by cursor P1. This integer should be
3539 ** the rowid of the table entry to which this index entry points.
3541 ** See also: Rowid, MakeIdxKey.
3543 case OP_IdxRowid: {
3544 int i = pOp->p1;
3545 BtCursor *pCrsr;
3546 Cursor *pC;
3548 assert( i>=0 && i<p->nCursor );
3549 assert( p->apCsr[i]!=0 );
3550 pTos++;
3551 pTos->flags = MEM_Null;
3552 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3553 i64 rowid;
3555 assert( pC->deferredMoveto==0 );
3556 assert( pC->isTable==0 );
3557 if( pC->nullRow ){
3558 pTos->flags = MEM_Null;
3559 }else{
3560 rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3561 if( rc!=SQLITE_OK ){
3562 goto abort_due_to_error;
3564 pTos->flags = MEM_Int;
3565 pTos->i = rowid;
3568 break;
3571 /* Opcode: IdxGT P1 P2 *
3573 ** The top of the stack is an index entry that omits the ROWID. Compare
3574 ** the top of stack against the index that P1 is currently pointing to.
3575 ** Ignore the ROWID on the P1 index.
3577 ** The top of the stack might have fewer columns that P1.
3579 ** If the P1 index entry is greater than the top of the stack
3580 ** then jump to P2. Otherwise fall through to the next instruction.
3581 ** In either case, the stack is popped once.
3583 /* Opcode: IdxGE P1 P2 P3
3585 ** The top of the stack is an index entry that omits the ROWID. Compare
3586 ** the top of stack against the index that P1 is currently pointing to.
3587 ** Ignore the ROWID on the P1 index.
3589 ** If the P1 index entry is greater than or equal to the top of the stack
3590 ** then jump to P2. Otherwise fall through to the next instruction.
3591 ** In either case, the stack is popped once.
3593 ** If P3 is the "+" string (or any other non-NULL string) then the
3594 ** index taken from the top of the stack is temporarily increased by
3595 ** an epsilon prior to the comparison. This make the opcode work
3596 ** like IdxGT except that if the key from the stack is a prefix of
3597 ** the key in the cursor, the result is false whereas it would be
3598 ** true with IdxGT.
3600 /* Opcode: IdxLT P1 P2 P3
3602 ** The top of the stack is an index entry that omits the ROWID. Compare
3603 ** the top of stack against the index that P1 is currently pointing to.
3604 ** Ignore the ROWID on the P1 index.
3606 ** If the P1 index entry is less than the top of the stack
3607 ** then jump to P2. Otherwise fall through to the next instruction.
3608 ** In either case, the stack is popped once.
3610 ** If P3 is the "+" string (or any other non-NULL string) then the
3611 ** index taken from the top of the stack is temporarily increased by
3612 ** an epsilon prior to the comparison. This makes the opcode work
3613 ** like IdxLE.
3615 case OP_IdxLT: /* no-push */
3616 case OP_IdxGT: /* no-push */
3617 case OP_IdxGE: { /* no-push */
3618 int i= pOp->p1;
3619 BtCursor *pCrsr;
3620 Cursor *pC;
3622 assert( i>=0 && i<p->nCursor );
3623 assert( p->apCsr[i]!=0 );
3624 assert( pTos>=p->aStack );
3625 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3626 int res, rc;
3628 assert( pTos->flags & MEM_Blob ); /* Created using OP_Make*Key */
3629 Stringify(pTos, db->enc);
3630 assert( pC->deferredMoveto==0 );
3631 *pC->pIncrKey = pOp->p3!=0;
3632 assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
3633 rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, pTos->z, &res);
3634 *pC->pIncrKey = 0;
3635 if( rc!=SQLITE_OK ){
3636 break;
3638 if( pOp->opcode==OP_IdxLT ){
3639 res = -res;
3640 }else if( pOp->opcode==OP_IdxGE ){
3641 res++;
3643 if( res>0 ){
3644 pc = pOp->p2 - 1 ;
3647 Release(pTos);
3648 pTos--;
3649 break;
3652 /* Opcode: IdxIsNull P1 P2 *
3654 ** The top of the stack contains an index entry such as might be generated
3655 ** by the MakeIdxKey opcode. This routine looks at the first P1 fields of
3656 ** that key. If any of the first P1 fields are NULL, then a jump is made
3657 ** to address P2. Otherwise we fall straight through.
3659 ** The index entry is always popped from the stack.
3661 case OP_IdxIsNull: { /* no-push */
3662 int i = pOp->p1;
3663 int k, n;
3664 const char *z;
3665 u32 serial_type;
3667 assert( pTos>=p->aStack );
3668 assert( pTos->flags & MEM_Blob );
3669 z = pTos->z;
3670 n = pTos->n;
3671 k = sqlite3GetVarint32(z, &serial_type);
3672 for(; k<n && i>0; i--){
3673 k += sqlite3GetVarint32(&z[k], &serial_type);
3674 if( serial_type==0 ){ /* Serial type 0 is a NULL */
3675 pc = pOp->p2-1;
3676 break;
3679 Release(pTos);
3680 pTos--;
3681 break;
3684 /* Opcode: Destroy P1 P2 *
3686 ** Delete an entire database table or index whose root page in the database
3687 ** file is given by P1.
3689 ** The table being destroyed is in the main database file if P2==0. If
3690 ** P2==1 then the table to be clear is in the auxiliary database file
3691 ** that is used to store tables create using CREATE TEMPORARY TABLE.
3693 ** If AUTOVACUUM is enabled then it is possible that another root page
3694 ** might be moved into the newly deleted root page in order to keep all
3695 ** root pages contiguous at the beginning of the database. The former
3696 ** value of the root page that moved - its value before the move occurred -
3697 ** is pushed onto the stack. If no page movement was required (because
3698 ** the table being dropped was already the last one in the database) then
3699 ** a zero is pushed onto the stack. If AUTOVACUUM is disabled
3700 ** then a zero is pushed onto the stack.
3702 ** See also: Clear
3704 case OP_Destroy: {
3705 int iMoved;
3706 if( db->activeVdbeCnt>1 ){
3707 rc = SQLITE_LOCKED;
3708 }else{
3709 assert( db->activeVdbeCnt==1 );
3710 rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
3711 pTos++;
3712 pTos->flags = MEM_Int;
3713 pTos->i = iMoved;
3714 #ifndef SQLITE_OMIT_AUTOVACUUM
3715 if( rc==SQLITE_OK && iMoved!=0 ){
3716 sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
3718 #endif
3720 break;
3723 /* Opcode: Clear P1 P2 *
3725 ** Delete all contents of the database table or index whose root page
3726 ** in the database file is given by P1. But, unlike Destroy, do not
3727 ** remove the table or index from the database file.
3729 ** The table being clear is in the main database file if P2==0. If
3730 ** P2==1 then the table to be clear is in the auxiliary database file
3731 ** that is used to store tables create using CREATE TEMPORARY TABLE.
3733 ** See also: Destroy
3735 case OP_Clear: { /* no-push */
3736 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
3737 break;
3740 /* Opcode: CreateTable P1 * *
3742 ** Allocate a new table in the main database file if P2==0 or in the
3743 ** auxiliary database file if P2==1. Push the page number
3744 ** for the root page of the new table onto the stack.
3746 ** The difference between a table and an index is this: A table must
3747 ** have a 4-byte integer key and can have arbitrary data. An index
3748 ** has an arbitrary key but no data.
3750 ** See also: CreateIndex
3752 /* Opcode: CreateIndex P1 * *
3754 ** Allocate a new index in the main database file if P2==0 or in the
3755 ** auxiliary database file if P2==1. Push the page number of the
3756 ** root page of the new index onto the stack.
3758 ** See documentation on OP_CreateTable for additional information.
3760 case OP_CreateIndex:
3761 case OP_CreateTable: {
3762 int pgno;
3763 int flags;
3764 Db *pDb;
3765 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3766 pDb = &db->aDb[pOp->p1];
3767 assert( pDb->pBt!=0 );
3768 if( pOp->opcode==OP_CreateTable ){
3769 /* flags = BTREE_INTKEY; */
3770 flags = BTREE_LEAFDATA|BTREE_INTKEY;
3771 }else{
3772 flags = BTREE_ZERODATA;
3774 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
3775 pTos++;
3776 if( rc==SQLITE_OK ){
3777 pTos->i = pgno;
3778 pTos->flags = MEM_Int;
3779 }else{
3780 pTos->flags = MEM_Null;
3782 break;
3785 /* Opcode: ParseSchema P1 * P3
3787 ** Read and parse all entries from the SQLITE_MASTER table of database P1
3788 ** that match the WHERE clause P3.
3790 ** This opcode invokes the parser to create a new virtual machine,
3791 ** then runs the new virtual machine. It is thus a reentrant opcode.
3793 case OP_ParseSchema: { /* no-push */
3794 char *zSql;
3795 int iDb = pOp->p1;
3796 const char *zMaster;
3797 InitData initData;
3799 assert( iDb>=0 && iDb<db->nDb );
3800 if( !DbHasProperty(db, iDb, DB_SchemaLoaded) ) break;
3801 zMaster = SCHEMA_TABLE(iDb);
3802 initData.db = db;
3803 initData.pzErrMsg = &p->zErrMsg;
3804 zSql = sqlite3MPrintf(
3805 "SELECT name, rootpage, sql, %d FROM '%q'.%s WHERE %s",
3806 pOp->p1, db->aDb[iDb].zName, zMaster, pOp->p3);
3807 if( zSql==0 ) goto no_mem;
3808 sqlite3SafetyOff(db);
3809 assert( db->init.busy==0 );
3810 db->init.busy = 1;
3811 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
3812 db->init.busy = 0;
3813 sqlite3SafetyOn(db);
3814 sqliteFree(zSql);
3815 break;
3818 /* Opcode: DropTable P1 * P3
3820 ** Remove the internal (in-memory) data structures that describe
3821 ** the table named P3 in database P1. This is called after a table
3822 ** is dropped in order to keep the internal representation of the
3823 ** schema consistent with what is on disk.
3825 case OP_DropTable: { /* no-push */
3826 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
3827 break;
3830 /* Opcode: DropIndex P1 * P3
3832 ** Remove the internal (in-memory) data structures that describe
3833 ** the index named P3 in database P1. This is called after an index
3834 ** is dropped in order to keep the internal representation of the
3835 ** schema consistent with what is on disk.
3837 case OP_DropIndex: { /* no-push */
3838 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
3839 break;
3842 /* Opcode: DropTrigger P1 * P3
3844 ** Remove the internal (in-memory) data structures that describe
3845 ** the trigger named P3 in database P1. This is called after a trigger
3846 ** is dropped in order to keep the internal representation of the
3847 ** schema consistent with what is on disk.
3849 case OP_DropTrigger: { /* no-push */
3850 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
3851 break;
3855 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
3856 /* Opcode: IntegrityCk * P2 *
3858 ** Do an analysis of the currently open database. Push onto the
3859 ** stack the text of an error message describing any problems.
3860 ** If there are no errors, push a "ok" onto the stack.
3862 ** The root page numbers of all tables in the database are integer
3863 ** values on the stack. This opcode pulls as many integers as it
3864 ** can off of the stack and uses those numbers as the root pages.
3866 ** If P2 is not zero, the check is done on the auxiliary database
3867 ** file, not the main database file.
3869 ** This opcode is used for testing purposes only.
3871 case OP_IntegrityCk: {
3872 int nRoot;
3873 int *aRoot;
3874 int j;
3875 char *z;
3877 for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
3878 if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
3880 assert( nRoot>0 );
3881 aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
3882 if( aRoot==0 ) goto no_mem;
3883 for(j=0; j<nRoot; j++){
3884 Mem *pMem = &pTos[-j];
3885 aRoot[j] = pMem->i;
3887 aRoot[j] = 0;
3888 popStack(&pTos, nRoot);
3889 pTos++;
3890 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
3891 if( z==0 || z[0]==0 ){
3892 if( z ) sqliteFree(z);
3893 pTos->z = "ok";
3894 pTos->n = 2;
3895 pTos->flags = MEM_Str | MEM_Static | MEM_Term;
3896 }else{
3897 pTos->z = z;
3898 pTos->n = strlen(z);
3899 pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
3900 pTos->xDel = 0;
3902 pTos->enc = SQLITE_UTF8;
3903 sqlite3VdbeChangeEncoding(pTos, db->enc);
3904 sqliteFree(aRoot);
3905 break;
3907 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
3909 /* Opcode: ListWrite * * *
3911 ** Write the integer on the top of the stack
3912 ** into the temporary storage list.
3914 case OP_ListWrite: { /* no-push */
3915 Keylist *pKeylist;
3916 assert( pTos>=p->aStack );
3917 pKeylist = p->pList;
3918 if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
3919 pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
3920 if( pKeylist==0 ) goto no_mem;
3921 pKeylist->nKey = 1000;
3922 pKeylist->nRead = 0;
3923 pKeylist->nUsed = 0;
3924 pKeylist->pNext = p->pList;
3925 p->pList = pKeylist;
3927 Integerify(pTos);
3928 pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
3929 assert( (pTos->flags & MEM_Dyn)==0 );
3930 pTos--;
3931 break;
3934 /* Opcode: ListRewind * * *
3936 ** Rewind the temporary buffer back to the beginning.
3938 case OP_ListRewind: { /* no-push */
3939 /* What this opcode codes, really, is reverse the order of the
3940 ** linked list of Keylist structures so that they are read out
3941 ** in the same order that they were read in. */
3942 Keylist *pRev, *pTop;
3943 pRev = 0;
3944 while( p->pList ){
3945 pTop = p->pList;
3946 p->pList = pTop->pNext;
3947 pTop->pNext = pRev;
3948 pRev = pTop;
3950 p->pList = pRev;
3951 break;
3954 /* Opcode: ListRead * P2 *
3956 ** Attempt to read an integer from the temporary storage buffer
3957 ** and push it onto the stack. If the storage buffer is empty,
3958 ** push nothing but instead jump to P2.
3960 case OP_ListRead: {
3961 Keylist *pKeylist;
3962 CHECK_FOR_INTERRUPT;
3963 pKeylist = p->pList;
3964 if( pKeylist!=0 ){
3965 assert( pKeylist->nRead>=0 );
3966 assert( pKeylist->nRead<pKeylist->nUsed );
3967 assert( pKeylist->nRead<pKeylist->nKey );
3968 pTos++;
3969 pTos->i = pKeylist->aKey[pKeylist->nRead++];
3970 pTos->flags = MEM_Int;
3971 if( pKeylist->nRead>=pKeylist->nUsed ){
3972 p->pList = pKeylist->pNext;
3973 sqliteFree(pKeylist);
3975 }else{
3976 pc = pOp->p2 - 1;
3978 break;
3981 /* Opcode: ListReset * * *
3983 ** Reset the temporary storage buffer so that it holds nothing.
3985 case OP_ListReset: { /* no-push */
3986 if( p->pList ){
3987 sqlite3VdbeKeylistFree(p->pList);
3988 p->pList = 0;
3990 break;
3993 #ifndef SQLITE_OMIT_SUBQUERY
3994 /* Opcode: AggContextPush * * *
3996 ** Save the state of the current aggregator. It is restored an
3997 ** AggContextPop opcode.
4000 case OP_AggContextPush: { /* no-push */
4001 p->pAgg++;
4002 assert( p->pAgg<&p->apAgg[p->nAgg] );
4003 break;
4006 /* Opcode: AggContextPop * * *
4008 ** Restore the aggregator to the state it was in when AggContextPush
4009 ** was last called. Any data in the current aggregator is deleted.
4011 case OP_AggContextPop: { /* no-push */
4012 p->pAgg--;
4013 assert( p->pAgg>=p->apAgg );
4014 break;
4016 #endif
4018 #ifndef SQLITE_OMIT_TRIGGER
4019 /* Opcode: ContextPush * * *
4021 ** Save the current Vdbe context such that it can be restored by a ContextPop
4022 ** opcode. The context stores the last insert row id, the last statement change
4023 ** count, and the current statement change count.
4025 case OP_ContextPush: { /* no-push */
4026 int i = p->contextStackTop++;
4027 Context *pContext;
4029 assert( i>=0 );
4030 /* FIX ME: This should be allocated as part of the vdbe at compile-time */
4031 if( i>=p->contextStackDepth ){
4032 p->contextStackDepth = i+1;
4033 p->contextStack = sqliteRealloc(p->contextStack, sizeof(Context)*(i+1));
4034 if( p->contextStack==0 ) goto no_mem;
4036 pContext = &p->contextStack[i];
4037 pContext->lastRowid = db->lastRowid;
4038 pContext->nChange = p->nChange;
4039 pContext->pList = p->pList;
4040 p->pList = 0;
4041 break;
4044 /* Opcode: ContextPop * * *
4046 ** Restore the Vdbe context to the state it was in when contextPush was last
4047 ** executed. The context stores the last insert row id, the last statement
4048 ** change count, and the current statement change count.
4050 case OP_ContextPop: { /* no-push */
4051 Context *pContext = &p->contextStack[--p->contextStackTop];
4052 assert( p->contextStackTop>=0 );
4053 db->lastRowid = pContext->lastRowid;
4054 p->nChange = pContext->nChange;
4055 sqlite3VdbeKeylistFree(p->pList);
4056 p->pList = pContext->pList;
4057 break;
4059 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
4061 /* Opcode: SortInsert * * *
4063 ** The TOS is the key and the NOS is the data. Pop both from the stack
4064 ** and put them on the sorter. The key and data should have been
4065 ** made using the MakeRecord opcode.
4067 case OP_SortInsert: { /* no-push */
4068 Mem *pNos = &pTos[-1];
4069 Sorter *pSorter;
4070 assert( pNos>=p->aStack );
4071 if( Dynamicify(pTos, db->enc) ) goto no_mem;
4072 pSorter = sqliteMallocRaw( sizeof(Sorter) );
4073 if( pSorter==0 ) goto no_mem;
4074 pSorter->pNext = 0;
4075 if( p->pSortTail ){
4076 p->pSortTail->pNext = pSorter;
4077 }else{
4078 p->pSort = pSorter;
4080 p->pSortTail = pSorter;
4081 assert( pTos->flags & MEM_Dyn );
4082 pSorter->nKey = pTos->n;
4083 pSorter->zKey = pTos->z;
4084 pSorter->data.flags = MEM_Null;
4085 rc = sqlite3VdbeMemMove(&pSorter->data, pNos);
4086 pTos -= 2;
4087 break;
4090 /* Opcode: Sort * * P3
4092 ** Sort all elements on the sorter. The algorithm is a
4093 ** mergesort. The P3 argument is a pointer to a KeyInfo structure
4094 ** that describes the keys to be sorted.
4096 case OP_Sort: { /* no-push */
4097 int i;
4098 KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
4099 Sorter *pElem;
4100 Sorter *apSorter[NSORT];
4101 sqlite3_sort_count++;
4102 pKeyInfo->enc = p->db->enc;
4103 for(i=0; i<NSORT; i++){
4104 apSorter[i] = 0;
4106 while( p->pSort ){
4107 pElem = p->pSort;
4108 p->pSort = pElem->pNext;
4109 pElem->pNext = 0;
4110 for(i=0; i<NSORT-1; i++){
4111 if( apSorter[i]==0 ){
4112 apSorter[i] = pElem;
4113 break;
4114 }else{
4115 pElem = Merge(apSorter[i], pElem, pKeyInfo);
4116 apSorter[i] = 0;
4119 if( i>=NSORT-1 ){
4120 apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem, pKeyInfo);
4123 pElem = 0;
4124 for(i=0; i<NSORT; i++){
4125 pElem = Merge(apSorter[i], pElem, pKeyInfo);
4127 p->pSort = pElem;
4128 break;
4131 /* Opcode: SortNext * P2 *
4133 ** Push the data for the topmost element in the sorter onto the
4134 ** stack, then remove the element from the sorter. If the sorter
4135 ** is empty, push nothing on the stack and instead jump immediately
4136 ** to instruction P2.
4138 case OP_SortNext: {
4139 Sorter *pSorter = p->pSort;
4140 CHECK_FOR_INTERRUPT;
4141 if( pSorter!=0 ){
4142 p->pSort = pSorter->pNext;
4143 pTos++;
4144 pTos->flags = MEM_Null;
4145 rc = sqlite3VdbeMemMove(pTos, &pSorter->data);
4146 sqliteFree(pSorter->zKey);
4147 sqliteFree(pSorter);
4148 }else{
4149 pc = pOp->p2 - 1;
4151 break;
4154 /* Opcode: SortReset * * *
4156 ** Remove any elements that remain on the sorter.
4158 case OP_SortReset: { /* no-push */
4159 sqlite3VdbeSorterReset(p);
4160 break;
4163 /* Opcode: MemStore P1 P2 *
4165 ** Write the top of the stack into memory location P1.
4166 ** P1 should be a small integer since space is allocated
4167 ** for all memory locations between 0 and P1 inclusive.
4169 ** After the data is stored in the memory location, the
4170 ** stack is popped once if P2 is 1. If P2 is zero, then
4171 ** the original data remains on the stack.
4173 case OP_MemStore: { /* no-push */
4174 assert( pTos>=p->aStack );
4175 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4176 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
4177 pTos--;
4179 /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
4180 ** restore the top of the stack to its original value.
4182 if( pOp->p2 ){
4183 break;
4186 /* Opcode: MemLoad P1 * *
4188 ** Push a copy of the value in memory location P1 onto the stack.
4190 ** If the value is a string, then the value pushed is a pointer to
4191 ** the string that is stored in the memory location. If the memory
4192 ** location is subsequently changed (using OP_MemStore) then the
4193 ** value pushed onto the stack will change too.
4195 case OP_MemLoad: {
4196 int i = pOp->p1;
4197 assert( i>=0 && i<p->nMem );
4198 pTos++;
4199 sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
4200 break;
4203 #ifndef SQLITE_OMIT_AUTOINCREMENT
4204 /* Opcode: MemMax P1 * *
4206 ** Set the value of memory cell P1 to the maximum of its current value
4207 ** and the value on the top of the stack. The stack is unchanged.
4209 ** This instruction throws an error if the memory cell is not initially
4210 ** an integer.
4212 case OP_MemMax: { /* no-push */
4213 int i = pOp->p1;
4214 Mem *pMem;
4215 assert( pTos>=p->aStack );
4216 assert( i>=0 && i<p->nMem );
4217 pMem = &p->aMem[i];
4218 Integerify(pMem);
4219 Integerify(pTos);
4220 if( pMem->i<pTos->i){
4221 pMem->i = pTos->i;
4223 break;
4225 #endif /* SQLITE_OMIT_AUTOINCREMENT */
4227 /* Opcode: MemIncr P1 P2 *
4229 ** Increment the integer valued memory cell P1 by 1. If P2 is not zero
4230 ** and the result after the increment is exactly 1, then jump
4231 ** to P2.
4233 ** This instruction throws an error if the memory cell is not initially
4234 ** an integer.
4236 case OP_MemIncr: { /* no-push */
4237 int i = pOp->p1;
4238 Mem *pMem;
4239 assert( i>=0 && i<p->nMem );
4240 pMem = &p->aMem[i];
4241 assert( pMem->flags==MEM_Int );
4242 pMem->i++;
4243 if( pOp->p2>0 && pMem->i==1 ){
4244 pc = pOp->p2 - 1;
4246 break;
4249 /* Opcode: IfMemPos P1 P2 *
4251 ** If the value of memory cell P1 is 1 or greater, jump to P2. This
4252 ** opcode assumes that memory cell P1 holds an integer value.
4254 case OP_IfMemPos: { /* no-push */
4255 int i = pOp->p1;
4256 Mem *pMem;
4257 assert( i>=0 && i<p->nMem );
4258 pMem = &p->aMem[i];
4259 assert( pMem->flags==MEM_Int );
4260 if( pMem->i>0 ){
4261 pc = pOp->p2 - 1;
4263 break;
4266 /* Opcode: AggReset P1 P2 P3
4268 ** Reset the current aggregator context so that it no longer contains any
4269 ** data. Future aggregator elements will contain P2 values each and be sorted
4270 ** using the KeyInfo structure pointed to by P3.
4272 ** If P1 is non-zero, then only a single aggregator row is available (i.e.
4273 ** there is no GROUP BY expression). In this case it is illegal to invoke
4274 ** OP_AggFocus.
4276 case OP_AggReset: { /* no-push */
4277 assert( !pOp->p3 || pOp->p3type==P3_KEYINFO );
4278 if( pOp->p1 ){
4279 rc = sqlite3VdbeAggReset(0, p->pAgg, (KeyInfo *)pOp->p3);
4280 p->pAgg->nMem = pOp->p2; /* Agg.nMem is used by AggInsert() */
4281 rc = AggInsert(p->pAgg, 0, 0);
4282 }else{
4283 rc = sqlite3VdbeAggReset(db, p->pAgg, (KeyInfo *)pOp->p3);
4284 p->pAgg->nMem = pOp->p2;
4286 if( rc!=SQLITE_OK ){
4287 goto abort_due_to_error;
4289 p->pAgg->apFunc = sqliteMalloc( p->pAgg->nMem*sizeof(p->pAgg->apFunc[0]) );
4290 if( p->pAgg->apFunc==0 ) goto no_mem;
4291 break;
4294 /* Opcode: AggInit P1 P2 P3
4296 ** Initialize the function parameters for an aggregate function.
4297 ** The aggregate will operate out of aggregate column P2.
4298 ** P3 is a pointer to the FuncDef structure for the function.
4300 ** The P1 argument is not used by this opcode. However if the SSE
4301 ** extension is compiled in, P1 is set to the number of arguments that
4302 ** will be passed to the aggregate function, if any. This is used
4303 ** by SSE to select the correct function when (de)serializing statements.
4305 case OP_AggInit: { /* no-push */
4306 int i = pOp->p2;
4307 assert( i>=0 && i<p->pAgg->nMem );
4308 p->pAgg->apFunc[i] = (FuncDef*)pOp->p3;
4309 break;
4312 /* Opcode: AggFunc * P2 P3
4314 ** Execute the step function for an aggregate. The
4315 ** function has P2 arguments. P3 is a pointer to the FuncDef
4316 ** structure that specifies the function.
4318 ** The top of the stack must be an integer which is the index of
4319 ** the aggregate column that corresponds to this aggregate function.
4320 ** Ideally, this index would be another parameter, but there are
4321 ** no free parameters left. The integer is popped from the stack.
4323 case OP_AggFunc: { /* no-push */
4324 int n = pOp->p2;
4325 int i;
4326 Mem *pMem, *pRec;
4327 sqlite3_context ctx;
4328 sqlite3_value **apVal;
4330 assert( n>=0 );
4331 assert( pTos->flags==MEM_Int );
4332 pRec = &pTos[-n];
4333 assert( pRec>=p->aStack );
4335 apVal = p->apArg;
4336 assert( apVal || n==0 );
4338 for(i=0; i<n; i++, pRec++){
4339 apVal[i] = pRec;
4340 storeTypeInfo(pRec, db->enc);
4342 i = pTos->i;
4343 assert( i>=0 && i<p->pAgg->nMem );
4344 ctx.pFunc = (FuncDef*)pOp->p3;
4345 pMem = &p->pAgg->pCurrent->aMem[i];
4346 ctx.s.z = pMem->zShort; /* Space used for small aggregate contexts */
4347 ctx.pAgg = pMem->z;
4348 ctx.cnt = ++pMem->i;
4349 ctx.isError = 0;
4350 ctx.pColl = 0;
4351 if( ctx.pFunc->needCollSeq ){
4352 assert( pOp>p->aOp );
4353 assert( pOp[-1].p3type==P3_COLLSEQ );
4354 assert( pOp[-1].opcode==OP_CollSeq );
4355 ctx.pColl = (CollSeq *)pOp[-1].p3;
4357 (ctx.pFunc->xStep)(&ctx, n, apVal);
4358 pMem->z = ctx.pAgg;
4359 pMem->flags = MEM_AggCtx;
4360 popStack(&pTos, n+1);
4361 if( ctx.isError ){
4362 rc = SQLITE_ERROR;
4364 break;
4367 /* Opcode: AggFocus * P2 *
4369 ** Pop the top of the stack and use that as an aggregator key. If
4370 ** an aggregator with that same key already exists, then make the
4371 ** aggregator the current aggregator and jump to P2. If no aggregator
4372 ** with the given key exists, create one and make it current but
4373 ** do not jump.
4375 ** The order of aggregator opcodes is important. The order is:
4376 ** AggReset AggFocus AggNext. In other words, you must execute
4377 ** AggReset first, then zero or more AggFocus operations, then
4378 ** zero or more AggNext operations. You must not execute an AggFocus
4379 ** in between an AggNext and an AggReset.
4381 case OP_AggFocus: { /* no-push */
4382 char *zKey;
4383 int nKey;
4384 int res;
4385 assert( pTos>=p->aStack );
4386 Stringify(pTos, db->enc);
4387 zKey = pTos->z;
4388 nKey = pTos->n;
4389 assert( p->pAgg->pBtree );
4390 assert( p->pAgg->pCsr );
4391 rc = sqlite3BtreeMoveto(p->pAgg->pCsr, zKey, nKey, &res);
4392 if( rc!=SQLITE_OK ){
4393 goto abort_due_to_error;
4395 if( res==0 ){
4396 rc = sqlite3BtreeData(p->pAgg->pCsr, 0, sizeof(AggElem*),
4397 (char *)&p->pAgg->pCurrent);
4398 pc = pOp->p2 - 1;
4399 }else{
4400 rc = AggInsert(p->pAgg, zKey, nKey);
4402 if( rc!=SQLITE_OK ){
4403 goto abort_due_to_error;
4405 Release(pTos);
4406 pTos--;
4407 break;
4410 /* Opcode: AggSet * P2 *
4412 ** Move the top of the stack into the P2-th field of the current
4413 ** aggregate. String values are duplicated into new memory.
4415 case OP_AggSet: { /* no-push */
4416 AggElem *pFocus;
4417 int i = pOp->p2;
4418 pFocus = p->pAgg->pCurrent;
4419 assert( pTos>=p->aStack );
4420 if( pFocus==0 ) goto no_mem;
4421 assert( i>=0 && i<p->pAgg->nMem );
4422 rc = sqlite3VdbeMemMove(&pFocus->aMem[i], pTos);
4423 pTos--;
4424 break;
4427 /* Opcode: AggGet P1 P2 *
4429 ** Push a new entry onto the stack which is a copy of the P2-th field
4430 ** of the current aggregate. Strings are not duplicated so
4431 ** string values will be ephemeral.
4433 ** If P1 is zero, then the value is pulled out of the current aggregate
4434 ** in the current aggregate context. If P1 is greater than zero, then
4435 ** the value is taken from the P1th outer aggregate context. (i.e. if
4436 ** P1==1 then read from the aggregate context that will be restored
4437 ** by the next OP_AggContextPop opcode).
4439 case OP_AggGet: {
4440 AggElem *pFocus;
4441 int i = pOp->p2;
4442 Agg *pAgg = &p->pAgg[-pOp->p1];
4443 assert( pAgg>=p->apAgg );
4444 pFocus = pAgg->pCurrent;
4445 if( pFocus==0 ){
4446 int res;
4447 if( sqlite3_malloc_failed ) goto no_mem;
4448 rc = sqlite3BtreeFirst(pAgg->pCsr, &res);
4449 if( rc!=SQLITE_OK ){
4450 return rc;
4452 if( res!=0 ){
4453 rc = AggInsert(pAgg, "", 1);
4454 pFocus = pAgg->pCurrent;
4455 }else{
4456 rc = sqlite3BtreeData(pAgg->pCsr, 0, 4, (char *)&pFocus);
4459 assert( i>=0 && i<pAgg->nMem );
4460 pTos++;
4461 sqlite3VdbeMemShallowCopy(pTos, &pFocus->aMem[i], MEM_Ephem);
4462 if( pTos->flags&MEM_Str ){
4463 sqlite3VdbeChangeEncoding(pTos, db->enc);
4465 break;
4468 /* Opcode: AggNext * P2 *
4470 ** Make the next aggregate value the current aggregate. The prior
4471 ** aggregate is deleted. If all aggregate values have been consumed,
4472 ** jump to P2.
4474 ** The order of aggregator opcodes is important. The order is:
4475 ** AggReset AggFocus AggNext. In other words, you must execute
4476 ** AggReset first, then zero or more AggFocus operations, then
4477 ** zero or more AggNext operations. You must not execute an AggFocus
4478 ** in between an AggNext and an AggReset.
4480 case OP_AggNext: { /* no-push */
4481 int res;
4482 assert( rc==SQLITE_OK );
4483 CHECK_FOR_INTERRUPT;
4484 if( p->pAgg->searching==0 ){
4485 p->pAgg->searching = 1;
4486 if( p->pAgg->pCsr ){
4487 rc = sqlite3BtreeFirst(p->pAgg->pCsr, &res);
4488 }else{
4489 res = 0;
4491 }else{
4492 if( p->pAgg->pCsr ){
4493 rc = sqlite3BtreeNext(p->pAgg->pCsr, &res);
4494 }else{
4495 res = 1;
4498 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4499 if( res!=0 ){
4500 pc = pOp->p2 - 1;
4501 }else{
4502 int i;
4503 sqlite3_context ctx;
4504 Mem *aMem;
4506 if( p->pAgg->pCsr ){
4507 rc = sqlite3BtreeData(p->pAgg->pCsr, 0, sizeof(AggElem*),
4508 (char *)&p->pAgg->pCurrent);
4509 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4511 aMem = p->pAgg->pCurrent->aMem;
4512 for(i=0; i<p->pAgg->nMem; i++){
4513 FuncDef *pFunc = p->pAgg->apFunc[i];
4514 Mem *pMem = &aMem[i];
4515 if( pFunc==0 || pFunc->xFinalize==0 ) continue;
4516 ctx.s.flags = MEM_Null;
4517 ctx.s.z = pMem->zShort;
4518 ctx.pAgg = (void*)pMem->z;
4519 ctx.cnt = pMem->i;
4520 ctx.pFunc = pFunc;
4521 pFunc->xFinalize(&ctx);
4522 pMem->z = ctx.pAgg;
4523 if( pMem->z && pMem->z!=pMem->zShort ){
4524 sqliteFree( pMem->z );
4526 *pMem = ctx.s;
4527 if( pMem->flags & MEM_Short ){
4528 pMem->z = pMem->zShort;
4532 break;
4535 /* Opcode: Vacuum * * *
4537 ** Vacuum the entire database. This opcode will cause other virtual
4538 ** machines to be created and run. It may not be called from within
4539 ** a transaction.
4541 case OP_Vacuum: { /* no-push */
4542 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4543 rc = sqlite3RunVacuum(&p->zErrMsg, db);
4544 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4545 break;
4548 /* Opcode: Expire P1 * *
4550 ** Cause precompiled statements to become expired. An expired statement
4551 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
4552 ** (via sqlite3_step()).
4554 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4555 ** then only the currently executing statement is affected.
4557 case OP_Expire: { /* no-push */
4558 if( !pOp->p1 ){
4559 sqlite3ExpirePreparedStatements(db);
4560 }else{
4561 p->expired = 1;
4563 break;
4567 /* An other opcode is illegal...
4569 default: {
4570 sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",pOp->opcode);
4571 sqlite3SetString(&p->zErrMsg, "unknown opcode ", zBuf, (char*)0);
4572 rc = SQLITE_INTERNAL;
4573 break;
4576 /*****************************************************************************
4577 ** The cases of the switch statement above this line should all be indented
4578 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
4579 ** readability. From this point on down, the normal indentation rules are
4580 ** restored.
4581 *****************************************************************************/
4584 /* Make sure the stack limit was not exceeded */
4585 assert( pTos<=pStackLimit );
4587 #ifdef VDBE_PROFILE
4589 long long elapse = hwtime() - start;
4590 pOp->cycles += elapse;
4591 pOp->cnt++;
4592 #if 0
4593 fprintf(stdout, "%10lld ", elapse);
4594 sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
4595 #endif
4597 #endif
4599 /* The following code adds nothing to the actual functionality
4600 ** of the program. It is only here for testing and debugging.
4601 ** On the other hand, it does burn CPU cycles every time through
4602 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
4604 #ifndef NDEBUG
4605 /* Sanity checking on the top element of the stack */
4606 if( pTos>=p->aStack ){
4607 sqlite3VdbeMemSanity(pTos, db->enc);
4609 if( pc<-1 || pc>=p->nOp ){
4610 sqlite3SetString(&p->zErrMsg, "jump destination out of range", (char*)0);
4611 rc = SQLITE_INTERNAL;
4613 #ifdef SQLITE_DEBUG
4614 /* Code for tracing the vdbe stack. */
4615 if( p->trace && pTos>=p->aStack ){
4616 int i;
4617 fprintf(p->trace, "Stack:");
4618 for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
4619 if( pTos[i].flags & MEM_Null ){
4620 fprintf(p->trace, " NULL");
4621 }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
4622 fprintf(p->trace, " si:%lld", pTos[i].i);
4623 }else if( pTos[i].flags & MEM_Int ){
4624 fprintf(p->trace, " i:%lld", pTos[i].i);
4625 }else if( pTos[i].flags & MEM_Real ){
4626 fprintf(p->trace, " r:%g", pTos[i].r);
4627 }else{
4628 char zBuf[100];
4629 sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf, 100);
4630 fprintf(p->trace, " ");
4631 fprintf(p->trace, "%s", zBuf);
4634 if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
4635 fprintf(p->trace,"\n");
4637 #endif /* SQLITE_DEBUG */
4638 #endif /* NDEBUG */
4639 } /* The end of the for(;;) loop the loops through opcodes */
4641 /* If we reach this point, it means that execution is finished.
4643 vdbe_halt:
4644 if( rc ){
4645 p->rc = rc;
4646 rc = SQLITE_ERROR;
4647 }else{
4648 rc = SQLITE_DONE;
4650 sqlite3VdbeHalt(p);
4651 p->pTos = pTos;
4652 return rc;
4654 /* Jump to here if a malloc() fails. It's hard to get a malloc()
4655 ** to fail on a modern VM computer, so this code is untested.
4657 no_mem:
4658 sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
4659 rc = SQLITE_NOMEM;
4660 goto vdbe_halt;
4662 /* Jump to here for an SQLITE_MISUSE error.
4664 abort_due_to_misuse:
4665 rc = SQLITE_MISUSE;
4666 /* Fall thru into abort_due_to_error */
4668 /* Jump to here for any other kind of fatal error. The "rc" variable
4669 ** should hold the error number.
4671 abort_due_to_error:
4672 if( p->zErrMsg==0 ){
4673 if( sqlite3_malloc_failed ) rc = SQLITE_NOMEM;
4674 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
4676 goto vdbe_halt;
4678 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
4679 ** flag.
4681 abort_due_to_interrupt:
4682 assert( db->flags & SQLITE_Interrupt );
4683 db->flags &= ~SQLITE_Interrupt;
4684 if( db->magic!=SQLITE_MAGIC_BUSY ){
4685 rc = SQLITE_MISUSE;
4686 }else{
4687 rc = SQLITE_INTERRUPT;
4689 p->rc = rc;
4690 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
4691 goto vdbe_halt;