monotone

monotone Mtn Source Tree

Root/sqlite/vdbe.c

1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** The code in this file implements 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.
17**
18** In the external interface, an "sqlite3_stmt*" is an opaque pointer
19** to a VDBE.
20**
21** The SQL parser generates a program which is then executed by
22** the VDBE to do the work of the SQL statement. VDBE programs are
23** similar in form to assembly language. The program consists of
24** a linear sequence of operations. Each operation has an opcode
25** and 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.
29**
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.
39**
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.
45**
46** $Id: vdbe.c,v 1.626 2007/06/15 14:53:53 danielk1977 Exp $
47*/
48#include "sqliteInt.h"
49#include "os.h"
50#include <ctype.h>
51#include <math.h>
52#include "vdbeInt.h"
53
54/*
55** The following global variable is incremented every time a cursor
56** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
57** procedures use this information to make sure that indices are
58** working correctly. This variable has no function other than to
59** help verify the correct operation of the library.
60*/
61#ifdef SQLITE_TEST
62int sqlite3_search_count = 0;
63#endif
64
65/*
66** When this global variable is positive, it gets decremented once before
67** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
68** field of the sqlite3 structure is set in order to simulate and interrupt.
69**
70** This facility is used for testing purposes only. It does not function
71** in an ordinary build.
72*/
73#ifdef SQLITE_TEST
74int sqlite3_interrupt_count = 0;
75#endif
76
77/*
78** The next global variable is incremented each type the OP_Sort opcode
79** is executed. The test procedures use this information to make sure that
80** sorting is occurring or not occuring at appropriate times. This variable
81** has no function other than to help verify the correct operation of the
82** library.
83*/
84#ifdef SQLITE_TEST
85int sqlite3_sort_count = 0;
86#endif
87
88/*
89** The next global variable records the size of the largest MEM_Blob
90** or MEM_Str that has appeared on the VDBE stack. The test procedures
91** use this information to make sure that the zero-blob functionality
92** is working correctly. This variable has no function other than to
93** help verify the correct operation of the library.
94*/
95#ifdef SQLITE_TEST
96int sqlite3_max_blobsize = 0;
97#endif
98
99/*
100** Release the memory associated with the given stack level. This
101** leaves the Mem.flags field in an inconsistent state.
102*/
103#define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
104
105/*
106** Convert the given stack entity into a string if it isn't one
107** already. Return non-zero if a malloc() fails.
108*/
109#define Stringify(P, enc) \
110 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
111 { goto no_mem; }
112
113/*
114** Convert the given stack entity into a string that has been obtained
115** from sqliteMalloc(). This is different from Stringify() above in that
116** Stringify() will use the NBFS bytes of static string space if the string
117** will fit but this routine always mallocs for space.
118** Return non-zero if we run out of memory.
119*/
120#define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
121
122/*
123** The header of a record consists of a sequence variable-length integers.
124** These integers are almost always small and are encoded as a single byte.
125** The following macro takes advantage this fact to provide a fast decode
126** of the integers in a record header. It is faster for the common case
127** where the integer is a single byte. It is a little slower when the
128** integer is two or more bytes. But overall it is faster.
129**
130** The following expressions are equivalent:
131**
132** x = sqlite3GetVarint32( A, &B );
133**
134** x = GetVarint( A, B );
135**
136*/
137#define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
138
139/*
140** An ephemeral string value (signified by the MEM_Ephem flag) contains
141** a pointer to a dynamically allocated string where some other entity
142** is responsible for deallocating that string. Because the stack entry
143** does not control the string, it might be deleted without the stack
144** entry knowing it.
145**
146** This routine converts an ephemeral string into a dynamically allocated
147** string that the stack entry itself controls. In other words, it
148** converts an MEM_Ephem string into an MEM_Dyn string.
149*/
150#define Deephemeralize(P) \
151 if( ((P)->flags&MEM_Ephem)!=0 \
152 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
153
154/*
155** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
156** P if required.
157*/
158#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
159
160/*
161** Argument pMem points at a memory cell that will be passed to a
162** user-defined function or returned to the user as the result of a query.
163** The second argument, 'db_enc' is the text encoding used by the vdbe for
164** stack variables. This routine sets the pMem->enc and pMem->type
165** variables used by the sqlite3_value_*() routines.
166*/
167#define storeTypeInfo(A,B) _storeTypeInfo(A)
168static void _storeTypeInfo(Mem *pMem){
169 int flags = pMem->flags;
170 if( flags & MEM_Null ){
171 pMem->type = SQLITE_NULL;
172 }
173 else if( flags & MEM_Int ){
174 pMem->type = SQLITE_INTEGER;
175 }
176 else if( flags & MEM_Real ){
177 pMem->type = SQLITE_FLOAT;
178 }
179 else if( flags & MEM_Str ){
180 pMem->type = SQLITE_TEXT;
181 }else{
182 pMem->type = SQLITE_BLOB;
183 }
184}
185
186/*
187** Pop the stack N times.
188*/
189static void popStack(Mem **ppTos, int N){
190 Mem *pTos = *ppTos;
191 while( N>0 ){
192 N--;
193 Release(pTos);
194 pTos--;
195 }
196 *ppTos = pTos;
197}
198
199/*
200** Allocate cursor number iCur. Return a pointer to it. Return NULL
201** if we run out of memory.
202*/
203static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
204 Cursor *pCx;
205 assert( iCur<p->nCursor );
206 if( p->apCsr[iCur] ){
207 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
208 }
209 p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
210 if( pCx ){
211 pCx->iDb = iDb;
212 }
213 return pCx;
214}
215
216/*
217** Try to convert a value into a numeric representation if we can
218** do so without loss of information. In other words, if the string
219** looks like a number, convert it into a number. If it does not
220** look like a number, leave it alone.
221*/
222static void applyNumericAffinity(Mem *pRec){
223 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
224 int realnum;
225 sqlite3VdbeMemNulTerminate(pRec);
226 if( (pRec->flags&MEM_Str)
227 && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
228 i64 value;
229 sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
230 if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
231 sqlite3VdbeMemRelease(pRec);
232 pRec->u.i = value;
233 pRec->flags = MEM_Int;
234 }else{
235 sqlite3VdbeMemRealify(pRec);
236 }
237 }
238 }
239}
240
241/*
242** Processing is determine by the affinity parameter:
243**
244** SQLITE_AFF_INTEGER:
245** SQLITE_AFF_REAL:
246** SQLITE_AFF_NUMERIC:
247** Try to convert pRec to an integer representation or a
248** floating-point representation if an integer representation
249** is not possible. Note that the integer representation is
250** always preferred, even if the affinity is REAL, because
251** an integer representation is more space efficient on disk.
252**
253** SQLITE_AFF_TEXT:
254** Convert pRec to a text representation.
255**
256** SQLITE_AFF_NONE:
257** No-op. pRec is unchanged.
258*/
259static void applyAffinity(Mem *pRec, char affinity, u8 enc){
260 if( affinity==SQLITE_AFF_TEXT ){
261 /* Only attempt the conversion to TEXT if there is an integer or real
262 ** representation (blob and NULL do not get converted) but no string
263 ** representation.
264 */
265 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
266 sqlite3VdbeMemStringify(pRec, enc);
267 }
268 pRec->flags &= ~(MEM_Real|MEM_Int);
269 }else if( affinity!=SQLITE_AFF_NONE ){
270 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
271 || affinity==SQLITE_AFF_NUMERIC );
272 applyNumericAffinity(pRec);
273 if( pRec->flags & MEM_Real ){
274 sqlite3VdbeIntegerAffinity(pRec);
275 }
276 }
277}
278
279/*
280** Try to convert the type of a function argument or a result column
281** into a numeric representation. Use either INTEGER or REAL whichever
282** is appropriate. But only do the conversion if it is possible without
283** loss of information and return the revised type of the argument.
284**
285** This is an EXPERIMENTAL api and is subject to change or removal.
286*/
287int sqlite3_value_numeric_type(sqlite3_value *pVal){
288 Mem *pMem = (Mem*)pVal;
289 applyNumericAffinity(pMem);
290 storeTypeInfo(pMem, 0);
291 return pMem->type;
292}
293
294/*
295** Exported version of applyAffinity(). This one works on sqlite3_value*,
296** not the internal Mem* type.
297*/
298void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
299 applyAffinity((Mem *)pVal, affinity, enc);
300}
301
302#ifdef SQLITE_DEBUG
303/*
304** Write a nice string representation of the contents of cell pMem
305** into buffer zBuf, length nBuf.
306*/
307void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
308 char *zCsr = zBuf;
309 int f = pMem->flags;
310
311 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
312
313 if( f&MEM_Blob ){
314 int i;
315 char c;
316 if( f & MEM_Dyn ){
317 c = 'z';
318 assert( (f & (MEM_Static|MEM_Ephem))==0 );
319 }else if( f & MEM_Static ){
320 c = 't';
321 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
322 }else if( f & MEM_Ephem ){
323 c = 'e';
324 assert( (f & (MEM_Static|MEM_Dyn))==0 );
325 }else{
326 c = 's';
327 }
328
329 sqlite3_snprintf(100, zCsr, "%c", c);
330 zCsr += strlen(zCsr);
331 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
332 zCsr += strlen(zCsr);
333 for(i=0; i<16 && i<pMem->n; i++){
334 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
335 zCsr += strlen(zCsr);
336 }
337 for(i=0; i<16 && i<pMem->n; i++){
338 char z = pMem->z[i];
339 if( z<32 || z>126 ) *zCsr++ = '.';
340 else *zCsr++ = z;
341 }
342
343 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
344 zCsr += strlen(zCsr);
345 if( f & MEM_Zero ){
346 sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
347 zCsr += strlen(zCsr);
348 }
349 *zCsr = '\0';
350 }else if( f & MEM_Str ){
351 int j, k;
352 zBuf[0] = ' ';
353 if( f & MEM_Dyn ){
354 zBuf[1] = 'z';
355 assert( (f & (MEM_Static|MEM_Ephem))==0 );
356 }else if( f & MEM_Static ){
357 zBuf[1] = 't';
358 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
359 }else if( f & MEM_Ephem ){
360 zBuf[1] = 'e';
361 assert( (f & (MEM_Static|MEM_Dyn))==0 );
362 }else{
363 zBuf[1] = 's';
364 }
365 k = 2;
366 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
367 k += strlen(&zBuf[k]);
368 zBuf[k++] = '[';
369 for(j=0; j<15 && j<pMem->n; j++){
370 u8 c = pMem->z[j];
371 if( c>=0x20 && c<0x7f ){
372 zBuf[k++] = c;
373 }else{
374 zBuf[k++] = '.';
375 }
376 }
377 zBuf[k++] = ']';
378 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
379 k += strlen(&zBuf[k]);
380 zBuf[k++] = 0;
381 }
382}
383#endif
384
385
386#ifdef VDBE_PROFILE
387/*
388** The following routine only works on pentium-class processors.
389** It uses the RDTSC opcode to read the cycle count value out of the
390** processor and returns that value. This can be used for high-res
391** profiling.
392*/
393__inline__ unsigned long long int hwtime(void){
394 unsigned long long int x;
395 __asm__("rdtsc\n\t"
396 "mov %%edx, %%ecx\n\t"
397 :"=A" (x));
398 return x;
399}
400#endif
401
402/*
403** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
404** sqlite3_interrupt() routine has been called. If it has been, then
405** processing of the VDBE program is interrupted.
406**
407** This macro added to every instruction that does a jump in order to
408** implement a loop. This test used to be on every single instruction,
409** but that meant we more testing that we needed. By only testing the
410** flag on jump instructions, we get a (small) speed improvement.
411*/
412#define CHECK_FOR_INTERRUPT \
413 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
414
415
416/*
417** Execute as much of a VDBE program as we can then return.
418**
419** sqlite3VdbeMakeReady() must be called before this routine in order to
420** close the program with a final OP_Halt and to set up the callbacks
421** and the error message pointer.
422**
423** Whenever a row or result data is available, this routine will either
424** invoke the result callback (if there is one) or return with
425** SQLITE_ROW.
426**
427** If an attempt is made to open a locked database, then this routine
428** will either invoke the busy callback (if there is one) or it will
429** return SQLITE_BUSY.
430**
431** If an error occurs, an error message is written to memory obtained
432** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
433** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
434**
435** If the callback ever returns non-zero, then the program exits
436** immediately. There will be no error message but the p->rc field is
437** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
438**
439** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
440** routine to return SQLITE_ERROR.
441**
442** Other fatal errors return SQLITE_ERROR.
443**
444** After this routine has finished, sqlite3VdbeFinalize() should be
445** used to clean up the mess that was left behind.
446*/
447int sqlite3VdbeExec(
448 Vdbe *p /* The VDBE */
449){
450 int pc; /* The program counter */
451 Op *pOp; /* Current operation */
452 int rc = SQLITE_OK; /* Value to return */
453 sqlite3 *db = p->db; /* The database */
454 u8 encoding = ENC(db); /* The database encoding */
455 Mem *pTos; /* Top entry in the operand stack */
456#ifdef VDBE_PROFILE
457 unsigned long long start; /* CPU clock count at start of opcode */
458 int origPc; /* Program counter at start of opcode */
459#endif
460#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
461 int nProgressOps = 0; /* Opcodes executed since progress callback. */
462#endif
463#ifndef NDEBUG
464 Mem *pStackLimit;
465#endif
466
467 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
468 assert( db->magic==SQLITE_MAGIC_BUSY );
469 pTos = p->pTos;
470 if( p->rc==SQLITE_NOMEM ){
471 /* This happens if a malloc() inside a call to sqlite3_column_text() or
472 ** sqlite3_column_text16() failed. */
473 goto no_mem;
474 }
475 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
476 p->rc = SQLITE_OK;
477 assert( p->explain==0 );
478 if( p->popStack ){
479 popStack(&pTos, p->popStack);
480 p->popStack = 0;
481 }
482 p->resOnStack = 0;
483 db->busyHandler.nBusy = 0;
484 CHECK_FOR_INTERRUPT;
485 sqlite3VdbeIOTraceSql(p);
486#ifdef SQLITE_DEBUG
487 if( (p->db->flags & SQLITE_VdbeListing)!=0
488 || sqlite3OsFileExists("vdbe_explain")
489 ){
490 int i;
491 printf("VDBE Program Listing:\n");
492 sqlite3VdbePrintSql(p);
493 for(i=0; i<p->nOp; i++){
494 sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
495 }
496 }
497 if( sqlite3OsFileExists("vdbe_trace") ){
498 p->trace = stdout;
499 }
500#endif
501 for(pc=p->pc; rc==SQLITE_OK; pc++){
502 assert( pc>=0 && pc<p->nOp );
503 assert( pTos<=&p->aStack[pc] );
504 if( sqlite3MallocFailed() ) goto no_mem;
505#ifdef VDBE_PROFILE
506 origPc = pc;
507 start = hwtime();
508#endif
509 pOp = &p->aOp[pc];
510
511 /* Only allow tracing if SQLITE_DEBUG is defined.
512 */
513#ifdef SQLITE_DEBUG
514 if( p->trace ){
515 if( pc==0 ){
516 printf("VDBE Execution Trace:\n");
517 sqlite3VdbePrintSql(p);
518 }
519 sqlite3VdbePrintOp(p->trace, pc, pOp);
520 }
521 if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
522 sqlite3VdbePrintSql(p);
523 }
524#endif
525
526
527 /* Check to see if we need to simulate an interrupt. This only happens
528 ** if we have a special test build.
529 */
530#ifdef SQLITE_TEST
531 if( sqlite3_interrupt_count>0 ){
532 sqlite3_interrupt_count--;
533 if( sqlite3_interrupt_count==0 ){
534 sqlite3_interrupt(db);
535 }
536 }
537#endif
538
539#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
540 /* Call the progress callback if it is configured and the required number
541 ** of VDBE ops have been executed (either since this invocation of
542 ** sqlite3VdbeExec() or since last time the progress callback was called).
543 ** If the progress callback returns non-zero, exit the virtual machine with
544 ** a return code SQLITE_ABORT.
545 */
546 if( db->xProgress ){
547 if( db->nProgressOps==nProgressOps ){
548 int prc;
549 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
550 prc =db->xProgress(db->pProgressArg);
551 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
552 if( prc!=0 ){
553 rc = SQLITE_INTERRUPT;
554 goto vdbe_halt;
555 }
556 nProgressOps = 0;
557 }
558 nProgressOps++;
559 }
560#endif
561
562#ifndef NDEBUG
563 /* This is to check that the return value of static function
564 ** opcodeNoPush() (see vdbeaux.c) returns values that match the
565 ** implementation of the virtual machine in this file. If
566 ** opcodeNoPush() returns non-zero, then the stack is guarenteed
567 ** not to grow when the opcode is executed. If it returns zero, then
568 ** the stack may grow by at most 1.
569 **
570 ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
571 ** available if NDEBUG is defined at build time.
572 */
573 pStackLimit = pTos;
574 if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
575 pStackLimit++;
576 }
577#endif
578
579 switch( pOp->opcode ){
580
581/*****************************************************************************
582** What follows is a massive switch statement where each case implements a
583** separate instruction in the virtual machine. If we follow the usual
584** indentation conventions, each case should be indented by 6 spaces. But
585** that is a lot of wasted space on the left margin. So the code within
586** the switch statement will break with convention and be flush-left. Another
587** big comment (similar to this one) will mark the point in the code where
588** we transition back to normal indentation.
589**
590** The formatting of each case is important. The makefile for SQLite
591** generates two C files "opcodes.h" and "opcodes.c" by scanning this
592** file looking for lines that begin with "case OP_". The opcodes.h files
593** will be filled with #defines that give unique integer values to each
594** opcode and the opcodes.c file is filled with an array of strings where
595** each string is the symbolic name for the corresponding opcode. If the
596** case statement is followed by a comment of the form "/# same as ... #/"
597** that comment is used to determine the particular value of the opcode.
598**
599** If a comment on the same line as the "case OP_" construction contains
600** the word "no-push", then the opcode is guarenteed not to grow the
601** vdbe stack when it is executed. See function opcode() in
602** vdbeaux.c for details.
603**
604** Documentation about VDBE opcodes is generated by scanning this file
605** for lines of that contain "Opcode:". That line and all subsequent
606** comment lines are used in the generation of the opcode.html documentation
607** file.
608**
609** SUMMARY:
610**
611** Formatting is important to scripts that scan this file.
612** Do not deviate from the formatting style currently in use.
613**
614*****************************************************************************/
615
616/* Opcode: Goto * P2 *
617**
618** An unconditional jump to address P2.
619** The next instruction executed will be
620** the one at index P2 from the beginning of
621** the program.
622*/
623case OP_Goto: { /* no-push */
624 CHECK_FOR_INTERRUPT;
625 pc = pOp->p2 - 1;
626 break;
627}
628
629/* Opcode: Gosub * P2 *
630**
631** Push the current address plus 1 onto the return address stack
632** and then jump to address P2.
633**
634** The return address stack is of limited depth. If too many
635** OP_Gosub operations occur without intervening OP_Returns, then
636** the return address stack will fill up and processing will abort
637** with a fatal error.
638*/
639case OP_Gosub: { /* no-push */
640 assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
641 p->returnStack[p->returnDepth++] = pc+1;
642 pc = pOp->p2 - 1;
643 break;
644}
645
646/* Opcode: Return * * *
647**
648** Jump immediately to the next instruction after the last unreturned
649** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
650** processing aborts with a fatal error.
651*/
652case OP_Return: { /* no-push */
653 assert( p->returnDepth>0 );
654 p->returnDepth--;
655 pc = p->returnStack[p->returnDepth] - 1;
656 break;
657}
658
659/* Opcode: Halt P1 P2 P3
660**
661** Exit immediately. All open cursors, Fifos, etc are closed
662** automatically.
663**
664** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
665** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
666** For errors, it can be some other value. If P1!=0 then P2 will determine
667** whether or not to rollback the current transaction. Do not rollback
668** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
669** then back out all changes that have occurred during this execution of the
670** VDBE, but do not rollback the transaction.
671**
672** If P3 is not null then it is an error message string.
673**
674** There is an implied "Halt 0 0 0" instruction inserted at the very end of
675** every program. So a jump past the last instruction of the program
676** is the same as executing Halt.
677*/
678case OP_Halt: { /* no-push */
679 p->pTos = pTos;
680 p->rc = pOp->p1;
681 p->pc = pc;
682 p->errorAction = pOp->p2;
683 if( pOp->p3 ){
684 sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
685 }
686 rc = sqlite3VdbeHalt(p);
687 assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
688 if( rc==SQLITE_BUSY ){
689 p->rc = SQLITE_BUSY;
690 return SQLITE_BUSY;
691 }
692 return p->rc ? SQLITE_ERROR : SQLITE_DONE;
693}
694
695/* Opcode: Integer P1 * *
696**
697** The 32-bit integer value P1 is pushed onto the stack.
698*/
699case OP_Integer: {
700 pTos++;
701 pTos->flags = MEM_Int;
702 pTos->u.i = pOp->p1;
703 break;
704}
705
706/* Opcode: Int64 * * P3
707**
708** P3 is a string representation of an integer. Convert that integer
709** to a 64-bit value and push it onto the stack.
710*/
711case OP_Int64: {
712 pTos++;
713 assert( pOp->p3!=0 );
714 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
715 pTos->z = pOp->p3;
716 pTos->n = strlen(pTos->z);
717 pTos->enc = SQLITE_UTF8;
718 pTos->u.i = sqlite3VdbeIntValue(pTos);
719 pTos->flags |= MEM_Int;
720 break;
721}
722
723/* Opcode: Real * * P3
724**
725** The string value P3 is converted to a real and pushed on to the stack.
726*/
727case OP_Real: { /* same as TK_FLOAT, */
728 pTos++;
729 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
730 pTos->z = pOp->p3;
731 pTos->n = strlen(pTos->z);
732 pTos->enc = SQLITE_UTF8;
733 pTos->r = sqlite3VdbeRealValue(pTos);
734 pTos->flags |= MEM_Real;
735 sqlite3VdbeChangeEncoding(pTos, encoding);
736 break;
737}
738
739/* Opcode: String8 * * P3
740**
741** P3 points to a nul terminated UTF-8 string. This opcode is transformed
742** into an OP_String before it is executed for the first time.
743*/
744case OP_String8: { /* same as TK_STRING */
745 assert( pOp->p3!=0 );
746 pOp->opcode = OP_String;
747 pOp->p1 = strlen(pOp->p3);
748 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
749 assert( pOp->p1 < SQLITE_MAX_LENGTH );
750
751#ifndef SQLITE_OMIT_UTF16
752 if( encoding!=SQLITE_UTF8 ){
753 pTos++;
754 sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
755 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
756 if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
757 pTos->flags &= ~(MEM_Dyn);
758 pTos->flags |= MEM_Static;
759 if( pOp->p3type==P3_DYNAMIC ){
760 sqliteFree(pOp->p3);
761 }
762 pOp->p3type = P3_DYNAMIC;
763 pOp->p3 = pTos->z;
764 pOp->p1 = pTos->n;
765 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
766 break;
767 }
768#endif
769 /* Otherwise fall through to the next case, OP_String */
770}
771
772/* Opcode: String P1 * P3
773**
774** The string value P3 of length P1 (bytes) is pushed onto the stack.
775*/
776case OP_String: {
777 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
778 pTos++;
779 assert( pOp->p3!=0 );
780 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
781 pTos->z = pOp->p3;
782 pTos->n = pOp->p1;
783 pTos->enc = encoding;
784 break;
785}
786
787/* Opcode: Null * * *
788**
789** Push a NULL onto the stack.
790*/
791case OP_Null: {
792 pTos++;
793 pTos->flags = MEM_Null;
794 pTos->n = 0;
795 break;
796}
797
798
799#ifndef SQLITE_OMIT_BLOB_LITERAL
800/* Opcode: HexBlob * * P3
801**
802** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
803** vdbe stack.
804**
805** The first time this instruction executes, in transforms itself into a
806** 'Blob' opcode with a binary blob as P3.
807*/
808case OP_HexBlob: { /* same as TK_BLOB */
809 pOp->opcode = OP_Blob;
810 pOp->p1 = strlen(pOp->p3)/2;
811 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
812 assert( pOp->p1 < SQLITE_MAX_LENGTH );
813 if( pOp->p1 ){
814 char *zBlob = sqlite3HexToBlob(pOp->p3);
815 if( !zBlob ) goto no_mem;
816 if( pOp->p3type==P3_DYNAMIC ){
817 sqliteFree(pOp->p3);
818 }
819 pOp->p3 = zBlob;
820 pOp->p3type = P3_DYNAMIC;
821 }else{
822 if( pOp->p3type==P3_DYNAMIC ){
823 sqliteFree(pOp->p3);
824 }
825 pOp->p3type = P3_STATIC;
826 pOp->p3 = "";
827 }
828
829 /* Fall through to the next case, OP_Blob. */
830}
831
832/* Opcode: Blob P1 * P3
833**
834** P3 points to a blob of data P1 bytes long. Push this
835** value onto the stack. This instruction is not coded directly
836** by the compiler. Instead, the compiler layer specifies
837** an OP_HexBlob opcode, with the hex string representation of
838** the blob as P3. This opcode is transformed to an OP_Blob
839** the first time it is executed.
840*/
841case OP_Blob: {
842 pTos++;
843 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
844 sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
845 pTos->enc = encoding;
846 break;
847}
848#endif /* SQLITE_OMIT_BLOB_LITERAL */
849
850/* Opcode: Variable P1 * *
851**
852** Push the value of variable P1 onto the stack. A variable is
853** an unknown in the original SQL string as handed to sqlite3_compile().
854** Any occurance of the '?' character in the original SQL is considered
855** a variable. Variables in the SQL string are number from left to
856** right beginning with 1. The values of variables are set using the
857** sqlite3_bind() API.
858*/
859case OP_Variable: {
860 int j = pOp->p1 - 1;
861 Mem *pVar;
862 assert( j>=0 && j<p->nVar );
863
864 pVar = &p->aVar[j];
865 if( sqlite3VdbeMemTooBig(pVar) ){
866 goto too_big;
867 }
868 pTos++;
869 sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
870 break;
871}
872
873/* Opcode: Pop P1 * *
874**
875** P1 elements are popped off of the top of stack and discarded.
876*/
877case OP_Pop: { /* no-push */
878 assert( pOp->p1>=0 );
879 popStack(&pTos, pOp->p1);
880 assert( pTos>=&p->aStack[-1] );
881 break;
882}
883
884/* Opcode: Dup P1 P2 *
885**
886** A copy of the P1-th element of the stack
887** is made and pushed onto the top of the stack.
888** The top of the stack is element 0. So the
889** instruction "Dup 0 0 0" will make a copy of the
890** top of the stack.
891**
892** If the content of the P1-th element is a dynamically
893** allocated string, then a new copy of that string
894** is made if P2==0. If P2!=0, then just a pointer
895** to the string is copied.
896**
897** Also see the Pull instruction.
898*/
899case OP_Dup: {
900 Mem *pFrom = &pTos[-pOp->p1];
901 assert( pFrom<=pTos && pFrom>=p->aStack );
902 pTos++;
903 sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
904 if( pOp->p2 ){
905 Deephemeralize(pTos);
906 }
907 break;
908}
909
910/* Opcode: Pull P1 * *
911**
912** The P1-th element is removed from its current location on
913** the stack and pushed back on top of the stack. The
914** top of the stack is element 0, so "Pull 0 0 0" is
915** a no-op. "Pull 1 0 0" swaps the top two elements of
916** the stack.
917**
918** See also the Dup instruction.
919*/
920case OP_Pull: { /* no-push */
921 Mem *pFrom = &pTos[-pOp->p1];
922 int i;
923 Mem ts;
924
925 ts = *pFrom;
926 Deephemeralize(pTos);
927 for(i=0; i<pOp->p1; i++, pFrom++){
928 Deephemeralize(&pFrom[1]);
929 assert( (pFrom[1].flags & MEM_Ephem)==0 );
930 *pFrom = pFrom[1];
931 if( pFrom->flags & MEM_Short ){
932 assert( pFrom->flags & (MEM_Str|MEM_Blob) );
933 assert( pFrom->z==pFrom[1].zShort );
934 pFrom->z = pFrom->zShort;
935 }
936 }
937 *pTos = ts;
938 if( pTos->flags & MEM_Short ){
939 assert( pTos->flags & (MEM_Str|MEM_Blob) );
940 assert( pTos->z==pTos[-pOp->p1].zShort );
941 pTos->z = pTos->zShort;
942 }
943 break;
944}
945
946/* Opcode: Push P1 * *
947**
948** Overwrite the value of the P1-th element down on the
949** stack (P1==0 is the top of the stack) with the value
950** of the top of the stack. Then pop the top of the stack.
951*/
952case OP_Push: { /* no-push */
953 Mem *pTo = &pTos[-pOp->p1];
954
955 assert( pTo>=p->aStack );
956 sqlite3VdbeMemMove(pTo, pTos);
957 pTos--;
958 break;
959}
960
961/* Opcode: Callback P1 * *
962**
963** The top P1 values on the stack represent a single result row from
964** a query. This opcode causes the sqlite3_step() call to terminate
965** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
966** structure to provide access to the top P1 values as the result
967** row. When the sqlite3_step() function is run again, the top P1
968** values will be automatically popped from the stack before the next
969** instruction executes.
970*/
971case OP_Callback: { /* no-push */
972 Mem *pMem;
973 Mem *pFirstColumn;
974 assert( p->nResColumn==pOp->p1 );
975
976 /* Data in the pager might be moved or changed out from under us
977 ** in between the return from this sqlite3_step() call and the
978 ** next call to sqlite3_step(). So deephermeralize everything on
979 ** the stack. Note that ephemeral data is never stored in memory
980 ** cells so we do not have to worry about them.
981 */
982 pFirstColumn = &pTos[0-pOp->p1];
983 for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
984 Deephemeralize(pMem);
985 }
986
987 /* Invalidate all ephemeral cursor row caches */
988 p->cacheCtr = (p->cacheCtr + 2)|1;
989
990 /* Make sure the results of the current row are \000 terminated
991 ** and have an assigned type. The results are deephemeralized as
992 ** as side effect.
993 */
994 for(; pMem<=pTos; pMem++ ){
995 sqlite3VdbeMemNulTerminate(pMem);
996 storeTypeInfo(pMem, encoding);
997 }
998
999 /* Set up the statement structure so that it will pop the current
1000 ** results from the stack when the statement returns.
1001 */
1002 p->resOnStack = 1;
1003 p->nCallback++;
1004 p->popStack = pOp->p1;
1005 p->pc = pc + 1;
1006 p->pTos = pTos;
1007 return SQLITE_ROW;
1008}
1009
1010/* Opcode: Concat P1 P2 *
1011**
1012** Look at the first P1+2 elements of the stack. Append them all
1013** together with the lowest element first. The original P1+2 elements
1014** are popped from the stack if P2==0 and retained if P2==1. If
1015** any element of the stack is NULL, then the result is NULL.
1016**
1017** When P1==1, this routine makes a copy of the top stack element
1018** into memory obtained from sqliteMalloc().
1019*/
1020case OP_Concat: { /* same as TK_CONCAT */
1021 char *zNew;
1022 i64 nByte;
1023 int nField;
1024 int i, j;
1025 Mem *pTerm;
1026
1027 /* Loop through the stack elements to see how long the result will be. */
1028 nField = pOp->p1 + 2;
1029 pTerm = &pTos[1-nField];
1030 nByte = 0;
1031 for(i=0; i<nField; i++, pTerm++){
1032 assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
1033 if( pTerm->flags&MEM_Null ){
1034 nByte = -1;
1035 break;
1036 }
1037 ExpandBlob(pTerm);
1038 Stringify(pTerm, encoding);
1039 nByte += pTerm->n;
1040 }
1041
1042 if( nByte<0 ){
1043 /* If nByte is less than zero, then there is a NULL value on the stack.
1044 ** In this case just pop the values off the stack (if required) and
1045 ** push on a NULL.
1046 */
1047 if( pOp->p2==0 ){
1048 popStack(&pTos, nField);
1049 }
1050 pTos++;
1051 pTos->flags = MEM_Null;
1052 }else{
1053 /* Otherwise malloc() space for the result and concatenate all the
1054 ** stack values.
1055 */
1056 if( nByte+2>SQLITE_MAX_LENGTH ){
1057 goto too_big;
1058 }
1059 zNew = sqliteMallocRaw( nByte+2 );
1060 if( zNew==0 ) goto no_mem;
1061 j = 0;
1062 pTerm = &pTos[1-nField];
1063 for(i=j=0; i<nField; i++, pTerm++){
1064 int n = pTerm->n;
1065 assert( pTerm->flags & (MEM_Str|MEM_Blob) );
1066 memcpy(&zNew[j], pTerm->z, n);
1067 j += n;
1068 }
1069 zNew[j] = 0;
1070 zNew[j+1] = 0;
1071 assert( j==nByte );
1072
1073 if( pOp->p2==0 ){
1074 popStack(&pTos, nField);
1075 }
1076 pTos++;
1077 pTos->n = j;
1078 pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
1079 pTos->xDel = 0;
1080 pTos->enc = encoding;
1081 pTos->z = zNew;
1082 }
1083 break;
1084}
1085
1086/* Opcode: Add * * *
1087**
1088** Pop the top two elements from the stack, add them together,
1089** and push the result back onto the stack. If either element
1090** is a string then it is converted to a double using the atof()
1091** function before the addition.
1092** If either operand is NULL, the result is NULL.
1093*/
1094/* Opcode: Multiply * * *
1095**
1096** Pop the top two elements from the stack, multiply them together,
1097** and push the result back onto the stack. If either element
1098** is a string then it is converted to a double using the atof()
1099** function before the multiplication.
1100** If either operand is NULL, the result is NULL.
1101*/
1102/* Opcode: Subtract * * *
1103**
1104** Pop the top two elements from the stack, subtract the
1105** first (what was on top of the stack) from the second (the
1106** next on stack)
1107** and push the result back onto the stack. If either element
1108** is a string then it is converted to a double using the atof()
1109** function before the subtraction.
1110** If either operand is NULL, the result is NULL.
1111*/
1112/* Opcode: Divide * * *
1113**
1114** Pop the top two elements from the stack, divide the
1115** first (what was on top of the stack) from the second (the
1116** next on stack)
1117** and push the result back onto the stack. If either element
1118** is a string then it is converted to a double using the atof()
1119** function before the division. Division by zero returns NULL.
1120** If either operand is NULL, the result is NULL.
1121*/
1122/* Opcode: Remainder * * *
1123**
1124** Pop the top two elements from the stack, divide the
1125** first (what was on top of the stack) from the second (the
1126** next on stack)
1127** and push the remainder after division onto the stack. If either element
1128** is a string then it is converted to a double using the atof()
1129** function before the division. Division by zero returns NULL.
1130** If either operand is NULL, the result is NULL.
1131*/
1132case OP_Add: /* same as TK_PLUS, no-push */
1133case OP_Subtract: /* same as TK_MINUS, no-push */
1134case OP_Multiply: /* same as TK_STAR, no-push */
1135case OP_Divide: /* same as TK_SLASH, no-push */
1136case OP_Remainder: { /* same as TK_REM, no-push */
1137 Mem *pNos = &pTos[-1];
1138 int flags;
1139 assert( pNos>=p->aStack );
1140 flags = pTos->flags | pNos->flags;
1141 if( (flags & MEM_Null)!=0 ){
1142 Release(pTos);
1143 pTos--;
1144 Release(pTos);
1145 pTos->flags = MEM_Null;
1146 }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
1147 i64 a, b;
1148 a = pTos->u.i;
1149 b = pNos->u.i;
1150 switch( pOp->opcode ){
1151 case OP_Add: b += a; break;
1152 case OP_Subtract: b -= a; break;
1153 case OP_Multiply: b *= a; break;
1154 case OP_Divide: {
1155 if( a==0 ) goto divide_by_zero;
1156 b /= a;
1157 break;
1158 }
1159 default: {
1160 if( a==0 ) goto divide_by_zero;
1161 b %= a;
1162 break;
1163 }
1164 }
1165 Release(pTos);
1166 pTos--;
1167 Release(pTos);
1168 pTos->u.i = b;
1169 pTos->flags = MEM_Int;
1170 }else{
1171 double a, b;
1172 a = sqlite3VdbeRealValue(pTos);
1173 b = sqlite3VdbeRealValue(pNos);
1174 switch( pOp->opcode ){
1175 case OP_Add: b += a; break;
1176 case OP_Subtract: b -= a; break;
1177 case OP_Multiply: b *= a; break;
1178 case OP_Divide: {
1179 if( a==0.0 ) goto divide_by_zero;
1180 b /= a;
1181 break;
1182 }
1183 default: {
1184 i64 ia = (i64)a;
1185 i64 ib = (i64)b;
1186 if( ia==0 ) goto divide_by_zero;
1187 b = ib % ia;
1188 break;
1189 }
1190 }
1191 if( isnan(b) ){
1192 goto divide_by_zero;
1193 }
1194 Release(pTos);
1195 pTos--;
1196 Release(pTos);
1197 pTos->r = b;
1198 pTos->flags = MEM_Real;
1199 if( (flags & MEM_Real)==0 ){
1200 sqlite3VdbeIntegerAffinity(pTos);
1201 }
1202 }
1203 break;
1204
1205divide_by_zero:
1206 Release(pTos);
1207 pTos--;
1208 Release(pTos);
1209 pTos->flags = MEM_Null;
1210 break;
1211}
1212
1213/* Opcode: CollSeq * * P3
1214**
1215** P3 is a pointer to a CollSeq struct. If the next call to a user function
1216** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1217** be returned. This is used by the built-in min(), max() and nullif()
1218** functions.
1219**
1220** The interface used by the implementation of the aforementioned functions
1221** to retrieve the collation sequence set by this opcode is not available
1222** publicly, only to user functions defined in func.c.
1223*/
1224case OP_CollSeq: { /* no-push */
1225 assert( pOp->p3type==P3_COLLSEQ );
1226 break;
1227}
1228
1229/* Opcode: Function P1 P2 P3
1230**
1231** Invoke a user function (P3 is a pointer to a Function structure that
1232** defines the function) with P2 arguments taken from the stack. Pop all
1233** arguments from the stack and push back the result.
1234**
1235** P1 is a 32-bit bitmask indicating whether or not each argument to the
1236** function was determined to be constant at compile time. If the first
1237** argument was constant then bit 0 of P1 is set. This is used to determine
1238** whether meta data associated with a user function argument using the
1239** sqlite3_set_auxdata() API may be safely retained until the next
1240** invocation of this opcode.
1241**
1242** See also: AggStep and AggFinal
1243*/
1244case OP_Function: {
1245 int i;
1246 Mem *pArg;
1247 sqlite3_context ctx;
1248 sqlite3_value **apVal;
1249 int n = pOp->p2;
1250
1251 apVal = p->apArg;
1252 assert( apVal || n==0 );
1253
1254 pArg = &pTos[1-n];
1255 for(i=0; i<n; i++, pArg++){
1256 apVal[i] = pArg;
1257 storeTypeInfo(pArg, encoding);
1258 }
1259
1260 assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
1261 if( pOp->p3type==P3_FUNCDEF ){
1262 ctx.pFunc = (FuncDef*)pOp->p3;
1263 ctx.pVdbeFunc = 0;
1264 }else{
1265 ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
1266 ctx.pFunc = ctx.pVdbeFunc->pFunc;
1267 }
1268
1269 ctx.s.flags = MEM_Null;
1270 ctx.s.z = 0;
1271 ctx.s.xDel = 0;
1272 ctx.isError = 0;
1273 if( ctx.pFunc->needCollSeq ){
1274 assert( pOp>p->aOp );
1275 assert( pOp[-1].p3type==P3_COLLSEQ );
1276 assert( pOp[-1].opcode==OP_CollSeq );
1277 ctx.pColl = (CollSeq *)pOp[-1].p3;
1278 }
1279 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1280 (*ctx.pFunc->xFunc)(&ctx, n, apVal);
1281 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
1282 if( sqlite3MallocFailed() ) goto no_mem;
1283 popStack(&pTos, n);
1284
1285 /* If any auxilary data functions have been called by this user function,
1286 ** immediately call the destructor for any non-static values.
1287 */
1288 if( ctx.pVdbeFunc ){
1289 sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1290 pOp->p3 = (char *)ctx.pVdbeFunc;
1291 pOp->p3type = P3_VDBEFUNC;
1292 }
1293
1294 /* If the function returned an error, throw an exception */
1295 if( ctx.isError ){
1296 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
1297 rc = SQLITE_ERROR;
1298 }
1299
1300 /* Copy the result of the function to the top of the stack */
1301 sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1302 pTos++;
1303 pTos->flags = 0;
1304 sqlite3VdbeMemMove(pTos, &ctx.s);
1305 if( sqlite3VdbeMemTooBig(pTos) ){
1306 goto too_big;
1307 }
1308 break;
1309}
1310
1311/* Opcode: BitAnd * * *
1312**
1313** Pop the top two elements from the stack. Convert both elements
1314** to integers. Push back onto the stack the bit-wise AND of the
1315** two elements.
1316** If either operand is NULL, the result is NULL.
1317*/
1318/* Opcode: BitOr * * *
1319**
1320** Pop the top two elements from the stack. Convert both elements
1321** to integers. Push back onto the stack the bit-wise OR of the
1322** two elements.
1323** If either operand is NULL, the result is NULL.
1324*/
1325/* Opcode: ShiftLeft * * *
1326**
1327** Pop the top two elements from the stack. Convert both elements
1328** to integers. Push back onto the stack the second element shifted
1329** left by N bits where N is the top element on the stack.
1330** If either operand is NULL, the result is NULL.
1331*/
1332/* Opcode: ShiftRight * * *
1333**
1334** Pop the top two elements from the stack. Convert both elements
1335** to integers. Push back onto the stack the second element shifted
1336** right by N bits where N is the top element on the stack.
1337** If either operand is NULL, the result is NULL.
1338*/
1339case OP_BitAnd: /* same as TK_BITAND, no-push */
1340case OP_BitOr: /* same as TK_BITOR, no-push */
1341case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
1342case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
1343 Mem *pNos = &pTos[-1];
1344 i64 a, b;
1345
1346 assert( pNos>=p->aStack );
1347 if( (pTos->flags | pNos->flags) & MEM_Null ){
1348 popStack(&pTos, 2);
1349 pTos++;
1350 pTos->flags = MEM_Null;
1351 break;
1352 }
1353 a = sqlite3VdbeIntValue(pNos);
1354 b = sqlite3VdbeIntValue(pTos);
1355 switch( pOp->opcode ){
1356 case OP_BitAnd: a &= b; break;
1357 case OP_BitOr: a |= b; break;
1358 case OP_ShiftLeft: a <<= b; break;
1359 case OP_ShiftRight: a >>= b; break;
1360 default: /* CANT HAPPEN */ break;
1361 }
1362 Release(pTos);
1363 pTos--;
1364 Release(pTos);
1365 pTos->u.i = a;
1366 pTos->flags = MEM_Int;
1367 break;
1368}
1369
1370/* Opcode: AddImm P1 * *
1371**
1372** Add the value P1 to whatever is on top of the stack. The result
1373** is always an integer.
1374**
1375** To force the top of the stack to be an integer, just add 0.
1376*/
1377case OP_AddImm: { /* no-push */
1378 assert( pTos>=p->aStack );
1379 sqlite3VdbeMemIntegerify(pTos);
1380 pTos->u.i += pOp->p1;
1381 break;
1382}
1383
1384/* Opcode: ForceInt P1 P2 *
1385**
1386** Convert the top of the stack into an integer. If the current top of
1387** the stack is not numeric (meaning that is is a NULL or a string that
1388** does not look like an integer or floating point number) then pop the
1389** stack and jump to P2. If the top of the stack is numeric then
1390** convert it into the least integer that is greater than or equal to its
1391** current value if P1==0, or to the least integer that is strictly
1392** greater than its current value if P1==1.
1393*/
1394case OP_ForceInt: { /* no-push */
1395 i64 v;
1396 assert( pTos>=p->aStack );
1397 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1398 if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
1399 Release(pTos);
1400 pTos--;
1401 pc = pOp->p2 - 1;
1402 break;
1403 }
1404 if( pTos->flags & MEM_Int ){
1405 v = pTos->u.i + (pOp->p1!=0);
1406 }else{
1407 /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */
1408 sqlite3VdbeMemRealify(pTos);
1409 v = (int)pTos->r;
1410 if( pTos->r>(double)v ) v++;
1411 if( pOp->p1 && pTos->r==(double)v ) v++;
1412 }
1413 Release(pTos);
1414 pTos->u.i = v;
1415 pTos->flags = MEM_Int;
1416 break;
1417}
1418
1419/* Opcode: MustBeInt P1 P2 *
1420**
1421** Force the top of the stack to be an integer. If the top of the
1422** stack is not an integer and cannot be converted into an integer
1423** with out data loss, then jump immediately to P2, or if P2==0
1424** raise an SQLITE_MISMATCH exception.
1425**
1426** If the top of the stack is not an integer and P2 is not zero and
1427** P1 is 1, then the stack is popped. In all other cases, the depth
1428** of the stack is unchanged.
1429*/
1430case OP_MustBeInt: { /* no-push */
1431 assert( pTos>=p->aStack );
1432 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
1433 if( (pTos->flags & MEM_Int)==0 ){
1434 if( pOp->p2==0 ){
1435 rc = SQLITE_MISMATCH;
1436 goto abort_due_to_error;
1437 }else{
1438 if( pOp->p1 ) popStack(&pTos, 1);
1439 pc = pOp->p2 - 1;
1440 }
1441 }else{
1442 Release(pTos);
1443 pTos->flags = MEM_Int;
1444 }
1445 break;
1446}
1447
1448/* Opcode: RealAffinity * * *
1449**
1450** If the top of the stack is an integer, convert it to a real value.
1451**
1452** This opcode is used when extracting information from a column that
1453** has REAL affinity. Such column values may still be stored as
1454** integers, for space efficiency, but after extraction we want them
1455** to have only a real value.
1456*/
1457case OP_RealAffinity: { /* no-push */
1458 assert( pTos>=p->aStack );
1459 if( pTos->flags & MEM_Int ){
1460 sqlite3VdbeMemRealify(pTos);
1461 }
1462 break;
1463}
1464
1465#ifndef SQLITE_OMIT_CAST
1466/* Opcode: ToText * * *
1467**
1468** Force the value on the top of the stack to be text.
1469** If the value is numeric, convert it to a string using the
1470** equivalent of printf(). Blob values are unchanged and
1471** are afterwards simply interpreted as text.
1472**
1473** A NULL value is not changed by this routine. It remains NULL.
1474*/
1475case OP_ToText: { /* same as TK_TO_TEXT, no-push */
1476 assert( pTos>=p->aStack );
1477 if( pTos->flags & MEM_Null ) break;
1478 assert( MEM_Str==(MEM_Blob>>3) );
1479 pTos->flags |= (pTos->flags&MEM_Blob)>>3;
1480 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1481 rc = ExpandBlob(pTos);
1482 assert( pTos->flags & MEM_Str );
1483 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
1484 break;
1485}
1486
1487/* Opcode: ToBlob * * *
1488**
1489** Force the value on the top of the stack to be a BLOB.
1490** If the value is numeric, convert it to a string first.
1491** Strings are simply reinterpreted as blobs with no change
1492** to the underlying data.
1493**
1494** A NULL value is not changed by this routine. It remains NULL.
1495*/
1496case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */
1497 assert( pTos>=p->aStack );
1498 if( pTos->flags & MEM_Null ) break;
1499 if( (pTos->flags & MEM_Blob)==0 ){
1500 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
1501 assert( pTos->flags & MEM_Str );
1502 pTos->flags |= MEM_Blob;
1503 }
1504 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
1505 break;
1506}
1507
1508/* Opcode: ToNumeric * * *
1509**
1510** Force the value on the top of the stack to be numeric (either an
1511** integer or a floating-point number.)
1512** If the value is text or blob, try to convert it to an using the
1513** equivalent of atoi() or atof() and store 0 if no such conversion
1514** is possible.
1515**
1516** A NULL value is not changed by this routine. It remains NULL.
1517*/
1518case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */
1519 assert( pTos>=p->aStack );
1520 if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
1521 sqlite3VdbeMemNumerify(pTos);
1522 }
1523 break;
1524}
1525#endif /* SQLITE_OMIT_CAST */
1526
1527/* Opcode: ToInt * * *
1528**
1529** Force the value on the top of the stack to be an integer. If
1530** The value is currently a real number, drop its fractional part.
1531** If the value is text or blob, try to convert it to an integer using the
1532** equivalent of atoi() and store 0 if no such conversion is possible.
1533**
1534** A NULL value is not changed by this routine. It remains NULL.
1535*/
1536case OP_ToInt: { /* same as TK_TO_INT, no-push */
1537 assert( pTos>=p->aStack );
1538 if( (pTos->flags & MEM_Null)==0 ){
1539 sqlite3VdbeMemIntegerify(pTos);
1540 }
1541 break;
1542}
1543
1544#ifndef SQLITE_OMIT_CAST
1545/* Opcode: ToReal * * *
1546**
1547** Force the value on the top of the stack to be a floating point number.
1548** If The value is currently an integer, convert it.
1549** If the value is text or blob, try to convert it to an integer using the
1550** equivalent of atoi() and store 0 if no such conversion is possible.
1551**
1552** A NULL value is not changed by this routine. It remains NULL.
1553*/
1554case OP_ToReal: { /* same as TK_TO_REAL, no-push */
1555 assert( pTos>=p->aStack );
1556 if( (pTos->flags & MEM_Null)==0 ){
1557 sqlite3VdbeMemRealify(pTos);
1558 }
1559 break;
1560}
1561#endif /* SQLITE_OMIT_CAST */
1562
1563/* Opcode: Eq P1 P2 P3
1564**
1565** Pop the top two elements from the stack. If they are equal, then
1566** jump to instruction P2. Otherwise, continue to the next instruction.
1567**
1568** If the 0x100 bit of P1 is true and either operand is NULL then take the
1569** jump. If the 0x100 bit of P1 is clear then fall thru if either operand
1570** is NULL.
1571**
1572** If the 0x200 bit of P1 is set and either operand is NULL then
1573** both operands are converted to integers prior to comparison.
1574** NULL operands are converted to zero and non-NULL operands are
1575** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true
1576** whereas it would normally be NULL. Similarly, NULL==123 is false when
1577** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
1578**
1579** The least significant byte of P1 (mask 0xff) must be an affinity character -
1580** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1581** to coerce both values
1582** according to the affinity before the comparison is made. If the byte is
1583** 0x00, then numeric affinity is used.
1584**
1585** Once any conversions have taken place, and neither value is NULL,
1586** the values are compared. If both values are blobs, or both are text,
1587** then memcmp() is used to determine the results of the comparison. If
1588** both values are numeric, then a numeric comparison is used. If the
1589** two values are of different types, then they are inequal.
1590**
1591** If P2 is zero, do not jump. Instead, push an integer 1 onto the
1592** stack if the jump would have been taken, or a 0 if not. Push a
1593** NULL if either operand was NULL.
1594**
1595** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
1596** structure) that defines how to compare text.
1597*/
1598/* Opcode: Ne P1 P2 P3
1599**
1600** This works just like the Eq opcode except that the jump is taken if
1601** the operands from the stack are not equal. See the Eq opcode for
1602** additional information.
1603*/
1604/* Opcode: Lt P1 P2 P3
1605**
1606** This works just like the Eq opcode except that the jump is taken if
1607** the 2nd element down on the stack is less than the top of the stack.
1608** See the Eq opcode for additional information.
1609*/
1610/* Opcode: Le P1 P2 P3
1611**
1612** This works just like the Eq opcode except that the jump is taken if
1613** the 2nd element down on the stack is less than or equal to the
1614** top of the stack. See the Eq opcode for additional information.
1615*/
1616/* Opcode: Gt P1 P2 P3
1617**
1618** This works just like the Eq opcode except that the jump is taken if
1619** the 2nd element down on the stack is greater than the top of the stack.
1620** See the Eq opcode for additional information.
1621*/
1622/* Opcode: Ge P1 P2 P3
1623**
1624** This works just like the Eq opcode except that the jump is taken if
1625** the 2nd element down on the stack is greater than or equal to the
1626** top of the stack. See the Eq opcode for additional information.
1627*/
1628case OP_Eq: /* same as TK_EQ, no-push */
1629case OP_Ne: /* same as TK_NE, no-push */
1630case OP_Lt: /* same as TK_LT, no-push */
1631case OP_Le: /* same as TK_LE, no-push */
1632case OP_Gt: /* same as TK_GT, no-push */
1633case OP_Ge: { /* same as TK_GE, no-push */
1634 Mem *pNos;
1635 int flags;
1636 int res;
1637 char affinity;
1638
1639 pNos = &pTos[-1];
1640 flags = pTos->flags|pNos->flags;
1641
1642 /* If either value is a NULL P2 is not zero, take the jump if the least
1643 ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
1644 ** the stack.
1645 */
1646 if( flags&MEM_Null ){
1647 if( (pOp->p1 & 0x200)!=0 ){
1648 /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
1649 ** magic SQL value it normally is - treat it as if it were another
1650 ** integer".
1651 **
1652 ** With 0x200 set, if either operand is NULL then both operands
1653 ** are converted to integers prior to being passed down into the
1654 ** normal comparison logic below. NULL operands are converted to
1655 ** zero and non-NULL operands are converted to 1. Thus, for example,
1656 ** with 0x200 set, NULL==NULL is true whereas it would normally
1657 ** be NULL. Similarly, NULL!=123 is true.
1658 */
1659 sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
1660 sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
1661 }else{
1662 /* If the 0x200 bit of P1 is clear and either operand is NULL then
1663 ** the result is always NULL. The jump is taken if the 0x100 bit
1664 ** of P1 is set.
1665 */
1666 popStack(&pTos, 2);
1667 if( pOp->p2 ){
1668 if( pOp->p1 & 0x100 ){
1669 pc = pOp->p2-1;
1670 }
1671 }else{
1672 pTos++;
1673 pTos->flags = MEM_Null;
1674 }
1675 break;
1676 }
1677 }
1678
1679 affinity = pOp->p1 & 0xFF;
1680 if( affinity ){
1681 applyAffinity(pNos, affinity, encoding);
1682 applyAffinity(pTos, affinity, encoding);
1683 }
1684
1685 assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
1686 ExpandBlob(pNos);
1687 ExpandBlob(pTos);
1688 res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
1689 switch( pOp->opcode ){
1690 case OP_Eq: res = res==0; break;
1691 case OP_Ne: res = res!=0; break;
1692 case OP_Lt: res = res<0; break;
1693 case OP_Le: res = res<=0; break;
1694 case OP_Gt: res = res>0; break;
1695 default: res = res>=0; break;
1696 }
1697
1698 popStack(&pTos, 2);
1699 if( pOp->p2 ){
1700 if( res ){
1701 pc = pOp->p2-1;
1702 }
1703 }else{
1704 pTos++;
1705 pTos->flags = MEM_Int;
1706 pTos->u.i = res;
1707 }
1708 break;
1709}
1710
1711/* Opcode: And * * *
1712**
1713** Pop two values off the stack. Take the logical AND of the
1714** two values and push the resulting boolean value back onto the
1715** stack.
1716*/
1717/* Opcode: Or * * *
1718**
1719** Pop two values off the stack. Take the logical OR of the
1720** two values and push the resulting boolean value back onto the
1721** stack.
1722*/
1723case OP_And: /* same as TK_AND, no-push */
1724case OP_Or: { /* same as TK_OR, no-push */
1725 Mem *pNos = &pTos[-1];
1726 int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
1727
1728 assert( pNos>=p->aStack );
1729 if( pTos->flags & MEM_Null ){
1730 v1 = 2;
1731 }else{
1732 sqlite3VdbeMemIntegerify(pTos);
1733 v1 = pTos->u.i==0;
1734 }
1735 if( pNos->flags & MEM_Null ){
1736 v2 = 2;
1737 }else{
1738 sqlite3VdbeMemIntegerify(pNos);
1739 v2 = pNos->u.i==0;
1740 }
1741 if( pOp->opcode==OP_And ){
1742 static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1743 v1 = and_logic[v1*3+v2];
1744 }else{
1745 static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1746 v1 = or_logic[v1*3+v2];
1747 }
1748 popStack(&pTos, 2);
1749 pTos++;
1750 if( v1==2 ){
1751 pTos->flags = MEM_Null;
1752 }else{
1753 pTos->u.i = v1==0;
1754 pTos->flags = MEM_Int;
1755 }
1756 break;
1757}
1758
1759/* Opcode: Negative * * *
1760**
1761** Treat the top of the stack as a numeric quantity. Replace it
1762** with its additive inverse. If the top of the stack is NULL
1763** its value is unchanged.
1764*/
1765/* Opcode: AbsValue * * *
1766**
1767** Treat the top of the stack as a numeric quantity. Replace it
1768** with its absolute value. If the top of the stack is NULL
1769** its value is unchanged.
1770*/
1771case OP_Negative: /* same as TK_UMINUS, no-push */
1772case OP_AbsValue: {
1773 assert( pTos>=p->aStack );
1774 if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
1775 sqlite3VdbeMemNumerify(pTos);
1776 }
1777 if( pTos->flags & MEM_Real ){
1778 Release(pTos);
1779 if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
1780 pTos->r = -pTos->r;
1781 }
1782 pTos->flags = MEM_Real;
1783 }else if( pTos->flags & MEM_Int ){
1784 Release(pTos);
1785 if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
1786 pTos->u.i = -pTos->u.i;
1787 }
1788 pTos->flags = MEM_Int;
1789 }
1790 break;
1791}
1792
1793/* Opcode: Not * * *
1794**
1795** Interpret the top of the stack as a boolean value. Replace it
1796** with its complement. If the top of the stack is NULL its value
1797** is unchanged.
1798*/
1799case OP_Not: { /* same as TK_NOT, no-push */
1800 assert( pTos>=p->aStack );
1801 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1802 sqlite3VdbeMemIntegerify(pTos);
1803 assert( (pTos->flags & MEM_Dyn)==0 );
1804 pTos->u.i = !pTos->u.i;
1805 pTos->flags = MEM_Int;
1806 break;
1807}
1808
1809/* Opcode: BitNot * * *
1810**
1811** Interpret the top of the stack as an value. Replace it
1812** with its ones-complement. If the top of the stack is NULL its
1813** value is unchanged.
1814*/
1815case OP_BitNot: { /* same as TK_BITNOT, no-push */
1816 assert( pTos>=p->aStack );
1817 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
1818 sqlite3VdbeMemIntegerify(pTos);
1819 assert( (pTos->flags & MEM_Dyn)==0 );
1820 pTos->u.i = ~pTos->u.i;
1821 pTos->flags = MEM_Int;
1822 break;
1823}
1824
1825/* Opcode: Noop * * *
1826**
1827** Do nothing. This instruction is often useful as a jump
1828** destination.
1829*/
1830/*
1831** The magic Explain opcode are only inserted when explain==2 (which
1832** is to say when the EXPLAIN QUERY PLAN syntax is used.)
1833** This opcode records information from the optimizer. It is the
1834** the same as a no-op. This opcodesnever appears in a real VM program.
1835*/
1836case OP_Explain:
1837case OP_Noop: { /* no-push */
1838 break;
1839}
1840
1841/* Opcode: If P1 P2 *
1842**
1843** Pop a single boolean from the stack. If the boolean popped is
1844** true, then jump to p2. Otherwise continue to the next instruction.
1845** An integer is false if zero and true otherwise. A string is
1846** false if it has zero length and true otherwise.
1847**
1848** If the value popped of the stack is NULL, then take the jump if P1
1849** is true and fall through if P1 is false.
1850*/
1851/* Opcode: IfNot P1 P2 *
1852**
1853** Pop a single boolean from the stack. If the boolean popped is
1854** false, then jump to p2. Otherwise continue to the next instruction.
1855** An integer is false if zero and true otherwise. A string is
1856** false if it has zero length and true otherwise.
1857**
1858** If the value popped of the stack is NULL, then take the jump if P1
1859** is true and fall through if P1 is false.
1860*/
1861case OP_If: /* no-push */
1862case OP_IfNot: { /* no-push */
1863 int c;
1864 assert( pTos>=p->aStack );
1865 if( pTos->flags & MEM_Null ){
1866 c = pOp->p1;
1867 }else{
1868#ifdef SQLITE_OMIT_FLOATING_POINT
1869 c = sqlite3VdbeIntValue(pTos);
1870#else
1871 c = sqlite3VdbeRealValue(pTos)!=0.0;
1872#endif
1873 if( pOp->opcode==OP_IfNot ) c = !c;
1874 }
1875 Release(pTos);
1876 pTos--;
1877 if( c ) pc = pOp->p2-1;
1878 break;
1879}
1880
1881/* Opcode: IsNull P1 P2 *
1882**
1883** Check the top of the stack and jump to P2 if the top of the stack
1884** is NULL. If P1 is positive, then pop P1 elements from the stack
1885** regardless of whether or not the jump is taken. If P1 is negative,
1886** pop -P1 elements from the stack only if the jump is taken and leave
1887** the stack unchanged if the jump is not taken.
1888*/
1889case OP_IsNull: { /* same as TK_ISNULL, no-push */
1890 if( pTos->flags & MEM_Null ){
1891 pc = pOp->p2-1;
1892 if( pOp->p1<0 ){
1893 popStack(&pTos, -pOp->p1);
1894 }
1895 }
1896 if( pOp->p1>0 ){
1897 popStack(&pTos, pOp->p1);
1898 }
1899 break;
1900}
1901
1902/* Opcode: NotNull P1 P2 *
1903**
1904** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
1905** Regardless of whether or not the jump is taken, pop the stack
1906** P1 times if P1 is greater than zero. But if P1 is negative,
1907** leave the stack unchanged.
1908*/
1909case OP_NotNull: { /* same as TK_NOTNULL, no-push */
1910 int i, cnt;
1911 cnt = pOp->p1;
1912 if( cnt<0 ) cnt = -cnt;
1913 assert( &pTos[1-cnt] >= p->aStack );
1914 for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
1915 if( i>=cnt ) pc = pOp->p2-1;
1916 if( pOp->p1>0 ) popStack(&pTos, cnt);
1917 break;
1918}
1919
1920/* Opcode: SetNumColumns P1 P2 *
1921**
1922** Before the OP_Column opcode can be executed on a cursor, this
1923** opcode must be called to set the number of fields in the table.
1924**
1925** This opcode sets the number of columns for cursor P1 to P2.
1926**
1927** If OP_KeyAsData is to be applied to cursor P1, it must be executed
1928** before this op-code.
1929*/
1930case OP_SetNumColumns: { /* no-push */
1931 Cursor *pC;
1932 assert( (pOp->p1)<p->nCursor );
1933 assert( p->apCsr[pOp->p1]!=0 );
1934 pC = p->apCsr[pOp->p1];
1935 pC->nField = pOp->p2;
1936 break;
1937}
1938
1939/* Opcode: Column P1 P2 P3
1940**
1941** Interpret the data that cursor P1 points to as a structure built using
1942** the MakeRecord instruction. (See the MakeRecord opcode for additional
1943** information about the format of the data.) Push onto the stack the value
1944** of the P2-th column contained in the data. If there are less that (P2+1)
1945** values in the record, push a NULL onto the stack.
1946**
1947** If the KeyAsData opcode has previously executed on this cursor, then the
1948** field might be extracted from the key rather than the data.
1949**
1950** If the column contains fewer than P2 fields, then push a NULL. Or
1951** if P3 is of type P3_MEM, then push the P3 value. The P3 value will
1952** be default value for a column that has been added using the ALTER TABLE
1953** ADD COLUMN command. If P3 is an ordinary string, just push a NULL.
1954** When P3 is a string it is really just a comment describing the value
1955** to be pushed, not a default value.
1956*/
1957case OP_Column: {
1958 u32 payloadSize; /* Number of bytes in the record */
1959 int p1 = pOp->p1; /* P1 value of the opcode */
1960 int p2 = pOp->p2; /* column number to retrieve */
1961 Cursor *pC = 0; /* The VDBE cursor */
1962 char *zRec; /* Pointer to complete record-data */
1963 BtCursor *pCrsr; /* The BTree cursor */
1964 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
1965 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
1966 u32 nField; /* number of fields in the record */
1967 int len; /* The length of the serialized data for the column */
1968 int i; /* Loop counter */
1969 char *zData; /* Part of the record being decoded */
1970 Mem sMem; /* For storing the record being decoded */
1971
1972 sMem.flags = 0;
1973 assert( p1<p->nCursor );
1974 pTos++;
1975 pTos->flags = MEM_Null;
1976
1977 /* This block sets the variable payloadSize to be the total number of
1978 ** bytes in the record.
1979 **
1980 ** zRec is set to be the complete text of the record if it is available.
1981 ** The complete record text is always available for pseudo-tables
1982 ** If the record is stored in a cursor, the complete record text
1983 ** might be available in the pC->aRow cache. Or it might not be.
1984 ** If the data is unavailable, zRec is set to NULL.
1985 **
1986 ** We also compute the number of columns in the record. For cursors,
1987 ** the number of columns is stored in the Cursor.nField element. For
1988 ** records on the stack, the next entry down on the stack is an integer
1989 ** which is the number of records.
1990 */
1991 pC = p->apCsr[p1];
1992#ifndef SQLITE_OMIT_VIRTUALTABLE
1993 assert( pC->pVtabCursor==0 );
1994#endif
1995 assert( pC!=0 );
1996 if( pC->pCursor!=0 ){
1997 /* The record is stored in a B-Tree */
1998 rc = sqlite3VdbeCursorMoveto(pC);
1999 if( rc ) goto abort_due_to_error;
2000 zRec = 0;
2001 pCrsr = pC->pCursor;
2002 if( pC->nullRow ){
2003 payloadSize = 0;
2004 }else if( pC->cacheStatus==p->cacheCtr ){
2005 payloadSize = pC->payloadSize;
2006 zRec = (char*)pC->aRow;
2007 }else if( pC->isIndex ){
2008 i64 payloadSize64;
2009 sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2010 payloadSize = payloadSize64;
2011 }else{
2012 sqlite3BtreeDataSize(pCrsr, &payloadSize);
2013 }
2014 nField = pC->nField;
2015 }else if( pC->pseudoTable ){
2016 /* The record is the sole entry of a pseudo-table */
2017 payloadSize = pC->nData;
2018 zRec = pC->pData;
2019 pC->cacheStatus = CACHE_STALE;
2020 assert( payloadSize==0 || zRec!=0 );
2021 nField = pC->nField;
2022 pCrsr = 0;
2023 }else{
2024 zRec = 0;
2025 payloadSize = 0;
2026 pCrsr = 0;
2027 nField = 0;
2028 }
2029
2030 /* If payloadSize is 0, then just push a NULL onto the stack. */
2031 if( payloadSize==0 ){
2032 assert( pTos->flags==MEM_Null );
2033 break;
2034 }
2035 if( payloadSize>SQLITE_MAX_LENGTH ){
2036 goto too_big;
2037 }
2038
2039 assert( p2<nField );
2040
2041 /* Read and parse the table header. Store the results of the parse
2042 ** into the record header cache fields of the cursor.
2043 */
2044 if( pC && pC->cacheStatus==p->cacheCtr ){
2045 aType = pC->aType;
2046 aOffset = pC->aOffset;
2047 }else{
2048 u8 *zIdx; /* Index into header */
2049 u8 *zEndHdr; /* Pointer to first byte after the header */
2050 u32 offset; /* Offset into the data */
2051 int szHdrSz; /* Size of the header size field at start of record */
2052 int avail; /* Number of bytes of available data */
2053
2054 aType = pC->aType;
2055 if( aType==0 ){
2056 pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
2057 }
2058 if( aType==0 ){
2059 goto no_mem;
2060 }
2061 pC->aOffset = aOffset = &aType[nField];
2062 pC->payloadSize = payloadSize;
2063 pC->cacheStatus = p->cacheCtr;
2064
2065 /* Figure out how many bytes are in the header */
2066 if( zRec ){
2067 zData = zRec;
2068 }else{
2069 if( pC->isIndex ){
2070 zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2071 }else{
2072 zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
2073 }
2074 /* If KeyFetch()/DataFetch() managed to get the entire payload,
2075 ** save the payload in the pC->aRow cache. That will save us from
2076 ** having to make additional calls to fetch the content portion of
2077 ** the record.
2078 */
2079 if( avail>=payloadSize ){
2080 zRec = zData;
2081 pC->aRow = (u8*)zData;
2082 }else{
2083 pC->aRow = 0;
2084 }
2085 }
2086 /* The following assert is true in all cases accept when
2087 ** the database file has been corrupted externally.
2088 ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
2089 szHdrSz = GetVarint((u8*)zData, offset);
2090
2091 /* The KeyFetch() or DataFetch() above are fast and will get the entire
2092 ** record header in most cases. But they will fail to get the complete
2093 ** record header if the record header does not fit on a single page
2094 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
2095 ** acquire the complete header text.
2096 */
2097 if( !zRec && avail<offset ){
2098 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
2099 if( rc!=SQLITE_OK ){
2100 goto op_column_out;
2101 }
2102 zData = sMem.z;
2103 }
2104 zEndHdr = (u8 *)&zData[offset];
2105 zIdx = (u8 *)&zData[szHdrSz];
2106
2107 /* Scan the header and use it to fill in the aType[] and aOffset[]
2108 ** arrays. aType[i] will contain the type integer for the i-th
2109 ** column and aOffset[i] will contain the offset from the beginning
2110 ** of the record to the start of the data for the i-th column
2111 */
2112 for(i=0; i<nField; i++){
2113 if( zIdx<zEndHdr ){
2114 aOffset[i] = offset;
2115 zIdx += GetVarint(zIdx, aType[i]);
2116 offset += sqlite3VdbeSerialTypeLen(aType[i]);
2117 }else{
2118 /* If i is less that nField, then there are less fields in this
2119 ** record than SetNumColumns indicated there are columns in the
2120 ** table. Set the offset for any extra columns not present in
2121 ** the record to 0. This tells code below to push a NULL onto the
2122 ** stack instead of deserializing a value from the record.
2123 */
2124 aOffset[i] = 0;
2125 }
2126 }
2127 Release(&sMem);
2128 sMem.flags = MEM_Null;
2129
2130 /* If we have read more header data than was contained in the header,
2131 ** or if the end of the last field appears to be past the end of the
2132 ** record, then we must be dealing with a corrupt database.
2133 */
2134 if( zIdx>zEndHdr || offset>payloadSize ){
2135 rc = SQLITE_CORRUPT_BKPT;
2136 goto op_column_out;
2137 }
2138 }
2139
2140 /* Get the column information. If aOffset[p2] is non-zero, then
2141 ** deserialize the value from the record. If aOffset[p2] is zero,
2142 ** then there are not enough fields in the record to satisfy the
2143 ** request. In this case, set the value NULL or to P3 if P3 is
2144 ** a pointer to a Mem object.
2145 */
2146 if( aOffset[p2] ){
2147 assert( rc==SQLITE_OK );
2148 if( zRec ){
2149 zData = &zRec[aOffset[p2]];
2150 }else{
2151 len = sqlite3VdbeSerialTypeLen(aType[p2]);
2152 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
2153 if( rc!=SQLITE_OK ){
2154 goto op_column_out;
2155 }
2156 zData = sMem.z;
2157 }
2158 sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
2159 pTos->enc = encoding;
2160 }else{
2161 if( pOp->p3type==P3_MEM ){
2162 sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
2163 }else{
2164 pTos->flags = MEM_Null;
2165 }
2166 }
2167
2168 /* If we dynamically allocated space to hold the data (in the
2169 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2170 ** dynamically allocated space over to the pTos structure.
2171 ** This prevents a memory copy.
2172 */
2173 if( (sMem.flags & MEM_Dyn)!=0 ){
2174 assert( pTos->flags & MEM_Ephem );
2175 assert( pTos->flags & (MEM_Str|MEM_Blob) );
2176 assert( pTos->z==sMem.z );
2177 assert( sMem.flags & MEM_Term );
2178 pTos->flags &= ~MEM_Ephem;
2179 pTos->flags |= MEM_Dyn|MEM_Term;
2180 }
2181
2182 /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
2183 ** can abandon sMem */
2184 rc = sqlite3VdbeMemMakeWriteable(pTos);
2185
2186op_column_out:
2187 break;
2188}
2189
2190/* Opcode: MakeRecord P1 P2 P3
2191**
2192** Convert the top abs(P1) entries of the stack into a single entry
2193** suitable for use as a data record in a database table or as a key
2194** in an index. The details of the format are irrelavant as long as
2195** the OP_Column opcode can decode the record later and as long as the
2196** sqlite3VdbeRecordCompare function will correctly compare two encoded
2197** records. Refer to source code comments for the details of the record
2198** format.
2199**
2200** The original stack entries are popped from the stack if P1>0 but
2201** remain on the stack if P1<0.
2202**
2203** If P2 is not zero and one or more of the entries are NULL, then jump
2204** to the address given by P2. This feature can be used to skip a
2205** uniqueness test on indices.
2206**
2207** P3 may be a string that is P1 characters long. The nth character of the
2208** string indicates the column affinity that should be used for the nth
2209** field of the index key (i.e. the first character of P3 corresponds to the
2210** lowest element on the stack).
2211**
2212** The mapping from character to affinity is given by the SQLITE_AFF_
2213** macros defined in sqliteInt.h.
2214**
2215** If P3 is NULL then all index fields have the affinity NONE.
2216**
2217** See also OP_MakeIdxRec
2218*/
2219/* Opcode: MakeIdxRec P1 P2 P3
2220**
2221** This opcode works just OP_MakeRecord except that it reads an extra
2222** integer from the stack (thus reading a total of abs(P1+1) entries)
2223** and appends that extra integer to the end of the record as a varint.
2224** This results in an index key.
2225*/
2226case OP_MakeIdxRec:
2227case OP_MakeRecord: {
2228 /* Assuming the record contains N fields, the record format looks
2229 ** like this:
2230 **
2231 ** ------------------------------------------------------------------------
2232 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2233 ** ------------------------------------------------------------------------
2234 **
2235 ** Data(0) is taken from the lowest element of the stack and data(N-1) is
2236 ** the top of the stack.
2237 **
2238 ** Each type field is a varint representing the serial type of the
2239 ** corresponding data element (see sqlite3VdbeSerialType()). The
2240 ** hdr-size field is also a varint which is the offset from the beginning
2241 ** of the record to data0.
2242 */
2243 u8 *zNewRecord; /* A buffer to hold the data for the new record */
2244 Mem *pRec; /* The new record */
2245 Mem *pRowid = 0; /* Rowid appended to the new record */
2246 u64 nData = 0; /* Number of bytes of data space */
2247 int nHdr = 0; /* Number of bytes of header space */
2248 u64 nByte = 0; /* Data space required for this record */
2249 int nZero = 0; /* Number of zero bytes at the end of the record */
2250 int nVarint; /* Number of bytes in a varint */
2251 u32 serial_type; /* Type field */
2252 int containsNull = 0; /* True if any of the data fields are NULL */
2253 Mem *pData0; /* Bottom of the stack */
2254 int leaveOnStack; /* If true, leave the entries on the stack */
2255 int nField; /* Number of fields in the record */
2256 int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
2257 int addRowid; /* True to append a rowid column at the end */
2258 char *zAffinity; /* The affinity string for the record */
2259 int file_format; /* File format to use for encoding */
2260 int i; /* Space used in zNewRecord[] */
2261 char zTemp[NBFS]; /* Space to hold small records */
2262
2263 leaveOnStack = ((pOp->p1<0)?1:0);
2264 nField = pOp->p1 * (leaveOnStack?-1:1);
2265 jumpIfNull = pOp->p2;
2266 addRowid = pOp->opcode==OP_MakeIdxRec;
2267 zAffinity = pOp->p3;
2268
2269 pData0 = &pTos[1-nField];
2270 assert( pData0>=p->aStack );
2271 containsNull = 0;
2272 file_format = p->minWriteFileFormat;
2273
2274 /* Loop through the elements that will make up the record to figure
2275 ** out how much space is required for the new record.
2276 */
2277 for(pRec=pData0; pRec<=pTos; pRec++){
2278 int len;
2279 if( zAffinity ){
2280 applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2281 }
2282 if( pRec->flags&MEM_Null ){
2283 containsNull = 1;
2284 }
2285 if( pRec->flags&MEM_Zero && pRec->n>0 ){
2286 ExpandBlob(pRec);
2287 }
2288 serial_type = sqlite3VdbeSerialType(pRec, file_format);
2289 len = sqlite3VdbeSerialTypeLen(serial_type);
2290 nData += len;
2291 nHdr += sqlite3VarintLen(serial_type);
2292 if( pRec->flags & MEM_Zero ){
2293 /* Only pure zero-filled BLOBs can be input to this Opcode.
2294 ** We do not allow blobs with a prefix and a zero-filled tail. */
2295 nZero += pRec->u.i;
2296 }else if( len ){
2297 nZero = 0;
2298 }
2299 }
2300
2301 /* If we have to append a varint rowid to this record, set pRowid
2302 ** to the value of the rowid and increase nByte by the amount of space
2303 ** required to store it.
2304 */
2305 if( addRowid ){
2306 pRowid = &pTos[0-nField];
2307 assert( pRowid>=p->aStack );
2308 sqlite3VdbeMemIntegerify(pRowid);
2309 serial_type = sqlite3VdbeSerialType(pRowid, 0);
2310 nData += sqlite3VdbeSerialTypeLen(serial_type);
2311 nHdr += sqlite3VarintLen(serial_type);
2312 nZero = 0;
2313 }
2314
2315 /* Add the initial header varint and total the size */
2316 nHdr += nVarint = sqlite3VarintLen(nHdr);
2317 if( nVarint<sqlite3VarintLen(nHdr) ){
2318 nHdr++;
2319 }
2320 nByte = nHdr+nData-nZero;
2321 if( nByte>SQLITE_MAX_LENGTH ){
2322 goto too_big;
2323 }
2324
2325 /* Allocate space for the new record. */
2326 if( nByte>sizeof(zTemp) ){
2327 zNewRecord = sqliteMallocRaw(nByte);
2328 if( !zNewRecord ){
2329 goto no_mem;
2330 }
2331 }else{
2332 zNewRecord = (u8*)zTemp;
2333 }
2334
2335 /* Write the record */
2336 i = sqlite3PutVarint(zNewRecord, nHdr);
2337 for(pRec=pData0; pRec<=pTos; pRec++){
2338 serial_type = sqlite3VdbeSerialType(pRec, file_format);
2339 i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */
2340 }
2341 if( addRowid ){
2342 i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
2343 }
2344 for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */
2345 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
2346 }
2347 if( addRowid ){
2348 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
2349 }
2350 assert( i==nByte );
2351
2352 /* Pop entries off the stack if required. Push the new record on. */
2353 if( !leaveOnStack ){
2354 popStack(&pTos, nField+addRowid);
2355 }
2356 pTos++;
2357 pTos->n = nByte;
2358 if( nByte<=sizeof(zTemp) ){
2359 assert( zNewRecord==(unsigned char *)zTemp );
2360 pTos->z = pTos->zShort;
2361 memcpy(pTos->zShort, zTemp, nByte);
2362 pTos->flags = MEM_Blob | MEM_Short;
2363 }else{
2364 assert( zNewRecord!=(unsigned char *)zTemp );
2365 pTos->z = (char*)zNewRecord;
2366 pTos->flags = MEM_Blob | MEM_Dyn;
2367 pTos->xDel = 0;
2368 }
2369 if( nZero ){
2370 pTos->u.i = nZero;
2371 pTos->flags |= MEM_Zero;
2372 }
2373 pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
2374
2375 /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
2376 if( jumpIfNull && containsNull ){
2377 pc = jumpIfNull - 1;
2378 }
2379 break;
2380}
2381
2382/* Opcode: Statement P1 * *
2383**
2384** Begin an individual statement transaction which is part of a larger
2385** BEGIN..COMMIT transaction. This is needed so that the statement
2386** can be rolled back after an error without having to roll back the
2387** entire transaction. The statement transaction will automatically
2388** commit when the VDBE halts.
2389**
2390** The statement is begun on the database file with index P1. The main
2391** database file has an index of 0 and the file used for temporary tables
2392** has an index of 1.
2393*/
2394case OP_Statement: { /* no-push */
2395 int i = pOp->p1;
2396 Btree *pBt;
2397 if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
2398 assert( sqlite3BtreeIsInTrans(pBt) );
2399 if( !sqlite3BtreeIsInStmt(pBt) ){
2400 rc = sqlite3BtreeBeginStmt(pBt);
2401 }
2402 }
2403 break;
2404}
2405
2406/* Opcode: AutoCommit P1 P2 *
2407**
2408** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2409** back any currently active btree transactions. If there are any active
2410** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2411**
2412** This instruction causes the VM to halt.
2413*/
2414case OP_AutoCommit: { /* no-push */
2415 u8 i = pOp->p1;
2416 u8 rollback = pOp->p2;
2417
2418 assert( i==1 || i==0 );
2419 assert( i==1 || rollback==0 );
2420
2421 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
2422
2423 if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2424 /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2425 ** still running, and a transaction is active, return an error indicating
2426 ** that the other VMs must complete first.
2427 */
2428 sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2429 " transaction - SQL statements in progress", (char*)0);
2430 rc = SQLITE_ERROR;
2431 }else if( i!=db->autoCommit ){
2432 if( pOp->p2 ){
2433 assert( i==1 );
2434 sqlite3RollbackAll(db);
2435 db->autoCommit = 1;
2436 }else{
2437 db->autoCommit = i;
2438 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2439 p->pTos = pTos;
2440 p->pc = pc;
2441 db->autoCommit = 1-i;
2442 p->rc = SQLITE_BUSY;
2443 return SQLITE_BUSY;
2444 }
2445 }
2446 if( p->rc==SQLITE_OK ){
2447 return SQLITE_DONE;
2448 }else{
2449 return SQLITE_ERROR;
2450 }
2451 }else{
2452 sqlite3SetString(&p->zErrMsg,
2453 (!i)?"cannot start a transaction within a transaction":(
2454 (rollback)?"cannot rollback - no transaction is active":
2455 "cannot commit - no transaction is active"), (char*)0);
2456
2457 rc = SQLITE_ERROR;
2458 }
2459 break;
2460}
2461
2462/* Opcode: Transaction P1 P2 *
2463**
2464** Begin a transaction. The transaction ends when a Commit or Rollback
2465** opcode is encountered. Depending on the ON CONFLICT setting, the
2466** transaction might also be rolled back if an error is encountered.
2467**
2468** P1 is the index of the database file on which the transaction is
2469** started. Index 0 is the main database file and index 1 is the
2470** file used for temporary tables.
2471**
2472** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
2473** obtained on the database file when a write-transaction is started. No
2474** other process can start another write transaction while this transaction is
2475** underway. Starting a write transaction also creates a rollback journal. A
2476** write transaction must be started before any changes can be made to the
2477** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2478** on the file.
2479**
2480** If P2 is zero, then a read-lock is obtained on the database file.
2481*/
2482case OP_Transaction: { /* no-push */
2483 int i = pOp->p1;
2484 Btree *pBt;
2485
2486 assert( i>=0 && i<db->nDb );
2487 pBt = db->aDb[i].pBt;
2488
2489 if( pBt ){
2490 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2491 if( rc==SQLITE_BUSY ){
2492 p->pc = pc;
2493 p->rc = SQLITE_BUSY;
2494 p->pTos = pTos;
2495 return SQLITE_BUSY;
2496 }
2497 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2498 goto abort_due_to_error;
2499 }
2500 }
2501 break;
2502}
2503
2504/* Opcode: ReadCookie P1 P2 *
2505**
2506** Read cookie number P2 from database P1 and push it onto the stack.
2507** P2==0 is the schema version. P2==1 is the database format.
2508** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2509** the main database file and P1==1 is the database file used to store
2510** temporary tables.
2511**
2512** There must be a read-lock on the database (either a transaction
2513** must be started or there must be an open cursor) before
2514** executing this instruction.
2515*/
2516case OP_ReadCookie: {
2517 int iMeta;
2518 assert( pOp->p2<SQLITE_N_BTREE_META );
2519 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2520 assert( db->aDb[pOp->p1].pBt!=0 );
2521 /* The indexing of meta values at the schema layer is off by one from
2522 ** the indexing in the btree layer. The btree considers meta[0] to
2523 ** be the number of free pages in the database (a read-only value)
2524 ** and meta[1] to be the schema cookie. The schema layer considers
2525 ** meta[1] to be the schema cookie. So we have to shift the index
2526 ** by one in the following statement.
2527 */
2528 rc = sqlite3BtreeGetMeta(db->aDb[pOp->p1].pBt, 1 + pOp->p2, (u32 *)&iMeta);
2529 pTos++;
2530 pTos->u.i = iMeta;
2531 pTos->flags = MEM_Int;
2532 break;
2533}
2534
2535/* Opcode: SetCookie P1 P2 *
2536**
2537** Write the top of the stack into cookie number P2 of database P1.
2538** P2==0 is the schema version. P2==1 is the database format.
2539** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2540** the main database file and P1==1 is the database file used to store
2541** temporary tables.
2542**
2543** A transaction must be started before executing this opcode.
2544*/
2545case OP_SetCookie: { /* no-push */
2546 Db *pDb;
2547 assert( pOp->p2<SQLITE_N_BTREE_META );
2548 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2549 pDb = &db->aDb[pOp->p1];
2550 assert( pDb->pBt!=0 );
2551 assert( pTos>=p->aStack );
2552 sqlite3VdbeMemIntegerify(pTos);
2553 /* See note about index shifting on OP_ReadCookie */
2554 rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
2555 if( pOp->p2==0 ){
2556 /* When the schema cookie changes, record the new cookie internally */
2557 pDb->pSchema->schema_cookie = pTos->u.i;
2558 db->flags |= SQLITE_InternChanges;
2559 }else if( pOp->p2==1 ){
2560 /* Record changes in the file format */
2561 pDb->pSchema->file_format = pTos->u.i;
2562 }
2563 assert( (pTos->flags & MEM_Dyn)==0 );
2564 pTos--;
2565 if( pOp->p1==1 ){
2566 /* Invalidate all prepared statements whenever the TEMP database
2567 ** schema is changed. Ticket #1644 */
2568 sqlite3ExpirePreparedStatements(db);
2569 }
2570 break;
2571}
2572
2573/* Opcode: VerifyCookie P1 P2 *
2574**
2575** Check the value of global database parameter number 0 (the
2576** schema version) and make sure it is equal to P2.
2577** P1 is the database number which is 0 for the main database file
2578** and 1 for the file holding temporary tables and some higher number
2579** for auxiliary databases.
2580**
2581** The cookie changes its value whenever the database schema changes.
2582** This operation is used to detect when that the cookie has changed
2583** and that the current process needs to reread the schema.
2584**
2585** Either a transaction needs to have been started or an OP_Open needs
2586** to be executed (to establish a read lock) before this opcode is
2587** invoked.
2588*/
2589case OP_VerifyCookie: { /* no-push */
2590 int iMeta;
2591 Btree *pBt;
2592 assert( pOp->p1>=0 && pOp->p1<db->nDb );
2593 pBt = db->aDb[pOp->p1].pBt;
2594 if( pBt ){
2595 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2596 }else{
2597 rc = SQLITE_OK;
2598 iMeta = 0;
2599 }
2600 if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2601 sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
2602 /* If the schema-cookie from the database file matches the cookie
2603 ** stored with the in-memory representation of the schema, do
2604 ** not reload the schema from the database file.
2605 **
2606 ** If virtual-tables are in use, this is not just an optimisation.
2607 ** Often, v-tables store their data in other SQLite tables, which
2608 ** are queried from within xNext() and other v-table methods using
2609 ** prepared queries. If such a query is out-of-date, we do not want to
2610 ** discard the database schema, as the user code implementing the
2611 ** v-table would have to be ready for the sqlite3_vtab structure itself
2612 ** to be invalidated whenever sqlite3_step() is called from within
2613 ** a v-table method.
2614 */
2615 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2616 sqlite3ResetInternalSchema(db, pOp->p1);
2617 }
2618
2619 sqlite3ExpirePreparedStatements(db);
2620 rc = SQLITE_SCHEMA;
2621 }
2622 break;
2623}
2624
2625/* Opcode: OpenRead P1 P2 P3
2626**
2627** Open a read-only cursor for the database table whose root page is
2628** P2 in a database file. The database file is determined by an
2629** integer from the top of the stack. 0 means the main database and
2630** 1 means the database used for temporary tables. Give the new
2631** cursor an identifier of P1. The P1 values need not be contiguous
2632** but all P1 values should be small integers. It is an error for
2633** P1 to be negative.
2634**
2635** If P2==0 then take the root page number from the next of the stack.
2636**
2637** There will be a read lock on the database whenever there is an
2638** open cursor. If the database was unlocked prior to this instruction
2639** then a read lock is acquired as part of this instruction. A read
2640** lock allows other processes to read the database but prohibits
2641** any other process from modifying the database. The read lock is
2642** released when all cursors are closed. If this instruction attempts
2643** to get a read lock but fails, the script terminates with an
2644** SQLITE_BUSY error code.
2645**
2646** The P3 value is a pointer to a KeyInfo structure that defines the
2647** content and collating sequence of indices. P3 is NULL for cursors
2648** that are not pointing to indices.
2649**
2650** See also OpenWrite.
2651*/
2652/* Opcode: OpenWrite P1 P2 P3
2653**
2654** Open a read/write cursor named P1 on the table or index whose root
2655** page is P2. If P2==0 then take the root page number from the stack.
2656**
2657** The P3 value is a pointer to a KeyInfo structure that defines the
2658** content and collating sequence of indices. P3 is NULL for cursors
2659** that are not pointing to indices.
2660**
2661** This instruction works just like OpenRead except that it opens the cursor
2662** in read/write mode. For a given table, there can be one or more read-only
2663** cursors or a single read/write cursor but not both.
2664**
2665** See also OpenRead.
2666*/
2667case OP_OpenRead: /* no-push */
2668case OP_OpenWrite: { /* no-push */
2669 int i = pOp->p1;
2670 int p2 = pOp->p2;
2671 int wrFlag;
2672 Btree *pX;
2673 int iDb;
2674 Cursor *pCur;
2675 Db *pDb;
2676
2677 assert( pTos>=p->aStack );
2678 sqlite3VdbeMemIntegerify(pTos);
2679 iDb = pTos->u.i;
2680 assert( (pTos->flags & MEM_Dyn)==0 );
2681 pTos--;
2682 assert( iDb>=0 && iDb<db->nDb );
2683 pDb = &db->aDb[iDb];
2684 pX = pDb->pBt;
2685 assert( pX!=0 );
2686 if( pOp->opcode==OP_OpenWrite ){
2687 wrFlag = 1;
2688 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
2689 p->minWriteFileFormat = pDb->pSchema->file_format;
2690 }
2691 }else{
2692 wrFlag = 0;
2693 }
2694 if( p2<=0 ){
2695 assert( pTos>=p->aStack );
2696 sqlite3VdbeMemIntegerify(pTos);
2697 p2 = pTos->u.i;
2698 assert( (pTos->flags & MEM_Dyn)==0 );
2699 pTos--;
2700 assert( p2>=2 );
2701 }
2702 assert( i>=0 );
2703 pCur = allocateCursor(p, i, iDb);
2704 if( pCur==0 ) goto no_mem;
2705 pCur->nullRow = 1;
2706 if( pX==0 ) break;
2707 /* We always provide a key comparison function. If the table being
2708 ** opened is of type INTKEY, the comparision function will be ignored. */
2709 rc = sqlite3BtreeCursor(pX, p2, wrFlag,
2710 sqlite3VdbeRecordCompare, pOp->p3,
2711 &pCur->pCursor);
2712 if( pOp->p3type==P3_KEYINFO ){
2713 pCur->pKeyInfo = (KeyInfo*)pOp->p3;
2714 pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2715 pCur->pKeyInfo->enc = ENC(p->db);
2716 }else{
2717 pCur->pKeyInfo = 0;
2718 pCur->pIncrKey = &pCur->bogusIncrKey;
2719 }
2720 switch( rc ){
2721 case SQLITE_BUSY: {
2722 p->pc = pc;
2723 p->rc = SQLITE_BUSY;
2724 p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
2725 return SQLITE_BUSY;
2726 }
2727 case SQLITE_OK: {
2728 int flags = sqlite3BtreeFlags(pCur->pCursor);
2729 /* Sanity checking. Only the lower four bits of the flags byte should
2730 ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
2731 ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2732 ** 2 (zerodata for indices). If these conditions are not met it can
2733 ** only mean that we are dealing with a corrupt database file
2734 */
2735 if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2736 rc = SQLITE_CORRUPT_BKPT;
2737 goto abort_due_to_error;
2738 }
2739 pCur->isTable = (flags & BTREE_INTKEY)!=0;
2740 pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2741 /* If P3==0 it means we are expected to open a table. If P3!=0 then
2742 ** we expect to be opening an index. If this is not what happened,
2743 ** then the database is corrupt
2744 */
2745 if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
2746 || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
2747 rc = SQLITE_CORRUPT_BKPT;
2748 goto abort_due_to_error;
2749 }
2750 break;
2751 }
2752 case SQLITE_EMPTY: {
2753 pCur->isTable = pOp->p3type!=P3_KEYINFO;
2754 pCur->isIndex = !pCur->isTable;
2755 rc = SQLITE_OK;
2756 break;
2757 }
2758 default: {
2759 goto abort_due_to_error;
2760 }
2761 }
2762 break;
2763}
2764
2765/* Opcode: OpenEphemeral P1 P2 P3
2766**
2767** Open a new cursor P1 to a transient table.
2768** The cursor is always opened read/write even if
2769** the main database is read-only. The transient or virtual
2770** table is deleted automatically when the cursor is closed.
2771**
2772** P2 is the number of columns in the virtual table.
2773** The cursor points to a BTree table if P3==0 and to a BTree index
2774** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
2775** that defines the format of keys in the index.
2776**
2777** This opcode was once called OpenTemp. But that created
2778** confusion because the term "temp table", might refer either
2779** to a TEMP table at the SQL level, or to a table opened by
2780** this opcode. Then this opcode was call OpenVirtual. But
2781** that created confusion with the whole virtual-table idea.
2782*/
2783case OP_OpenEphemeral: { /* no-push */
2784 int i = pOp->p1;
2785 Cursor *pCx;
2786 assert( i>=0 );
2787 pCx = allocateCursor(p, i, -1);
2788 if( pCx==0 ) goto no_mem;
2789 pCx->nullRow = 1;
2790 rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, &pCx->pBt);
2791 if( rc==SQLITE_OK ){
2792 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2793 }
2794 if( rc==SQLITE_OK ){
2795 /* If a transient index is required, create it by calling
2796 ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2797 ** opening it. If a transient table is required, just use the
2798 ** automatically created table with root-page 1 (an INTKEY table).
2799 */
2800 if( pOp->p3 ){
2801 int pgno;
2802 assert( pOp->p3type==P3_KEYINFO );
2803 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2804 if( rc==SQLITE_OK ){
2805 assert( pgno==MASTER_ROOT+1 );
2806 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
2807 pOp->p3, &pCx->pCursor);
2808 pCx->pKeyInfo = (KeyInfo*)pOp->p3;
2809 pCx->pKeyInfo->enc = ENC(p->db);
2810 pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2811 }
2812 pCx->isTable = 0;
2813 }else{
2814 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
2815 pCx->isTable = 1;
2816 pCx->pIncrKey = &pCx->bogusIncrKey;
2817 }
2818 }
2819 pCx->nField = pOp->p2;
2820 pCx->isIndex = !pCx->isTable;
2821 break;
2822}
2823
2824/* Opcode: OpenPseudo P1 * *
2825**
2826** Open a new cursor that points to a fake table that contains a single
2827** row of data. Any attempt to write a second row of data causes the
2828** first row to be deleted. All data is deleted when the cursor is
2829** closed.
2830**
2831** A pseudo-table created by this opcode is useful for holding the
2832** NEW or OLD tables in a trigger. Also used to hold the a single
2833** row output from the sorter so that the row can be decomposed into
2834** individual columns using the OP_Column opcode.
2835*/
2836case OP_OpenPseudo: { /* no-push */
2837 int i = pOp->p1;
2838 Cursor *pCx;
2839 assert( i>=0 );
2840 pCx = allocateCursor(p, i, -1);
2841 if( pCx==0 ) goto no_mem;
2842 pCx->nullRow = 1;
2843 pCx->pseudoTable = 1;
2844 pCx->pIncrKey = &pCx->bogusIncrKey;
2845 pCx->isTable = 1;
2846 pCx->isIndex = 0;
2847 break;
2848}
2849
2850/* Opcode: Close P1 * *
2851**
2852** Close a cursor previously opened as P1. If P1 is not
2853** currently open, this instruction is a no-op.
2854*/
2855case OP_Close: { /* no-push */
2856 int i = pOp->p1;
2857 if( i>=0 && i<p->nCursor ){
2858 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
2859 p->apCsr[i] = 0;
2860 }
2861 break;
2862}
2863
2864/* Opcode: MoveGe P1 P2 *
2865**
2866** Pop the top of the stack and use its value as a key. Reposition
2867** cursor P1 so that it points to the smallest entry that is greater
2868** than or equal to the key that was popped ffrom the stack.
2869** If there are no records greater than or equal to the key and P2
2870** is not zero, then jump to P2.
2871**
2872** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2873*/
2874/* Opcode: MoveGt P1 P2 *
2875**
2876** Pop the top of the stack and use its value as a key. Reposition
2877** cursor P1 so that it points to the smallest entry that is greater
2878** than the key from the stack.
2879** If there are no records greater than the key and P2 is not zero,
2880** then jump to P2.
2881**
2882** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2883*/
2884/* Opcode: MoveLt P1 P2 *
2885**
2886** Pop the top of the stack and use its value as a key. Reposition
2887** cursor P1 so that it points to the largest entry that is less
2888** than the key from the stack.
2889** If there are no records less than the key and P2 is not zero,
2890** then jump to P2.
2891**
2892** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2893*/
2894/* Opcode: MoveLe P1 P2 *
2895**
2896** Pop the top of the stack and use its value as a key. Reposition
2897** cursor P1 so that it points to the largest entry that is less than
2898** or equal to the key that was popped from the stack.
2899** If there are no records less than or eqal to the key and P2 is not zero,
2900** then jump to P2.
2901**
2902** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2903*/
2904case OP_MoveLt: /* no-push */
2905case OP_MoveLe: /* no-push */
2906case OP_MoveGe: /* no-push */
2907case OP_MoveGt: { /* no-push */
2908 int i = pOp->p1;
2909 Cursor *pC;
2910
2911 assert( pTos>=p->aStack );
2912 assert( i>=0 && i<p->nCursor );
2913 pC = p->apCsr[i];
2914 assert( pC!=0 );
2915 if( pC->pCursor!=0 ){
2916 int res, oc;
2917 oc = pOp->opcode;
2918 pC->nullRow = 0;
2919 *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2920 if( pC->isTable ){
2921 i64 iKey;
2922 sqlite3VdbeMemIntegerify(pTos);
2923 iKey = intToKey(pTos->u.i);
2924 if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
2925 pC->movetoTarget = iKey;
2926 pC->deferredMoveto = 1;
2927 assert( (pTos->flags & MEM_Dyn)==0 );
2928 pTos--;
2929 break;
2930 }
2931 rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
2932 if( rc!=SQLITE_OK ){
2933 goto abort_due_to_error;
2934 }
2935 pC->lastRowid = pTos->u.i;
2936 pC->rowidIsValid = res==0;
2937 }else{
2938 assert( pTos->flags & MEM_Blob );
2939 ExpandBlob(pTos);
2940 rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
2941 if( rc!=SQLITE_OK ){
2942 goto abort_due_to_error;
2943 }
2944 pC->rowidIsValid = 0;
2945 }
2946 pC->deferredMoveto = 0;
2947 pC->cacheStatus = CACHE_STALE;
2948 *pC->pIncrKey = 0;
2949#ifdef SQLITE_TEST
2950 sqlite3_search_count++;
2951#endif
2952 if( oc==OP_MoveGe || oc==OP_MoveGt ){
2953 if( res<0 ){
2954 rc = sqlite3BtreeNext(pC->pCursor, &res);
2955 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2956 pC->rowidIsValid = 0;
2957 }else{
2958 res = 0;
2959 }
2960 }else{
2961 assert( oc==OP_MoveLt || oc==OP_MoveLe );
2962 if( res>=0 ){
2963 rc = sqlite3BtreePrevious(pC->pCursor, &res);
2964 if( rc!=SQLITE_OK ) goto abort_due_to_error;
2965 pC->rowidIsValid = 0;
2966 }else{
2967 /* res might be negative because the table is empty. Check to
2968 ** see if this is the case.
2969 */
2970 res = sqlite3BtreeEof(pC->pCursor);
2971 }
2972 }
2973 if( res ){
2974 if( pOp->p2>0 ){
2975 pc = pOp->p2 - 1;
2976 }else{
2977 pC->nullRow = 1;
2978 }
2979 }
2980 }
2981 Release(pTos);
2982 pTos--;
2983 break;
2984}
2985
2986/* Opcode: Distinct P1 P2 *
2987**
2988** Use the top of the stack as a record created using MakeRecord. P1 is a
2989** cursor on a table that declared as an index. If that table contains an
2990** entry that matches the top of the stack fall thru. If the top of the stack
2991** matches no entry in P1 then jump to P2.
2992**
2993** The cursor is left pointing at the matching entry if it exists. The
2994** record on the top of the stack is not popped.
2995**
2996** This instruction is similar to NotFound except that this operation
2997** does not pop the key from the stack.
2998**
2999** The instruction is used to implement the DISTINCT operator on SELECT
3000** statements. The P1 table is not a true index but rather a record of
3001** all results that have produced so far.
3002**
3003** See also: Found, NotFound, MoveTo, IsUnique, NotExists
3004*/
3005/* Opcode: Found P1 P2 *
3006**
3007** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
3008** If an entry that matches the top of the stack exists in P1 then
3009** jump to P2. If the top of the stack does not match any entry in P1
3010** then fall thru. The P1 cursor is left pointing at the matching entry
3011** if it exists. The blob is popped off the top of the stack.
3012**
3013** This instruction is used to implement the IN operator where the
3014** left-hand side is a SELECT statement. P1 is not a true index but
3015** is instead a temporary index that holds the results of the SELECT
3016** statement. This instruction just checks to see if the left-hand side
3017** of the IN operator (stored on the top of the stack) exists in the
3018** result of the SELECT statement.
3019**
3020** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
3021*/
3022/* Opcode: NotFound P1 P2 *
3023**
3024** The top of the stack holds a blob constructed by MakeRecord. P1 is
3025** an index. If no entry exists in P1 that matches the blob then jump
3026** to P2. If an entry does existing, fall through. The cursor is left
3027** pointing to the entry that matches. The blob is popped from the stack.
3028**
3029** The difference between this operation and Distinct is that
3030** Distinct does not pop the key from the stack.
3031**
3032** See also: Distinct, Found, MoveTo, NotExists, IsUnique
3033*/
3034case OP_Distinct: /* no-push */
3035case OP_NotFound: /* no-push */
3036case OP_Found: { /* no-push */
3037 int i = pOp->p1;
3038 int alreadyExists = 0;
3039 Cursor *pC;
3040 assert( pTos>=p->aStack );
3041 assert( i>=0 && i<p->nCursor );
3042 assert( p->apCsr[i]!=0 );
3043 if( (pC = p->apCsr[i])->pCursor!=0 ){
3044 int res, rx;
3045 assert( pC->isTable==0 );
3046 assert( pTos->flags & MEM_Blob );
3047 Stringify(pTos, encoding);
3048 rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
3049 alreadyExists = rx==SQLITE_OK && res==0;
3050 pC->deferredMoveto = 0;
3051 pC->cacheStatus = CACHE_STALE;
3052 }
3053 if( pOp->opcode==OP_Found ){
3054 if( alreadyExists ) pc = pOp->p2 - 1;
3055 }else{
3056 if( !alreadyExists ) pc = pOp->p2 - 1;
3057 }
3058 if( pOp->opcode!=OP_Distinct ){
3059 Release(pTos);
3060 pTos--;
3061 }
3062 break;
3063}
3064
3065/* Opcode: IsUnique P1 P2 *
3066**
3067** The top of the stack is an integer record number. Call this
3068** record number R. The next on the stack is an index key created
3069** using MakeIdxRec. Call it K. This instruction pops R from the
3070** stack but it leaves K unchanged.
3071**
3072** P1 is an index. So it has no data and its key consists of a
3073** record generated by OP_MakeRecord where the last field is the
3074** rowid of the entry that the index refers to.
3075**
3076** This instruction asks if there is an entry in P1 where the
3077** fields matches K but the rowid is different from R.
3078** If there is no such entry, then there is an immediate
3079** jump to P2. If any entry does exist where the index string
3080** matches K but the record number is not R, then the record
3081** number for that entry is pushed onto the stack and control
3082** falls through to the next instruction.
3083**
3084** See also: Distinct, NotFound, NotExists, Found
3085*/
3086case OP_IsUnique: { /* no-push */
3087 int i = pOp->p1;
3088 Mem *pNos = &pTos[-1];
3089 Cursor *pCx;
3090 BtCursor *pCrsr;
3091 i64 R;
3092
3093 /* Pop the value R off the top of the stack
3094 */
3095 assert( pNos>=p->aStack );
3096 sqlite3VdbeMemIntegerify(pTos);
3097 R = pTos->u.i;
3098 assert( (pTos->flags & MEM_Dyn)==0 );
3099 pTos--;
3100 assert( i>=0 && i<p->nCursor );
3101 pCx = p->apCsr[i];
3102 assert( pCx!=0 );
3103 pCrsr = pCx->pCursor;
3104 if( pCrsr!=0 ){
3105 int res;
3106 i64 v; /* The record number on the P1 entry that matches K */
3107 char *zKey; /* The value of K */
3108 int nKey; /* Number of bytes in K */
3109 int len; /* Number of bytes in K without the rowid at the end */
3110 int szRowid; /* Size of the rowid column at the end of zKey */
3111
3112 /* Make sure K is a string and make zKey point to K
3113 */
3114 assert( pNos->flags & MEM_Blob );
3115 Stringify(pNos, encoding);
3116 zKey = pNos->z;
3117 nKey = pNos->n;
3118
3119 szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
3120 len = nKey-szRowid;
3121
3122 /* Search for an entry in P1 where all but the last four bytes match K.
3123 ** If there is no such entry, jump immediately to P2.
3124 */
3125 assert( pCx->deferredMoveto==0 );
3126 pCx->cacheStatus = CACHE_STALE;
3127 rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
3128 if( rc!=SQLITE_OK ){
3129 goto abort_due_to_error;
3130 }
3131 if( res<0 ){
3132 rc = sqlite3BtreeNext(pCrsr, &res);
3133 if( res ){
3134 pc = pOp->p2 - 1;
3135 break;
3136 }
3137 }
3138 rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
3139 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3140 if( res>0 ){
3141 pc = pOp->p2 - 1;
3142 break;
3143 }
3144
3145 /* At this point, pCrsr is pointing to an entry in P1 where all but
3146 ** the final entry (the rowid) matches K. Check to see if the
3147 ** final rowid column is different from R. If it equals R then jump
3148 ** immediately to P2.
3149 */
3150 rc = sqlite3VdbeIdxRowid(pCrsr, &v);
3151 if( rc!=SQLITE_OK ){
3152 goto abort_due_to_error;
3153 }
3154 if( v==R ){
3155 pc = pOp->p2 - 1;
3156 break;
3157 }
3158
3159 /* The final varint of the key is different from R. Push it onto
3160 ** the stack. (The record number of an entry that violates a UNIQUE
3161 ** constraint.)
3162 */
3163 pTos++;
3164 pTos->u.i = v;
3165 pTos->flags = MEM_Int;
3166 }
3167 break;
3168}
3169
3170/* Opcode: NotExists P1 P2 *
3171**
3172** Use the top of the stack as a integer key. If a record with that key
3173** does not exist in table of P1, then jump to P2. If the record
3174** does exist, then fall thru. The cursor is left pointing to the
3175** record if it exists. The integer key is popped from the stack.
3176**
3177** The difference between this operation and NotFound is that this
3178** operation assumes the key is an integer and that P1 is a table whereas
3179** NotFound assumes key is a blob constructed from MakeRecord and
3180** P1 is an index.
3181**
3182** See also: Distinct, Found, MoveTo, NotFound, IsUnique
3183*/
3184case OP_NotExists: { /* no-push */
3185 int i = pOp->p1;
3186 Cursor *pC;
3187 BtCursor *pCrsr;
3188 assert( pTos>=p->aStack );
3189 assert( i>=0 && i<p->nCursor );
3190 assert( p->apCsr[i]!=0 );
3191 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3192 int res;
3193 u64 iKey;
3194 assert( pTos->flags & MEM_Int );
3195 assert( p->apCsr[i]->isTable );
3196 iKey = intToKey(pTos->u.i);
3197 rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
3198 pC->lastRowid = pTos->u.i;
3199 pC->rowidIsValid = res==0;
3200 pC->nullRow = 0;
3201 pC->cacheStatus = CACHE_STALE;
3202 /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
3203 ** processing is about to abort so we really do not care whether or not
3204 ** the following jump is taken. (In other words, do not stress over
3205 ** the error that valgrind sometimes shows on the next statement when
3206 ** running ioerr.test and similar failure-recovery test scripts.) */
3207 if( res!=0 ){
3208 pc = pOp->p2 - 1;
3209 pC->rowidIsValid = 0;
3210 }
3211 }
3212 Release(pTos);
3213 pTos--;
3214 break;
3215}
3216
3217/* Opcode: Sequence P1 * *
3218**
3219** Push an integer onto the stack which is the next available
3220** sequence number for cursor P1. The sequence number on the
3221** cursor is incremented after the push.
3222*/
3223case OP_Sequence: {
3224 int i = pOp->p1;
3225 assert( pTos>=p->aStack );
3226 assert( i>=0 && i<p->nCursor );
3227 assert( p->apCsr[i]!=0 );
3228 pTos++;
3229 pTos->u.i = p->apCsr[i]->seqCount++;
3230 pTos->flags = MEM_Int;
3231 break;
3232}
3233
3234
3235/* Opcode: NewRowid P1 P2 *
3236**
3237** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3238** The record number is not previously used as a key in the database
3239** table that cursor P1 points to. The new record number is pushed
3240** onto the stack.
3241**
3242** If P2>0 then P2 is a memory cell that holds the largest previously
3243** generated record number. No new record numbers are allowed to be less
3244** than this value. When this value reaches its maximum, a SQLITE_FULL
3245** error is generated. The P2 memory cell is updated with the generated
3246** record number. This P2 mechanism is used to help implement the
3247** AUTOINCREMENT feature.
3248*/
3249case OP_NewRowid: {
3250 int i = pOp->p1;
3251 i64 v = 0;
3252 Cursor *pC;
3253 assert( i>=0 && i<p->nCursor );
3254 assert( p->apCsr[i]!=0 );
3255 if( (pC = p->apCsr[i])->pCursor==0 ){
3256 /* The zero initialization above is all that is needed */
3257 }else{
3258 /* The next rowid or record number (different terms for the same
3259 ** thing) is obtained in a two-step algorithm.
3260 **
3261 ** First we attempt to find the largest existing rowid and add one
3262 ** to that. But if the largest existing rowid is already the maximum
3263 ** positive integer, we have to fall through to the second
3264 ** probabilistic algorithm
3265 **
3266 ** The second algorithm is to select a rowid at random and see if
3267 ** it already exists in the table. If it does not exist, we have
3268 ** succeeded. If the random rowid does exist, we select a new one
3269 ** and try again, up to 1000 times.
3270 **
3271 ** For a table with less than 2 billion entries, the probability
3272 ** of not finding a unused rowid is about 1.0e-300. This is a
3273 ** non-zero probability, but it is still vanishingly small and should
3274 ** never cause a problem. You are much, much more likely to have a
3275 ** hardware failure than for this algorithm to fail.
3276 **
3277 ** The analysis in the previous paragraph assumes that you have a good
3278 ** source of random numbers. Is a library function like lrand48()
3279 ** good enough? Maybe. Maybe not. It's hard to know whether there
3280 ** might be subtle bugs is some implementations of lrand48() that
3281 ** could cause problems. To avoid uncertainty, SQLite uses its own
3282 ** random number generator based on the RC4 algorithm.
3283 **
3284 ** To promote locality of reference for repetitive inserts, the
3285 ** first few attempts at chosing a random rowid pick values just a little
3286 ** larger than the previous rowid. This has been shown experimentally
3287 ** to double the speed of the COPY operation.
3288 */
3289 int res, rx=SQLITE_OK, cnt;
3290 i64 x;
3291 cnt = 0;
3292 if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
3293 BTREE_INTKEY ){
3294 rc = SQLITE_CORRUPT_BKPT;
3295 goto abort_due_to_error;
3296 }
3297 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3298 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3299
3300#ifdef SQLITE_32BIT_ROWID
3301# define MAX_ROWID 0x7fffffff
3302#else
3303 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
3304 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
3305 ** to provide the constant while making all compilers happy.
3306 */
3307# define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3308#endif
3309
3310 if( !pC->useRandomRowid ){
3311 if( pC->nextRowidValid ){
3312 v = pC->nextRowid;
3313 }else{
3314 rc = sqlite3BtreeLast(pC->pCursor, &res);
3315 if( rc!=SQLITE_OK ){
3316 goto abort_due_to_error;
3317 }
3318 if( res ){
3319 v = 1;
3320 }else{
3321 sqlite3BtreeKeySize(pC->pCursor, &v);
3322 v = keyToInt(v);
3323 if( v==MAX_ROWID ){
3324 pC->useRandomRowid = 1;
3325 }else{
3326 v++;
3327 }
3328 }
3329 }
3330
3331#ifndef SQLITE_OMIT_AUTOINCREMENT
3332 if( pOp->p2 ){
3333 Mem *pMem;
3334 assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
3335 pMem = &p->aMem[pOp->p2];
3336 sqlite3VdbeMemIntegerify(pMem);
3337 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
3338 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3339 rc = SQLITE_FULL;
3340 goto abort_due_to_error;
3341 }
3342 if( v<pMem->u.i+1 ){
3343 v = pMem->u.i + 1;
3344 }
3345 pMem->u.i = v;
3346 }
3347#endif
3348
3349 if( v<MAX_ROWID ){
3350 pC->nextRowidValid = 1;
3351 pC->nextRowid = v+1;
3352 }else{
3353 pC->nextRowidValid = 0;
3354 }
3355 }
3356 if( pC->useRandomRowid ){
3357 assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
3358 v = db->priorNewRowid;
3359 cnt = 0;
3360 do{
3361 if( v==0 || cnt>2 ){
3362 sqlite3Randomness(sizeof(v), &v);
3363 if( cnt<5 ) v &= 0xffffff;
3364 }else{
3365 unsigned char r;
3366 sqlite3Randomness(1, &r);
3367 v += r + 1;
3368 }
3369 if( v==0 ) continue;
3370 x = intToKey(v);
3371 rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
3372 cnt++;
3373 }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3374 db->priorNewRowid = v;
3375 if( rx==SQLITE_OK && res==0 ){
3376 rc = SQLITE_FULL;
3377 goto abort_due_to_error;
3378 }
3379 }
3380 pC->rowidIsValid = 0;
3381 pC->deferredMoveto = 0;
3382 pC->cacheStatus = CACHE_STALE;
3383 }
3384 pTos++;
3385 pTos->u.i = v;
3386 pTos->flags = MEM_Int;
3387 break;
3388}
3389
3390/* Opcode: Insert P1 P2 P3
3391**
3392** Write an entry into the table of cursor P1. A new entry is
3393** created if it doesn't already exist or the data for an existing
3394** entry is overwritten. The data is the value on the top of the
3395** stack. The key is the next value down on the stack. The key must
3396** be an integer. The stack is popped twice by this instruction.
3397**
3398** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3399** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
3400** then rowid is stored for subsequent return by the
3401** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
3402**
3403** Parameter P3 may point to a string containing the table-name, or
3404** may be NULL. If it is not NULL, then the update-hook
3405** (sqlite3.xUpdateCallback) is invoked following a successful insert.
3406**
3407** This instruction only works on tables. The equivalent instruction
3408** for indices is OP_IdxInsert.
3409*/
3410case OP_Insert: { /* no-push */
3411 Mem *pNos = &pTos[-1];
3412 int i = pOp->p1;
3413 Cursor *pC;
3414 assert( pNos>=p->aStack );
3415 assert( i>=0 && i<p->nCursor );
3416 assert( p->apCsr[i]!=0 );
3417 if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3418 i64 iKey; /* The integer ROWID or key for the record to be inserted */
3419
3420 assert( pNos->flags & MEM_Int );
3421 assert( pC->isTable );
3422 iKey = intToKey(pNos->u.i);
3423
3424 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3425 if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
3426 if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
3427 pC->nextRowidValid = 0;
3428 }
3429 if( pTos->flags & MEM_Null ){
3430 pTos->z = 0;
3431 pTos->n = 0;
3432 }else{
3433 assert( pTos->flags & (MEM_Blob|MEM_Str) );
3434 }
3435 if( pC->pseudoTable ){
3436 sqliteFree(pC->pData);
3437 pC->iKey = iKey;
3438 pC->nData = pTos->n;
3439 if( pTos->flags & MEM_Dyn ){
3440 pC->pData = pTos->z;
3441 pTos->flags = MEM_Null;
3442 }else{
3443 pC->pData = sqliteMallocRaw( pC->nData+2 );
3444 if( !pC->pData ) goto no_mem;
3445 memcpy(pC->pData, pTos->z, pC->nData);
3446 pC->pData[pC->nData] = 0;
3447 pC->pData[pC->nData+1] = 0;
3448 }
3449 pC->nullRow = 0;
3450 }else{
3451 int nZero;
3452 if( pTos->flags & MEM_Zero ){
3453 nZero = pTos->u.i;
3454 }else{
3455 nZero = 0;
3456 }
3457 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3458 pTos->z, pTos->n, nZero,
3459 pOp->p2 & OPFLAG_APPEND);
3460 }
3461
3462 pC->rowidIsValid = 0;
3463 pC->deferredMoveto = 0;
3464 pC->cacheStatus = CACHE_STALE;
3465
3466 /* Invoke the update-hook if required. */
3467 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3468 const char *zDb = db->aDb[pC->iDb].zName;
3469 const char *zTbl = pOp->p3;
3470 int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3471 assert( pC->isTable );
3472 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3473 assert( pC->iDb>=0 );
3474 }
3475 }
3476 popStack(&pTos, 2);
3477
3478 break;
3479}
3480
3481/* Opcode: Delete P1 P2 P3
3482**
3483** Delete the record at which the P1 cursor is currently pointing.
3484**
3485** The cursor will be left pointing at either the next or the previous
3486** record in the table. If it is left pointing at the next record, then
3487** the next Next instruction will be a no-op. Hence it is OK to delete
3488** a record from within an Next loop.
3489**
3490** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3491** incremented (otherwise not).
3492**
3493** If P1 is a pseudo-table, then this instruction is a no-op.
3494*/
3495case OP_Delete: { /* no-push */
3496 int i = pOp->p1;
3497 Cursor *pC;
3498 assert( i>=0 && i<p->nCursor );
3499 pC = p->apCsr[i];
3500 assert( pC!=0 );
3501 if( pC->pCursor!=0 ){
3502 i64 iKey;
3503
3504 /* If the update-hook will be invoked, set iKey to the rowid of the
3505 ** row being deleted.
3506 */
3507 if( db->xUpdateCallback && pOp->p3 ){
3508 assert( pC->isTable );
3509 if( pC->rowidIsValid ){
3510 iKey = pC->lastRowid;
3511 }else{
3512 rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
3513 if( rc ){
3514 goto abort_due_to_error;
3515 }
3516 iKey = keyToInt(iKey);
3517 }
3518 }
3519
3520 rc = sqlite3VdbeCursorMoveto(pC);
3521 if( rc ) goto abort_due_to_error;
3522 rc = sqlite3BtreeDelete(pC->pCursor);
3523 pC->nextRowidValid = 0;
3524 pC->cacheStatus = CACHE_STALE;
3525
3526 /* Invoke the update-hook if required. */
3527 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
3528 const char *zDb = db->aDb[pC->iDb].zName;
3529 const char *zTbl = pOp->p3;
3530 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3531 assert( pC->iDb>=0 );
3532 }
3533 }
3534 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3535 break;
3536}
3537
3538/* Opcode: ResetCount P1 * *
3539**
3540** This opcode resets the VMs internal change counter to 0. If P1 is true,
3541** then the value of the change counter is copied to the database handle
3542** change counter (returned by subsequent calls to sqlite3_changes())
3543** before it is reset. This is used by trigger programs.
3544*/
3545case OP_ResetCount: { /* no-push */
3546 if( pOp->p1 ){
3547 sqlite3VdbeSetChanges(db, p->nChange);
3548 }
3549 p->nChange = 0;
3550 break;
3551}
3552
3553/* Opcode: RowData P1 * *
3554**
3555** Push onto the stack the complete row data for cursor P1.
3556** There is no interpretation of the data. It is just copied
3557** onto the stack exactly as it is found in the database file.
3558**
3559** If the cursor is not pointing to a valid row, a NULL is pushed
3560** onto the stack.
3561*/
3562/* Opcode: RowKey P1 * *
3563**
3564** Push onto the stack the complete row key for cursor P1.
3565** There is no interpretation of the key. It is just copied
3566** onto the stack exactly as it is found in the database file.
3567**
3568** If the cursor is not pointing to a valid row, a NULL is pushed
3569** onto the stack.
3570*/
3571case OP_RowKey:
3572case OP_RowData: {
3573 int i = pOp->p1;
3574 Cursor *pC;
3575 u32 n;
3576
3577 /* Note that RowKey and RowData are really exactly the same instruction */
3578 pTos++;
3579 assert( i>=0 && i<p->nCursor );
3580 pC = p->apCsr[i];
3581 assert( pC->isTable || pOp->opcode==OP_RowKey );
3582 assert( pC->isIndex || pOp->opcode==OP_RowData );
3583 assert( pC!=0 );
3584 if( pC->nullRow ){
3585 pTos->flags = MEM_Null;
3586 }else if( pC->pCursor!=0 ){
3587 BtCursor *pCrsr = pC->pCursor;
3588 rc = sqlite3VdbeCursorMoveto(pC);
3589 if( rc ) goto abort_due_to_error;
3590 if( pC->nullRow ){
3591 pTos->flags = MEM_Null;
3592 break;
3593 }else if( pC->isIndex ){
3594 i64 n64;
3595 assert( !pC->isTable );
3596 sqlite3BtreeKeySize(pCrsr, &n64);
3597 if( n64>SQLITE_MAX_LENGTH ){
3598 goto too_big;
3599 }
3600 n = n64;
3601 }else{
3602 sqlite3BtreeDataSize(pCrsr, &n);
3603 }
3604 if( n>SQLITE_MAX_LENGTH ){
3605 goto too_big;
3606 }
3607 pTos->n = n;
3608 if( n<=NBFS ){
3609 pTos->flags = MEM_Blob | MEM_Short;
3610 pTos->z = pTos->zShort;
3611 }else{
3612 char *z = sqliteMallocRaw( n );
3613 if( z==0 ) goto no_mem;
3614 pTos->flags = MEM_Blob | MEM_Dyn;
3615 pTos->xDel = 0;
3616 pTos->z = z;
3617 }
3618 if( pC->isIndex ){
3619 rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
3620 }else{
3621 rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
3622 }
3623 }else if( pC->pseudoTable ){
3624 pTos->n = pC->nData;
3625 assert( pC->nData<=SQLITE_MAX_LENGTH );
3626 pTos->z = pC->pData;
3627 pTos->flags = MEM_Blob|MEM_Ephem;
3628 }else{
3629 pTos->flags = MEM_Null;
3630 }
3631 pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
3632 break;
3633}
3634
3635/* Opcode: Rowid P1 * *
3636**
3637** Push onto the stack an integer which is the key of the table entry that
3638** P1 is currently point to.
3639*/
3640case OP_Rowid: {
3641 int i = pOp->p1;
3642 Cursor *pC;
3643 i64 v;
3644
3645 assert( i>=0 && i<p->nCursor );
3646 pC = p->apCsr[i];
3647 assert( pC!=0 );
3648 rc = sqlite3VdbeCursorMoveto(pC);
3649 if( rc ) goto abort_due_to_error;
3650 pTos++;
3651 if( pC->rowidIsValid ){
3652 v = pC->lastRowid;
3653 }else if( pC->pseudoTable ){
3654 v = keyToInt(pC->iKey);
3655 }else if( pC->nullRow || pC->pCursor==0 ){
3656 pTos->flags = MEM_Null;
3657 break;
3658 }else{
3659 assert( pC->pCursor!=0 );
3660 sqlite3BtreeKeySize(pC->pCursor, &v);
3661 v = keyToInt(v);
3662 }
3663 pTos->u.i = v;
3664 pTos->flags = MEM_Int;
3665 break;
3666}
3667
3668/* Opcode: NullRow P1 * *
3669**
3670** Move the cursor P1 to a null row. Any OP_Column operations
3671** that occur while the cursor is on the null row will always push
3672** a NULL onto the stack.
3673*/
3674case OP_NullRow: { /* no-push */
3675 int i = pOp->p1;
3676 Cursor *pC;
3677
3678 assert( i>=0 && i<p->nCursor );
3679 pC = p->apCsr[i];
3680 assert( pC!=0 );
3681 pC->nullRow = 1;
3682 pC->rowidIsValid = 0;
3683 break;
3684}
3685
3686/* Opcode: Last P1 P2 *
3687**
3688** The next use of the Rowid or Column or Next instruction for P1
3689** will refer to the last entry in the database table or index.
3690** If the table or index is empty and P2>0, then jump immediately to P2.
3691** If P2 is 0 or if the table or index is not empty, fall through
3692** to the following instruction.
3693*/
3694case OP_Last: { /* no-push */
3695 int i = pOp->p1;
3696 Cursor *pC;
3697 BtCursor *pCrsr;
3698
3699 assert( i>=0 && i<p->nCursor );
3700 pC = p->apCsr[i];
3701 assert( pC!=0 );
3702 if( (pCrsr = pC->pCursor)!=0 ){
3703 int res;
3704 rc = sqlite3BtreeLast(pCrsr, &res);
3705 pC->nullRow = res;
3706 pC->deferredMoveto = 0;
3707 pC->cacheStatus = CACHE_STALE;
3708 if( res && pOp->p2>0 ){
3709 pc = pOp->p2 - 1;
3710 }
3711 }else{
3712 pC->nullRow = 0;
3713 }
3714 break;
3715}
3716
3717
3718/* Opcode: Sort P1 P2 *
3719**
3720** This opcode does exactly the same thing as OP_Rewind except that
3721** it increments an undocumented global variable used for testing.
3722**
3723** Sorting is accomplished by writing records into a sorting index,
3724** then rewinding that index and playing it back from beginning to
3725** end. We use the OP_Sort opcode instead of OP_Rewind to do the
3726** rewinding so that the global variable will be incremented and
3727** regression tests can determine whether or not the optimizer is
3728** correctly optimizing out sorts.
3729*/
3730case OP_Sort: { /* no-push */
3731#ifdef SQLITE_TEST
3732 sqlite3_sort_count++;
3733 sqlite3_search_count--;
3734#endif
3735 /* Fall through into OP_Rewind */
3736}
3737/* Opcode: Rewind P1 P2 *
3738**
3739** The next use of the Rowid or Column or Next instruction for P1
3740** will refer to the first entry in the database table or index.
3741** If the table or index is empty and P2>0, then jump immediately to P2.
3742** If P2 is 0 or if the table or index is not empty, fall through
3743** to the following instruction.
3744*/
3745case OP_Rewind: { /* no-push */
3746 int i = pOp->p1;
3747 Cursor *pC;
3748 BtCursor *pCrsr;
3749 int res;
3750
3751 assert( i>=0 && i<p->nCursor );
3752 pC = p->apCsr[i];
3753 assert( pC!=0 );
3754 if( (pCrsr = pC->pCursor)!=0 ){
3755 rc = sqlite3BtreeFirst(pCrsr, &res);
3756 pC->atFirst = res==0;
3757 pC->deferredMoveto = 0;
3758 pC->cacheStatus = CACHE_STALE;
3759 }else{
3760 res = 1;
3761 }
3762 pC->nullRow = res;
3763 if( res && pOp->p2>0 ){
3764 pc = pOp->p2 - 1;
3765 }
3766 break;
3767}
3768
3769/* Opcode: Next P1 P2 *
3770**
3771** Advance cursor P1 so that it points to the next key/data pair in its
3772** table or index. If there are no more key/value pairs then fall through
3773** to the following instruction. But if the cursor advance was successful,
3774** jump immediately to P2.
3775**
3776** See also: Prev
3777*/
3778/* Opcode: Prev P1 P2 *
3779**
3780** Back up cursor P1 so that it points to the previous key/data pair in its
3781** table or index. If there is no previous key/value pairs then fall through
3782** to the following instruction. But if the cursor backup was successful,
3783** jump immediately to P2.
3784*/
3785case OP_Prev: /* no-push */
3786case OP_Next: { /* no-push */
3787 Cursor *pC;
3788 BtCursor *pCrsr;
3789
3790 CHECK_FOR_INTERRUPT;
3791 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3792 pC = p->apCsr[pOp->p1];
3793 if( pC==0 ){
3794 break; /* See ticket #2273 */
3795 }
3796 if( (pCrsr = pC->pCursor)!=0 ){
3797 int res;
3798 if( pC->nullRow ){
3799 res = 1;
3800 }else{
3801 assert( pC->deferredMoveto==0 );
3802 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3803 sqlite3BtreePrevious(pCrsr, &res);
3804 pC->nullRow = res;
3805 pC->cacheStatus = CACHE_STALE;
3806 }
3807 if( res==0 ){
3808 pc = pOp->p2 - 1;
3809#ifdef SQLITE_TEST
3810 sqlite3_search_count++;
3811#endif
3812 }
3813 }else{
3814 pC->nullRow = 1;
3815 }
3816 pC->rowidIsValid = 0;
3817 break;
3818}
3819
3820/* Opcode: IdxInsert P1 P2 *
3821**
3822** The top of the stack holds a SQL index key made using either the
3823** MakeIdxRec or MakeRecord instructions. This opcode writes that key
3824** into the index P1. Data for the entry is nil.
3825**
3826** P2 is a flag that provides a hint to the b-tree layer that this
3827** insert is likely to be an append.
3828**
3829** This instruction only works for indices. The equivalent instruction
3830** for tables is OP_Insert.
3831*/
3832case OP_IdxInsert: { /* no-push */
3833 int i = pOp->p1;
3834 Cursor *pC;
3835 BtCursor *pCrsr;
3836 assert( pTos>=p->aStack );
3837 assert( i>=0 && i<p->nCursor );
3838 assert( p->apCsr[i]!=0 );
3839 assert( pTos->flags & MEM_Blob );
3840 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3841 assert( pC->isTable==0 );
3842 rc = ExpandBlob(pTos);
3843 if( rc==SQLITE_OK ){
3844 int nKey = pTos->n;
3845 const char *zKey = pTos->z;
3846 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
3847 assert( pC->deferredMoveto==0 );
3848 pC->cacheStatus = CACHE_STALE;
3849 }
3850 }
3851 Release(pTos);
3852 pTos--;
3853 break;
3854}
3855
3856/* Opcode: IdxDelete P1 * *
3857**
3858** The top of the stack is an index key built using the either the
3859** MakeIdxRec or MakeRecord opcodes.
3860** This opcode removes that entry from the index.
3861*/
3862case OP_IdxDelete: { /* no-push */
3863 int i = pOp->p1;
3864 Cursor *pC;
3865 BtCursor *pCrsr;
3866 assert( pTos>=p->aStack );
3867 assert( pTos->flags & MEM_Blob );
3868 assert( i>=0 && i<p->nCursor );
3869 assert( p->apCsr[i]!=0 );
3870 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3871 int res;
3872 rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
3873 if( rc==SQLITE_OK && res==0 ){
3874 rc = sqlite3BtreeDelete(pCrsr);
3875 }
3876 assert( pC->deferredMoveto==0 );
3877 pC->cacheStatus = CACHE_STALE;
3878 }
3879 Release(pTos);
3880 pTos--;
3881 break;
3882}
3883
3884/* Opcode: IdxRowid P1 * *
3885**
3886** Push onto the stack an integer which is the last entry in the record at
3887** the end of the index key pointed to by cursor P1. This integer should be
3888** the rowid of the table entry to which this index entry points.
3889**
3890** See also: Rowid, MakeIdxRec.
3891*/
3892case OP_IdxRowid: {
3893 int i = pOp->p1;
3894 BtCursor *pCrsr;
3895 Cursor *pC;
3896
3897 assert( i>=0 && i<p->nCursor );
3898 assert( p->apCsr[i]!=0 );
3899 pTos++;
3900 pTos->flags = MEM_Null;
3901 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3902 i64 rowid;
3903
3904 assert( pC->deferredMoveto==0 );
3905 assert( pC->isTable==0 );
3906 if( pC->nullRow ){
3907 pTos->flags = MEM_Null;
3908 }else{
3909 rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3910 if( rc!=SQLITE_OK ){
3911 goto abort_due_to_error;
3912 }
3913 pTos->flags = MEM_Int;
3914 pTos->u.i = rowid;
3915 }
3916 }
3917 break;
3918}
3919
3920/* Opcode: IdxGT P1 P2 *
3921**
3922** The top of the stack is an index entry that omits the ROWID. Compare
3923** the top of stack against the index that P1 is currently pointing to.
3924** Ignore the ROWID on the P1 index.
3925**
3926** The top of the stack might have fewer columns that P1.
3927**
3928** If the P1 index entry is greater than the top of the stack
3929** then jump to P2. Otherwise fall through to the next instruction.
3930** In either case, the stack is popped once.
3931*/
3932/* Opcode: IdxGE P1 P2 P3
3933**
3934** The top of the stack is an index entry that omits the ROWID. Compare
3935** the top of stack against the index that P1 is currently pointing to.
3936** Ignore the ROWID on the P1 index.
3937**
3938** If the P1 index entry is greater than or equal to the top of the stack
3939** then jump to P2. Otherwise fall through to the next instruction.
3940** In either case, the stack is popped once.
3941**
3942** If P3 is the "+" string (or any other non-NULL string) then the
3943** index taken from the top of the stack is temporarily increased by
3944** an epsilon prior to the comparison. This make the opcode work
3945** like IdxGT except that if the key from the stack is a prefix of
3946** the key in the cursor, the result is false whereas it would be
3947** true with IdxGT.
3948*/
3949/* Opcode: IdxLT P1 P2 P3
3950**
3951** The top of the stack is an index entry that omits the ROWID. Compare
3952** the top of stack against the index that P1 is currently pointing to.
3953** Ignore the ROWID on the P1 index.
3954**
3955** If the P1 index entry is less than the top of the stack
3956** then jump to P2. Otherwise fall through to the next instruction.
3957** In either case, the stack is popped once.
3958**
3959** If P3 is the "+" string (or any other non-NULL string) then the
3960** index taken from the top of the stack is temporarily increased by
3961** an epsilon prior to the comparison. This makes the opcode work
3962** like IdxLE.
3963*/
3964case OP_IdxLT: /* no-push */
3965case OP_IdxGT: /* no-push */
3966case OP_IdxGE: { /* no-push */
3967 int i= pOp->p1;
3968 Cursor *pC;
3969
3970 assert( i>=0 && i<p->nCursor );
3971 assert( p->apCsr[i]!=0 );
3972 assert( pTos>=p->aStack );
3973 if( (pC = p->apCsr[i])->pCursor!=0 ){
3974 int res;
3975
3976 assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */
3977 assert( pC->deferredMoveto==0 );
3978 ExpandBlob(pTos);
3979 *pC->pIncrKey = pOp->p3!=0;
3980 assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
3981 rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
3982 *pC->pIncrKey = 0;
3983 if( rc!=SQLITE_OK ){
3984 break;
3985 }
3986 if( pOp->opcode==OP_IdxLT ){
3987 res = -res;
3988 }else if( pOp->opcode==OP_IdxGE ){
3989 res++;
3990 }
3991 if( res>0 ){
3992 pc = pOp->p2 - 1 ;
3993 }
3994 }
3995 Release(pTos);
3996 pTos--;
3997 break;
3998}
3999
4000/* Opcode: Destroy P1 P2 *
4001**
4002** Delete an entire database table or index whose root page in the database
4003** file is given by P1.
4004**
4005** The table being destroyed is in the main database file if P2==0. If
4006** P2==1 then the table to be clear is in the auxiliary database file
4007** that is used to store tables create using CREATE TEMPORARY TABLE.
4008**
4009** If AUTOVACUUM is enabled then it is possible that another root page
4010** might be moved into the newly deleted root page in order to keep all
4011** root pages contiguous at the beginning of the database. The former
4012** value of the root page that moved - its value before the move occurred -
4013** is pushed onto the stack. If no page movement was required (because
4014** the table being dropped was already the last one in the database) then
4015** a zero is pushed onto the stack. If AUTOVACUUM is disabled
4016** then a zero is pushed onto the stack.
4017**
4018** See also: Clear
4019*/
4020case OP_Destroy: {
4021 int iMoved;
4022 int iCnt;
4023#ifndef SQLITE_OMIT_VIRTUALTABLE
4024 Vdbe *pVdbe;
4025 iCnt = 0;
4026 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
4027 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
4028 iCnt++;
4029 }
4030 }
4031#else
4032 iCnt = db->activeVdbeCnt;
4033#endif
4034 if( iCnt>1 ){
4035 rc = SQLITE_LOCKED;
4036 }else{
4037 assert( iCnt==1 );
4038 rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
4039 pTos++;
4040 pTos->flags = MEM_Int;
4041 pTos->u.i = iMoved;
4042#ifndef SQLITE_OMIT_AUTOVACUUM
4043 if( rc==SQLITE_OK && iMoved!=0 ){
4044 sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
4045 }
4046#endif
4047 }
4048 break;
4049}
4050
4051/* Opcode: Clear P1 P2 *
4052**
4053** Delete all contents of the database table or index whose root page
4054** in the database file is given by P1. But, unlike Destroy, do not
4055** remove the table or index from the database file.
4056**
4057** The table being clear is in the main database file if P2==0. If
4058** P2==1 then the table to be clear is in the auxiliary database file
4059** that is used to store tables create using CREATE TEMPORARY TABLE.
4060**
4061** See also: Destroy
4062*/
4063case OP_Clear: { /* no-push */
4064
4065 /* For consistency with the way other features of SQLite operate
4066 ** with a truncate, we will also skip the update callback.
4067 */
4068#if 0
4069 Btree *pBt = db->aDb[pOp->p2].pBt;
4070 if( db->xUpdateCallback && pOp->p3 ){
4071 const char *zDb = db->aDb[pOp->p2].zName;
4072 const char *zTbl = pOp->p3;
4073 BtCursor *pCur = 0;
4074 int fin = 0;
4075
4076 rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
4077 if( rc!=SQLITE_OK ){
4078 goto abort_due_to_error;
4079 }
4080 for(
4081 rc=sqlite3BtreeFirst(pCur, &fin);
4082 rc==SQLITE_OK && !fin;
4083 rc=sqlite3BtreeNext(pCur, &fin)
4084 ){
4085 i64 iKey;
4086 rc = sqlite3BtreeKeySize(pCur, &iKey);
4087 if( rc ){
4088 break;
4089 }
4090 iKey = keyToInt(iKey);
4091 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
4092 }
4093 sqlite3BtreeCloseCursor(pCur);
4094 if( rc!=SQLITE_OK ){
4095 goto abort_due_to_error;
4096 }
4097 }
4098#endif
4099 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4100 break;
4101}
4102
4103/* Opcode: CreateTable P1 * *
4104**
4105** Allocate a new table in the main database file if P2==0 or in the
4106** auxiliary database file if P2==1. Push the page number
4107** for the root page of the new table onto the stack.
4108**
4109** The difference between a table and an index is this: A table must
4110** have a 4-byte integer key and can have arbitrary data. An index
4111** has an arbitrary key but no data.
4112**
4113** See also: CreateIndex
4114*/
4115/* Opcode: CreateIndex P1 * *
4116**
4117** Allocate a new index in the main database file if P2==0 or in the
4118** auxiliary database file if P2==1. Push the page number of the
4119** root page of the new index onto the stack.
4120**
4121** See documentation on OP_CreateTable for additional information.
4122*/
4123case OP_CreateIndex:
4124case OP_CreateTable: {
4125 int pgno;
4126 int flags;
4127 Db *pDb;
4128 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4129 pDb = &db->aDb[pOp->p1];
4130 assert( pDb->pBt!=0 );
4131 if( pOp->opcode==OP_CreateTable ){
4132 /* flags = BTREE_INTKEY; */
4133 flags = BTREE_LEAFDATA|BTREE_INTKEY;
4134 }else{
4135 flags = BTREE_ZERODATA;
4136 }
4137 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4138 pTos++;
4139 if( rc==SQLITE_OK ){
4140 pTos->u.i = pgno;
4141 pTos->flags = MEM_Int;
4142 }else{
4143 pTos->flags = MEM_Null;
4144 }
4145 break;
4146}
4147
4148/* Opcode: ParseSchema P1 P2 P3
4149**
4150** Read and parse all entries from the SQLITE_MASTER table of database P1
4151** that match the WHERE clause P3. P2 is the "force" flag. Always do
4152** the parsing if P2 is true. If P2 is false, then this routine is a
4153** no-op if the schema is not currently loaded. In other words, if P2
4154** is false, the SQLITE_MASTER table is only parsed if the rest of the
4155** schema is already loaded into the symbol table.
4156**
4157** This opcode invokes the parser to create a new virtual machine,
4158** then runs the new virtual machine. It is thus a reentrant opcode.
4159*/
4160case OP_ParseSchema: { /* no-push */
4161 char *zSql;
4162 int iDb = pOp->p1;
4163 const char *zMaster;
4164 InitData initData;
4165
4166 assert( iDb>=0 && iDb<db->nDb );
4167 if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
4168 break;
4169 }
4170 zMaster = SCHEMA_TABLE(iDb);
4171 initData.db = db;
4172 initData.iDb = pOp->p1;
4173 initData.pzErrMsg = &p->zErrMsg;
4174 zSql = sqlite3MPrintf(
4175 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
4176 db->aDb[iDb].zName, zMaster, pOp->p3);
4177 if( zSql==0 ) goto no_mem;
4178 sqlite3SafetyOff(db);
4179 assert( db->init.busy==0 );
4180 db->init.busy = 1;
4181 assert( !sqlite3MallocFailed() );
4182 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4183 if( rc==SQLITE_ABORT ) rc = initData.rc;
4184 sqliteFree(zSql);
4185 db->init.busy = 0;
4186 sqlite3SafetyOn(db);
4187 if( rc==SQLITE_NOMEM ){
4188 sqlite3FailedMalloc();
4189 goto no_mem;
4190 }
4191 break;
4192}
4193
4194#if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
4195/* Opcode: LoadAnalysis P1 * *
4196**
4197** Read the sqlite_stat1 table for database P1 and load the content
4198** of that table into the internal index hash table. This will cause
4199** the analysis to be used when preparing all subsequent queries.
4200*/
4201case OP_LoadAnalysis: { /* no-push */
4202 int iDb = pOp->p1;
4203 assert( iDb>=0 && iDb<db->nDb );
4204 rc = sqlite3AnalysisLoad(db, iDb);
4205 break;
4206}
4207#endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
4208
4209/* Opcode: DropTable P1 * P3
4210**
4211** Remove the internal (in-memory) data structures that describe
4212** the table named P3 in database P1. This is called after a table
4213** is dropped in order to keep the internal representation of the
4214** schema consistent with what is on disk.
4215*/
4216case OP_DropTable: { /* no-push */
4217 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
4218 break;
4219}
4220
4221/* Opcode: DropIndex P1 * P3
4222**
4223** Remove the internal (in-memory) data structures that describe
4224** the index named P3 in database P1. This is called after an index
4225** is dropped in order to keep the internal representation of the
4226** schema consistent with what is on disk.
4227*/
4228case OP_DropIndex: { /* no-push */
4229 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
4230 break;
4231}
4232
4233/* Opcode: DropTrigger P1 * P3
4234**
4235** Remove the internal (in-memory) data structures that describe
4236** the trigger named P3 in database P1. This is called after a trigger
4237** is dropped in order to keep the internal representation of the
4238** schema consistent with what is on disk.
4239*/
4240case OP_DropTrigger: { /* no-push */
4241 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
4242 break;
4243}
4244
4245
4246#ifndef SQLITE_OMIT_INTEGRITY_CHECK
4247/* Opcode: IntegrityCk P1 P2 *
4248**
4249** Do an analysis of the currently open database. Push onto the
4250** stack the text of an error message describing any problems.
4251** If no problems are found, push a NULL onto the stack.
4252**
4253** P1 is the address of a memory cell that contains the maximum
4254** number of allowed errors. At most mem[P1] errors will be reported.
4255** In other words, the analysis stops as soon as mem[P1] errors are
4256** seen. Mem[P1] is updated with the number of errors remaining.
4257**
4258** The root page numbers of all tables in the database are integer
4259** values on the stack. This opcode pulls as many integers as it
4260** can off of the stack and uses those numbers as the root pages.
4261**
4262** If P2 is not zero, the check is done on the auxiliary database
4263** file, not the main database file.
4264**
4265** This opcode is used to implement the integrity_check pragma.
4266*/
4267case OP_IntegrityCk: {
4268 int nRoot;
4269 int *aRoot;
4270 int j;
4271 int nErr;
4272 char *z;
4273 Mem *pnErr;
4274
4275 for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
4276 if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
4277 }
4278 assert( nRoot>0 );
4279 aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
4280 if( aRoot==0 ) goto no_mem;
4281 j = pOp->p1;
4282 assert( j>=0 && j<p->nMem );
4283 pnErr = &p->aMem[j];
4284 assert( (pnErr->flags & MEM_Int)!=0 );
4285 for(j=0; j<nRoot; j++){
4286 aRoot[j] = (pTos-j)->u.i;
4287 }
4288 aRoot[j] = 0;
4289 popStack(&pTos, nRoot);
4290 pTos++;
4291 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
4292 pnErr->u.i, &nErr);
4293 pnErr->u.i -= nErr;
4294 if( nErr==0 ){
4295 assert( z==0 );
4296 pTos->flags = MEM_Null;
4297 }else{
4298 pTos->z = z;
4299 pTos->n = strlen(z);
4300 pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
4301 pTos->xDel = 0;
4302 }
4303 pTos->enc = SQLITE_UTF8;
4304 sqlite3VdbeChangeEncoding(pTos, encoding);
4305 sqliteFree(aRoot);
4306 break;
4307}
4308#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4309
4310/* Opcode: FifoWrite * * *
4311**
4312** Write the integer on the top of the stack
4313** into the Fifo.
4314*/
4315case OP_FifoWrite: { /* no-push */
4316 assert( pTos>=p->aStack );
4317 sqlite3VdbeMemIntegerify(pTos);
4318 sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i);
4319 assert( (pTos->flags & MEM_Dyn)==0 );
4320 pTos--;
4321 break;
4322}
4323
4324/* Opcode: FifoRead * P2 *
4325**
4326** Attempt to read a single integer from the Fifo
4327** and push it onto the stack. If the Fifo is empty
4328** push nothing but instead jump to P2.
4329*/
4330case OP_FifoRead: {
4331 i64 v;
4332 CHECK_FOR_INTERRUPT;
4333 if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
4334 pc = pOp->p2 - 1;
4335 }else{
4336 pTos++;
4337 pTos->u.i = v;
4338 pTos->flags = MEM_Int;
4339 }
4340 break;
4341}
4342
4343#ifndef SQLITE_OMIT_TRIGGER
4344/* Opcode: ContextPush * * *
4345**
4346** Save the current Vdbe context such that it can be restored by a ContextPop
4347** opcode. The context stores the last insert row id, the last statement change
4348** count, and the current statement change count.
4349*/
4350case OP_ContextPush: { /* no-push */
4351 int i = p->contextStackTop++;
4352 Context *pContext;
4353
4354 assert( i>=0 );
4355 /* FIX ME: This should be allocated as part of the vdbe at compile-time */
4356 if( i>=p->contextStackDepth ){
4357 p->contextStackDepth = i+1;
4358 p->contextStack = sqliteReallocOrFree(p->contextStack,
4359 sizeof(Context)*(i+1));
4360 if( p->contextStack==0 ) goto no_mem;
4361 }
4362 pContext = &p->contextStack[i];
4363 pContext->lastRowid = db->lastRowid;
4364 pContext->nChange = p->nChange;
4365 pContext->sFifo = p->sFifo;
4366 sqlite3VdbeFifoInit(&p->sFifo);
4367 break;
4368}
4369
4370/* Opcode: ContextPop * * *
4371**
4372** Restore the Vdbe context to the state it was in when contextPush was last
4373** executed. The context stores the last insert row id, the last statement
4374** change count, and the current statement change count.
4375*/
4376case OP_ContextPop: { /* no-push */
4377 Context *pContext = &p->contextStack[--p->contextStackTop];
4378 assert( p->contextStackTop>=0 );
4379 db->lastRowid = pContext->lastRowid;
4380 p->nChange = pContext->nChange;
4381 sqlite3VdbeFifoClear(&p->sFifo);
4382 p->sFifo = pContext->sFifo;
4383 break;
4384}
4385#endif /* #ifndef SQLITE_OMIT_TRIGGER */
4386
4387/* Opcode: MemStore P1 P2 *
4388**
4389** Write the top of the stack into memory location P1.
4390** P1 should be a small integer since space is allocated
4391** for all memory locations between 0 and P1 inclusive.
4392**
4393** After the data is stored in the memory location, the
4394** stack is popped once if P2 is 1. If P2 is zero, then
4395** the original data remains on the stack.
4396*/
4397case OP_MemStore: { /* no-push */
4398 assert( pTos>=p->aStack );
4399 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4400 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
4401 pTos--;
4402
4403 /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
4404 ** restore the top of the stack to its original value.
4405 */
4406 if( pOp->p2 ){
4407 break;
4408 }
4409}
4410/* Opcode: MemLoad P1 * *
4411**
4412** Push a copy of the value in memory location P1 onto the stack.
4413**
4414** If the value is a string, then the value pushed is a pointer to
4415** the string that is stored in the memory location. If the memory
4416** location is subsequently changed (using OP_MemStore) then the
4417** value pushed onto the stack will change too.
4418*/
4419case OP_MemLoad: {
4420 int i = pOp->p1;
4421 assert( i>=0 && i<p->nMem );
4422 pTos++;
4423 sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
4424 break;
4425}
4426
4427#ifndef SQLITE_OMIT_AUTOINCREMENT
4428/* Opcode: MemMax P1 * *
4429**
4430** Set the value of memory cell P1 to the maximum of its current value
4431** and the value on the top of the stack. The stack is unchanged.
4432**
4433** This instruction throws an error if the memory cell is not initially
4434** an integer.
4435*/
4436case OP_MemMax: { /* no-push */
4437 int i = pOp->p1;
4438 Mem *pMem;
4439 assert( pTos>=p->aStack );
4440 assert( i>=0 && i<p->nMem );
4441 pMem = &p->aMem[i];
4442 sqlite3VdbeMemIntegerify(pMem);
4443 sqlite3VdbeMemIntegerify(pTos);
4444 if( pMem->u.i<pTos->u.i){
4445 pMem->u.i = pTos->u.i;
4446 }
4447 break;
4448}
4449#endif /* SQLITE_OMIT_AUTOINCREMENT */
4450
4451/* Opcode: MemIncr P1 P2 *
4452**
4453** Increment the integer valued memory cell P2 by the value in P1.
4454**
4455** It is illegal to use this instruction on a memory cell that does
4456** not contain an integer. An assertion fault will result if you try.
4457*/
4458case OP_MemIncr: { /* no-push */
4459 int i = pOp->p2;
4460 Mem *pMem;
4461 assert( i>=0 && i<p->nMem );
4462 pMem = &p->aMem[i];
4463 assert( pMem->flags==MEM_Int );
4464 pMem->u.i += pOp->p1;
4465 break;
4466}
4467
4468/* Opcode: IfMemPos P1 P2 *
4469**
4470** If the value of memory cell P1 is 1 or greater, jump to P2.
4471**
4472** It is illegal to use this instruction on a memory cell that does
4473** not contain an integer. An assertion fault will result if you try.
4474*/
4475case OP_IfMemPos: { /* no-push */
4476 int i = pOp->p1;
4477 Mem *pMem;
4478 assert( i>=0 && i<p->nMem );
4479 pMem = &p->aMem[i];
4480 assert( pMem->flags==MEM_Int );
4481 if( pMem->u.i>0 ){
4482 pc = pOp->p2 - 1;
4483 }
4484 break;
4485}
4486
4487/* Opcode: IfMemNeg P1 P2 *
4488**
4489** If the value of memory cell P1 is less than zero, jump to P2.
4490**
4491** It is illegal to use this instruction on a memory cell that does
4492** not contain an integer. An assertion fault will result if you try.
4493*/
4494case OP_IfMemNeg: { /* no-push */
4495 int i = pOp->p1;
4496 Mem *pMem;
4497 assert( i>=0 && i<p->nMem );
4498 pMem = &p->aMem[i];
4499 assert( pMem->flags==MEM_Int );
4500 if( pMem->u.i<0 ){
4501 pc = pOp->p2 - 1;
4502 }
4503 break;
4504}
4505
4506/* Opcode: IfMemZero P1 P2 *
4507**
4508** If the value of memory cell P1 is exactly 0, jump to P2.
4509**
4510** It is illegal to use this instruction on a memory cell that does
4511** not contain an integer. An assertion fault will result if you try.
4512*/
4513case OP_IfMemZero: { /* no-push */
4514 int i = pOp->p1;
4515 Mem *pMem;
4516 assert( i>=0 && i<p->nMem );
4517 pMem = &p->aMem[i];
4518 assert( pMem->flags==MEM_Int );
4519 if( pMem->u.i==0 ){
4520 pc = pOp->p2 - 1;
4521 }
4522 break;
4523}
4524
4525/* Opcode: MemNull P1 * *
4526**
4527** Store a NULL in memory cell P1
4528*/
4529case OP_MemNull: {
4530 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4531 sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
4532 break;
4533}
4534
4535/* Opcode: MemInt P1 P2 *
4536**
4537** Store the integer value P1 in memory cell P2.
4538*/
4539case OP_MemInt: {
4540 assert( pOp->p2>=0 && pOp->p2<p->nMem );
4541 sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
4542 break;
4543}
4544
4545/* Opcode: MemMove P1 P2 *
4546**
4547** Move the content of memory cell P2 over to memory cell P1.
4548** Any prior content of P1 is erased. Memory cell P2 is left
4549** containing a NULL.
4550*/
4551case OP_MemMove: {
4552 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4553 assert( pOp->p2>=0 && pOp->p2<p->nMem );
4554 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
4555 break;
4556}
4557
4558/* Opcode: AggStep P1 P2 P3
4559**
4560** Execute the step function for an aggregate. The
4561** function has P2 arguments. P3 is a pointer to the FuncDef
4562** structure that specifies the function. Use memory location
4563** P1 as the accumulator.
4564**
4565** The P2 arguments are popped from the stack.
4566*/
4567case OP_AggStep: { /* no-push */
4568 int n = pOp->p2;
4569 int i;
4570 Mem *pMem, *pRec;
4571 sqlite3_context ctx;
4572 sqlite3_value **apVal;
4573
4574 assert( n>=0 );
4575 pRec = &pTos[1-n];
4576 assert( pRec>=p->aStack );
4577 apVal = p->apArg;
4578 assert( apVal || n==0 );
4579 for(i=0; i<n; i++, pRec++){
4580 apVal[i] = pRec;
4581 storeTypeInfo(pRec, encoding);
4582 }
4583 ctx.pFunc = (FuncDef*)pOp->p3;
4584 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4585 ctx.pMem = pMem = &p->aMem[pOp->p1];
4586 pMem->n++;
4587 ctx.s.flags = MEM_Null;
4588 ctx.s.z = 0;
4589 ctx.s.xDel = 0;
4590 ctx.isError = 0;
4591 ctx.pColl = 0;
4592 if( ctx.pFunc->needCollSeq ){
4593 assert( pOp>p->aOp );
4594 assert( pOp[-1].p3type==P3_COLLSEQ );
4595 assert( pOp[-1].opcode==OP_CollSeq );
4596 ctx.pColl = (CollSeq *)pOp[-1].p3;
4597 }
4598 (ctx.pFunc->xStep)(&ctx, n, apVal);
4599 popStack(&pTos, n);
4600 if( ctx.isError ){
4601 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
4602 rc = SQLITE_ERROR;
4603 }
4604 sqlite3VdbeMemRelease(&ctx.s);
4605 break;
4606}
4607
4608/* Opcode: AggFinal P1 P2 P3
4609**
4610** Execute the finalizer function for an aggregate. P1 is
4611** the memory location that is the accumulator for the aggregate.
4612**
4613** P2 is the number of arguments that the step function takes and
4614** P3 is a pointer to the FuncDef for this function. The P2
4615** argument is not used by this opcode. It is only there to disambiguate
4616** functions that can take varying numbers of arguments. The
4617** P3 argument is only needed for the degenerate case where
4618** the step function was not previously called.
4619*/
4620case OP_AggFinal: { /* no-push */
4621 Mem *pMem;
4622 assert( pOp->p1>=0 && pOp->p1<p->nMem );
4623 pMem = &p->aMem[pOp->p1];
4624 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
4625 rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
4626 if( rc==SQLITE_ERROR ){
4627 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
4628 }
4629 if( sqlite3VdbeMemTooBig(pMem) ){
4630 goto too_big;
4631 }
4632 break;
4633}
4634
4635
4636#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
4637/* Opcode: Vacuum * * *
4638**
4639** Vacuum the entire database. This opcode will cause other virtual
4640** machines to be created and run. It may not be called from within
4641** a transaction.
4642*/
4643case OP_Vacuum: { /* no-push */
4644 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4645 rc = sqlite3RunVacuum(&p->zErrMsg, db);
4646 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4647 break;
4648}
4649#endif
4650
4651#if !defined(SQLITE_OMIT_AUTOVACUUM)
4652/* Opcode: IncrVacuum P1 P2 *
4653**
4654** Perform a single step of the incremental vacuum procedure on
4655** the P1 database. If the vacuum has finished, jump to instruction
4656** P2. Otherwise, fall through to the next instruction.
4657*/
4658case OP_IncrVacuum: { /* no-push */
4659 Btree *pBt;
4660
4661 assert( pOp->p1>=0 && pOp->p1<db->nDb );
4662 pBt = db->aDb[pOp->p1].pBt;
4663 rc = sqlite3BtreeIncrVacuum(pBt);
4664 if( rc==SQLITE_DONE ){
4665 pc = pOp->p2 - 1;
4666 rc = SQLITE_OK;
4667 }
4668 break;
4669}
4670#endif
4671
4672/* Opcode: Expire P1 * *
4673**
4674** Cause precompiled statements to become expired. An expired statement
4675** fails with an error code of SQLITE_SCHEMA if it is ever executed
4676** (via sqlite3_step()).
4677**
4678** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4679** then only the currently executing statement is affected.
4680*/
4681case OP_Expire: { /* no-push */
4682 if( !pOp->p1 ){
4683 sqlite3ExpirePreparedStatements(db);
4684 }else{
4685 p->expired = 1;
4686 }
4687 break;
4688}
4689
4690#ifndef SQLITE_OMIT_SHARED_CACHE
4691/* Opcode: TableLock P1 P2 P3
4692**
4693** Obtain a lock on a particular table. This instruction is only used when
4694** the shared-cache feature is enabled.
4695**
4696** If P1 is not negative, then it is the index of the database
4697** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
4698** write-lock is required. In this case the index of the database is the
4699** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
4700** required.
4701**
4702** P2 contains the root-page of the table to lock.
4703**
4704** P3 contains a pointer to the name of the table being locked. This is only
4705** used to generate an error message if the lock cannot be obtained.
4706*/
4707case OP_TableLock: { /* no-push */
4708 int p1 = pOp->p1;
4709 u8 isWriteLock = (p1<0);
4710 if( isWriteLock ){
4711 p1 = (-1*p1)-1;
4712 }
4713 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
4714 if( rc==SQLITE_LOCKED ){
4715 const char *z = (const char *)pOp->p3;
4716 sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
4717 }
4718 break;
4719}
4720#endif /* SQLITE_OMIT_SHARED_CACHE */
4721
4722#ifndef SQLITE_OMIT_VIRTUALTABLE
4723/* Opcode: VBegin * * P3
4724**
4725** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
4726** for that table.
4727*/
4728case OP_VBegin: { /* no-push */
4729 rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
4730 break;
4731}
4732#endif /* SQLITE_OMIT_VIRTUALTABLE */
4733
4734#ifndef SQLITE_OMIT_VIRTUALTABLE
4735/* Opcode: VCreate P1 * P3
4736**
4737** P3 is the name of a virtual table in database P1. Call the xCreate method
4738** for that table.
4739*/
4740case OP_VCreate: { /* no-push */
4741 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
4742 break;
4743}
4744#endif /* SQLITE_OMIT_VIRTUALTABLE */
4745
4746#ifndef SQLITE_OMIT_VIRTUALTABLE
4747/* Opcode: VDestroy P1 * P3
4748**
4749** P3 is the name of a virtual table in database P1. Call the xDestroy method
4750** of that table.
4751*/
4752case OP_VDestroy: { /* no-push */
4753 p->inVtabMethod = 2;
4754 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
4755 p->inVtabMethod = 0;
4756 break;
4757}
4758#endif /* SQLITE_OMIT_VIRTUALTABLE */
4759
4760#ifndef SQLITE_OMIT_VIRTUALTABLE
4761/* Opcode: VOpen P1 * P3
4762**
4763** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4764** P1 is a cursor number. This opcode opens a cursor to the virtual
4765** table and stores that cursor in P1.
4766*/
4767case OP_VOpen: { /* no-push */
4768 Cursor *pCur = 0;
4769 sqlite3_vtab_cursor *pVtabCursor = 0;
4770
4771 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
4772 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4773
4774 assert(pVtab && pModule);
4775 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4776 rc = pModule->xOpen(pVtab, &pVtabCursor);
4777 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4778 if( SQLITE_OK==rc ){
4779 /* Initialise sqlite3_vtab_cursor base class */
4780 pVtabCursor->pVtab = pVtab;
4781
4782 /* Initialise vdbe cursor object */
4783 pCur = allocateCursor(p, pOp->p1, -1);
4784 if( pCur ){
4785 pCur->pVtabCursor = pVtabCursor;
4786 pCur->pModule = pVtabCursor->pVtab->pModule;
4787 }else{
4788 pModule->xClose(pVtabCursor);
4789 }
4790 }
4791 break;
4792}
4793#endif /* SQLITE_OMIT_VIRTUALTABLE */
4794
4795#ifndef SQLITE_OMIT_VIRTUALTABLE
4796/* Opcode: VFilter P1 P2 P3
4797**
4798** P1 is a cursor opened using VOpen. P2 is an address to jump to if
4799** the filtered result set is empty.
4800**
4801** P3 is either NULL or a string that was generated by the xBestIndex
4802** method of the module. The interpretation of the P3 string is left
4803** to the module implementation.
4804**
4805** This opcode invokes the xFilter method on the virtual table specified
4806** by P1. The integer query plan parameter to xFilter is the top of the
4807** stack. Next down on the stack is the argc parameter. Beneath the
4808** next of stack are argc additional parameters which are passed to
4809** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
4810** the stack) becomes argv[argc-1] when passed to xFilter.
4811**
4812** The integer query plan parameter, argc, and all argv stack values
4813** are popped from the stack before this instruction completes.
4814**
4815** A jump is made to P2 if the result set after filtering would be
4816** empty.
4817*/
4818case OP_VFilter: { /* no-push */
4819 int nArg;
4820
4821 const sqlite3_module *pModule;
4822
4823 Cursor *pCur = p->apCsr[pOp->p1];
4824 assert( pCur->pVtabCursor );
4825 pModule = pCur->pVtabCursor->pVtab->pModule;
4826
4827 /* Grab the index number and argc parameters off the top of the stack. */
4828 assert( (&pTos[-1])>=p->aStack );
4829 assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
4830 nArg = pTos[-1].u.i;
4831
4832 /* Invoke the xFilter method */
4833 {
4834 int res = 0;
4835 int i;
4836 Mem **apArg = p->apArg;
4837 for(i = 0; i<nArg; i++){
4838 apArg[i] = &pTos[i+1-2-nArg];
4839 storeTypeInfo(apArg[i], 0);
4840 }
4841
4842 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4843 p->inVtabMethod = 1;
4844 rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
4845 p->inVtabMethod = 0;
4846 if( rc==SQLITE_OK ){
4847 res = pModule->xEof(pCur->pVtabCursor);
4848 }
4849 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4850
4851 if( res ){
4852 pc = pOp->p2 - 1;
4853 }
4854 }
4855
4856 /* Pop the index number, argc value and parameters off the stack */
4857 popStack(&pTos, 2+nArg);
4858 break;
4859}
4860#endif /* SQLITE_OMIT_VIRTUALTABLE */
4861
4862#ifndef SQLITE_OMIT_VIRTUALTABLE
4863/* Opcode: VRowid P1 * *
4864**
4865** Push an integer onto the stack which is the rowid of
4866** the virtual-table that the P1 cursor is pointing to.
4867*/
4868case OP_VRowid: {
4869 const sqlite3_module *pModule;
4870
4871 Cursor *pCur = p->apCsr[pOp->p1];
4872 assert( pCur->pVtabCursor );
4873 pModule = pCur->pVtabCursor->pVtab->pModule;
4874 if( pModule->xRowid==0 ){
4875 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
4876 rc = SQLITE_ERROR;
4877 } else {
4878 sqlite_int64 iRow;
4879
4880 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4881 rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
4882 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4883
4884 pTos++;
4885 pTos->flags = MEM_Int;
4886 pTos->u.i = iRow;
4887 }
4888
4889 break;
4890}
4891#endif /* SQLITE_OMIT_VIRTUALTABLE */
4892
4893#ifndef SQLITE_OMIT_VIRTUALTABLE
4894/* Opcode: VColumn P1 P2 *
4895**
4896** Push onto the stack the value of the P2-th column of
4897** the row of the virtual-table that the P1 cursor is pointing to.
4898*/
4899case OP_VColumn: {
4900 const sqlite3_module *pModule;
4901
4902 Cursor *pCur = p->apCsr[pOp->p1];
4903 assert( pCur->pVtabCursor );
4904 pModule = pCur->pVtabCursor->pVtab->pModule;
4905 if( pModule->xColumn==0 ){
4906 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
4907 rc = SQLITE_ERROR;
4908 } else {
4909 sqlite3_context sContext;
4910 memset(&sContext, 0, sizeof(sContext));
4911 sContext.s.flags = MEM_Null;
4912 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4913 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
4914
4915 /* Copy the result of the function to the top of the stack. We
4916 ** do this regardless of whether or not an error occured to ensure any
4917 ** dynamic allocation in sContext.s (a Mem struct) is released.
4918 */
4919 sqlite3VdbeChangeEncoding(&sContext.s, encoding);
4920 pTos++;
4921 pTos->flags = 0;
4922 sqlite3VdbeMemMove(pTos, &sContext.s);
4923
4924 if( sqlite3SafetyOn(db) ){
4925 goto abort_due_to_misuse;
4926 }
4927 if( sqlite3VdbeMemTooBig(pTos) ){
4928 goto too_big;
4929 }
4930 }
4931
4932 break;
4933}
4934#endif /* SQLITE_OMIT_VIRTUALTABLE */
4935
4936#ifndef SQLITE_OMIT_VIRTUALTABLE
4937/* Opcode: VNext P1 P2 *
4938**
4939** Advance virtual table P1 to the next row in its result set and
4940** jump to instruction P2. Or, if the virtual table has reached
4941** the end of its result set, then fall through to the next instruction.
4942*/
4943case OP_VNext: { /* no-push */
4944 const sqlite3_module *pModule;
4945 int res = 0;
4946
4947 Cursor *pCur = p->apCsr[pOp->p1];
4948 assert( pCur->pVtabCursor );
4949 pModule = pCur->pVtabCursor->pVtab->pModule;
4950 if( pModule->xNext==0 ){
4951 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
4952 rc = SQLITE_ERROR;
4953 } else {
4954 /* Invoke the xNext() method of the module. There is no way for the
4955 ** underlying implementation to return an error if one occurs during
4956 ** xNext(). Instead, if an error occurs, true is returned (indicating that
4957 ** data is available) and the error code returned when xColumn or
4958 ** some other method is next invoked on the save virtual table cursor.
4959 */
4960 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4961 p->inVtabMethod = 1;
4962 rc = pModule->xNext(pCur->pVtabCursor);
4963 p->inVtabMethod = 0;
4964 if( rc==SQLITE_OK ){
4965 res = pModule->xEof(pCur->pVtabCursor);
4966 }
4967 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4968
4969 if( !res ){
4970 /* If there is data, jump to P2 */
4971 pc = pOp->p2 - 1;
4972 }
4973 }
4974
4975 break;
4976}
4977#endif /* SQLITE_OMIT_VIRTUALTABLE */
4978
4979
4980#ifndef SQLITE_OMIT_VIRTUALTABLE
4981/* Opcode: VUpdate P1 P2 P3
4982**
4983** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
4984** This opcode invokes the corresponding xUpdate method. P2 values
4985** are taken from the stack to pass to the xUpdate invocation. The
4986** value on the top of the stack corresponds to the p2th element
4987** of the argv array passed to xUpdate.
4988**
4989** The xUpdate method will do a DELETE or an INSERT or both.
4990** The argv[0] element (which corresponds to the P2-th element down
4991** on the stack) is the rowid of a row to delete. If argv[0] is
4992** NULL then no deletion occurs. The argv[1] element is the rowid
4993** of the new row. This can be NULL to have the virtual table
4994** select the new rowid for itself. The higher elements in the
4995** stack are the values of columns in the new row.
4996**
4997** If P2==1 then no insert is performed. argv[0] is the rowid of
4998** a row to delete.
4999**
5000** P1 is a boolean flag. If it is set to true and the xUpdate call
5001** is successful, then the value returned by sqlite3_last_insert_rowid()
5002** is set to the value of the rowid for the row just inserted.
5003*/
5004case OP_VUpdate: { /* no-push */
5005 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
5006 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
5007 int nArg = pOp->p2;
5008 assert( pOp->p3type==P3_VTAB );
5009 if( pModule->xUpdate==0 ){
5010 sqlite3SetString(&p->zErrMsg, "read-only table", 0);
5011 rc = SQLITE_ERROR;
5012 }else{
5013 int i;
5014 sqlite_int64 rowid;
5015 Mem **apArg = p->apArg;
5016 Mem *pX = &pTos[1-nArg];
5017 for(i = 0; i<nArg; i++, pX++){
5018 storeTypeInfo(pX, 0);
5019 apArg[i] = pX;
5020 }
5021 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
5022 sqlite3VtabLock(pVtab);
5023 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
5024 sqlite3VtabUnlock(db, pVtab);
5025 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
5026 if( pOp->p1 && rc==SQLITE_OK ){
5027 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
5028 db->lastRowid = rowid;
5029 }
5030 }
5031 popStack(&pTos, nArg);
5032 break;
5033}
5034#endif /* SQLITE_OMIT_VIRTUALTABLE */
5035
5036/* An other opcode is illegal...
5037*/
5038default: {
5039 assert( 0 );
5040 break;
5041}
5042
5043/*****************************************************************************
5044** The cases of the switch statement above this line should all be indented
5045** by 6 spaces. But the left-most 6 spaces have been removed to improve the
5046** readability. From this point on down, the normal indentation rules are
5047** restored.
5048*****************************************************************************/
5049 }
5050
5051 /* Make sure the stack limit was not exceeded */
5052 assert( pTos<=pStackLimit );