4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
7
** May you do good and not evil.
8
** May you find forgiveness for yourself and forgive others.
9
** May you share freely, never taking more than you give.
11
*************************************************************************
12
** The code in this file implements execution method of the
13
** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
14
** handles housekeeping details such as creating and deleting
15
** VDBE instances. This file is solely interested in executing
18
** In the external interface, an "sqlite3_stmt*" is an opaque pointer
21
** The SQL parser generates a program which is then executed by
22
** the VDBE to do the work of the SQL statement. VDBE programs are
23
** similar in form to assembly language. The program consists of
24
** a linear sequence of operations. Each operation has an opcode
25
** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
26
** is a null-terminated string. Operand P5 is an unsigned character.
27
** Few opcodes use all 5 operands.
29
** Computation results are stored on a set of registers numbered beginning
30
** with 1 and going up to Vdbe.nMem. Each register can store
31
** either an integer, a null-terminated string, a floating point
32
** number, or the SQL "NULL" value. An implicit conversion from one
33
** type to the other occurs as necessary.
35
** Most of the code in this file is taken up by the sqlite3VdbeExec()
36
** function which does the work of interpreting a VDBE program.
37
** But other routines are also provided to help in building up
38
** a program instruction by instruction.
40
** Various scripts scan this source file in order to generate HTML
41
** documentation, headers files, or other derived files. The formatting
42
** of the code in this file is, therefore, important. See other comments
43
** in this file for details. If in doubt, do not deviate from existing
44
** commenting and indentation practices when changing or adding code.
46
** $Id: vdbe.c,v 1.772 2008/08/02 15:10:09 danielk1977 Exp $
48
#include "sqliteInt.h"
53
** The following global variable is incremented every time a cursor
54
** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
55
** procedures use this information to make sure that indices are
56
** working correctly. This variable has no function other than to
57
** help verify the correct operation of the library.
60
int sqlite3_search_count = 0;
64
** When this global variable is positive, it gets decremented once before
65
** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
66
** field of the sqlite3 structure is set in order to simulate and interrupt.
68
** This facility is used for testing purposes only. It does not function
69
** in an ordinary build.
72
int sqlite3_interrupt_count = 0;
76
** The next global variable is incremented each type the OP_Sort opcode
77
** is executed. The test procedures use this information to make sure that
78
** sorting is occurring or not occurring at appropriate times. This variable
79
** has no function other than to help verify the correct operation of the
83
int sqlite3_sort_count = 0;
87
** The next global variable records the size of the largest MEM_Blob
88
** or MEM_Str that has been used by a VDBE opcode. The test procedures
89
** use this information to make sure that the zero-blob functionality
90
** is working correctly. This variable has no function other than to
91
** help verify the correct operation of the library.
94
int sqlite3_max_blobsize = 0;
95
static void updateMaxBlobsize(Mem *p){
96
if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
97
sqlite3_max_blobsize = p->n;
103
** Test a register to see if it exceeds the current maximum blob size.
104
** If it does, record the new maximum blob size.
106
#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
107
# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
109
# define UPDATE_MAX_BLOBSIZE(P)
113
** Release the memory associated with a register. This
114
** leaves the Mem.flags field in an inconsistent state.
116
#define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
119
** Convert the given register into a string if it isn't one
120
** already. Return non-zero if a malloc() fails.
122
#define Stringify(P, enc) \
123
if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
127
** An ephemeral string value (signified by the MEM_Ephem flag) contains
128
** a pointer to a dynamically allocated string where some other entity
129
** is responsible for deallocating that string. Because the register
130
** does not control the string, it might be deleted without the register
133
** This routine converts an ephemeral string into a dynamically allocated
134
** string that the register itself controls. In other words, it
135
** converts an MEM_Ephem string into an MEM_Dyn string.
137
#define Deephemeralize(P) \
138
if( ((P)->flags&MEM_Ephem)!=0 \
139
&& sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
142
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
145
#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
148
** Argument pMem points at a register that will be passed to a
149
** user-defined function or returned to the user as the result of a query.
150
** The second argument, 'db_enc' is the text encoding used by the vdbe for
151
** register variables. This routine sets the pMem->enc and pMem->type
152
** variables used by the sqlite3_value_*() routines.
154
#define storeTypeInfo(A,B) _storeTypeInfo(A)
155
static void _storeTypeInfo(Mem *pMem){
156
int flags = pMem->flags;
157
if( flags & MEM_Null ){
158
pMem->type = SQLITE_NULL;
160
else if( flags & MEM_Int ){
161
pMem->type = SQLITE_INTEGER;
163
else if( flags & MEM_Real ){
164
pMem->type = SQLITE_FLOAT;
166
else if( flags & MEM_Str ){
167
pMem->type = SQLITE_TEXT;
169
pMem->type = SQLITE_BLOB;
174
** Properties of opcodes. The OPFLG_INITIALIZER macro is
175
** created by mkopcodeh.awk during compilation. Data is obtained
176
** from the comments following the "case OP_xxxx:" statements in
179
static unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
182
** Return true if an opcode has any of the OPFLG_xxx properties
183
** specified by mask.
185
int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
186
assert( opcode>0 && opcode<sizeof(opcodeProperty) );
187
return (opcodeProperty[opcode]&mask)!=0;
191
** Allocate cursor number iCur. Return a pointer to it. Return NULL
192
** if we run out of memory.
194
static Cursor *allocateCursor(
201
/* Find the memory cell that will be used to store the blob of memory
202
** required for this Cursor structure. It is convenient to use a
203
** vdbe memory cell to manage the memory allocation required for a
204
** Cursor structure for the following reasons:
206
** * Sometimes cursor numbers are used for a couple of different
207
** purposes in a vdbe program. The different uses might require
208
** different sized allocations. Memory cells provide growable
211
** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
212
** be freed lazily via the sqlite3_release_memory() API. This
213
** minimizes the number of malloc calls made by the system.
215
** Memory cells for cursors are allocated at the top of the address
216
** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
217
** cursor 1 is managed by memory cell (p->nMem-1), etc.
219
Mem *pMem = &p->aMem[p->nMem-iCur];
223
/* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
224
** the number of fields in the records contained in the table or
225
** index being opened. Use this to reserve space for the
226
** Cursor.aType[] array.
229
if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
234
(isBtreeCursor?sqlite3BtreeCursorSize():0) +
235
2*nField*sizeof(u32);
237
assert( iCur<p->nCursor );
238
if( p->apCsr[iCur] ){
239
sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
242
if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
243
p->apCsr[iCur] = pCx = (Cursor *)pMem->z;
244
memset(pMem->z, 0, nByte);
246
pCx->nField = nField;
248
pCx->aType = (u32 *)&pMem->z[sizeof(Cursor)];
251
pCx->pCursor = (BtCursor *)&pMem->z[sizeof(Cursor)+2*nField*sizeof(u32)];
258
** Try to convert a value into a numeric representation if we can
259
** do so without loss of information. In other words, if the string
260
** looks like a number, convert it into a number. If it does not
261
** look like a number, leave it alone.
263
static void applyNumericAffinity(Mem *pRec){
264
if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
266
sqlite3VdbeMemNulTerminate(pRec);
267
if( (pRec->flags&MEM_Str)
268
&& sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
270
sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
271
if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
273
MemSetTypeFlag(pRec, MEM_Int);
275
sqlite3VdbeMemRealify(pRec);
282
** Processing is determine by the affinity parameter:
284
** SQLITE_AFF_INTEGER:
286
** SQLITE_AFF_NUMERIC:
287
** Try to convert pRec to an integer representation or a
288
** floating-point representation if an integer representation
289
** is not possible. Note that the integer representation is
290
** always preferred, even if the affinity is REAL, because
291
** an integer representation is more space efficient on disk.
294
** Convert pRec to a text representation.
297
** No-op. pRec is unchanged.
299
static void applyAffinity(
300
Mem *pRec, /* The value to apply affinity to */
301
char affinity, /* The affinity to be applied */
302
u8 enc /* Use this text encoding */
304
if( affinity==SQLITE_AFF_TEXT ){
305
/* Only attempt the conversion to TEXT if there is an integer or real
306
** representation (blob and NULL do not get converted) but no string
309
if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
310
sqlite3VdbeMemStringify(pRec, enc);
312
pRec->flags &= ~(MEM_Real|MEM_Int);
313
}else if( affinity!=SQLITE_AFF_NONE ){
314
assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
315
|| affinity==SQLITE_AFF_NUMERIC );
316
applyNumericAffinity(pRec);
317
if( pRec->flags & MEM_Real ){
318
sqlite3VdbeIntegerAffinity(pRec);
324
** Try to convert the type of a function argument or a result column
325
** into a numeric representation. Use either INTEGER or REAL whichever
326
** is appropriate. But only do the conversion if it is possible without
327
** loss of information and return the revised type of the argument.
329
** This is an EXPERIMENTAL api and is subject to change or removal.
331
int sqlite3_value_numeric_type(sqlite3_value *pVal){
332
Mem *pMem = (Mem*)pVal;
333
applyNumericAffinity(pMem);
334
storeTypeInfo(pMem, 0);
339
** Exported version of applyAffinity(). This one works on sqlite3_value*,
340
** not the internal Mem* type.
342
void sqlite3ValueApplyAffinity(
347
applyAffinity((Mem *)pVal, affinity, enc);
352
** Write a nice string representation of the contents of cell pMem
353
** into buffer zBuf, length nBuf.
355
void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
359
static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
366
assert( (f & (MEM_Static|MEM_Ephem))==0 );
367
}else if( f & MEM_Static ){
369
assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
370
}else if( f & MEM_Ephem ){
372
assert( (f & (MEM_Static|MEM_Dyn))==0 );
377
sqlite3_snprintf(100, zCsr, "%c", c);
378
zCsr += strlen(zCsr);
379
sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
380
zCsr += strlen(zCsr);
381
for(i=0; i<16 && i<pMem->n; i++){
382
sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
383
zCsr += strlen(zCsr);
385
for(i=0; i<16 && i<pMem->n; i++){
387
if( z<32 || z>126 ) *zCsr++ = '.';
391
sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
392
zCsr += strlen(zCsr);
394
sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
395
zCsr += strlen(zCsr);
398
}else if( f & MEM_Str ){
403
assert( (f & (MEM_Static|MEM_Ephem))==0 );
404
}else if( f & MEM_Static ){
406
assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
407
}else if( f & MEM_Ephem ){
409
assert( (f & (MEM_Static|MEM_Dyn))==0 );
414
sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
415
k += strlen(&zBuf[k]);
417
for(j=0; j<15 && j<pMem->n; j++){
419
if( c>=0x20 && c<0x7f ){
426
sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
427
k += strlen(&zBuf[k]);
435
** Print the value of a register for tracing purposes:
437
static void memTracePrint(FILE *out, Mem *p){
438
if( p->flags & MEM_Null ){
439
fprintf(out, " NULL");
440
}else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
441
fprintf(out, " si:%lld", p->u.i);
442
}else if( p->flags & MEM_Int ){
443
fprintf(out, " i:%lld", p->u.i);
444
}else if( p->flags & MEM_Real ){
445
fprintf(out, " r:%g", p->r);
448
sqlite3VdbeMemPrettyPrint(p, zBuf);
450
fprintf(out, "%s", zBuf);
453
static void registerTrace(FILE *out, int iReg, Mem *p){
454
fprintf(out, "REG[%d] = ", iReg);
455
memTracePrint(out, p);
461
# define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
463
# define REGISTER_TRACE(R,M)
470
** hwtime.h contains inline assembler code for implementing
471
** high-performance timing routines.
478
** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
479
** sqlite3_interrupt() routine has been called. If it has been, then
480
** processing of the VDBE program is interrupted.
482
** This macro added to every instruction that does a jump in order to
483
** implement a loop. This test used to be on every single instruction,
484
** but that meant we more testing that we needed. By only testing the
485
** flag on jump instructions, we get a (small) speed improvement.
487
#define CHECK_FOR_INTERRUPT \
488
if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
491
static int fileExists(sqlite3 *db, const char *zFile){
495
/* If we are currently testing IO errors, then do not call OsAccess() to
496
** test for the presence of zFile. This is because any IO error that
497
** occurs here will not be reported, causing the test to fail.
499
extern int sqlite3_io_error_pending;
500
if( sqlite3_io_error_pending<=0 )
502
rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
503
return (res && rc==SQLITE_OK);
508
** Execute as much of a VDBE program as we can then return.
510
** sqlite3VdbeMakeReady() must be called before this routine in order to
511
** close the program with a final OP_Halt and to set up the callbacks
512
** and the error message pointer.
514
** Whenever a row or result data is available, this routine will either
515
** invoke the result callback (if there is one) or return with
518
** If an attempt is made to open a locked database, then this routine
519
** will either invoke the busy callback (if there is one) or it will
520
** return SQLITE_BUSY.
522
** If an error occurs, an error message is written to memory obtained
523
** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
524
** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
526
** If the callback ever returns non-zero, then the program exits
527
** immediately. There will be no error message but the p->rc field is
528
** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
530
** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
531
** routine to return SQLITE_ERROR.
533
** Other fatal errors return SQLITE_ERROR.
535
** After this routine has finished, sqlite3VdbeFinalize() should be
536
** used to clean up the mess that was left behind.
539
Vdbe *p /* The VDBE */
541
int pc; /* The program counter */
542
Op *pOp; /* Current operation */
543
int rc = SQLITE_OK; /* Value to return */
544
sqlite3 *db = p->db; /* The database */
545
u8 encoding = ENC(db); /* The database encoding */
546
Mem *pIn1, *pIn2, *pIn3; /* Input operands */
547
Mem *pOut; /* Output operand */
549
int iCompare = 0; /* Result of last OP_Compare operation */
550
int *aPermute = 0; /* Permuation of columns for OP_Compare */
552
u64 start; /* CPU clock count at start of opcode */
553
int origPc; /* Program counter at start of opcode */
555
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
556
int nProgressOps = 0; /* Opcodes executed since progress callback. */
559
assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
560
assert( db->magic==SQLITE_MAGIC_BUSY );
561
sqlite3BtreeMutexArrayEnter(&p->aMutex);
562
if( p->rc==SQLITE_NOMEM ){
563
/* This happens if a malloc() inside a call to sqlite3_column_text() or
564
** sqlite3_column_text16() failed. */
567
assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
569
assert( p->explain==0 );
571
db->busyHandler.nBusy = 0;
573
sqlite3VdbeIOTraceSql(p);
575
sqlite3BeginBenignMalloc();
577
&& ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
580
printf("VDBE Program Listing:\n");
581
sqlite3VdbePrintSql(p);
582
for(i=0; i<p->nOp; i++){
583
sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
586
if( fileExists(db, "vdbe_trace") ){
589
sqlite3EndBenignMalloc();
591
for(pc=p->pc; rc==SQLITE_OK; pc++){
592
assert( pc>=0 && pc<p->nOp );
593
if( db->mallocFailed ) goto no_mem;
596
start = sqlite3Hwtime();
600
/* Only allow tracing if SQLITE_DEBUG is defined.
605
printf("VDBE Execution Trace:\n");
606
sqlite3VdbePrintSql(p);
608
sqlite3VdbePrintOp(p->trace, pc, pOp);
610
if( p->trace==0 && pc==0 ){
611
sqlite3BeginBenignMalloc();
612
if( fileExists(db, "vdbe_sqltrace") ){
613
sqlite3VdbePrintSql(p);
615
sqlite3EndBenignMalloc();
620
/* Check to see if we need to simulate an interrupt. This only happens
621
** if we have a special test build.
624
if( sqlite3_interrupt_count>0 ){
625
sqlite3_interrupt_count--;
626
if( sqlite3_interrupt_count==0 ){
627
sqlite3_interrupt(db);
632
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
633
/* Call the progress callback if it is configured and the required number
634
** of VDBE ops have been executed (either since this invocation of
635
** sqlite3VdbeExec() or since last time the progress callback was called).
636
** If the progress callback returns non-zero, exit the virtual machine with
637
** a return code SQLITE_ABORT.
640
if( db->nProgressOps==nProgressOps ){
642
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
643
prc =db->xProgress(db->pProgressArg);
644
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
646
rc = SQLITE_INTERRUPT;
647
goto vdbe_error_halt;
655
/* Do common setup processing for any opcode that is marked
656
** with the "out2-prerelease" tag. Such opcodes have a single
657
** output which is specified by the P2 parameter. The P2 register
658
** is initialized to a NULL.
660
opProperty = opcodeProperty[pOp->opcode];
661
if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
663
assert( pOp->p2<=p->nMem );
664
pOut = &p->aMem[pOp->p2];
665
sqlite3VdbeMemReleaseExternal(pOut);
666
pOut->flags = MEM_Null;
669
/* Do common setup for opcodes marked with one of the following
670
** combinations of properties.
677
** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
678
** registers for inputs. Variable pOut points to the output register.
680
if( (opProperty & OPFLG_IN1)!=0 ){
682
assert( pOp->p1<=p->nMem );
683
pIn1 = &p->aMem[pOp->p1];
684
REGISTER_TRACE(pOp->p1, pIn1);
685
if( (opProperty & OPFLG_IN2)!=0 ){
687
assert( pOp->p2<=p->nMem );
688
pIn2 = &p->aMem[pOp->p2];
689
REGISTER_TRACE(pOp->p2, pIn2);
690
if( (opProperty & OPFLG_OUT3)!=0 ){
692
assert( pOp->p3<=p->nMem );
693
pOut = &p->aMem[pOp->p3];
695
}else if( (opProperty & OPFLG_IN3)!=0 ){
697
assert( pOp->p3<=p->nMem );
698
pIn3 = &p->aMem[pOp->p3];
699
REGISTER_TRACE(pOp->p3, pIn3);
701
}else if( (opProperty & OPFLG_IN2)!=0 ){
703
assert( pOp->p2<=p->nMem );
704
pIn2 = &p->aMem[pOp->p2];
705
REGISTER_TRACE(pOp->p2, pIn2);
706
}else if( (opProperty & OPFLG_IN3)!=0 ){
708
assert( pOp->p3<=p->nMem );
709
pIn3 = &p->aMem[pOp->p3];
710
REGISTER_TRACE(pOp->p3, pIn3);
713
switch( pOp->opcode ){
715
/*****************************************************************************
716
** What follows is a massive switch statement where each case implements a
717
** separate instruction in the virtual machine. If we follow the usual
718
** indentation conventions, each case should be indented by 6 spaces. But
719
** that is a lot of wasted space on the left margin. So the code within
720
** the switch statement will break with convention and be flush-left. Another
721
** big comment (similar to this one) will mark the point in the code where
722
** we transition back to normal indentation.
724
** The formatting of each case is important. The makefile for SQLite
725
** generates two C files "opcodes.h" and "opcodes.c" by scanning this
726
** file looking for lines that begin with "case OP_". The opcodes.h files
727
** will be filled with #defines that give unique integer values to each
728
** opcode and the opcodes.c file is filled with an array of strings where
729
** each string is the symbolic name for the corresponding opcode. If the
730
** case statement is followed by a comment of the form "/# same as ... #/"
731
** that comment is used to determine the particular value of the opcode.
733
** Other keywords in the comment that follows each case are used to
734
** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
735
** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
736
** the mkopcodeh.awk script for additional information.
738
** Documentation about VDBE opcodes is generated by scanning this file
739
** for lines of that contain "Opcode:". That line and all subsequent
740
** comment lines are used in the generation of the opcode.html documentation
745
** Formatting is important to scripts that scan this file.
746
** Do not deviate from the formatting style currently in use.
748
*****************************************************************************/
750
/* Opcode: Goto * P2 * * *
752
** An unconditional jump to address P2.
753
** The next instruction executed will be
754
** the one at index P2 from the beginning of
757
case OP_Goto: { /* jump */
763
/* Opcode: Gosub P1 P2 * * *
765
** Write the current address onto register P1
766
** and then jump to address P2.
768
case OP_Gosub: { /* jump */
770
assert( pOp->p1<=p->nMem );
771
pIn1 = &p->aMem[pOp->p1];
772
assert( (pIn1->flags & MEM_Dyn)==0 );
773
pIn1->flags = MEM_Int;
775
REGISTER_TRACE(pOp->p1, pIn1);
780
/* Opcode: Return P1 * * * *
782
** Jump to the next instruction after the address in register P1.
784
case OP_Return: { /* in1 */
785
assert( pIn1->flags & MEM_Int );
790
/* Opcode: Yield P1 * * * *
792
** Swap the program counter with the value in register P1.
797
assert( pOp->p1<=p->nMem );
798
pIn1 = &p->aMem[pOp->p1];
799
assert( (pIn1->flags & MEM_Dyn)==0 );
800
pIn1->flags = MEM_Int;
803
REGISTER_TRACE(pOp->p1, pIn1);
809
/* Opcode: Halt P1 P2 * P4 *
811
** Exit immediately. All open cursors, Fifos, etc are closed
814
** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
815
** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
816
** For errors, it can be some other value. If P1!=0 then P2 will determine
817
** whether or not to rollback the current transaction. Do not rollback
818
** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
819
** then back out all changes that have occurred during this execution of the
820
** VDBE, but do not rollback the transaction.
822
** If P4 is not null then it is an error message string.
824
** There is an implied "Halt 0 0 0" instruction inserted at the very end of
825
** every program. So a jump past the last instruction of the program
826
** is the same as executing Halt.
831
p->errorAction = pOp->p2;
833
sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
835
rc = sqlite3VdbeHalt(p);
836
assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
837
if( rc==SQLITE_BUSY ){
838
p->rc = rc = SQLITE_BUSY;
840
rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
845
/* Opcode: Integer P1 P2 * * *
847
** The 32-bit integer value P1 is written into register P2.
849
case OP_Integer: { /* out2-prerelease */
850
pOut->flags = MEM_Int;
855
/* Opcode: Int64 * P2 * P4 *
857
** P4 is a pointer to a 64-bit integer value.
858
** Write that value into register P2.
860
case OP_Int64: { /* out2-prerelease */
861
assert( pOp->p4.pI64!=0 );
862
pOut->flags = MEM_Int;
863
pOut->u.i = *pOp->p4.pI64;
867
/* Opcode: Real * P2 * P4 *
869
** P4 is a pointer to a 64-bit floating point value.
870
** Write that value into register P2.
872
case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
873
pOut->flags = MEM_Real;
874
assert( !sqlite3IsNaN(*pOp->p4.pReal) );
875
pOut->r = *pOp->p4.pReal;
879
/* Opcode: String8 * P2 * P4 *
881
** P4 points to a nul terminated UTF-8 string. This opcode is transformed
882
** into an OP_String before it is executed for the first time.
884
case OP_String8: { /* same as TK_STRING, out2-prerelease */
885
assert( pOp->p4.z!=0 );
886
pOp->opcode = OP_String;
887
pOp->p1 = strlen(pOp->p4.z);
889
#ifndef SQLITE_OMIT_UTF16
890
if( encoding!=SQLITE_UTF8 ){
891
sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
892
if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
893
if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
895
pOut->flags |= MEM_Static;
896
pOut->flags &= ~MEM_Dyn;
897
if( pOp->p4type==P4_DYNAMIC ){
898
sqlite3DbFree(db, pOp->p4.z);
900
pOp->p4type = P4_DYNAMIC;
903
if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
906
UPDATE_MAX_BLOBSIZE(pOut);
910
if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
913
/* Fall through to the next case, OP_String */
916
/* Opcode: String P1 P2 * P4 *
918
** The string value P4 of length P1 (bytes) is stored in register P2.
920
case OP_String: { /* out2-prerelease */
921
assert( pOp->p4.z!=0 );
922
pOut->flags = MEM_Str|MEM_Static|MEM_Term;
925
pOut->enc = encoding;
926
UPDATE_MAX_BLOBSIZE(pOut);
930
/* Opcode: Null * P2 * * *
932
** Write a NULL into register P2.
934
case OP_Null: { /* out2-prerelease */
939
#ifndef SQLITE_OMIT_BLOB_LITERAL
940
/* Opcode: Blob P1 P2 * P4
942
** P4 points to a blob of data P1 bytes long. Store this
943
** blob in register P2. This instruction is not coded directly
944
** by the compiler. Instead, the compiler layer specifies
945
** an OP_HexBlob opcode, with the hex string representation of
946
** the blob as P4. This opcode is transformed to an OP_Blob
947
** the first time it is executed.
949
case OP_Blob: { /* out2-prerelease */
950
assert( pOp->p1 <= SQLITE_MAX_LENGTH );
951
sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
952
pOut->enc = encoding;
953
UPDATE_MAX_BLOBSIZE(pOut);
956
#endif /* SQLITE_OMIT_BLOB_LITERAL */
958
/* Opcode: Variable P1 P2 * * *
960
** The value of variable P1 is written into register P2. A variable is
961
** an unknown in the original SQL string as handed to sqlite3_compile().
962
** Any occurrence of the '?' character in the original SQL is considered
963
** a variable. Variables in the SQL string are number from left to
964
** right beginning with 1. The values of variables are set using the
965
** sqlite3_bind() API.
967
case OP_Variable: { /* out2-prerelease */
970
assert( j>=0 && j<p->nVar );
973
if( sqlite3VdbeMemTooBig(pVar) ){
976
sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
977
UPDATE_MAX_BLOBSIZE(pOut);
981
/* Opcode: Move P1 P2 P3 * *
983
** Move the values in register P1..P1+P3-1 over into
984
** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
985
** left holding a NULL. It is an error for register ranges
986
** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
995
assert( p1+n<p->nMem );
998
assert( p2+n<p->nMem );
1000
assert( p1+n<=p2 || p2+n<=p1 );
1002
zMalloc = pOut->zMalloc;
1004
sqlite3VdbeMemMove(pOut, pIn1);
1005
pIn1->zMalloc = zMalloc;
1006
REGISTER_TRACE(p2++, pOut);
1013
/* Opcode: Copy P1 P2 * * *
1015
** Make a copy of register P1 into register P2.
1017
** This instruction makes a deep copy of the value. A duplicate
1018
** is made of any string or blob constant. See also OP_SCopy.
1021
assert( pOp->p1>0 );
1022
assert( pOp->p1<=p->nMem );
1023
pIn1 = &p->aMem[pOp->p1];
1024
assert( pOp->p2>0 );
1025
assert( pOp->p2<=p->nMem );
1026
pOut = &p->aMem[pOp->p2];
1027
assert( pOut!=pIn1 );
1028
sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1029
Deephemeralize(pOut);
1030
REGISTER_TRACE(pOp->p2, pOut);
1034
/* Opcode: SCopy P1 P2 * * *
1036
** Make a shallow copy of register P1 into register P2.
1038
** This instruction makes a shallow copy of the value. If the value
1039
** is a string or blob, then the copy is only a pointer to the
1040
** original and hence if the original changes so will the copy.
1041
** Worse, if the original is deallocated, the copy becomes invalid.
1042
** Thus the program must guarantee that the original will not change
1043
** during the lifetime of the copy. Use OP_Copy to make a complete
1047
assert( pOp->p1>0 );
1048
assert( pOp->p1<=p->nMem );
1049
pIn1 = &p->aMem[pOp->p1];
1050
REGISTER_TRACE(pOp->p1, pIn1);
1051
assert( pOp->p2>0 );
1052
assert( pOp->p2<=p->nMem );
1053
pOut = &p->aMem[pOp->p2];
1054
assert( pOut!=pIn1 );
1055
sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
1056
REGISTER_TRACE(pOp->p2, pOut);
1060
/* Opcode: ResultRow P1 P2 * * *
1062
** The registers P1 through P1+P2-1 contain a single row of
1063
** results. This opcode causes the sqlite3_step() call to terminate
1064
** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
1065
** structure to provide access to the top P1 values as the result
1068
case OP_ResultRow: {
1071
assert( p->nResColumn==pOp->p2 );
1072
assert( pOp->p1>0 );
1073
assert( pOp->p1+pOp->p2<=p->nMem );
1075
/* Invalidate all ephemeral cursor row caches */
1076
p->cacheCtr = (p->cacheCtr + 2)|1;
1078
/* Make sure the results of the current row are \000 terminated
1079
** and have an assigned type. The results are de-ephemeralized as
1082
pMem = p->pResultSet = &p->aMem[pOp->p1];
1083
for(i=0; i<pOp->p2; i++){
1084
sqlite3VdbeMemNulTerminate(&pMem[i]);
1085
storeTypeInfo(&pMem[i], encoding);
1086
REGISTER_TRACE(pOp->p1+i, &pMem[i]);
1088
if( db->mallocFailed ) goto no_mem;
1090
/* Return SQLITE_ROW
1098
/* Opcode: Concat P1 P2 P3 * *
1100
** Add the text in register P1 onto the end of the text in
1101
** register P2 and store the result in register P3.
1102
** If either the P1 or P2 text are NULL then store NULL in P3.
1106
** It is illegal for P1 and P3 to be the same register. Sometimes,
1107
** if P3 is the same register as P2, the implementation is able
1108
** to avoid a memcpy().
1110
case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
1113
assert( pIn1!=pOut );
1114
if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1115
sqlite3VdbeMemSetNull(pOut);
1119
Stringify(pIn1, encoding);
1121
Stringify(pIn2, encoding);
1122
nByte = pIn1->n + pIn2->n;
1123
if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1126
MemSetTypeFlag(pOut, MEM_Str);
1127
if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
1131
memcpy(pOut->z, pIn2->z, pIn2->n);
1133
memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
1135
pOut->z[nByte+1] = 0;
1136
pOut->flags |= MEM_Term;
1138
pOut->enc = encoding;
1139
UPDATE_MAX_BLOBSIZE(pOut);
1143
/* Opcode: Add P1 P2 P3 * *
1145
** Add the value in register P1 to the value in register P2
1146
** and store the result in register P3.
1147
** If either input is NULL, the result is NULL.
1149
/* Opcode: Multiply P1 P2 P3 * *
1152
** Multiply the value in register P1 by the value in register P2
1153
** and store the result in register P3.
1154
** If either input is NULL, the result is NULL.
1156
/* Opcode: Subtract P1 P2 P3 * *
1158
** Subtract the value in register P1 from the value in register P2
1159
** and store the result in register P3.
1160
** If either input is NULL, the result is NULL.
1162
/* Opcode: Divide P1 P2 P3 * *
1164
** Divide the value in register P1 by the value in register P2
1165
** and store the result in register P3. If the value in register P2
1166
** is zero, then the result is NULL.
1167
** If either input is NULL, the result is NULL.
1169
/* Opcode: Remainder P1 P2 P3 * *
1171
** Compute the remainder after integer division of the value in
1172
** register P1 by the value in register P2 and store the result in P3.
1173
** If the value in register P2 is zero the result is NULL.
1174
** If either operand is NULL, the result is NULL.
1176
case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
1177
case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
1178
case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
1179
case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
1180
case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
1182
applyNumericAffinity(pIn1);
1183
applyNumericAffinity(pIn2);
1184
flags = pIn1->flags | pIn2->flags;
1185
if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
1186
if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
1190
switch( pOp->opcode ){
1191
case OP_Add: b += a; break;
1192
case OP_Subtract: b -= a; break;
1193
case OP_Multiply: b *= a; break;
1195
if( a==0 ) goto arithmetic_result_is_null;
1196
/* Dividing the largest possible negative 64-bit integer (1<<63) by
1197
** -1 returns an integer too large to store in a 64-bit data-type. On
1198
** some architectures, the value overflows to (1<<63). On others,
1199
** a SIGFPE is issued. The following statement normalizes this
1200
** behavior so that all architectures behave as if integer
1201
** overflow occurred.
1203
if( a==-1 && b==SMALLEST_INT64 ) a = 1;
1208
if( a==0 ) goto arithmetic_result_is_null;
1215
MemSetTypeFlag(pOut, MEM_Int);
1218
a = sqlite3VdbeRealValue(pIn1);
1219
b = sqlite3VdbeRealValue(pIn2);
1220
switch( pOp->opcode ){
1221
case OP_Add: b += a; break;
1222
case OP_Subtract: b -= a; break;
1223
case OP_Multiply: b *= a; break;
1225
if( a==0.0 ) goto arithmetic_result_is_null;
1232
if( ia==0 ) goto arithmetic_result_is_null;
1233
if( ia==-1 ) ia = 1;
1238
if( sqlite3IsNaN(b) ){
1239
goto arithmetic_result_is_null;
1242
MemSetTypeFlag(pOut, MEM_Real);
1243
if( (flags & MEM_Real)==0 ){
1244
sqlite3VdbeIntegerAffinity(pOut);
1249
arithmetic_result_is_null:
1250
sqlite3VdbeMemSetNull(pOut);
1254
/* Opcode: CollSeq * * P4
1256
** P4 is a pointer to a CollSeq struct. If the next call to a user function
1257
** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
1258
** be returned. This is used by the built-in min(), max() and nullif()
1261
** The interface used by the implementation of the aforementioned functions
1262
** to retrieve the collation sequence set by this opcode is not available
1263
** publicly, only to user functions defined in func.c.
1266
assert( pOp->p4type==P4_COLLSEQ );
1270
/* Opcode: Function P1 P2 P3 P4 P5
1272
** Invoke a user function (P4 is a pointer to a Function structure that
1273
** defines the function) with P5 arguments taken from register P2 and
1274
** successors. The result of the function is stored in register P3.
1275
** Register P3 must not be one of the function inputs.
1277
** P1 is a 32-bit bitmask indicating whether or not each argument to the
1278
** function was determined to be constant at compile time. If the first
1279
** argument was constant then bit 0 of P1 is set. This is used to determine
1280
** whether meta data associated with a user function argument using the
1281
** sqlite3_set_auxdata() API may be safely retained until the next
1282
** invocation of this opcode.
1284
** See also: AggStep and AggFinal
1289
sqlite3_context ctx;
1290
sqlite3_value **apVal;
1294
assert( apVal || n==0 );
1296
assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
1297
assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
1298
pArg = &p->aMem[pOp->p2];
1299
for(i=0; i<n; i++, pArg++){
1301
storeTypeInfo(pArg, encoding);
1302
REGISTER_TRACE(pOp->p2, pArg);
1305
assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
1306
if( pOp->p4type==P4_FUNCDEF ){
1307
ctx.pFunc = pOp->p4.pFunc;
1310
ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
1311
ctx.pFunc = ctx.pVdbeFunc->pFunc;
1314
assert( pOp->p3>0 && pOp->p3<=p->nMem );
1315
pOut = &p->aMem[pOp->p3];
1316
ctx.s.flags = MEM_Null;
1321
/* The output cell may already have a buffer allocated. Move
1322
** the pointer to ctx.s so in case the user-function can use
1323
** the already allocated buffer instead of allocating a new one.
1325
sqlite3VdbeMemMove(&ctx.s, pOut);
1326
MemSetTypeFlag(&ctx.s, MEM_Null);
1329
if( ctx.pFunc->needCollSeq ){
1330
assert( pOp>p->aOp );
1331
assert( pOp[-1].p4type==P4_COLLSEQ );
1332
assert( pOp[-1].opcode==OP_CollSeq );
1333
ctx.pColl = pOp[-1].p4.pColl;
1335
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
1336
(*ctx.pFunc->xFunc)(&ctx, n, apVal);
1337
if( sqlite3SafetyOn(db) ){
1338
sqlite3VdbeMemRelease(&ctx.s);
1339
goto abort_due_to_misuse;
1341
if( db->mallocFailed ){
1342
/* Even though a malloc() has failed, the implementation of the
1343
** user function may have called an sqlite3_result_XXX() function
1344
** to return a value. The following call releases any resources
1345
** associated with such a value.
1347
** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
1348
** fails also (the if(...) statement above). But if people are
1349
** misusing sqlite, they have bigger problems than a leaked value.
1351
sqlite3VdbeMemRelease(&ctx.s);
1355
/* If any auxiliary data functions have been called by this user function,
1356
** immediately call the destructor for any non-static values.
1358
if( ctx.pVdbeFunc ){
1359
sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
1360
pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
1361
pOp->p4type = P4_VDBEFUNC;
1364
/* If the function returned an error, throw an exception */
1366
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
1370
/* Copy the result of the function into register P3 */
1371
sqlite3VdbeChangeEncoding(&ctx.s, encoding);
1372
sqlite3VdbeMemMove(pOut, &ctx.s);
1373
if( sqlite3VdbeMemTooBig(pOut) ){
1376
REGISTER_TRACE(pOp->p3, pOut);
1377
UPDATE_MAX_BLOBSIZE(pOut);
1381
/* Opcode: BitAnd P1 P2 P3 * *
1383
** Take the bit-wise AND of the values in register P1 and P2 and
1384
** store the result in register P3.
1385
** If either input is NULL, the result is NULL.
1387
/* Opcode: BitOr P1 P2 P3 * *
1389
** Take the bit-wise OR of the values in register P1 and P2 and
1390
** store the result in register P3.
1391
** If either input is NULL, the result is NULL.
1393
/* Opcode: ShiftLeft P1 P2 P3 * *
1395
** Shift the integer value in register P2 to the left by the
1396
** number of bits specified by the integer in regiser P1.
1397
** Store the result in register P3.
1398
** If either input is NULL, the result is NULL.
1400
/* Opcode: ShiftRight P1 P2 P3 * *
1402
** Shift the integer value in register P2 to the right by the
1403
** number of bits specified by the integer in register P1.
1404
** Store the result in register P3.
1405
** If either input is NULL, the result is NULL.
1407
case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
1408
case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
1409
case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
1410
case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
1413
if( (pIn1->flags | pIn2->flags) & MEM_Null ){
1414
sqlite3VdbeMemSetNull(pOut);
1417
a = sqlite3VdbeIntValue(pIn2);
1418
b = sqlite3VdbeIntValue(pIn1);
1419
switch( pOp->opcode ){
1420
case OP_BitAnd: a &= b; break;
1421
case OP_BitOr: a |= b; break;
1422
case OP_ShiftLeft: a <<= b; break;
1423
default: assert( pOp->opcode==OP_ShiftRight );
1427
MemSetTypeFlag(pOut, MEM_Int);
1431
/* Opcode: AddImm P1 P2 * * *
1433
** Add the constant P2 to the value in register P1.
1434
** The result is always an integer.
1436
** To force any register to be an integer, just add 0.
1438
case OP_AddImm: { /* in1 */
1439
sqlite3VdbeMemIntegerify(pIn1);
1440
pIn1->u.i += pOp->p2;
1444
/* Opcode: ForceInt P1 P2 P3 * *
1446
** Convert value in register P1 into an integer. If the value
1447
** in P1 is not numeric (meaning that is is a NULL or a string that
1448
** does not look like an integer or floating point number) then
1449
** jump to P2. If the value in P1 is numeric then
1450
** convert it into the least integer that is greater than or equal to its
1451
** current value if P3==0, or to the least integer that is strictly
1452
** greater than its current value if P3==1.
1454
case OP_ForceInt: { /* jump, in1 */
1456
applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1457
if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
1461
if( pIn1->flags & MEM_Int ){
1462
v = pIn1->u.i + (pOp->p3!=0);
1464
assert( pIn1->flags & MEM_Real );
1465
v = (sqlite3_int64)pIn1->r;
1466
if( pIn1->r>(double)v ) v++;
1467
if( pOp->p3 && pIn1->r==(double)v ) v++;
1470
MemSetTypeFlag(pIn1, MEM_Int);
1474
/* Opcode: MustBeInt P1 P2 * * *
1476
** Force the value in register P1 to be an integer. If the value
1477
** in P1 is not an integer and cannot be converted into an integer
1478
** without data loss, then jump immediately to P2, or if P2==0
1479
** raise an SQLITE_MISMATCH exception.
1481
case OP_MustBeInt: { /* jump, in1 */
1482
applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
1483
if( (pIn1->flags & MEM_Int)==0 ){
1485
rc = SQLITE_MISMATCH;
1486
goto abort_due_to_error;
1491
MemSetTypeFlag(pIn1, MEM_Int);
1496
/* Opcode: RealAffinity P1 * * * *
1498
** If register P1 holds an integer convert it to a real value.
1500
** This opcode is used when extracting information from a column that
1501
** has REAL affinity. Such column values may still be stored as
1502
** integers, for space efficiency, but after extraction we want them
1503
** to have only a real value.
1505
case OP_RealAffinity: { /* in1 */
1506
if( pIn1->flags & MEM_Int ){
1507
sqlite3VdbeMemRealify(pIn1);
1512
#ifndef SQLITE_OMIT_CAST
1513
/* Opcode: ToText P1 * * * *
1515
** Force the value in register P1 to be text.
1516
** If the value is numeric, convert it to a string using the
1517
** equivalent of printf(). Blob values are unchanged and
1518
** are afterwards simply interpreted as text.
1520
** A NULL value is not changed by this routine. It remains NULL.
1522
case OP_ToText: { /* same as TK_TO_TEXT, in1 */
1523
if( pIn1->flags & MEM_Null ) break;
1524
assert( MEM_Str==(MEM_Blob>>3) );
1525
pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
1526
applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1527
rc = ExpandBlob(pIn1);
1528
assert( pIn1->flags & MEM_Str || db->mallocFailed );
1529
pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
1530
UPDATE_MAX_BLOBSIZE(pIn1);
1534
/* Opcode: ToBlob P1 * * * *
1536
** Force the value in register P1 to be a BLOB.
1537
** If the value is numeric, convert it to a string first.
1538
** Strings are simply reinterpreted as blobs with no change
1539
** to the underlying data.
1541
** A NULL value is not changed by this routine. It remains NULL.
1543
case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
1544
if( pIn1->flags & MEM_Null ) break;
1545
if( (pIn1->flags & MEM_Blob)==0 ){
1546
applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
1547
assert( pIn1->flags & MEM_Str || db->mallocFailed );
1549
MemSetTypeFlag(pIn1, MEM_Blob);
1550
UPDATE_MAX_BLOBSIZE(pIn1);
1554
/* Opcode: ToNumeric P1 * * * *
1556
** Force the value in register P1 to be numeric (either an
1557
** integer or a floating-point number.)
1558
** If the value is text or blob, try to convert it to an using the
1559
** equivalent of atoi() or atof() and store 0 if no such conversion
1562
** A NULL value is not changed by this routine. It remains NULL.
1564
case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
1565
if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
1566
sqlite3VdbeMemNumerify(pIn1);
1570
#endif /* SQLITE_OMIT_CAST */
1572
/* Opcode: ToInt P1 * * * *
1574
** Force the value in register P1 be an integer. If
1575
** The value is currently a real number, drop its fractional part.
1576
** If the value is text or blob, try to convert it to an integer using the
1577
** equivalent of atoi() and store 0 if no such conversion is possible.
1579
** A NULL value is not changed by this routine. It remains NULL.
1581
case OP_ToInt: { /* same as TK_TO_INT, in1 */
1582
if( (pIn1->flags & MEM_Null)==0 ){
1583
sqlite3VdbeMemIntegerify(pIn1);
1588
#ifndef SQLITE_OMIT_CAST
1589
/* Opcode: ToReal P1 * * * *
1591
** Force the value in register P1 to be a floating point number.
1592
** If The value is currently an integer, convert it.
1593
** If the value is text or blob, try to convert it to an integer using the
1594
** equivalent of atoi() and store 0.0 if no such conversion is possible.
1596
** A NULL value is not changed by this routine. It remains NULL.
1598
case OP_ToReal: { /* same as TK_TO_REAL, in1 */
1599
if( (pIn1->flags & MEM_Null)==0 ){
1600
sqlite3VdbeMemRealify(pIn1);
1604
#endif /* SQLITE_OMIT_CAST */
1606
/* Opcode: Lt P1 P2 P3 P4 P5
1608
** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
1609
** jump to address P2.
1611
** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
1612
** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
1613
** bit is clear then fall thru if either operand is NULL.
1615
** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
1616
** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
1617
** to coerce both inputs according to this affinity before the
1618
** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
1619
** affinity is used. Note that the affinity conversions are stored
1620
** back into the input registers P1 and P3. So this opcode can cause
1621
** persistent changes to registers P1 and P3.
1623
** Once any conversions have taken place, and neither value is NULL,
1624
** the values are compared. If both values are blobs then memcmp() is
1625
** used to determine the results of the comparison. If both values
1626
** are text, then the appropriate collating function specified in
1627
** P4 is used to do the comparison. If P4 is not specified then
1628
** memcmp() is used to compare text string. If both values are
1629
** numeric, then a numeric comparison is used. If the two values
1630
** are of different types, then numbers are considered less than
1631
** strings and strings are considered less than blobs.
1633
** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
1634
** store a boolean result (either 0, or 1, or NULL) in register P2.
1636
/* Opcode: Ne P1 P2 P3 P4 P5
1638
** This works just like the Lt opcode except that the jump is taken if
1639
** the operands in registers P1 and P3 are not equal. See the Lt opcode for
1640
** additional information.
1642
/* Opcode: Eq P1 P2 P3 P4 P5
1644
** This works just like the Lt opcode except that the jump is taken if
1645
** the operands in registers P1 and P3 are equal.
1646
** See the Lt opcode for additional information.
1648
/* Opcode: Le P1 P2 P3 P4 P5
1650
** This works just like the Lt opcode except that the jump is taken if
1651
** the content of register P3 is less than or equal to the content of
1652
** register P1. See the Lt opcode for additional information.
1654
/* Opcode: Gt P1 P2 P3 P4 P5
1656
** This works just like the Lt opcode except that the jump is taken if
1657
** the content of register P3 is greater than the content of
1658
** register P1. See the Lt opcode for additional information.
1660
/* Opcode: Ge P1 P2 P3 P4 P5
1662
** This works just like the Lt opcode except that the jump is taken if
1663
** the content of register P3 is greater than or equal to the content of
1664
** register P1. See the Lt opcode for additional information.
1666
case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
1667
case OP_Ne: /* same as TK_NE, jump, in1, in3 */
1668
case OP_Lt: /* same as TK_LT, jump, in1, in3 */
1669
case OP_Le: /* same as TK_LE, jump, in1, in3 */
1670
case OP_Gt: /* same as TK_GT, jump, in1, in3 */
1671
case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
1676
flags = pIn1->flags|pIn3->flags;
1678
if( flags&MEM_Null ){
1679
/* If either operand is NULL then the result is always NULL.
1680
** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
1682
if( pOp->p5 & SQLITE_STOREP2 ){
1683
pOut = &p->aMem[pOp->p2];
1684
MemSetTypeFlag(pOut, MEM_Null);
1685
REGISTER_TRACE(pOp->p2, pOut);
1686
}else if( pOp->p5 & SQLITE_JUMPIFNULL ){
1692
affinity = pOp->p5 & SQLITE_AFF_MASK;
1694
applyAffinity(pIn1, affinity, encoding);
1695
applyAffinity(pIn3, affinity, encoding);
1698
assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
1701
res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
1702
switch( pOp->opcode ){
1703
case OP_Eq: res = res==0; break;
1704
case OP_Ne: res = res!=0; break;
1705
case OP_Lt: res = res<0; break;
1706
case OP_Le: res = res<=0; break;
1707
case OP_Gt: res = res>0; break;
1708
default: res = res>=0; break;
1711
if( pOp->p5 & SQLITE_STOREP2 ){
1712
pOut = &p->aMem[pOp->p2];
1713
MemSetTypeFlag(pOut, MEM_Int);
1715
REGISTER_TRACE(pOp->p2, pOut);
1722
/* Opcode: Permutation * * * P4 *
1724
** Set the permuation used by the OP_Compare operator to be the array
1725
** of integers in P4.
1727
** The permutation is only valid until the next OP_Permutation, OP_Compare,
1728
** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
1729
** immediately prior to the OP_Compare.
1731
case OP_Permutation: {
1732
assert( pOp->p4type==P4_INTARRAY );
1733
assert( pOp->p4.ai );
1734
aPermute = pOp->p4.ai;
1738
/* Opcode: Compare P1 P2 P3 P4 *
1740
** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
1741
** one "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
1742
** the comparison for use by the next OP_Jump instruct.
1744
** P4 is a KeyInfo structure that defines collating sequences and sort
1745
** orders for the comparison. The permutation applies to registers
1746
** only. The KeyInfo elements are used sequentially.
1748
** The comparison is a sort comparison, so NULLs compare equal,
1749
** NULLs are less than numbers, numbers are less than strings,
1750
** and strings are less than blobs.
1755
const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
1757
assert( pKeyInfo!=0 );
1759
assert( p1>0 && p1+n-1<p->nMem );
1761
assert( p2>0 && p2+n-1<p->nMem );
1763
int idx = aPermute ? aPermute[i] : i;
1764
CollSeq *pColl; /* Collating sequence to use on this term */
1765
int bRev; /* True for DESCENDING sort order */
1766
REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
1767
REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
1768
assert( i<pKeyInfo->nField );
1769
pColl = pKeyInfo->aColl[i];
1770
bRev = pKeyInfo->aSortOrder[i];
1771
iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
1773
if( bRev ) iCompare = -iCompare;
1781
/* Opcode: Jump P1 P2 P3 * *
1783
** Jump to the instruction at address P1, P2, or P3 depending on whether
1784
** in the most recent OP_Compare instruction the P1 vector was less than
1785
** equal to, or greater than the P2 vector, respectively.
1787
case OP_Jump: { /* jump */
1790
}else if( iCompare==0 ){
1798
/* Opcode: And P1 P2 P3 * *
1800
** Take the logical AND of the values in registers P1 and P2 and
1801
** write the result into register P3.
1803
** If either P1 or P2 is 0 (false) then the result is 0 even if
1804
** the other input is NULL. A NULL and true or two NULLs give
1807
/* Opcode: Or P1 P2 P3 * *
1809
** Take the logical OR of the values in register P1 and P2 and
1810
** store the answer in register P3.
1812
** If either P1 or P2 is nonzero (true) then the result is 1 (true)
1813
** even if the other input is NULL. A NULL and false or two NULLs
1814
** give a NULL output.
1816
case OP_And: /* same as TK_AND, in1, in2, out3 */
1817
case OP_Or: { /* same as TK_OR, in1, in2, out3 */
1818
int v1, v2; /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
1820
if( pIn1->flags & MEM_Null ){
1823
v1 = sqlite3VdbeIntValue(pIn1)!=0;
1825
if( pIn2->flags & MEM_Null ){
1828
v2 = sqlite3VdbeIntValue(pIn2)!=0;
1830
if( pOp->opcode==OP_And ){
1831
static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
1832
v1 = and_logic[v1*3+v2];
1834
static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
1835
v1 = or_logic[v1*3+v2];
1838
MemSetTypeFlag(pOut, MEM_Null);
1841
MemSetTypeFlag(pOut, MEM_Int);
1846
/* Opcode: Not P1 * * * *
1848
** Interpret the value in register P1 as a boolean value. Replace it
1849
** with its complement. If the value in register P1 is NULL its value
1852
case OP_Not: { /* same as TK_NOT, in1 */
1853
if( pIn1->flags & MEM_Null ) break; /* Do nothing to NULLs */
1854
sqlite3VdbeMemIntegerify(pIn1);
1855
pIn1->u.i = !pIn1->u.i;
1856
assert( pIn1->flags&MEM_Int );
1860
/* Opcode: BitNot P1 * * * *
1862
** Interpret the content of register P1 as an integer. Replace it
1863
** with its ones-complement. If the value is originally NULL, leave
1866
case OP_BitNot: { /* same as TK_BITNOT, in1 */
1867
if( pIn1->flags & MEM_Null ) break; /* Do nothing to NULLs */
1868
sqlite3VdbeMemIntegerify(pIn1);
1869
pIn1->u.i = ~pIn1->u.i;
1870
assert( pIn1->flags&MEM_Int );
1874
/* Opcode: If P1 P2 P3 * *
1876
** Jump to P2 if the value in register P1 is true. The value is
1877
** is considered true if it is numeric and non-zero. If the value
1878
** in P1 is NULL then take the jump if P3 is true.
1880
/* Opcode: IfNot P1 P2 P3 * *
1882
** Jump to P2 if the value in register P1 is False. The value is
1883
** is considered true if it has a numeric value of zero. If the value
1884
** in P1 is NULL then take the jump if P3 is true.
1886
case OP_If: /* jump, in1 */
1887
case OP_IfNot: { /* jump, in1 */
1889
if( pIn1->flags & MEM_Null ){
1892
#ifdef SQLITE_OMIT_FLOATING_POINT
1893
c = sqlite3VdbeIntValue(pIn1);
1895
c = sqlite3VdbeRealValue(pIn1)!=0.0;
1897
if( pOp->opcode==OP_IfNot ) c = !c;
1905
/* Opcode: IsNull P1 P2 P3 * *
1907
** Jump to P2 if the value in register P1 is NULL. If P3 is greater
1908
** than zero, then check all values reg(P1), reg(P1+1),
1909
** reg(P1+2), ..., reg(P1+P3-1).
1911
case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
1913
assert( pOp->p3==0 || pOp->p1>0 );
1915
if( (pIn1->flags & MEM_Null)!=0 ){
1924
/* Opcode: NotNull P1 P2 * * *
1926
** Jump to P2 if the value in register P1 is not NULL.
1928
case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
1929
if( (pIn1->flags & MEM_Null)==0 ){
1935
/* Opcode: SetNumColumns * P2 * * *
1937
** This opcode sets the number of columns for the cursor opened by the
1938
** following instruction to P2.
1940
** An OP_SetNumColumns is only useful if it occurs immediately before
1941
** one of the following opcodes:
1947
** If the OP_Column opcode is to be executed on a cursor, then
1948
** this opcode must be present immediately before the opcode that
1949
** opens the cursor.
1951
case OP_SetNumColumns: {
1955
/* Opcode: Column P1 P2 P3 P4 *
1957
** Interpret the data that cursor P1 points to as a structure built using
1958
** the MakeRecord instruction. (See the MakeRecord opcode for additional
1959
** information about the format of the data.) Extract the P2-th column
1960
** from this record. If there are less that (P2+1)
1961
** values in the record, extract a NULL.
1963
** The value extracted is stored in register P3.
1965
** If the KeyAsData opcode has previously executed on this cursor, then the
1966
** field might be extracted from the key rather than the data.
1968
** If the column contains fewer than P2 fields, then extract a NULL. Or,
1969
** if the P4 argument is a P4_MEM use the value of the P4 argument as
1973
u32 payloadSize; /* Number of bytes in the record */
1974
int p1 = pOp->p1; /* P1 value of the opcode */
1975
int p2 = pOp->p2; /* column number to retrieve */
1976
Cursor *pC = 0; /* The VDBE cursor */
1977
char *zRec; /* Pointer to complete record-data */
1978
BtCursor *pCrsr; /* The BTree cursor */
1979
u32 *aType; /* aType[i] holds the numeric type of the i-th column */
1980
u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
1981
u32 nField; /* number of fields in the record */
1982
int len; /* The length of the serialized data for the column */
1983
int i; /* Loop counter */
1984
char *zData; /* Part of the record being decoded */
1985
Mem *pDest; /* Where to write the extracted value */
1986
Mem sMem; /* For storing the record being decoded */
1991
assert( p1<p->nCursor );
1992
assert( pOp->p3>0 && pOp->p3<=p->nMem );
1993
pDest = &p->aMem[pOp->p3];
1994
MemSetTypeFlag(pDest, MEM_Null);
1996
/* This block sets the variable payloadSize to be the total number of
1997
** bytes in the record.
1999
** zRec is set to be the complete text of the record if it is available.
2000
** The complete record text is always available for pseudo-tables
2001
** If the record is stored in a cursor, the complete record text
2002
** might be available in the pC->aRow cache. Or it might not be.
2003
** If the data is unavailable, zRec is set to NULL.
2005
** We also compute the number of columns in the record. For cursors,
2006
** the number of columns is stored in the Cursor.nField element.
2010
#ifndef SQLITE_OMIT_VIRTUALTABLE
2011
assert( pC->pVtabCursor==0 );
2013
if( pC->pCursor!=0 ){
2014
/* The record is stored in a B-Tree */
2015
rc = sqlite3VdbeCursorMoveto(pC);
2016
if( rc ) goto abort_due_to_error;
2018
pCrsr = pC->pCursor;
2021
}else if( pC->cacheStatus==p->cacheCtr ){
2022
payloadSize = pC->payloadSize;
2023
zRec = (char*)pC->aRow;
2024
}else if( pC->isIndex ){
2026
sqlite3BtreeKeySize(pCrsr, &payloadSize64);
2027
payloadSize = payloadSize64;
2029
sqlite3BtreeDataSize(pCrsr, &payloadSize);
2031
nField = pC->nField;
2033
assert( pC->pseudoTable );
2034
/* The record is the sole entry of a pseudo-table */
2035
payloadSize = pC->nData;
2037
pC->cacheStatus = CACHE_STALE;
2038
assert( payloadSize==0 || zRec!=0 );
2039
nField = pC->nField;
2043
/* If payloadSize is 0, then just store a NULL */
2044
if( payloadSize==0 ){
2045
assert( pDest->flags&MEM_Null );
2048
if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2052
assert( p2<nField );
2054
/* Read and parse the table header. Store the results of the parse
2055
** into the record header cache fields of the cursor.
2058
if( pC->cacheStatus==p->cacheCtr ){
2059
aOffset = pC->aOffset;
2061
u8 *zIdx; /* Index into header */
2062
u8 *zEndHdr; /* Pointer to first byte after the header */
2063
u32 offset; /* Offset into the data */
2064
int szHdrSz; /* Size of the header size field at start of record */
2065
int avail; /* Number of bytes of available data */
2068
pC->aOffset = aOffset = &aType[nField];
2069
pC->payloadSize = payloadSize;
2070
pC->cacheStatus = p->cacheCtr;
2072
/* Figure out how many bytes are in the header */
2077
zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
2079
zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
2081
/* If KeyFetch()/DataFetch() managed to get the entire payload,
2082
** save the payload in the pC->aRow cache. That will save us from
2083
** having to make additional calls to fetch the content portion of
2086
if( avail>=payloadSize ){
2088
pC->aRow = (u8*)zData;
2093
/* The following assert is true in all cases accept when
2094
** the database file has been corrupted externally.
2095
** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
2096
szHdrSz = getVarint32((u8*)zData, offset);
2098
/* The KeyFetch() or DataFetch() above are fast and will get the entire
2099
** record header in most cases. But they will fail to get the complete
2100
** record header if the record header does not fit on a single page
2101
** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
2102
** acquire the complete header text.
2104
if( !zRec && avail<offset ){
2107
rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
2108
if( rc!=SQLITE_OK ){
2113
zEndHdr = (u8 *)&zData[offset];
2114
zIdx = (u8 *)&zData[szHdrSz];
2116
/* Scan the header and use it to fill in the aType[] and aOffset[]
2117
** arrays. aType[i] will contain the type integer for the i-th
2118
** column and aOffset[i] will contain the offset from the beginning
2119
** of the record to the start of the data for the i-th column
2121
for(i=0; i<nField; i++){
2123
aOffset[i] = offset;
2124
zIdx += getVarint32(zIdx, aType[i]);
2125
offset += sqlite3VdbeSerialTypeLen(aType[i]);
2127
/* If i is less that nField, then there are less fields in this
2128
** record than SetNumColumns indicated there are columns in the
2129
** table. Set the offset for any extra columns not present in
2130
** the record to 0. This tells code below to store a NULL
2131
** instead of deserializing a value from the record.
2136
sqlite3VdbeMemRelease(&sMem);
2137
sMem.flags = MEM_Null;
2139
/* If we have read more header data than was contained in the header,
2140
** or if the end of the last field appears to be past the end of the
2141
** record, or if the end of the last field appears to be before the end
2142
** of the record (when all fields present), then we must be dealing
2143
** with a corrupt database.
2145
if( zIdx>zEndHdr || offset>payloadSize || (zIdx==zEndHdr && offset!=payloadSize) ){
2146
rc = SQLITE_CORRUPT_BKPT;
2151
/* Get the column information. If aOffset[p2] is non-zero, then
2152
** deserialize the value from the record. If aOffset[p2] is zero,
2153
** then there are not enough fields in the record to satisfy the
2154
** request. In this case, set the value NULL or to P4 if P4 is
2155
** a pointer to a Mem object.
2158
assert( rc==SQLITE_OK );
2160
sqlite3VdbeMemReleaseExternal(pDest);
2161
sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
2163
len = sqlite3VdbeSerialTypeLen(aType[p2]);
2164
sqlite3VdbeMemMove(&sMem, pDest);
2165
rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
2166
if( rc!=SQLITE_OK ){
2170
sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
2172
pDest->enc = encoding;
2174
if( pOp->p4type==P4_MEM ){
2175
sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
2177
assert( pDest->flags&MEM_Null );
2181
/* If we dynamically allocated space to hold the data (in the
2182
** sqlite3VdbeMemFromBtree() call above) then transfer control of that
2183
** dynamically allocated space over to the pDest structure.
2184
** This prevents a memory copy.
2187
assert( sMem.z==sMem.zMalloc );
2188
assert( !(pDest->flags & MEM_Dyn) );
2189
assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
2190
pDest->flags &= ~(MEM_Ephem|MEM_Static);
2191
pDest->flags |= MEM_Term;
2193
pDest->zMalloc = sMem.zMalloc;
2196
rc = sqlite3VdbeMemMakeWriteable(pDest);
2199
UPDATE_MAX_BLOBSIZE(pDest);
2200
REGISTER_TRACE(pOp->p3, pDest);
2204
/* Opcode: Affinity P1 P2 * P4 *
2206
** Apply affinities to a range of P2 registers starting with P1.
2208
** P4 is a string that is P2 characters long. The nth character of the
2209
** string indicates the column affinity that should be used for the nth
2210
** memory cell in the range.
2213
char *zAffinity = pOp->p4.z;
2214
Mem *pData0 = &p->aMem[pOp->p1];
2215
Mem *pLast = &pData0[pOp->p2-1];
2218
for(pRec=pData0; pRec<=pLast; pRec++){
2220
applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2225
/* Opcode: MakeRecord P1 P2 P3 P4 *
2227
** Convert P2 registers beginning with P1 into a single entry
2228
** suitable for use as a data record in a database table or as a key
2229
** in an index. The details of the format are irrelevant as long as
2230
** the OP_Column opcode can decode the record later.
2231
** Refer to source code comments for the details of the record
2234
** P4 may be a string that is P2 characters long. The nth character of the
2235
** string indicates the column affinity that should be used for the nth
2236
** field of the index key.
2238
** The mapping from character to affinity is given by the SQLITE_AFF_
2239
** macros defined in sqliteInt.h.
2241
** If P4 is NULL then all index fields have the affinity NONE.
2243
case OP_MakeRecord: {
2244
/* Assuming the record contains N fields, the record format looks
2247
** ------------------------------------------------------------------------
2248
** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
2249
** ------------------------------------------------------------------------
2251
** Data(0) is taken from register P1. Data(1) comes from register P1+1
2254
** Each type field is a varint representing the serial type of the
2255
** corresponding data element (see sqlite3VdbeSerialType()). The
2256
** hdr-size field is also a varint which is the offset from the beginning
2257
** of the record to data0.
2259
u8 *zNewRecord; /* A buffer to hold the data for the new record */
2260
Mem *pRec; /* The new record */
2261
u64 nData = 0; /* Number of bytes of data space */
2262
int nHdr = 0; /* Number of bytes of header space */
2263
u64 nByte = 0; /* Data space required for this record */
2264
int nZero = 0; /* Number of zero bytes at the end of the record */
2265
int nVarint; /* Number of bytes in a varint */
2266
u32 serial_type; /* Type field */
2267
Mem *pData0; /* First field to be combined into the record */
2268
Mem *pLast; /* Last field of the record */
2269
int nField; /* Number of fields in the record */
2270
char *zAffinity; /* The affinity string for the record */
2271
int file_format; /* File format to use for encoding */
2272
int i; /* Space used in zNewRecord[] */
2275
zAffinity = pOp->p4.z;
2276
assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
2277
pData0 = &p->aMem[nField];
2279
pLast = &pData0[nField-1];
2280
file_format = p->minWriteFileFormat;
2282
/* Loop through the elements that will make up the record to figure
2283
** out how much space is required for the new record.
2285
for(pRec=pData0; pRec<=pLast; pRec++){
2288
applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
2290
if( pRec->flags&MEM_Zero && pRec->n>0 ){
2291
sqlite3VdbeMemExpandBlob(pRec);
2293
serial_type = sqlite3VdbeSerialType(pRec, file_format);
2294
len = sqlite3VdbeSerialTypeLen(serial_type);
2296
nHdr += sqlite3VarintLen(serial_type);
2297
if( pRec->flags & MEM_Zero ){
2298
/* Only pure zero-filled BLOBs can be input to this Opcode.
2299
** We do not allow blobs with a prefix and a zero-filled tail. */
2306
/* Add the initial header varint and total the size */
2307
nHdr += nVarint = sqlite3VarintLen(nHdr);
2308
if( nVarint<sqlite3VarintLen(nHdr) ){
2311
nByte = nHdr+nData-nZero;
2312
if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
2316
/* Make sure the output register has a buffer large enough to store
2317
** the new record. The output register (pOp->p3) is not allowed to
2318
** be one of the input registers (because the following call to
2319
** sqlite3VdbeMemGrow() could clobber the value before it is used).
2321
assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
2322
pOut = &p->aMem[pOp->p3];
2323
if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
2326
zNewRecord = (u8 *)pOut->z;
2328
/* Write the record */
2329
i = putVarint32(zNewRecord, nHdr);
2330
for(pRec=pData0; pRec<=pLast; pRec++){
2331
serial_type = sqlite3VdbeSerialType(pRec, file_format);
2332
i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
2334
for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */
2335
i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
2339
assert( pOp->p3>0 && pOp->p3<=p->nMem );
2341
pOut->flags = MEM_Blob | MEM_Dyn;
2345
pOut->flags |= MEM_Zero;
2347
pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
2348
REGISTER_TRACE(pOp->p3, pOut);
2349
UPDATE_MAX_BLOBSIZE(pOut);
2353
/* Opcode: Statement P1 * * * *
2355
** Begin an individual statement transaction which is part of a larger
2356
** transaction. This is needed so that the statement
2357
** can be rolled back after an error without having to roll back the
2358
** entire transaction. The statement transaction will automatically
2359
** commit when the VDBE halts.
2361
** If the database connection is currently in autocommit mode (that
2362
** is to say, if it is in between BEGIN and COMMIT)
2363
** and if there are no other active statements on the same database
2364
** connection, then this operation is a no-op. No statement transaction
2365
** is needed since any error can use the normal ROLLBACK process to
2368
** If a statement transaction is started, then a statement journal file
2369
** will be allocated and initialized.
2371
** The statement is begun on the database file with index P1. The main
2372
** database file has an index of 0 and the file used for temporary tables
2373
** has an index of 1.
2375
case OP_Statement: {
2376
if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
2379
assert( i>=0 && i<db->nDb );
2380
assert( db->aDb[i].pBt!=0 );
2381
pBt = db->aDb[i].pBt;
2382
assert( sqlite3BtreeIsInTrans(pBt) );
2383
assert( (p->btreeMask & (1<<i))!=0 );
2384
if( !sqlite3BtreeIsInStmt(pBt) ){
2385
rc = sqlite3BtreeBeginStmt(pBt);
2386
p->openedStatement = 1;
2392
/* Opcode: AutoCommit P1 P2 * * *
2394
** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2395
** back any currently active btree transactions. If there are any active
2396
** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2398
** This instruction causes the VM to halt.
2400
case OP_AutoCommit: {
2402
u8 rollback = pOp->p2;
2404
assert( i==1 || i==0 );
2405
assert( i==1 || rollback==0 );
2407
assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
2409
if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2410
/* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2411
** still running, and a transaction is active, return an error indicating
2412
** that the other VMs must complete first.
2414
sqlite3SetString(&p->zErrMsg, db, "cannot %s transaction - "
2415
"SQL statements in progress",
2416
rollback ? "rollback" : "commit");
2418
}else if( i!=db->autoCommit ){
2421
sqlite3RollbackAll(db);
2425
if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2427
db->autoCommit = 1-i;
2428
p->rc = rc = SQLITE_BUSY;
2432
if( p->rc==SQLITE_OK ){
2439
sqlite3SetString(&p->zErrMsg, db,
2440
(!i)?"cannot start a transaction within a transaction":(
2441
(rollback)?"cannot rollback - no transaction is active":
2442
"cannot commit - no transaction is active"));
2449
/* Opcode: Transaction P1 P2 * * *
2451
** Begin a transaction. The transaction ends when a Commit or Rollback
2452
** opcode is encountered. Depending on the ON CONFLICT setting, the
2453
** transaction might also be rolled back if an error is encountered.
2455
** P1 is the index of the database file on which the transaction is
2456
** started. Index 0 is the main database file and index 1 is the
2457
** file used for temporary tables. Indices of 2 or more are used for
2458
** attached databases.
2460
** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
2461
** obtained on the database file when a write-transaction is started. No
2462
** other process can start another write transaction while this transaction is
2463
** underway. Starting a write transaction also creates a rollback journal. A
2464
** write transaction must be started before any changes can be made to the
2465
** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
2468
** If P2 is zero, then a read-lock is obtained on the database file.
2470
case OP_Transaction: {
2474
assert( i>=0 && i<db->nDb );
2475
assert( (p->btreeMask & (1<<i))!=0 );
2476
pBt = db->aDb[i].pBt;
2479
rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
2480
if( rc==SQLITE_BUSY ){
2482
p->rc = rc = SQLITE_BUSY;
2485
if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
2486
goto abort_due_to_error;
2492
/* Opcode: ReadCookie P1 P2 P3 * *
2494
** Read cookie number P3 from database P1 and write it into register P2.
2495
** P3==0 is the schema version. P3==1 is the database format.
2496
** P3==2 is the recommended pager cache size, and so forth. P1==0 is
2497
** the main database file and P1==1 is the database file used to store
2498
** temporary tables.
2500
** If P1 is negative, then this is a request to read the size of a
2501
** databases free-list. P3 must be set to 1 in this case. The actual
2502
** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
2503
** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
2505
** There must be a read-lock on the database (either a transaction
2506
** must be started or there must be an open cursor) before
2507
** executing this instruction.
2509
case OP_ReadCookie: { /* out2-prerelease */
2512
int iCookie = pOp->p3;
2514
assert( pOp->p3<SQLITE_N_BTREE_META );
2519
assert( iDb>=0 && iDb<db->nDb );
2520
assert( db->aDb[iDb].pBt!=0 );
2521
assert( (p->btreeMask & (1<<iDb))!=0 );
2522
/* The indexing of meta values at the schema layer is off by one from
2523
** the indexing in the btree layer. The btree considers meta[0] to
2524
** be the number of free pages in the database (a read-only value)
2525
** and meta[1] to be the schema cookie. The schema layer considers
2526
** meta[1] to be the schema cookie. So we have to shift the index
2527
** by one in the following statement.
2529
rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
2531
MemSetTypeFlag(pOut, MEM_Int);
2535
/* Opcode: SetCookie P1 P2 P3 * *
2537
** Write the content of register P3 (interpreted as an integer)
2538
** into cookie number P2 of database P1.
2539
** P2==0 is the schema version. P2==1 is the database format.
2540
** P2==2 is the recommended pager cache size, and so forth. P1==0 is
2541
** the main database file and P1==1 is the database file used to store
2542
** temporary tables.
2544
** A transaction must be started before executing this opcode.
2546
case OP_SetCookie: { /* in3 */
2548
assert( pOp->p2<SQLITE_N_BTREE_META );
2549
assert( pOp->p1>=0 && pOp->p1<db->nDb );
2550
assert( (p->btreeMask & (1<<pOp->p1))!=0 );
2551
pDb = &db->aDb[pOp->p1];
2552
assert( pDb->pBt!=0 );
2553
sqlite3VdbeMemIntegerify(pIn3);
2554
/* See note about index shifting on OP_ReadCookie */
2555
rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
2557
/* When the schema cookie changes, record the new cookie internally */
2558
pDb->pSchema->schema_cookie = pIn3->u.i;
2559
db->flags |= SQLITE_InternChanges;
2560
}else if( pOp->p2==1 ){
2561
/* Record changes in the file format */
2562
pDb->pSchema->file_format = pIn3->u.i;
2565
/* Invalidate all prepared statements whenever the TEMP database
2566
** schema is changed. Ticket #1644 */
2567
sqlite3ExpirePreparedStatements(db);
2572
/* Opcode: VerifyCookie P1 P2 *
2574
** Check the value of global database parameter number 0 (the
2575
** schema version) and make sure it is equal to P2.
2576
** P1 is the database number which is 0 for the main database file
2577
** and 1 for the file holding temporary tables and some higher number
2578
** for auxiliary databases.
2580
** The cookie changes its value whenever the database schema changes.
2581
** This operation is used to detect when that the cookie has changed
2582
** and that the current process needs to reread the schema.
2584
** Either a transaction needs to have been started or an OP_Open needs
2585
** to be executed (to establish a read lock) before this opcode is
2588
case OP_VerifyCookie: {
2591
assert( pOp->p1>=0 && pOp->p1<db->nDb );
2592
assert( (p->btreeMask & (1<<pOp->p1))!=0 );
2593
pBt = db->aDb[pOp->p1].pBt;
2595
rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
2600
if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
2601
sqlite3DbFree(db, p->zErrMsg);
2602
p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
2603
/* If the schema-cookie from the database file matches the cookie
2604
** stored with the in-memory representation of the schema, do
2605
** not reload the schema from the database file.
2607
** If virtual-tables are in use, this is not just an optimization.
2608
** Often, v-tables store their data in other SQLite tables, which
2609
** are queried from within xNext() and other v-table methods using
2610
** prepared queries. If such a query is out-of-date, we do not want to
2611
** discard the database schema, as the user code implementing the
2612
** v-table would have to be ready for the sqlite3_vtab structure itself
2613
** to be invalidated whenever sqlite3_step() is called from within
2614
** a v-table method.
2616
if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
2617
sqlite3ResetInternalSchema(db, pOp->p1);
2620
sqlite3ExpirePreparedStatements(db);
2626
/* Opcode: OpenRead P1 P2 P3 P4 P5
2628
** Open a read-only cursor for the database table whose root page is
2629
** P2 in a database file. The database file is determined by P3.
2630
** P3==0 means the main database, P3==1 means the database used for
2631
** temporary tables, and P3>1 means used the corresponding attached
2632
** database. Give the new cursor an identifier of P1. The P1
2633
** values need not be contiguous but all P1 values should be small integers.
2634
** It is an error for P1 to be negative.
2636
** If P5!=0 then use the content of register P2 as the root page, not
2637
** the value of P2 itself.
2639
** There will be a read lock on the database whenever there is an
2640
** open cursor. If the database was unlocked prior to this instruction
2641
** then a read lock is acquired as part of this instruction. A read
2642
** lock allows other processes to read the database but prohibits
2643
** any other process from modifying the database. The read lock is
2644
** released when all cursors are closed. If this instruction attempts
2645
** to get a read lock but fails, the script terminates with an
2646
** SQLITE_BUSY error code.
2648
** The P4 value is a pointer to a KeyInfo structure that defines the
2649
** content and collating sequence of indices. P4 is NULL for cursors
2650
** that are not pointing to indices.
2652
** See also OpenWrite.
2654
/* Opcode: OpenWrite P1 P2 P3 P4 P5
2656
** Open a read/write cursor named P1 on the table or index whose root
2657
** page is P2. Or if P5!=0 use the content of register P2 to find the
2660
** The P4 value is a pointer to a KeyInfo structure that defines the
2661
** content and collating sequence of indices. P4 is NULL for cursors
2662
** that are not pointing to indices.
2664
** This instruction works just like OpenRead except that it opens the cursor
2665
** in read/write mode. For a given table, there can be one or more read-only
2666
** cursors or a single read/write cursor but not both.
2668
** See also OpenRead.
2671
case OP_OpenWrite: {
2680
assert( iDb>=0 && iDb<db->nDb );
2681
assert( (p->btreeMask & (1<<iDb))!=0 );
2682
pDb = &db->aDb[iDb];
2685
if( pOp->opcode==OP_OpenWrite ){
2687
if( pDb->pSchema->file_format < p->minWriteFileFormat ){
2688
p->minWriteFileFormat = pDb->pSchema->file_format;
2695
assert( p2<=p->nMem );
2696
pIn2 = &p->aMem[p2];
2697
sqlite3VdbeMemIntegerify(pIn2);
2702
pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
2703
if( pCur==0 ) goto no_mem;
2705
rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
2706
if( pOp->p4type==P4_KEYINFO ){
2707
pCur->pKeyInfo = pOp->p4.pKeyInfo;
2708
pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
2709
pCur->pKeyInfo->enc = ENC(p->db);
2712
pCur->pIncrKey = &pCur->bogusIncrKey;
2717
p->rc = rc = SQLITE_BUSY;
2721
int flags = sqlite3BtreeFlags(pCur->pCursor);
2722
/* Sanity checking. Only the lower four bits of the flags byte should
2723
** be used. Bit 3 (mask 0x08) is unpredictable. The lower 3 bits
2724
** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
2725
** 2 (zerodata for indices). If these conditions are not met it can
2726
** only mean that we are dealing with a corrupt database file
2728
if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
2729
rc = SQLITE_CORRUPT_BKPT;
2730
goto abort_due_to_error;
2732
pCur->isTable = (flags & BTREE_INTKEY)!=0;
2733
pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
2734
/* If P4==0 it means we are expected to open a table. If P4!=0 then
2735
** we expect to be opening an index. If this is not what happened,
2736
** then the database is corrupt
2738
if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
2739
|| (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
2740
rc = SQLITE_CORRUPT_BKPT;
2741
goto abort_due_to_error;
2745
case SQLITE_EMPTY: {
2746
pCur->isTable = pOp->p4type!=P4_KEYINFO;
2747
pCur->isIndex = !pCur->isTable;
2753
goto abort_due_to_error;
2759
/* Opcode: OpenEphemeral P1 P2 * P4 *
2761
** Open a new cursor P1 to a transient table.
2762
** The cursor is always opened read/write even if
2763
** the main database is read-only. The transient or virtual
2764
** table is deleted automatically when the cursor is closed.
2766
** P2 is the number of columns in the virtual table.
2767
** The cursor points to a BTree table if P4==0 and to a BTree index
2768
** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
2769
** that defines the format of keys in the index.
2771
** This opcode was once called OpenTemp. But that created
2772
** confusion because the term "temp table", might refer either
2773
** to a TEMP table at the SQL level, or to a table opened by
2774
** this opcode. Then this opcode was call OpenVirtual. But
2775
** that created confusion with the whole virtual-table idea.
2777
case OP_OpenEphemeral: {
2780
static const int openFlags =
2781
SQLITE_OPEN_READWRITE |
2782
SQLITE_OPEN_CREATE |
2783
SQLITE_OPEN_EXCLUSIVE |
2784
SQLITE_OPEN_DELETEONCLOSE |
2785
SQLITE_OPEN_TRANSIENT_DB;
2788
pCx = allocateCursor(p, i, pOp, -1, 1);
2789
if( pCx==0 ) goto no_mem;
2791
rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
2793
if( rc==SQLITE_OK ){
2794
rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
2796
if( rc==SQLITE_OK ){
2797
/* If a transient index is required, create it by calling
2798
** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
2799
** opening it. If a transient table is required, just use the
2800
** automatically created table with root-page 1 (an INTKEY table).
2802
if( pOp->p4.pKeyInfo ){
2804
assert( pOp->p4type==P4_KEYINFO );
2805
rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
2806
if( rc==SQLITE_OK ){
2807
assert( pgno==MASTER_ROOT+1 );
2808
rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1,
2809
(KeyInfo*)pOp->p4.z, pCx->pCursor);
2810
pCx->pKeyInfo = pOp->p4.pKeyInfo;
2811
pCx->pKeyInfo->enc = ENC(p->db);
2812
pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
2816
rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
2818
pCx->pIncrKey = &pCx->bogusIncrKey;
2821
pCx->isIndex = !pCx->isTable;
2825
/* Opcode: OpenPseudo P1 P2 * * *
2827
** Open a new cursor that points to a fake table that contains a single
2828
** row of data. Any attempt to write a second row of data causes the
2829
** first row to be deleted. All data is deleted when the cursor is
2832
** A pseudo-table created by this opcode is useful for holding the
2833
** NEW or OLD tables in a trigger. Also used to hold the a single
2834
** row output from the sorter so that the row can be decomposed into
2835
** individual columns using the OP_Column opcode.
2837
** When OP_Insert is executed to insert a row in to the pseudo table,
2838
** the pseudo-table cursor may or may not make it's own copy of the
2839
** original row data. If P2 is 0, then the pseudo-table will copy the
2840
** original row data. Otherwise, a pointer to the original memory cell
2841
** is stored. In this case, the vdbe program must ensure that the
2842
** memory cell containing the row data is not overwritten until the
2843
** pseudo table is closed (or a new row is inserted into it).
2845
case OP_OpenPseudo: {
2849
pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
2850
if( pCx==0 ) goto no_mem;
2852
pCx->pseudoTable = 1;
2853
pCx->ephemPseudoTable = pOp->p2;
2854
pCx->pIncrKey = &pCx->bogusIncrKey;
2860
/* Opcode: Close P1 * * * *
2862
** Close a cursor previously opened as P1. If P1 is not
2863
** currently open, this instruction is a no-op.
2867
assert( i>=0 && i<p->nCursor );
2868
sqlite3VdbeFreeCursor(p, p->apCsr[i]);
2873
/* Opcode: MoveGe P1 P2 P3 P4 *
2875
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
2876
** use the integer value in register P3 as a key. If cursor P1 refers
2877
** to an SQL index, then P3 is the first in an array of P4 registers
2878
** that are used as an unpacked index key.
2880
** Reposition cursor P1 so that it points to the smallest entry that
2881
** is greater than or equal to the key value. If there are no records
2882
** greater than or equal to the key and P2 is not zero, then jump to P2.
2884
** A special feature of this opcode (and different from the
2885
** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
2886
** zero and P1 is an SQL table (a b-tree with integer keys) then
2887
** the seek is deferred until it is actually needed. It might be
2888
** the case that the cursor is never accessed. By deferring the
2889
** seek, we avoid unnecessary seeks.
2891
** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
2893
/* Opcode: MoveGt P1 P2 P3 P4 *
2895
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
2896
** use the integer value in register P3 as a key. If cursor P1 refers
2897
** to an SQL index, then P3 is the first in an array of P4 registers
2898
** that are used as an unpacked index key.
2900
** Reposition cursor P1 so that it points to the smallest entry that
2901
** is greater than the key value. If there are no records greater than
2902
** the key and P2 is not zero, then jump to P2.
2904
** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
2906
/* Opcode: MoveLt P1 P2 P3 P4 *
2908
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
2909
** use the integer value in register P3 as a key. If cursor P1 refers
2910
** to an SQL index, then P3 is the first in an array of P4 registers
2911
** that are used as an unpacked index key.
2913
** Reposition cursor P1 so that it points to the largest entry that
2914
** is less than the key value. If there are no records less than
2915
** the key and P2 is not zero, then jump to P2.
2917
** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
2919
/* Opcode: MoveLe P1 P2 P3 P4 *
2921
** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
2922
** use the integer value in register P3 as a key. If cursor P1 refers
2923
** to an SQL index, then P3 is the first in an array of P4 registers
2924
** that are used as an unpacked index key.
2926
** Reposition cursor P1 so that it points to the largest entry that
2927
** is less than or equal to the key value. If there are no records
2928
** less than or equal to the key and P2 is not zero, then jump to P2.
2930
** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
2932
case OP_MoveLt: /* jump, in3 */
2933
case OP_MoveLe: /* jump, in3 */
2934
case OP_MoveGe: /* jump, in3 */
2935
case OP_MoveGt: { /* jump, in3 */
2939
assert( i>=0 && i<p->nCursor );
2942
if( pC->pCursor!=0 ){
2946
*pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
2948
i64 iKey = sqlite3VdbeIntValue(pIn3);
2950
assert( pOp->opcode==OP_MoveGe );
2951
pC->movetoTarget = iKey;
2952
pC->rowidIsValid = 0;
2953
pC->deferredMoveto = 1;
2956
rc = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)iKey, 0, &res);
2957
if( rc!=SQLITE_OK ){
2958
goto abort_due_to_error;
2960
pC->lastRowid = iKey;
2961
pC->rowidIsValid = res==0;
2964
int nField = pOp->p4.i;
2965
assert( pOp->p4type==P4_INT32 );
2967
r.pKeyInfo = pC->pKeyInfo;
2971
r.aMem = &p->aMem[pOp->p3];
2972
rc = sqlite3BtreeMoveto(pC->pCursor, 0, &r, 0, 0, &res);
2973
if( rc!=SQLITE_OK ){
2974
goto abort_due_to_error;
2976
pC->rowidIsValid = 0;
2978
pC->deferredMoveto = 0;
2979
pC->cacheStatus = CACHE_STALE;
2982
sqlite3_search_count++;
2984
if( oc==OP_MoveGe || oc==OP_MoveGt ){
2986
rc = sqlite3BtreeNext(pC->pCursor, &res);
2987
if( rc!=SQLITE_OK ) goto abort_due_to_error;
2988
pC->rowidIsValid = 0;
2993
assert( oc==OP_MoveLt || oc==OP_MoveLe );
2995
rc = sqlite3BtreePrevious(pC->pCursor, &res);
2996
if( rc!=SQLITE_OK ) goto abort_due_to_error;
2997
pC->rowidIsValid = 0;
2999
/* res might be negative because the table is empty. Check to
3000
** see if this is the case.
3002
res = sqlite3BtreeEof(pC->pCursor);
3005
assert( pOp->p2>0 );
3009
}else if( !pC->pseudoTable ){
3010
/* This happens when attempting to open the sqlite3_master table
3011
** for read access returns SQLITE_EMPTY. In this case always
3012
** take the jump (since there are no records in the table).
3019
/* Opcode: Found P1 P2 P3 * *
3021
** Register P3 holds a blob constructed by MakeRecord. P1 is an index.
3022
** If an entry that matches the value in register p3 exists in P1 then
3023
** jump to P2. If the P3 value does not match any entry in P1
3024
** then fall thru. The P1 cursor is left pointing at the matching entry
3027
** This instruction is used to implement the IN operator where the
3028
** left-hand side is a SELECT statement. P1 may be a true index, or it
3029
** may be a temporary index that holds the results of the SELECT
3030
** statement. This instruction is also used to implement the
3031
** DISTINCT keyword in SELECT statements.
3033
** This instruction checks if index P1 contains a record for which
3034
** the first N serialized values exactly match the N serialized values
3035
** in the record in register P3, where N is the total number of values in
3036
** the P3 record (the P3 record is a prefix of the P1 record).
3038
** See also: NotFound, MoveTo, IsUnique, NotExists
3040
/* Opcode: NotFound P1 P2 P3 * *
3042
** Register P3 holds a blob constructed by MakeRecord. P1 is
3043
** an index. If no entry exists in P1 that matches the blob then jump
3044
** to P2. If an entry does existing, fall through. The cursor is left
3045
** pointing to the entry that matches.
3047
** See also: Found, MoveTo, NotExists, IsUnique
3049
case OP_NotFound: /* jump, in3 */
3050
case OP_Found: { /* jump, in3 */
3052
int alreadyExists = 0;
3054
assert( i>=0 && i<p->nCursor );
3055
assert( p->apCsr[i]!=0 );
3056
if( (pC = p->apCsr[i])->pCursor!=0 ){
3058
assert( pC->isTable==0 );
3059
assert( pIn3->flags & MEM_Blob );
3060
if( pOp->opcode==OP_Found ){
3061
pC->pKeyInfo->prefixIsEqual = 1;
3063
rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, 0, pIn3->n, 0, &res);
3064
pC->pKeyInfo->prefixIsEqual = 0;
3065
if( rc!=SQLITE_OK ){
3068
alreadyExists = (res==0);
3069
pC->deferredMoveto = 0;
3070
pC->cacheStatus = CACHE_STALE;
3072
if( pOp->opcode==OP_Found ){
3073
if( alreadyExists ) pc = pOp->p2 - 1;
3075
if( !alreadyExists ) pc = pOp->p2 - 1;
3080
/* Opcode: IsUnique P1 P2 P3 P4 *
3082
** The P3 register contains an integer record number. Call this
3083
** record number R. The P4 register contains an index key created
3084
** using MakeIdxRec. Call it K.
3086
** P1 is an index. So it has no data and its key consists of a
3087
** record generated by OP_MakeRecord where the last field is the
3088
** rowid of the entry that the index refers to.
3090
** This instruction asks if there is an entry in P1 where the
3091
** fields matches K but the rowid is different from R.
3092
** If there is no such entry, then there is an immediate
3093
** jump to P2. If any entry does exist where the index string
3094
** matches K but the record number is not R, then the record
3095
** number for that entry is written into P3 and control
3096
** falls through to the next instruction.
3098
** See also: NotFound, NotExists, Found
3100
case OP_IsUnique: { /* jump, in3 */
3107
/* Pop the value R off the top of the stack
3109
assert( pOp->p4type==P4_INT32 );
3110
assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
3111
pK = &p->aMem[pOp->p4.i];
3112
sqlite3VdbeMemIntegerify(pIn3);
3114
assert( i>=0 && i<p->nCursor );
3117
pCrsr = pCx->pCursor;
3120
i64 v; /* The record number on the P1 entry that matches K */
3121
char *zKey; /* The value of K */
3122
int nKey; /* Number of bytes in K */
3123
int len; /* Number of bytes in K without the rowid at the end */
3124
int szRowid; /* Size of the rowid column at the end of zKey */
3126
/* Make sure K is a string and make zKey point to K
3128
assert( pK->flags & MEM_Blob );
3132
/* sqlite3VdbeIdxRowidLen() only returns other than SQLITE_OK when the
3133
** record passed as an argument corrupt. Since the record in this case
3134
** has just been created by an OP_MakeRecord instruction, and not loaded
3135
** from the database file, it is not possible for it to be corrupt.
3136
** Therefore, assert(rc==SQLITE_OK).
3138
rc = sqlite3VdbeIdxRowidLen((u8*)zKey, nKey, &szRowid);
3139
assert(rc==SQLITE_OK);
3142
/* Search for an entry in P1 where all but the last four bytes match K.
3143
** If there is no such entry, jump immediately to P2.
3145
assert( pCx->deferredMoveto==0 );
3146
pCx->cacheStatus = CACHE_STALE;
3147
rc = sqlite3BtreeMoveto(pCrsr, zKey, 0, len, 0, &res);
3148
if( rc!=SQLITE_OK ){
3149
goto abort_due_to_error;
3152
rc = sqlite3BtreeNext(pCrsr, &res);
3158
rc = sqlite3VdbeIdxKeyCompare(pCx, 0, len, (u8*)zKey, &res);
3159
if( rc!=SQLITE_OK ) goto abort_due_to_error;
3165
/* At this point, pCrsr is pointing to an entry in P1 where all but
3166
** the final entry (the rowid) matches K. Check to see if the
3167
** final rowid column is different from R. If it equals R then jump
3168
** immediately to P2.
3170
rc = sqlite3VdbeIdxRowid(pCrsr, &v);
3171
if( rc!=SQLITE_OK ){
3172
goto abort_due_to_error;
3179
/* The final varint of the key is different from R. Store it back
3180
** into register R3. (The record number of an entry that violates
3181
** a UNIQUE constraint.)
3184
assert( pIn3->flags&MEM_Int );
3189
/* Opcode: NotExists P1 P2 P3 * *
3191
** Use the content of register P3 as a integer key. If a record
3192
** with that key does not exist in table of P1, then jump to P2.
3193
** If the record does exist, then fall thru. The cursor is left
3194
** pointing to the record if it exists.
3196
** The difference between this operation and NotFound is that this
3197
** operation assumes the key is an integer and that P1 is a table whereas
3198
** NotFound assumes key is a blob constructed from MakeRecord and
3201
** See also: Found, MoveTo, NotFound, IsUnique
3203
case OP_NotExists: { /* jump, in3 */
3207
assert( i>=0 && i<p->nCursor );
3208
assert( p->apCsr[i]!=0 );
3209
if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3212
assert( pIn3->flags & MEM_Int );
3213
assert( p->apCsr[i]->isTable );
3214
iKey = intToKey(pIn3->u.i);
3215
rc = sqlite3BtreeMoveto(pCrsr, 0, 0, iKey, 0,&res);
3216
pC->lastRowid = pIn3->u.i;
3217
pC->rowidIsValid = res==0;
3219
pC->cacheStatus = CACHE_STALE;
3220
/* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
3221
** processing is about to abort so we really do not care whether or not
3222
** the following jump is taken. (In other words, do not stress over
3223
** the error that valgrind sometimes shows on the next statement when
3224
** running ioerr.test and similar failure-recovery test scripts.) */
3227
assert( pC->rowidIsValid==0 );
3229
}else if( !pC->pseudoTable ){
3230
/* This happens when an attempt to open a read cursor on the
3231
** sqlite_master table returns SQLITE_EMPTY.
3233
assert( pC->isTable );
3235
assert( pC->rowidIsValid==0 );
3240
/* Opcode: Sequence P1 P2 * * *
3242
** Find the next available sequence number for cursor P1.
3243
** Write the sequence number into register P2.
3244
** The sequence number on the cursor is incremented after this
3247
case OP_Sequence: { /* out2-prerelease */
3249
assert( i>=0 && i<p->nCursor );
3250
assert( p->apCsr[i]!=0 );
3251
pOut->u.i = p->apCsr[i]->seqCount++;
3252
MemSetTypeFlag(pOut, MEM_Int);
3257
/* Opcode: NewRowid P1 P2 P3 * *
3259
** Get a new integer record number (a.k.a "rowid") used as the key to a table.
3260
** The record number is not previously used as a key in the database
3261
** table that cursor P1 points to. The new record number is written
3262
** written to register P2.
3264
** If P3>0 then P3 is a register that holds the largest previously
3265
** generated record number. No new record numbers are allowed to be less
3266
** than this value. When this value reaches its maximum, a SQLITE_FULL
3267
** error is generated. The P3 register is updated with the generated
3268
** record number. This P3 mechanism is used to help implement the
3269
** AUTOINCREMENT feature.
3271
case OP_NewRowid: { /* out2-prerelease */
3275
assert( i>=0 && i<p->nCursor );
3276
assert( p->apCsr[i]!=0 );
3277
if( (pC = p->apCsr[i])->pCursor==0 ){
3278
/* The zero initialization above is all that is needed */
3280
/* The next rowid or record number (different terms for the same
3281
** thing) is obtained in a two-step algorithm.
3283
** First we attempt to find the largest existing rowid and add one
3284
** to that. But if the largest existing rowid is already the maximum
3285
** positive integer, we have to fall through to the second
3286
** probabilistic algorithm
3288
** The second algorithm is to select a rowid at random and see if
3289
** it already exists in the table. If it does not exist, we have
3290
** succeeded. If the random rowid does exist, we select a new one
3291
** and try again, up to 1000 times.
3293
** For a table with less than 2 billion entries, the probability
3294
** of not finding a unused rowid is about 1.0e-300. This is a
3295
** non-zero probability, but it is still vanishingly small and should
3296
** never cause a problem. You are much, much more likely to have a
3297
** hardware failure than for this algorithm to fail.
3299
** The analysis in the previous paragraph assumes that you have a good
3300
** source of random numbers. Is a library function like lrand48()
3301
** good enough? Maybe. Maybe not. It's hard to know whether there
3302
** might be subtle bugs is some implementations of lrand48() that
3303
** could cause problems. To avoid uncertainty, SQLite uses its own
3304
** random number generator based on the RC4 algorithm.
3306
** To promote locality of reference for repetitive inserts, the
3307
** first few attempts at choosing a random rowid pick values just a little
3308
** larger than the previous rowid. This has been shown experimentally
3309
** to double the speed of the COPY operation.
3311
int res, rx=SQLITE_OK, cnt;
3314
if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
3316
rc = SQLITE_CORRUPT_BKPT;
3317
goto abort_due_to_error;
3319
assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
3320
assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
3322
#ifdef SQLITE_32BIT_ROWID
3323
# define MAX_ROWID 0x7fffffff
3325
/* Some compilers complain about constants of the form 0x7fffffffffffffff.
3326
** Others complain about 0x7ffffffffffffffffLL. The following macro seems
3327
** to provide the constant while making all compilers happy.
3329
# define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
3332
if( !pC->useRandomRowid ){
3333
if( pC->nextRowidValid ){
3336
rc = sqlite3BtreeLast(pC->pCursor, &res);
3337
if( rc!=SQLITE_OK ){
3338
goto abort_due_to_error;
3343
sqlite3BtreeKeySize(pC->pCursor, &v);
3346
pC->useRandomRowid = 1;
3353
#ifndef SQLITE_OMIT_AUTOINCREMENT
3356
assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
3357
pMem = &p->aMem[pOp->p3];
3358
REGISTER_TRACE(pOp->p3, pMem);
3359
sqlite3VdbeMemIntegerify(pMem);
3360
assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
3361
if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
3363
goto abort_due_to_error;
3365
if( v<pMem->u.i+1 ){
3373
pC->nextRowidValid = 1;
3374
pC->nextRowid = v+1;
3376
pC->nextRowidValid = 0;
3379
if( pC->useRandomRowid ){
3380
assert( pOp->p3==0 ); /* SQLITE_FULL must have occurred prior to this */
3381
v = db->priorNewRowid;
3384
if( cnt==0 && (v&0xffffff)==v ){
3387
sqlite3_randomness(sizeof(v), &v);
3388
if( cnt<5 ) v &= 0xffffff;
3390
if( v==0 ) continue;
3392
rx = sqlite3BtreeMoveto(pC->pCursor, 0, 0, (u64)x, 0, &res);
3394
}while( cnt<100 && rx==SQLITE_OK && res==0 );
3395
db->priorNewRowid = v;
3396
if( rx==SQLITE_OK && res==0 ){
3398
goto abort_due_to_error;
3401
pC->rowidIsValid = 0;
3402
pC->deferredMoveto = 0;
3403
pC->cacheStatus = CACHE_STALE;
3405
MemSetTypeFlag(pOut, MEM_Int);
3410
/* Opcode: Insert P1 P2 P3 P4 P5
3412
** Write an entry into the table of cursor P1. A new entry is
3413
** created if it doesn't already exist or the data for an existing
3414
** entry is overwritten. The data is the value stored register
3415
** number P2. The key is stored in register P3. The key must
3418
** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
3419
** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
3420
** then rowid is stored for subsequent return by the
3421
** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
3423
** Parameter P4 may point to a string containing the table-name, or
3424
** may be NULL. If it is not NULL, then the update-hook
3425
** (sqlite3.xUpdateCallback) is invoked following a successful insert.
3427
** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
3428
** allocated, then ownership of P2 is transferred to the pseudo-cursor
3429
** and register P2 becomes ephemeral. If the cursor is changed, the
3430
** value of register P2 will then change. Make sure this does not
3431
** cause any problems.)
3433
** This instruction only works on tables. The equivalent instruction
3434
** for indices is OP_IdxInsert.
3437
Mem *pData = &p->aMem[pOp->p2];
3438
Mem *pKey = &p->aMem[pOp->p3];
3440
i64 iKey; /* The integer ROWID or key for the record to be inserted */
3443
assert( i>=0 && i<p->nCursor );
3446
assert( pC->pCursor!=0 || pC->pseudoTable );
3447
assert( pKey->flags & MEM_Int );
3448
assert( pC->isTable );
3449
REGISTER_TRACE(pOp->p2, pData);
3450
REGISTER_TRACE(pOp->p3, pKey);
3452
iKey = intToKey(pKey->u.i);
3453
if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
3454
if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
3455
if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
3456
pC->nextRowidValid = 0;
3458
if( pData->flags & MEM_Null ){
3462
assert( pData->flags & (MEM_Blob|MEM_Str) );
3464
if( pC->pseudoTable ){
3465
if( !pC->ephemPseudoTable ){
3466
sqlite3DbFree(db, pC->pData);
3469
pC->nData = pData->n;
3470
if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
3471
pC->pData = pData->z;
3472
if( !pC->ephemPseudoTable ){
3473
pData->flags &= ~MEM_Dyn;
3474
pData->flags |= MEM_Ephem;
3478
pC->pData = sqlite3Malloc( pC->nData+2 );
3479
if( !pC->pData ) goto no_mem;
3480
memcpy(pC->pData, pData->z, pC->nData);
3481
pC->pData[pC->nData] = 0;
3482
pC->pData[pC->nData+1] = 0;
3487
if( pData->flags & MEM_Zero ){
3492
rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
3493
pData->z, pData->n, nZero,
3494
pOp->p5 & OPFLAG_APPEND);
3497
pC->rowidIsValid = 0;
3498
pC->deferredMoveto = 0;
3499
pC->cacheStatus = CACHE_STALE;
3501
/* Invoke the update-hook if required. */
3502
if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
3503
const char *zDb = db->aDb[pC->iDb].zName;
3504
const char *zTbl = pOp->p4.z;
3505
int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
3506
assert( pC->isTable );
3507
db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
3508
assert( pC->iDb>=0 );
3513
/* Opcode: Delete P1 P2 * P4 *
3515
** Delete the record at which the P1 cursor is currently pointing.
3517
** The cursor will be left pointing at either the next or the previous
3518
** record in the table. If it is left pointing at the next record, then
3519
** the next Next instruction will be a no-op. Hence it is OK to delete
3520
** a record from within an Next loop.
3522
** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
3523
** incremented (otherwise not).
3525
** P1 must not be pseudo-table. It has to be a real table with
3528
** If P4 is not NULL, then it is the name of the table that P1 is
3529
** pointing to. The update hook will be invoked, if it exists.
3530
** If P4 is not NULL then the P1 cursor must have been positioned
3531
** using OP_NotFound prior to invoking this opcode.
3538
assert( i>=0 && i<p->nCursor );
3541
assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
3543
/* If the update-hook will be invoked, set iKey to the rowid of the
3544
** row being deleted.
3546
if( db->xUpdateCallback && pOp->p4.z ){
3547
assert( pC->isTable );
3548
assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
3549
iKey = pC->lastRowid;
3552
rc = sqlite3VdbeCursorMoveto(pC);
3553
if( rc ) goto abort_due_to_error;
3554
rc = sqlite3BtreeDelete(pC->pCursor);
3555
pC->nextRowidValid = 0;
3556
pC->cacheStatus = CACHE_STALE;
3558
/* Invoke the update-hook if required. */
3559
if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
3560
const char *zDb = db->aDb[pC->iDb].zName;
3561
const char *zTbl = pOp->p4.z;
3562
db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
3563
assert( pC->iDb>=0 );
3565
if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
3569
/* Opcode: ResetCount P1 * *
3571
** This opcode resets the VMs internal change counter to 0. If P1 is true,
3572
** then the value of the change counter is copied to the database handle
3573
** change counter (returned by subsequent calls to sqlite3_changes())
3574
** before it is reset. This is used by trigger programs.
3576
case OP_ResetCount: {
3578
sqlite3VdbeSetChanges(db, p->nChange);
3584
/* Opcode: RowData P1 P2 * * *
3586
** Write into register P2 the complete row data for cursor P1.
3587
** There is no interpretation of the data.
3588
** It is just copied onto the P2 register exactly as
3589
** it is found in the database file.
3591
** If the P1 cursor must be pointing to a valid row (not a NULL row)
3592
** of a real table, not a pseudo-table.
3594
/* Opcode: RowKey P1 P2 * * *
3596
** Write into register P2 the complete row key for cursor P1.
3597
** There is no interpretation of the data.
3598
** The key is copied onto the P3 register exactly as
3599
** it is found in the database file.
3601
** If the P1 cursor must be pointing to a valid row (not a NULL row)
3602
** of a real table, not a pseudo-table.
3611
pOut = &p->aMem[pOp->p2];
3613
/* Note that RowKey and RowData are really exactly the same instruction */
3614
assert( i>=0 && i<p->nCursor );
3616
assert( pC->isTable || pOp->opcode==OP_RowKey );
3617
assert( pC->isIndex || pOp->opcode==OP_RowData );
3619
assert( pC->nullRow==0 );
3620
assert( pC->pseudoTable==0 );
3621
assert( pC->pCursor!=0 );
3622
pCrsr = pC->pCursor;
3623
rc = sqlite3VdbeCursorMoveto(pC);
3624
if( rc ) goto abort_due_to_error;
3627
assert( !pC->isTable );
3628
sqlite3BtreeKeySize(pCrsr, &n64);
3629
if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3634
sqlite3BtreeDataSize(pCrsr, &n);
3635
if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
3639
if( sqlite3VdbeMemGrow(pOut, n, 0) ){
3643
MemSetTypeFlag(pOut, MEM_Blob);
3645
rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
3647
rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
3649
pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
3650
UPDATE_MAX_BLOBSIZE(pOut);
3654
/* Opcode: Rowid P1 P2 * * *
3656
** Store in register P2 an integer which is the key of the table entry that
3657
** P1 is currently point to.
3659
case OP_Rowid: { /* out2-prerelease */
3664
assert( i>=0 && i<p->nCursor );
3667
rc = sqlite3VdbeCursorMoveto(pC);
3668
if( rc ) goto abort_due_to_error;
3669
if( pC->rowidIsValid ){
3671
}else if( pC->pseudoTable ){
3672
v = keyToInt(pC->iKey);
3673
}else if( pC->nullRow ){
3674
/* Leave the rowid set to a NULL */
3677
assert( pC->pCursor!=0 );
3678
sqlite3BtreeKeySize(pC->pCursor, &v);
3682
MemSetTypeFlag(pOut, MEM_Int);
3686
/* Opcode: NullRow P1 * * * *
3688
** Move the cursor P1 to a null row. Any OP_Column operations
3689
** that occur while the cursor is on the null row will always
3696
assert( i>=0 && i<p->nCursor );
3700
pC->rowidIsValid = 0;
3704
/* Opcode: Last P1 P2 * * *
3706
** The next use of the Rowid or Column or Next instruction for P1
3707
** will refer to the last entry in the database table or index.
3708
** If the table or index is empty and P2>0, then jump immediately to P2.
3709
** If P2 is 0 or if the table or index is not empty, fall through
3710
** to the following instruction.
3712
case OP_Last: { /* jump */
3718
assert( i>=0 && i<p->nCursor );
3721
pCrsr = pC->pCursor;
3723
rc = sqlite3BtreeLast(pCrsr, &res);
3725
pC->deferredMoveto = 0;
3726
pC->cacheStatus = CACHE_STALE;
3727
if( res && pOp->p2>0 ){
3734
/* Opcode: Sort P1 P2 * * *
3736
** This opcode does exactly the same thing as OP_Rewind except that
3737
** it increments an undocumented global variable used for testing.
3739
** Sorting is accomplished by writing records into a sorting index,
3740
** then rewinding that index and playing it back from beginning to
3741
** end. We use the OP_Sort opcode instead of OP_Rewind to do the
3742
** rewinding so that the global variable will be incremented and
3743
** regression tests can determine whether or not the optimizer is
3744
** correctly optimizing out sorts.
3746
case OP_Sort: { /* jump */
3748
sqlite3_sort_count++;
3749
sqlite3_search_count--;
3751
/* Fall through into OP_Rewind */
3753
/* Opcode: Rewind P1 P2 * * *
3755
** The next use of the Rowid or Column or Next instruction for P1
3756
** will refer to the first entry in the database table or index.
3757
** If the table or index is empty and P2>0, then jump immediately to P2.
3758
** If P2 is 0 or if the table or index is not empty, fall through
3759
** to the following instruction.
3761
case OP_Rewind: { /* jump */
3767
assert( i>=0 && i<p->nCursor );
3770
if( (pCrsr = pC->pCursor)!=0 ){
3771
rc = sqlite3BtreeFirst(pCrsr, &res);
3772
pC->atFirst = res==0;
3773
pC->deferredMoveto = 0;
3774
pC->cacheStatus = CACHE_STALE;
3779
assert( pOp->p2>0 && pOp->p2<p->nOp );
3786
/* Opcode: Next P1 P2 * * *
3788
** Advance cursor P1 so that it points to the next key/data pair in its
3789
** table or index. If there are no more key/value pairs then fall through
3790
** to the following instruction. But if the cursor advance was successful,
3791
** jump immediately to P2.
3793
** The P1 cursor must be for a real table, not a pseudo-table.
3797
/* Opcode: Prev P1 P2 * * *
3799
** Back up cursor P1 so that it points to the previous key/data pair in its
3800
** table or index. If there is no previous key/value pairs then fall through
3801
** to the following instruction. But if the cursor backup was successful,
3802
** jump immediately to P2.
3804
** The P1 cursor must be for a real table, not a pseudo-table.
3806
case OP_Prev: /* jump */
3807
case OP_Next: { /* jump */
3812
CHECK_FOR_INTERRUPT;
3813
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
3814
pC = p->apCsr[pOp->p1];
3816
break; /* See ticket #2273 */
3818
pCrsr = pC->pCursor;
3821
assert( pC->deferredMoveto==0 );
3822
rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
3823
sqlite3BtreePrevious(pCrsr, &res);
3825
pC->cacheStatus = CACHE_STALE;
3829
sqlite3_search_count++;
3832
pC->rowidIsValid = 0;
3836
/* Opcode: IdxInsert P1 P2 P3 * *
3838
** Register P2 holds a SQL index key made using the
3839
** MakeIdxRec instructions. This opcode writes that key
3840
** into the index P1. Data for the entry is nil.
3842
** P3 is a flag that provides a hint to the b-tree layer that this
3843
** insert is likely to be an append.
3845
** This instruction only works for indices. The equivalent instruction
3846
** for tables is OP_Insert.
3848
case OP_IdxInsert: { /* in2 */
3852
assert( i>=0 && i<p->nCursor );
3853
assert( p->apCsr[i]!=0 );
3854
assert( pIn2->flags & MEM_Blob );
3855
if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3856
assert( pC->isTable==0 );
3857
rc = ExpandBlob(pIn2);
3858
if( rc==SQLITE_OK ){
3860
const char *zKey = pIn2->z;
3861
rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
3862
assert( pC->deferredMoveto==0 );
3863
pC->cacheStatus = CACHE_STALE;
3869
/* Opcode: IdxDeleteM P1 P2 P3 * *
3871
** The content of P3 registers starting at register P2 form
3872
** an unpacked index key. This opcode removes that entry from the
3873
** index opened by cursor P1.
3875
case OP_IdxDelete: {
3879
assert( pOp->p3>0 );
3880
assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
3881
assert( i>=0 && i<p->nCursor );
3882
assert( p->apCsr[i]!=0 );
3883
if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3886
r.pKeyInfo = pC->pKeyInfo;
3890
r.aMem = &p->aMem[pOp->p2];
3891
rc = sqlite3BtreeMoveto(pCrsr, 0, &r, 0, 0, &res);
3892
if( rc==SQLITE_OK && res==0 ){
3893
rc = sqlite3BtreeDelete(pCrsr);
3895
assert( pC->deferredMoveto==0 );
3896
pC->cacheStatus = CACHE_STALE;
3901
/* Opcode: IdxRowid P1 P2 * * *
3903
** Write into register P2 an integer which is the last entry in the record at
3904
** the end of the index key pointed to by cursor P1. This integer should be
3905
** the rowid of the table entry to which this index entry points.
3907
** See also: Rowid, MakeIdxRec.
3909
case OP_IdxRowid: { /* out2-prerelease */
3914
assert( i>=0 && i<p->nCursor );
3915
assert( p->apCsr[i]!=0 );
3916
if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
3919
assert( pC->deferredMoveto==0 );
3920
assert( pC->isTable==0 );
3922
rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
3923
if( rc!=SQLITE_OK ){
3924
goto abort_due_to_error;
3926
MemSetTypeFlag(pOut, MEM_Int);
3933
/* Opcode: IdxGE P1 P2 P3 P4 P5
3935
** The P4 register values beginning with P3 form an unpacked index
3936
** key that omits the ROWID. Compare this key value against the index
3937
** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
3939
** If the P1 index entry is greater than or equal to the key value
3940
** then jump to P2. Otherwise fall through to the next instruction.
3942
** If P5 is non-zero then the key value is increased by an epsilon
3943
** prior to the comparison. This make the opcode work like IdxGT except
3944
** that if the key from register P3 is a prefix of the key in the cursor,
3945
** the result is false whereas it would be true with IdxGT.
3947
/* Opcode: IdxLT P1 P2 P3 * P5
3949
** The P4 register values beginning with P3 form an unpacked index
3950
** key that omits the ROWID. Compare this key value against the index
3951
** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
3953
** If the P1 index entry is less than the key value then jump to P2.
3954
** Otherwise fall through to the next instruction.
3956
** If P5 is non-zero then the key value is increased by an epsilon prior
3957
** to the comparison. This makes the opcode work like IdxLE.
3959
case OP_IdxLT: /* jump, in3 */
3960
case OP_IdxGE: { /* jump, in3 */
3964
assert( i>=0 && i<p->nCursor );
3965
assert( p->apCsr[i]!=0 );
3966
if( (pC = p->apCsr[i])->pCursor!=0 ){
3969
assert( pC->deferredMoveto==0 );
3970
assert( pOp->p5==0 || pOp->p5==1 );
3971
assert( pOp->p4type==P4_INT32 );
3972
r.pKeyInfo = pC->pKeyInfo;
3973
r.nField = pOp->p4.i;
3976
r.aMem = &p->aMem[pOp->p3];
3977
*pC->pIncrKey = pOp->p5;
3978
rc = sqlite3VdbeIdxKeyCompare(pC, &r, 0, 0, &res);
3980
if( pOp->opcode==OP_IdxLT ){
3983
assert( pOp->opcode==OP_IdxGE );
3993
/* Opcode: Destroy P1 P2 P3 * *
3995
** Delete an entire database table or index whose root page in the database
3996
** file is given by P1.
3998
** The table being destroyed is in the main database file if P3==0. If
3999
** P3==1 then the table to be clear is in the auxiliary database file
4000
** that is used to store tables create using CREATE TEMPORARY TABLE.
4002
** If AUTOVACUUM is enabled then it is possible that another root page
4003
** might be moved into the newly deleted root page in order to keep all
4004
** root pages contiguous at the beginning of the database. The former
4005
** value of the root page that moved - its value before the move occurred -
4006
** is stored in register P2. If no page
4007
** movement was required (because the table being dropped was already
4008
** the last one in the database) then a zero is stored in register P2.
4009
** If AUTOVACUUM is disabled then a zero is stored in register P2.
4013
case OP_Destroy: { /* out2-prerelease */
4016
#ifndef SQLITE_OMIT_VIRTUALTABLE
4019
for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
4020
if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
4025
iCnt = db->activeVdbeCnt;
4029
p->errorAction = OE_Abort;
4033
assert( (p->btreeMask & (1<<iDb))!=0 );
4034
rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
4035
MemSetTypeFlag(pOut, MEM_Int);
4037
#ifndef SQLITE_OMIT_AUTOVACUUM
4038
if( rc==SQLITE_OK && iMoved!=0 ){
4039
sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
4046
/* Opcode: Clear P1 P2 *
4048
** Delete all contents of the database table or index whose root page
4049
** in the database file is given by P1. But, unlike Destroy, do not
4050
** remove the table or index from the database file.
4052
** The table being clear is in the main database file if P2==0. If
4053
** P2==1 then the table to be clear is in the auxiliary database file
4054
** that is used to store tables create using CREATE TEMPORARY TABLE.
4056
** See also: Destroy
4059
assert( (p->btreeMask & (1<<pOp->p2))!=0 );
4060
rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4064
/* Opcode: CreateTable P1 P2 * * *
4066
** Allocate a new table in the main database file if P1==0 or in the
4067
** auxiliary database file if P1==1 or in an attached database if
4068
** P1>1. Write the root page number of the new table into
4071
** The difference between a table and an index is this: A table must
4072
** have a 4-byte integer key and can have arbitrary data. An index
4073
** has an arbitrary key but no data.
4075
** See also: CreateIndex
4077
/* Opcode: CreateIndex P1 P2 * * *
4079
** Allocate a new index in the main database file if P1==0 or in the
4080
** auxiliary database file if P1==1 or in an attached database if
4081
** P1>1. Write the root page number of the new table into
4084
** See documentation on OP_CreateTable for additional information.
4086
case OP_CreateIndex: /* out2-prerelease */
4087
case OP_CreateTable: { /* out2-prerelease */
4091
assert( pOp->p1>=0 && pOp->p1<db->nDb );
4092
assert( (p->btreeMask & (1<<pOp->p1))!=0 );
4093
pDb = &db->aDb[pOp->p1];
4094
assert( pDb->pBt!=0 );
4095
if( pOp->opcode==OP_CreateTable ){
4096
/* flags = BTREE_INTKEY; */
4097
flags = BTREE_LEAFDATA|BTREE_INTKEY;
4099
flags = BTREE_ZERODATA;
4101
rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
4102
if( rc==SQLITE_OK ){
4104
MemSetTypeFlag(pOut, MEM_Int);
4109
/* Opcode: ParseSchema P1 P2 * P4 *
4111
** Read and parse all entries from the SQLITE_MASTER table of database P1
4112
** that match the WHERE clause P4. P2 is the "force" flag. Always do
4113
** the parsing if P2 is true. If P2 is false, then this routine is a
4114
** no-op if the schema is not currently loaded. In other words, if P2
4115
** is false, the SQLITE_MASTER table is only parsed if the rest of the
4116
** schema is already loaded into the symbol table.
4118
** This opcode invokes the parser to create a new virtual machine,
4119
** then runs the new virtual machine. It is thus a re-entrant opcode.
4121
case OP_ParseSchema: {
4124
const char *zMaster;
4127
assert( iDb>=0 && iDb<db->nDb );
4128
if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
4131
zMaster = SCHEMA_TABLE(iDb);
4133
initData.iDb = pOp->p1;
4134
initData.pzErrMsg = &p->zErrMsg;
4135
zSql = sqlite3MPrintf(db,
4136
"SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
4137
db->aDb[iDb].zName, zMaster, pOp->p4.z);
4138
if( zSql==0 ) goto no_mem;
4139
(void)sqlite3SafetyOff(db);
4140
assert( db->init.busy==0 );
4142
assert( !db->mallocFailed );
4143
rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
4144
if( rc==SQLITE_ABORT ) rc = initData.rc;
4145
sqlite3DbFree(db, zSql);
4147
(void)sqlite3SafetyOn(db);
4148
if( rc==SQLITE_NOMEM ){
4154
#if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
4155
/* Opcode: LoadAnalysis P1 * * * *
4157
** Read the sqlite_stat1 table for database P1 and load the content
4158
** of that table into the internal index hash table. This will cause
4159
** the analysis to be used when preparing all subsequent queries.
4161
case OP_LoadAnalysis: {
4163
assert( iDb>=0 && iDb<db->nDb );
4164
rc = sqlite3AnalysisLoad(db, iDb);
4167
#endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
4169
/* Opcode: DropTable P1 * * P4 *
4171
** Remove the internal (in-memory) data structures that describe
4172
** the table named P4 in database P1. This is called after a table
4173
** is dropped in order to keep the internal representation of the
4174
** schema consistent with what is on disk.
4176
case OP_DropTable: {
4177
sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
4181
/* Opcode: DropIndex P1 * * P4 *
4183
** Remove the internal (in-memory) data structures that describe
4184
** the index named P4 in database P1. This is called after an index
4185
** is dropped in order to keep the internal representation of the
4186
** schema consistent with what is on disk.
4188
case OP_DropIndex: {
4189
sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
4193
/* Opcode: DropTrigger P1 * * P4 *
4195
** Remove the internal (in-memory) data structures that describe
4196
** the trigger named P4 in database P1. This is called after a trigger
4197
** is dropped in order to keep the internal representation of the
4198
** schema consistent with what is on disk.
4200
case OP_DropTrigger: {
4201
sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
4206
#ifndef SQLITE_OMIT_INTEGRITY_CHECK
4207
/* Opcode: IntegrityCk P1 P2 P3 * P5
4209
** Do an analysis of the currently open database. Store in
4210
** register P1 the text of an error message describing any problems.
4211
** If no problems are found, store a NULL in register P1.
4213
** The register P3 contains the maximum number of allowed errors.
4214
** At most reg(P3) errors will be reported.
4215
** In other words, the analysis stops as soon as reg(P1) errors are
4216
** seen. Reg(P1) is updated with the number of errors remaining.
4218
** The root page numbers of all tables in the database are integer
4219
** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
4222
** If P5 is not zero, the check is done on the auxiliary database
4223
** file, not the main database file.
4225
** This opcode is used to implement the integrity_check pragma.
4227
case OP_IntegrityCk: {
4228
int nRoot; /* Number of tables to check. (Number of root pages.) */
4229
int *aRoot; /* Array of rootpage numbers for tables to be checked */
4230
int j; /* Loop counter */
4231
int nErr; /* Number of errors reported */
4232
char *z; /* Text of the error report */
4233
Mem *pnErr; /* Register keeping track of errors remaining */
4237
aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
4238
if( aRoot==0 ) goto no_mem;
4239
assert( pOp->p3>0 && pOp->p3<=p->nMem );
4240
pnErr = &p->aMem[pOp->p3];
4241
assert( (pnErr->flags & MEM_Int)!=0 );
4242
assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
4243
pIn1 = &p->aMem[pOp->p1];
4244
for(j=0; j<nRoot; j++){
4245
aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
4248
assert( pOp->p5<db->nDb );
4249
assert( (p->btreeMask & (1<<pOp->p5))!=0 );
4250
z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
4252
sqlite3DbFree(db, aRoot);
4254
sqlite3VdbeMemSetNull(pIn1);
4260
sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
4262
UPDATE_MAX_BLOBSIZE(pIn1);
4263
sqlite3VdbeChangeEncoding(pIn1, encoding);
4266
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
4268
/* Opcode: FifoWrite P1 * * * *
4270
** Write the integer from register P1 into the Fifo.
4272
case OP_FifoWrite: { /* in1 */
4274
if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
4280
/* Opcode: FifoRead P1 P2 * * *
4282
** Attempt to read a single integer from the Fifo. Store that
4283
** integer in register P1.
4285
** If the Fifo is empty jump to P2.
4287
case OP_FifoRead: { /* jump */
4288
CHECK_FOR_INTERRUPT;
4289
assert( pOp->p1>0 && pOp->p1<=p->nMem );
4290
pOut = &p->aMem[pOp->p1];
4291
MemSetTypeFlag(pOut, MEM_Int);
4292
if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
4298
#ifndef SQLITE_OMIT_TRIGGER
4299
/* Opcode: ContextPush * * *
4301
** Save the current Vdbe context such that it can be restored by a ContextPop
4302
** opcode. The context stores the last insert row id, the last statement change
4303
** count, and the current statement change count.
4305
case OP_ContextPush: {
4306
int i = p->contextStackTop++;
4310
/* FIX ME: This should be allocated as part of the vdbe at compile-time */
4311
if( i>=p->contextStackDepth ){
4312
p->contextStackDepth = i+1;
4313
p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
4314
sizeof(Context)*(i+1));
4315
if( p->contextStack==0 ) goto no_mem;
4317
pContext = &p->contextStack[i];
4318
pContext->lastRowid = db->lastRowid;
4319
pContext->nChange = p->nChange;
4320
pContext->sFifo = p->sFifo;
4321
sqlite3VdbeFifoInit(&p->sFifo, db);
4325
/* Opcode: ContextPop * * *
4327
** Restore the Vdbe context to the state it was in when contextPush was last
4328
** executed. The context stores the last insert row id, the last statement
4329
** change count, and the current statement change count.
4331
case OP_ContextPop: {
4332
Context *pContext = &p->contextStack[--p->contextStackTop];
4333
assert( p->contextStackTop>=0 );
4334
db->lastRowid = pContext->lastRowid;
4335
p->nChange = pContext->nChange;
4336
sqlite3VdbeFifoClear(&p->sFifo);
4337
p->sFifo = pContext->sFifo;
4340
#endif /* #ifndef SQLITE_OMIT_TRIGGER */
4342
#ifndef SQLITE_OMIT_AUTOINCREMENT
4343
/* Opcode: MemMax P1 P2 * * *
4345
** Set the value of register P1 to the maximum of its current value
4346
** and the value in register P2.
4348
** This instruction throws an error if the memory cell is not initially
4351
case OP_MemMax: { /* in1, in2 */
4352
sqlite3VdbeMemIntegerify(pIn1);
4353
sqlite3VdbeMemIntegerify(pIn2);
4354
if( pIn1->u.i<pIn2->u.i){
4355
pIn1->u.i = pIn2->u.i;
4359
#endif /* SQLITE_OMIT_AUTOINCREMENT */
4361
/* Opcode: IfPos P1 P2 * * *
4363
** If the value of register P1 is 1 or greater, jump to P2.
4365
** It is illegal to use this instruction on a register that does
4366
** not contain an integer. An assertion fault will result if you try.
4368
case OP_IfPos: { /* jump, in1 */
4369
assert( pIn1->flags&MEM_Int );
4376
/* Opcode: IfNeg P1 P2 * * *
4378
** If the value of register P1 is less than zero, jump to P2.
4380
** It is illegal to use this instruction on a register that does
4381
** not contain an integer. An assertion fault will result if you try.
4383
case OP_IfNeg: { /* jump, in1 */
4384
assert( pIn1->flags&MEM_Int );
4391
/* Opcode: IfZero P1 P2 * * *
4393
** If the value of register P1 is exactly 0, jump to P2.
4395
** It is illegal to use this instruction on a register that does
4396
** not contain an integer. An assertion fault will result if you try.
4398
case OP_IfZero: { /* jump, in1 */
4399
assert( pIn1->flags&MEM_Int );
4406
/* Opcode: AggStep * P2 P3 P4 P5
4408
** Execute the step function for an aggregate. The
4409
** function has P5 arguments. P4 is a pointer to the FuncDef
4410
** structure that specifies the function. Use register
4411
** P3 as the accumulator.
4413
** The P5 arguments are taken from register P2 and its
4420
sqlite3_context ctx;
4421
sqlite3_value **apVal;
4424
pRec = &p->aMem[pOp->p2];
4426
assert( apVal || n==0 );
4427
for(i=0; i<n; i++, pRec++){
4429
storeTypeInfo(pRec, encoding);
4431
ctx.pFunc = pOp->p4.pFunc;
4432
assert( pOp->p3>0 && pOp->p3<=p->nMem );
4433
ctx.pMem = pMem = &p->aMem[pOp->p3];
4435
ctx.s.flags = MEM_Null;
4442
if( ctx.pFunc->needCollSeq ){
4443
assert( pOp>p->aOp );
4444
assert( pOp[-1].p4type==P4_COLLSEQ );
4445
assert( pOp[-1].opcode==OP_CollSeq );
4446
ctx.pColl = pOp[-1].p4.pColl;
4448
(ctx.pFunc->xStep)(&ctx, n, apVal);
4450
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
4453
sqlite3VdbeMemRelease(&ctx.s);
4457
/* Opcode: AggFinal P1 P2 * P4 *
4459
** Execute the finalizer function for an aggregate. P1 is
4460
** the memory location that is the accumulator for the aggregate.
4462
** P2 is the number of arguments that the step function takes and
4463
** P4 is a pointer to the FuncDef for this function. The P2
4464
** argument is not used by this opcode. It is only there to disambiguate
4465
** functions that can take varying numbers of arguments. The
4466
** P4 argument is only needed for the degenerate case where
4467
** the step function was not previously called.
4471
assert( pOp->p1>0 && pOp->p1<=p->nMem );
4472
pMem = &p->aMem[pOp->p1];
4473
assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
4474
rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
4475
if( rc==SQLITE_ERROR ){
4476
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
4478
sqlite3VdbeChangeEncoding(pMem, encoding);
4479
UPDATE_MAX_BLOBSIZE(pMem);
4480
if( sqlite3VdbeMemTooBig(pMem) ){
4487
#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
4488
/* Opcode: Vacuum * * * * *
4490
** Vacuum the entire database. This opcode will cause other virtual
4491
** machines to be created and run. It may not be called from within
4495
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4496
rc = sqlite3RunVacuum(&p->zErrMsg, db);
4497
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4502
#if !defined(SQLITE_OMIT_AUTOVACUUM)
4503
/* Opcode: IncrVacuum P1 P2 * * *
4505
** Perform a single step of the incremental vacuum procedure on
4506
** the P1 database. If the vacuum has finished, jump to instruction
4507
** P2. Otherwise, fall through to the next instruction.
4509
case OP_IncrVacuum: { /* jump */
4512
assert( pOp->p1>=0 && pOp->p1<db->nDb );
4513
assert( (p->btreeMask & (1<<pOp->p1))!=0 );
4514
pBt = db->aDb[pOp->p1].pBt;
4515
rc = sqlite3BtreeIncrVacuum(pBt);
4516
if( rc==SQLITE_DONE ){
4524
/* Opcode: Expire P1 * * * *
4526
** Cause precompiled statements to become expired. An expired statement
4527
** fails with an error code of SQLITE_SCHEMA if it is ever executed
4528
** (via sqlite3_step()).
4530
** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
4531
** then only the currently executing statement is affected.
4535
sqlite3ExpirePreparedStatements(db);
4542
#ifndef SQLITE_OMIT_SHARED_CACHE
4543
/* Opcode: TableLock P1 P2 P3 P4 *
4545
** Obtain a lock on a particular table. This instruction is only used when
4546
** the shared-cache feature is enabled.
4548
** If P1 is the index of the database in sqlite3.aDb[] of the database
4549
** on which the lock is acquired. A readlock is obtained if P3==0 or
4550
** a write lock if P3==1.
4552
** P2 contains the root-page of the table to lock.
4554
** P4 contains a pointer to the name of the table being locked. This is only
4555
** used to generate an error message if the lock cannot be obtained.
4557
case OP_TableLock: {
4559
u8 isWriteLock = pOp->p3;
4560
assert( p1>=0 && p1<db->nDb );
4561
assert( (p->btreeMask & (1<<p1))!=0 );
4562
assert( isWriteLock==0 || isWriteLock==1 );
4563
rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
4564
if( rc==SQLITE_LOCKED ){
4565
const char *z = pOp->p4.z;
4566
sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
4570
#endif /* SQLITE_OMIT_SHARED_CACHE */
4572
#ifndef SQLITE_OMIT_VIRTUALTABLE
4573
/* Opcode: VBegin * * * P4 *
4575
** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
4576
** xBegin method for that table.
4578
** Also, whether or not P4 is set, check that this is not being called from
4579
** within a callback to a virtual table xSync() method. If it is, set the
4580
** error code to SQLITE_LOCKED.
4583
sqlite3_vtab *pVtab = pOp->p4.pVtab;
4584
rc = sqlite3VtabBegin(db, pVtab);
4586
sqlite3DbFree(db, p->zErrMsg);
4587
p->zErrMsg = pVtab->zErrMsg;
4592
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4594
#ifndef SQLITE_OMIT_VIRTUALTABLE
4595
/* Opcode: VCreate P1 * * P4 *
4597
** P4 is the name of a virtual table in database P1. Call the xCreate method
4601
rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
4604
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4606
#ifndef SQLITE_OMIT_VIRTUALTABLE
4607
/* Opcode: VDestroy P1 * * P4 *
4609
** P4 is the name of a virtual table in database P1. Call the xDestroy method
4613
p->inVtabMethod = 2;
4614
rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
4615
p->inVtabMethod = 0;
4618
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4620
#ifndef SQLITE_OMIT_VIRTUALTABLE
4621
/* Opcode: VOpen P1 * * P4 *
4623
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
4624
** P1 is a cursor number. This opcode opens a cursor to the virtual
4625
** table and stores that cursor in P1.
4629
sqlite3_vtab_cursor *pVtabCursor = 0;
4631
sqlite3_vtab *pVtab = pOp->p4.pVtab;
4632
sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4634
assert(pVtab && pModule);
4635
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4636
rc = pModule->xOpen(pVtab, &pVtabCursor);
4637
sqlite3DbFree(db, p->zErrMsg);
4638
p->zErrMsg = pVtab->zErrMsg;
4640
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4641
if( SQLITE_OK==rc ){
4642
/* Initialize sqlite3_vtab_cursor base class */
4643
pVtabCursor->pVtab = pVtab;
4645
/* Initialise vdbe cursor object */
4646
pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
4648
pCur->pVtabCursor = pVtabCursor;
4649
pCur->pModule = pVtabCursor->pVtab->pModule;
4651
db->mallocFailed = 1;
4652
pModule->xClose(pVtabCursor);
4657
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4659
#ifndef SQLITE_OMIT_VIRTUALTABLE
4660
/* Opcode: VFilter P1 P2 P3 P4 *
4662
** P1 is a cursor opened using VOpen. P2 is an address to jump to if
4663
** the filtered result set is empty.
4665
** P4 is either NULL or a string that was generated by the xBestIndex
4666
** method of the module. The interpretation of the P4 string is left
4667
** to the module implementation.
4669
** This opcode invokes the xFilter method on the virtual table specified
4670
** by P1. The integer query plan parameter to xFilter is stored in register
4671
** P3. Register P3+1 stores the argc parameter to be passed to the
4672
** xFilter method. Registers P3+2..P3+1+argc are the argc
4673
** additional parameters which are passed to
4674
** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
4676
** A jump is made to P2 if the result set after filtering would be empty.
4678
case OP_VFilter: { /* jump */
4681
const sqlite3_module *pModule;
4682
Mem *pQuery = &p->aMem[pOp->p3];
4683
Mem *pArgc = &pQuery[1];
4684
sqlite3_vtab_cursor *pVtabCursor;
4685
sqlite3_vtab *pVtab;
4687
Cursor *pCur = p->apCsr[pOp->p1];
4689
REGISTER_TRACE(pOp->p3, pQuery);
4690
assert( pCur->pVtabCursor );
4691
pVtabCursor = pCur->pVtabCursor;
4692
pVtab = pVtabCursor->pVtab;
4693
pModule = pVtab->pModule;
4695
/* Grab the index number and argc parameters */
4696
assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
4698
iQuery = pQuery->u.i;
4700
/* Invoke the xFilter method */
4704
Mem **apArg = p->apArg;
4705
for(i = 0; i<nArg; i++){
4706
apArg[i] = &pArgc[i+1];
4707
storeTypeInfo(apArg[i], 0);
4710
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4711
sqlite3VtabLock(pVtab);
4712
p->inVtabMethod = 1;
4713
rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
4714
p->inVtabMethod = 0;
4715
sqlite3DbFree(db, p->zErrMsg);
4716
p->zErrMsg = pVtab->zErrMsg;
4718
sqlite3VtabUnlock(db, pVtab);
4719
if( rc==SQLITE_OK ){
4720
res = pModule->xEof(pVtabCursor);
4722
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4732
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4734
#ifndef SQLITE_OMIT_VIRTUALTABLE
4735
/* Opcode: VRowid P1 P2 * * *
4737
** Store into register P2 the rowid of
4738
** the virtual-table that the P1 cursor is pointing to.
4740
case OP_VRowid: { /* out2-prerelease */
4741
sqlite3_vtab *pVtab;
4742
const sqlite3_module *pModule;
4744
Cursor *pCur = p->apCsr[pOp->p1];
4746
assert( pCur->pVtabCursor );
4747
if( pCur->nullRow ){
4750
pVtab = pCur->pVtabCursor->pVtab;
4751
pModule = pVtab->pModule;
4752
assert( pModule->xRowid );
4753
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4754
rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
4755
sqlite3DbFree(db, p->zErrMsg);
4756
p->zErrMsg = pVtab->zErrMsg;
4758
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4759
MemSetTypeFlag(pOut, MEM_Int);
4763
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4765
#ifndef SQLITE_OMIT_VIRTUALTABLE
4766
/* Opcode: VColumn P1 P2 P3 * *
4768
** Store the value of the P2-th column of
4769
** the row of the virtual-table that the
4770
** P1 cursor is pointing to into register P3.
4773
sqlite3_vtab *pVtab;
4774
const sqlite3_module *pModule;
4776
sqlite3_context sContext;
4778
Cursor *pCur = p->apCsr[pOp->p1];
4779
assert( pCur->pVtabCursor );
4780
assert( pOp->p3>0 && pOp->p3<=p->nMem );
4781
pDest = &p->aMem[pOp->p3];
4782
if( pCur->nullRow ){
4783
sqlite3VdbeMemSetNull(pDest);
4786
pVtab = pCur->pVtabCursor->pVtab;
4787
pModule = pVtab->pModule;
4788
assert( pModule->xColumn );
4789
memset(&sContext, 0, sizeof(sContext));
4791
/* The output cell may already have a buffer allocated. Move
4792
** the current contents to sContext.s so in case the user-function
4793
** can use the already allocated buffer instead of allocating a
4796
sqlite3VdbeMemMove(&sContext.s, pDest);
4797
MemSetTypeFlag(&sContext.s, MEM_Null);
4799
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4800
rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
4801
sqlite3DbFree(db, p->zErrMsg);
4802
p->zErrMsg = pVtab->zErrMsg;
4805
/* Copy the result of the function to the P3 register. We
4806
** do this regardless of whether or not an error occured to ensure any
4807
** dynamic allocation in sContext.s (a Mem struct) is released.
4809
sqlite3VdbeChangeEncoding(&sContext.s, encoding);
4810
REGISTER_TRACE(pOp->p3, pDest);
4811
sqlite3VdbeMemMove(pDest, &sContext.s);
4812
UPDATE_MAX_BLOBSIZE(pDest);
4814
if( sqlite3SafetyOn(db) ){
4815
goto abort_due_to_misuse;
4817
if( sqlite3VdbeMemTooBig(pDest) ){
4822
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4824
#ifndef SQLITE_OMIT_VIRTUALTABLE
4825
/* Opcode: VNext P1 P2 * * *
4827
** Advance virtual table P1 to the next row in its result set and
4828
** jump to instruction P2. Or, if the virtual table has reached
4829
** the end of its result set, then fall through to the next instruction.
4831
case OP_VNext: { /* jump */
4832
sqlite3_vtab *pVtab;
4833
const sqlite3_module *pModule;
4836
Cursor *pCur = p->apCsr[pOp->p1];
4837
assert( pCur->pVtabCursor );
4838
if( pCur->nullRow ){
4841
pVtab = pCur->pVtabCursor->pVtab;
4842
pModule = pVtab->pModule;
4843
assert( pModule->xNext );
4845
/* Invoke the xNext() method of the module. There is no way for the
4846
** underlying implementation to return an error if one occurs during
4847
** xNext(). Instead, if an error occurs, true is returned (indicating that
4848
** data is available) and the error code returned when xColumn or
4849
** some other method is next invoked on the save virtual table cursor.
4851
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4852
sqlite3VtabLock(pVtab);
4853
p->inVtabMethod = 1;
4854
rc = pModule->xNext(pCur->pVtabCursor);
4855
p->inVtabMethod = 0;
4856
sqlite3DbFree(db, p->zErrMsg);
4857
p->zErrMsg = pVtab->zErrMsg;
4859
sqlite3VtabUnlock(db, pVtab);
4860
if( rc==SQLITE_OK ){
4861
res = pModule->xEof(pCur->pVtabCursor);
4863
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4866
/* If there is data, jump to P2 */
4871
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4873
#ifndef SQLITE_OMIT_VIRTUALTABLE
4874
/* Opcode: VRename P1 * * P4 *
4876
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
4877
** This opcode invokes the corresponding xRename method. The value
4878
** in register P1 is passed as the zName argument to the xRename method.
4881
sqlite3_vtab *pVtab = pOp->p4.pVtab;
4882
Mem *pName = &p->aMem[pOp->p1];
4883
assert( pVtab->pModule->xRename );
4884
REGISTER_TRACE(pOp->p1, pName);
4886
Stringify(pName, encoding);
4888
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4889
sqlite3VtabLock(pVtab);
4890
rc = pVtab->pModule->xRename(pVtab, pName->z);
4891
sqlite3DbFree(db, p->zErrMsg);
4892
p->zErrMsg = pVtab->zErrMsg;
4894
sqlite3VtabUnlock(db, pVtab);
4895
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4901
#ifndef SQLITE_OMIT_VIRTUALTABLE
4902
/* Opcode: VUpdate P1 P2 P3 P4 *
4904
** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
4905
** This opcode invokes the corresponding xUpdate method. P2 values
4906
** are contiguous memory cells starting at P3 to pass to the xUpdate
4907
** invocation. The value in register (P3+P2-1) corresponds to the
4908
** p2th element of the argv array passed to xUpdate.
4910
** The xUpdate method will do a DELETE or an INSERT or both.
4911
** The argv[0] element (which corresponds to memory cell P3)
4912
** is the rowid of a row to delete. If argv[0] is NULL then no
4913
** deletion occurs. The argv[1] element is the rowid of the new
4914
** row. This can be NULL to have the virtual table select the new
4915
** rowid for itself. The subsequent elements in the array are
4916
** the values of columns in the new row.
4918
** If P2==1 then no insert is performed. argv[0] is the rowid of
4921
** P1 is a boolean flag. If it is set to true and the xUpdate call
4922
** is successful, then the value returned by sqlite3_last_insert_rowid()
4923
** is set to the value of the rowid for the row just inserted.
4926
sqlite3_vtab *pVtab = pOp->p4.pVtab;
4927
sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
4929
assert( pOp->p4type==P4_VTAB );
4930
if( pModule->xUpdate==0 ){
4931
sqlite3SetString(&p->zErrMsg, db, "read-only table");
4936
Mem **apArg = p->apArg;
4937
Mem *pX = &p->aMem[pOp->p3];
4938
for(i=0; i<nArg; i++){
4939
storeTypeInfo(pX, 0);
4943
if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
4944
sqlite3VtabLock(pVtab);
4945
rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
4946
sqlite3DbFree(db, p->zErrMsg);
4947
p->zErrMsg = pVtab->zErrMsg;
4949
sqlite3VtabUnlock(db, pVtab);
4950
if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
4951
if( pOp->p1 && rc==SQLITE_OK ){
4952
assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
4953
db->lastRowid = rowid;
4959
#endif /* SQLITE_OMIT_VIRTUALTABLE */
4961
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
4962
/* Opcode: Pagecount P1 P2 * * *
4964
** Write the current number of pages in database P1 to memory cell P2.
4966
case OP_Pagecount: { /* out2-prerelease */
4969
Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
4971
rc = sqlite3PagerPagecount(pPager, &nPage);
4972
if( rc==SQLITE_OK ){
4973
pOut->flags = MEM_Int;
4980
#ifndef SQLITE_OMIT_TRACE
4981
/* Opcode: Trace * * * P4 *
4983
** If tracing is enabled (by the sqlite3_trace()) interface, then
4984
** the UTF-8 string contained in P4 is emitted on the trace callback.
4989
db->xTrace(db->pTraceArg, pOp->p4.z);
4992
if( (db->flags & SQLITE_SqlTrace)!=0 ){
4993
sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
4995
#endif /* SQLITE_DEBUG */
5002
/* Opcode: Noop * * * * *
5004
** Do nothing. This instruction is often useful as a jump
5008
** The magic Explain opcode are only inserted when explain==2 (which
5009
** is to say when the EXPLAIN QUERY PLAN syntax is used.)
5010
** This opcode records information from the optimizer. It is the
5011
** the same as a no-op. This opcodesnever appears in a real VM program.
5013
default: { /* This is really OP_Noop and OP_Explain */
5017
/*****************************************************************************
5018
** The cases of the switch statement above this line should all be indented
5019
** by 6 spaces. But the left-most 6 spaces have been removed to improve the
5020
** readability. From this point on down, the normal indentation rules are
5022
*****************************************************************************/
5027
u64 elapsed = sqlite3Hwtime() - start;
5028
pOp->cycles += elapsed;
5031
fprintf(stdout, "%10llu ", elapsed);
5032
sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
5037
/* The following code adds nothing to the actual functionality
5038
** of the program. It is only here for testing and debugging.
5039
** On the other hand, it does burn CPU cycles every time through
5040
** the evaluator loop. So we can leave it out when NDEBUG is defined.
5043
assert( pc>=-1 && pc<p->nOp );
5047
if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
5048
if( opProperty & OPFLG_OUT2_PRERELEASE ){
5049
registerTrace(p->trace, pOp->p2, pOut);
5051
if( opProperty & OPFLG_OUT3 ){
5052
registerTrace(p->trace, pOp->p3, pOut);
5055
#endif /* SQLITE_DEBUG */
5057
} /* The end of the for(;;) loop the loops through opcodes */
5059
/* If we reach this point, it means that execution is finished with
5060
** an error of some kind.
5066
if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
5069
/* This is the only way out of this procedure. We have to
5070
** release the mutexes on btrees that were acquired at the
5073
sqlite3BtreeMutexArrayLeave(&p->aMutex);
5076
/* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
5080
sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
5082
goto vdbe_error_halt;
5084
/* Jump to here if a malloc() fails.
5087
db->mallocFailed = 1;
5088
sqlite3SetString(&p->zErrMsg, db, "out of memory");
5090
goto vdbe_error_halt;
5092
/* Jump to here for an SQLITE_MISUSE error.
5094
abort_due_to_misuse:
5096
/* Fall thru into abort_due_to_error */
5098
/* Jump to here for any other kind of fatal error. The "rc" variable
5099
** should hold the error number.
5102
assert( p->zErrMsg==0 );
5103
if( db->mallocFailed ) rc = SQLITE_NOMEM;
5104
if( rc!=SQLITE_IOERR_NOMEM ){
5105
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
5107
goto vdbe_error_halt;
5109
/* Jump to here if the sqlite3_interrupt() API sets the interrupt
5112
abort_due_to_interrupt:
5113
assert( db->u1.isInterrupted );
5114
rc = SQLITE_INTERRUPT;
5116
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
5117
goto vdbe_error_halt;