monotone

monotone Mtn Source Tree

Root/sqlite/vdbe.c

1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** The code in this file implements the Virtual Database Engine (VDBE)
13**
14** The SQL parser generates a program which is then executed by
15** the VDBE to do the work of the SQL statement. VDBE programs are
16** similar in form to assembly language. The program consists of
17** a linear sequence of operations. Each operation has an opcode
18** and 3 operands. Operands P1 and P2 are integers. Operand P3
19** is a null-terminated string. The P2 operand must be non-negative.
20** Opcodes will typically ignore one or more operands. Many opcodes
21** ignore all three operands.
22**
23** Computation results are stored on a stack. Each entry on the
24** stack is either an integer, a null-terminated string, a floating point
25** number, or the SQL "NULL" value. An inplicit conversion from one
26** type to the other occurs as necessary.
27**
28** Most of the code in this file is taken up by the sqliteVdbeExec()
29** function which does the work of interpreting a VDBE program.
30** But other routines are also provided to help in building up
31** a program instruction by instruction.
32**
33** Various scripts scan this source file in order to generate HTML
34** documentation, headers files, or other derived files. The formatting
35** of the code in this file is, therefore, important. See other comments
36** in this file for details. If in doubt, do not deviate from existing
37** commenting and indentation practices when changing or adding code.
38**
39** $Id: vdbe.c,v 1.1 2003/08/05 23:03:08 graydon Exp $
40*/
41#include "sqliteInt.h"
42#include <ctype.h>
43
44/*
45** The makefile scans this source file and creates the following
46** array of string constants which are the names of all VDBE opcodes.
47** This array is defined in a separate source code file named opcode.c
48** which is automatically generated by the makefile.
49*/
50extern char *sqliteOpcodeNames[];
51
52/*
53** The following global variable is incremented every time a cursor
54** moves, either by the OP_MoveTo or the OP_Next opcode. 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.
58*/
59int sqlite_search_count = 0;
60
61/*
62** SQL is translated into a sequence of instructions to be
63** executed by a virtual machine. Each instruction is an instance
64** of the following structure.
65*/
66typedef struct VdbeOp Op;
67
68/*
69** Boolean values
70*/
71typedef unsigned char Bool;
72
73/*
74** A cursor is a pointer into a single BTree within a database file.
75** The cursor can seek to a BTree entry with a particular key, or
76** loop over all entries of the Btree. You can also insert new BTree
77** entries or retrieve the key or data from the entry that the cursor
78** is currently pointing to.
79**
80** Every cursor that the virtual machine has open is represented by an
81** instance of the following structure.
82**
83** If the Cursor.isTriggerRow flag is set it means that this cursor is
84** really a single row that represents the NEW or OLD pseudo-table of
85** a row trigger. The data for the row is stored in Cursor.pData and
86** the rowid is in Cursor.iKey.
87*/
88struct Cursor {
89 BtCursor *pCursor; /* The cursor structure of the backend */
90 int lastRecno; /* Last recno from a Next or NextIdx operation */
91 int nextRowid; /* Next rowid returned by OP_NewRowid */
92 Bool recnoIsValid; /* True if lastRecno is valid */
93 Bool keyAsData; /* The OP_Column command works on key instead of data */
94 Bool atFirst; /* True if pointing to first entry */
95 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
96 Bool nullRow; /* True if pointing to a row with no data */
97 Bool nextRowidValid; /* True if the nextRowid field is valid */
98 Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
99 Btree *pBt; /* Separate file holding temporary table */
100 int nData; /* Number of bytes in pData */
101 char *pData; /* Data for a NEW or OLD pseudo-table */
102 int iKey; /* Key for the NEW or OLD pseudo-table row */
103};
104typedef struct Cursor Cursor;
105
106/*
107** A sorter builds a list of elements to be sorted. Each element of
108** the list is an instance of the following structure.
109*/
110typedef struct Sorter Sorter;
111struct Sorter {
112 int nKey; /* Number of bytes in the key */
113 char *zKey; /* The key by which we will sort */
114 int nData; /* Number of bytes in the data */
115 char *pData; /* The data associated with this key */
116 Sorter *pNext; /* Next in the list */
117};
118
119/*
120** Number of buckets used for merge-sort.
121*/
122#define NSORT 30
123
124/*
125** Number of bytes of string storage space available to each stack
126** layer without having to malloc. NBFS is short for Number of Bytes
127** For Strings.
128*/
129#define NBFS 32
130
131/*
132** A single level of the stack is an instance of the following
133** structure. Except, string values are stored on a separate
134** list of of pointers to character. The reason for storing
135** strings separately is so that they can be easily passed
136** to the callback function.
137*/
138struct Stack {
139 int i; /* Integer value */
140 int n; /* Number of characters in string value, including '\0' */
141 int flags; /* Some combination of STK_Null, STK_Str, STK_Dyn, etc. */
142 double r; /* Real value */
143 char z[NBFS]; /* Space for short strings */
144};
145typedef struct Stack Stack;
146
147/*
148** Memory cells use the same structure as the stack except that space
149** for an arbitrary string is added.
150*/
151struct Mem {
152 Stack s; /* All values of the memory cell besides string */
153 char *z; /* String value for this memory cell */
154};
155typedef struct Mem Mem;
156
157/*
158** Allowed values for Stack.flags
159*/
160#define STK_Null 0x0001 /* Value is NULL */
161#define STK_Str 0x0002 /* Value is a string */
162#define STK_Int 0x0004 /* Value is an integer */
163#define STK_Real 0x0008 /* Value is a real number */
164#define STK_Dyn 0x0010 /* Need to call sqliteFree() on zStack[] */
165#define STK_Static 0x0020 /* zStack[] points to a static string */
166#define STK_Ephem 0x0040 /* zStack[] points to an ephemeral string */
167
168/* The following STK_ value appears only in AggElem.aMem.s.flag fields.
169** It indicates that the corresponding AggElem.aMem.z points to a
170** aggregate function context that needs to be finalized.
171*/
172#define STK_AggCtx 0x0040 /* zStack[] points to an agg function context */
173
174/*
175** The "context" argument for a installable function. A pointer to an
176** instance of this structure is the first argument to the routines used
177** implement the SQL functions.
178**
179** There is a typedef for this structure in sqlite.h. So all routines,
180** even the public interface to SQLite, can use a pointer to this structure.
181** But this file is the only place where the internal details of this
182** structure are known.
183**
184** This structure is defined inside of vdbe.c because it uses substructures
185** (Stack) which are only defined there.
186*/
187struct sqlite_func {
188 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
189 Stack s; /* Small strings, ints, and double values go here */
190 char *z; /* Space for holding dynamic string results */
191 void *pAgg; /* Aggregate context */
192 u8 isError; /* Set to true for an error */
193 u8 isStep; /* Current in the step function */
194 int cnt; /* Number of times that the step function has been called */
195};
196
197/*
198** An Agg structure describes an Aggregator. Each Agg consists of
199** zero or more Aggregator elements (AggElem). Each AggElem contains
200** a key and one or more values. The values are used in processing
201** aggregate functions in a SELECT. The key is used to implement
202** the GROUP BY clause of a select.
203*/
204typedef struct Agg Agg;
205typedef struct AggElem AggElem;
206struct Agg {
207 int nMem; /* Number of values stored in each AggElem */
208 AggElem *pCurrent; /* The AggElem currently in focus */
209 HashElem *pSearch; /* The hash element for pCurrent */
210 Hash hash; /* Hash table of all aggregate elements */
211 FuncDef **apFunc; /* Information about aggregate functions */
212};
213struct AggElem {
214 char *zKey; /* The key to this AggElem */
215 int nKey; /* Number of bytes in the key, including '\0' at end */
216 Mem aMem[1]; /* The values for this AggElem */
217};
218
219/*
220** A Set structure is used for quick testing to see if a value
221** is part of a small set. Sets are used to implement code like
222** this:
223** x.y IN ('hi','hoo','hum')
224*/
225typedef struct Set Set;
226struct Set {
227 Hash hash; /* A set is just a hash table */
228 HashElem *prev; /* Previously accessed hash elemen */
229};
230
231/*
232** A Keylist is a bunch of keys into a table. The keylist can
233** grow without bound. The keylist stores the ROWIDs of database
234** records that need to be deleted or updated.
235*/
236typedef struct Keylist Keylist;
237struct Keylist {
238 int nKey; /* Number of slots in aKey[] */
239 int nUsed; /* Next unwritten slot in aKey[] */
240 int nRead; /* Next unread slot in aKey[] */
241 Keylist *pNext; /* Next block of keys */
242 int aKey[1]; /* One or more keys. Extra space allocated as needed */
243};
244
245/*
246** An instance of the virtual machine. This structure contains the complete
247** state of the virtual machine.
248**
249** The "sqlite_vm" structure pointer that is returned by sqlite_compile()
250** is really a pointer to an instance of this structure.
251*/
252struct Vdbe {
253 sqlite *db; /* The whole database */
254 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
255 FILE *trace; /* Write an execution trace here, if not NULL */
256 int nOp; /* Number of instructions in the program */
257 int nOpAlloc; /* Number of slots allocated for aOp[] */
258 Op *aOp; /* Space to hold the virtual machine's program */
259 int nLabel; /* Number of labels used */
260 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
261 int *aLabel; /* Space to hold the labels */
262 int tos; /* Index of top of stack */
263 Stack *aStack; /* The operand stack, except string values */
264 char **zStack; /* Text or binary values of the stack */
265 char **azColName; /* Becomes the 4th parameter to callbacks */
266 int nCursor; /* Number of slots in aCsr[] */
267 Cursor *aCsr; /* One element of this array for each open cursor */
268 Sorter *pSort; /* A linked list of objects to be sorted */
269 FILE *pFile; /* At most one open file handler */
270 int nField; /* Number of file fields */
271 char **azField; /* Data for each file field */
272 char *zLine; /* A single line from the input file */
273 int magic; /* Magic number for sanity checking */
274 int nLineAlloc; /* Number of spaces allocated for zLine */
275 int nMem; /* Number of memory locations currently allocated */
276 Mem *aMem; /* The memory locations */
277 Agg agg; /* Aggregate information */
278 int nSet; /* Number of sets allocated */
279 Set *aSet; /* An array of sets */
280 int nCallback; /* Number of callbacks invoked so far */
281 Keylist *pList; /* A list of ROWIDs */
282 int keylistStackDepth; /* The size of the "keylist" stack */
283 Keylist **keylistStack; /* The stack used by opcodes ListPush & ListPop */
284 int pc; /* The program counter */
285 int rc; /* Value to return */
286 unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
287 int errorAction; /* Recovery action to do in case of an error */
288 int undoTransOnError; /* If error, either ROLLBACK or COMMIT */
289 int inTempTrans; /* True if temp database is transactioned */
290 int returnStack[100]; /* Return address stack for OP_Gosub & OP_Return */
291 int returnDepth; /* Next unused element in returnStack[] */
292 int nResColumn; /* Number of columns in one row of the result set */
293 char **azResColumn; /* Values for one row of result */
294 int (*xCallback)(void*,int,char**,char**); /* Callback for SELECT results */
295 void *pCbArg; /* First argument to xCallback() */
296 int popStack; /* Pop the stack this much on entry to VdbeExec() */
297 char *zErrMsg; /* Error message written here */
298 u8 explain; /* True if EXPLAIN present on SQL command */
299};
300
301/*
302** The following are allowed values for Vdbe.magic
303*/
304#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
305#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
306#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
307#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
308
309/*
310** When debugging the code generator in a symbolic debugger, one can
311** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
312** as they are added to the instruction stream.
313*/
314#ifndef NDEBUG
315int sqlite_vdbe_addop_trace = 0;
316static void vdbePrintOp(FILE*, int, Op*);
317#endif
318
319/*
320** Create a new virtual database engine.
321*/
322Vdbe *sqliteVdbeCreate(sqlite *db){
323 Vdbe *p;
324 p = sqliteMalloc( sizeof(Vdbe) );
325 if( p==0 ) return 0;
326 p->db = db;
327 if( db->pVdbe ){
328 db->pVdbe->pPrev = p;
329 }
330 p->pNext = db->pVdbe;
331 p->pPrev = 0;
332 db->pVdbe = p;
333 p->magic = VDBE_MAGIC_INIT;
334 return p;
335}
336
337/*
338** Turn tracing on or off
339*/
340void sqliteVdbeTrace(Vdbe *p, FILE *trace){
341 p->trace = trace;
342}
343
344/*
345** Add a new instruction to the list of instructions current in the
346** VDBE. Return the address of the new instruction.
347**
348** Parameters:
349**
350** p Pointer to the VDBE
351**
352** op The opcode for this instruction
353**
354** p1, p2 First two of the three possible operands.
355**
356** Use the sqliteVdbeResolveLabel() function to fix an address and
357** the sqliteVdbeChangeP3() function to change the value of the P3
358** operand.
359*/
360int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
361 int i;
362
363 i = p->nOp;
364 p->nOp++;
365 assert( p->magic==VDBE_MAGIC_INIT );
366 if( i>=p->nOpAlloc ){
367 int oldSize = p->nOpAlloc;
368 Op *aNew;
369 p->nOpAlloc = p->nOpAlloc*2 + 100;
370 aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
371 if( aNew==0 ){
372 p->nOpAlloc = oldSize;
373 return 0;
374 }
375 p->aOp = aNew;
376 memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
377 }
378 p->aOp[i].opcode = op;
379 p->aOp[i].p1 = p1;
380 if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
381 p2 = p->aLabel[-1-p2];
382 }
383 p->aOp[i].p2 = p2;
384 p->aOp[i].p3 = 0;
385 p->aOp[i].p3type = P3_NOTUSED;
386#ifndef NDEBUG
387 if( sqlite_vdbe_addop_trace ) vdbePrintOp(0, i, &p->aOp[i]);
388#endif
389 return i;
390}
391
392/*
393** Create a new symbolic label for an instruction that has yet to be
394** coded. The symbolic label is really just a negative number. The
395** label can be used as the P2 value of an operation. Later, when
396** the label is resolved to a specific address, the VDBE will scan
397** through its operation list and change all values of P2 which match
398** the label into the resolved address.
399**
400** The VDBE knows that a P2 value is a label because labels are
401** always negative and P2 values are suppose to be non-negative.
402** Hence, a negative P2 value is a label that has yet to be resolved.
403*/
404int sqliteVdbeMakeLabel(Vdbe *p){
405 int i;
406 i = p->nLabel++;
407 assert( p->magic==VDBE_MAGIC_INIT );
408 if( i>=p->nLabelAlloc ){
409 int *aNew;
410 p->nLabelAlloc = p->nLabelAlloc*2 + 10;
411 aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
412 if( aNew==0 ){
413 sqliteFree(p->aLabel);
414 }
415 p->aLabel = aNew;
416 }
417 if( p->aLabel==0 ){
418 p->nLabel = 0;
419 p->nLabelAlloc = 0;
420 return 0;
421 }
422 p->aLabel[i] = -1;
423 return -1-i;
424}
425
426/*
427** Resolve label "x" to be the address of the next instruction to
428** be inserted. The parameter "x" must have been obtained from
429** a prior call to sqliteVdbeMakeLabel().
430*/
431void sqliteVdbeResolveLabel(Vdbe *p, int x){
432 int j;
433 assert( p->magic==VDBE_MAGIC_INIT );
434 if( x<0 && (-x)<=p->nLabel && p->aOp ){
435 if( p->aLabel[-1-x]==p->nOp ) return;
436 assert( p->aLabel[-1-x]<0 );
437 p->aLabel[-1-x] = p->nOp;
438 for(j=0; j<p->nOp; j++){
439 if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
440 }
441 }
442}
443
444/*
445** Return the address of the next instruction to be inserted.
446*/
447int sqliteVdbeCurrentAddr(Vdbe *p){
448 assert( p->magic==VDBE_MAGIC_INIT );
449 return p->nOp;
450}
451
452/*
453** Add a whole list of operations to the operation stack. Return the
454** address of the first operation added.
455*/
456int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOp const *aOp){
457 int addr;
458 assert( p->magic==VDBE_MAGIC_INIT );
459 if( p->nOp + nOp >= p->nOpAlloc ){
460 int oldSize = p->nOpAlloc;
461 Op *aNew;
462 p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
463 aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
464 if( aNew==0 ){
465 p->nOpAlloc = oldSize;
466 return 0;
467 }
468 p->aOp = aNew;
469 memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
470 }
471 addr = p->nOp;
472 if( nOp>0 ){
473 int i;
474 for(i=0; i<nOp; i++){
475 int p2 = aOp[i].p2;
476 p->aOp[i+addr] = aOp[i];
477 if( p2<0 ) p->aOp[i+addr].p2 = addr + ADDR(p2);
478 p->aOp[i+addr].p3type = aOp[i].p3 ? P3_STATIC : P3_NOTUSED;
479#ifndef NDEBUG
480 if( sqlite_vdbe_addop_trace ) vdbePrintOp(0, i+addr, &p->aOp[i+addr]);
481#endif
482 }
483 p->nOp += nOp;
484 }
485 return addr;
486}
487
488#if 0 /* NOT USED */
489/*
490** Change the value of the P1 operand for a specific instruction.
491** This routine is useful when a large program is loaded from a
492** static array using sqliteVdbeAddOpList but we want to make a
493** few minor changes to the program.
494*/
495void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
496 assert( p->magic==VDBE_MAGIC_INIT );
497 if( p && addr>=0 && p->nOp>addr && p->aOp ){
498 p->aOp[addr].p1 = val;
499 }
500}
501#endif /* NOT USED */
502
503/*
504** Change the value of the P2 operand for a specific instruction.
505** This routine is useful for setting a jump destination.
506*/
507void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
508 assert( val>=0 );
509 assert( p->magic==VDBE_MAGIC_INIT );
510 if( p && addr>=0 && p->nOp>addr && p->aOp ){
511 p->aOp[addr].p2 = val;
512 }
513}
514
515/*
516** Change the value of the P3 operand for a specific instruction.
517** This routine is useful when a large program is loaded from a
518** static array using sqliteVdbeAddOpList but we want to make a
519** few minor changes to the program.
520**
521** If n>=0 then the P3 operand is dynamic, meaning that a copy of
522** the string is made into memory obtained from sqliteMalloc().
523** A value of n==0 means copy bytes of zP3 up to and including the
524** first null byte. If n>0 then copy n+1 bytes of zP3.
525**
526** If n==P3_STATIC it means that zP3 is a pointer to a constant static
527** string and we can just copy the pointer. n==P3_POINTER means zP3 is
528** a pointer to some object other than a string.
529**
530** If addr<0 then change P3 on the most recently inserted instruction.
531*/
532void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
533 Op *pOp;
534 assert( p->magic==VDBE_MAGIC_INIT );
535 if( p==0 || p->aOp==0 ) return;
536 if( addr<0 || addr>=p->nOp ){
537 addr = p->nOp - 1;
538 if( addr<0 ) return;
539 }
540 pOp = &p->aOp[addr];
541 if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
542 sqliteFree(pOp->p3);
543 pOp->p3 = 0;
544 }
545 if( zP3==0 ){
546 pOp->p3 = 0;
547 pOp->p3type = P3_NOTUSED;
548 }else if( n<0 ){
549 pOp->p3 = (char*)zP3;
550 pOp->p3type = n;
551 }else{
552 sqliteSetNString(&pOp->p3, zP3, n, 0);
553 pOp->p3type = P3_DYNAMIC;
554 }
555}
556
557/*
558** If the P3 operand to the specified instruction appears
559** to be a quoted string token, then this procedure removes
560** the quotes.
561**
562** The quoting operator can be either a grave ascent (ASCII 0x27)
563** or a double quote character (ASCII 0x22). Two quotes in a row
564** resolve to be a single actual quote character within the string.
565*/
566void sqliteVdbeDequoteP3(Vdbe *p, int addr){
567 Op *pOp;
568 assert( p->magic==VDBE_MAGIC_INIT );
569 if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
570 pOp = &p->aOp[addr];
571 if( pOp->p3==0 || pOp->p3[0]==0 ) return;
572 if( pOp->p3type==P3_POINTER ) return;
573 if( pOp->p3type!=P3_DYNAMIC ){
574 pOp->p3 = sqliteStrDup(pOp->p3);
575 pOp->p3type = P3_DYNAMIC;
576 }
577 sqliteDequote(pOp->p3);
578}
579
580/*
581** On the P3 argument of the given instruction, change all
582** strings of whitespace characters into a single space and
583** delete leading and trailing whitespace.
584*/
585void sqliteVdbeCompressSpace(Vdbe *p, int addr){
586 char *z;
587 int i, j;
588 Op *pOp;
589 assert( p->magic==VDBE_MAGIC_INIT );
590 if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
591 pOp = &p->aOp[addr];
592 if( pOp->p3type==P3_POINTER ){
593 return;
594 }
595 if( pOp->p3type!=P3_DYNAMIC ){
596 pOp->p3 = sqliteStrDup(pOp->p3);
597 pOp->p3type = P3_DYNAMIC;
598 }
599 z = pOp->p3;
600 if( z==0 ) return;
601 i = j = 0;
602 while( isspace(z[i]) ){ i++; }
603 while( z[i] ){
604 if( isspace(z[i]) ){
605 z[j++] = ' ';
606 while( isspace(z[++i]) ){}
607 }else{
608 z[j++] = z[i++];
609 }
610 }
611 while( j>0 && isspace(z[j-1]) ){ j--; }
612 z[j] = 0;
613}
614
615/*
616** Search for the current program for the given opcode and P2
617** value. Return the address plus 1 if found and 0 if not found.
618*/
619int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
620 int i;
621 assert( p->magic==VDBE_MAGIC_INIT );
622 for(i=0; i<p->nOp; i++){
623 if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
624 }
625 return 0;
626}
627
628/*
629** Return the opcode for a given address.
630*/
631VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
632 assert( p->magic==VDBE_MAGIC_INIT );
633 assert( addr>=0 && addr<p->nOp );
634 return &p->aOp[addr];
635}
636
637/*
638** The following group or routines are employed by installable functions
639** to return their results.
640**
641** The sqlite_set_result_string() routine can be used to return a string
642** value or to return a NULL. To return a NULL, pass in NULL for zResult.
643** A copy is made of the string before this routine returns so it is safe
644** to pass in an ephemeral string.
645**
646** sqlite_set_result_error() works like sqlite_set_result_string() except
647** that it signals a fatal error. The string argument, if any, is the
648** error message. If the argument is NULL a generic substitute error message
649** is used.
650**
651** The sqlite_set_result_int() and sqlite_set_result_double() set the return
652** value of the user function to an integer or a double.
653**
654** These routines are defined here in vdbe.c because they depend on knowing
655** the internals of the sqlite_func structure which is only defined in
656** this source file.
657*/
658char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
659 assert( !p->isStep );
660 if( p->s.flags & STK_Dyn ){
661 sqliteFree(p->z);
662 }
663 if( zResult==0 ){
664 p->s.flags = STK_Null;
665 n = 0;
666 p->z = 0;
667 p->s.n = 0;
668 }else{
669 if( n<0 ) n = strlen(zResult);
670 if( n<NBFS-1 ){
671 memcpy(p->s.z, zResult, n);
672 p->s.z[n] = 0;
673 p->s.flags = STK_Str;
674 p->z = p->s.z;
675 }else{
676 p->z = sqliteMallocRaw( n+1 );
677 if( p->z ){
678 memcpy(p->z, zResult, n);
679 p->z[n] = 0;
680 }
681 p->s.flags = STK_Str | STK_Dyn;
682 }
683 p->s.n = n+1;
684 }
685 return p->z;
686}
687void sqlite_set_result_int(sqlite_func *p, int iResult){
688 assert( !p->isStep );
689 if( p->s.flags & STK_Dyn ){
690 sqliteFree(p->z);
691 }
692 p->s.i = iResult;
693 p->s.flags = STK_Int;
694}
695void sqlite_set_result_double(sqlite_func *p, double rResult){
696 assert( !p->isStep );
697 if( p->s.flags & STK_Dyn ){
698 sqliteFree(p->z);
699 }
700 p->s.r = rResult;
701 p->s.flags = STK_Real;
702}
703void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
704 assert( !p->isStep );
705 sqlite_set_result_string(p, zMsg, n);
706 p->isError = 1;
707}
708
709/*
710** Extract the user data from a sqlite_func structure and return a
711** pointer to it.
712**
713** This routine is defined here in vdbe.c because it depends on knowing
714** the internals of the sqlite_func structure which is only defined in
715** this source file.
716*/
717void *sqlite_user_data(sqlite_func *p){
718 assert( p && p->pFunc );
719 return p->pFunc->pUserData;
720}
721
722/*
723** Allocate or return the aggregate context for a user function. A new
724** context is allocated on the first call. Subsequent calls return the
725** same context that was returned on prior calls.
726**
727** This routine is defined here in vdbe.c because it depends on knowing
728** the internals of the sqlite_func structure which is only defined in
729** this source file.
730*/
731void *sqlite_aggregate_context(sqlite_func *p, int nByte){
732 assert( p && p->pFunc && p->pFunc->xStep );
733 if( p->pAgg==0 ){
734 if( nByte<=NBFS ){
735 p->pAgg = (void*)p->z;
736 }else{
737 p->pAgg = sqliteMalloc( nByte );
738 }
739 }
740 return p->pAgg;
741}
742
743/*
744** Return the number of times the Step function of a aggregate has been
745** called.
746**
747** This routine is defined here in vdbe.c because it depends on knowing
748** the internals of the sqlite_func structure which is only defined in
749** this source file.
750*/
751int sqlite_aggregate_count(sqlite_func *p){
752 assert( p && p->pFunc && p->pFunc->xStep );
753 return p->cnt;
754}
755
756/*
757** Advance the virtual machine to the next output row.
758**
759** The return vale will be either SQLITE_BUSY, SQLITE_DONE,
760** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
761**
762** SQLITE_BUSY means that the virtual machine attempted to open
763** a locked database and there is no busy callback registered.
764** Call sqlite_step() again to retry the open. *pN is set to 0
765** and *pazColName and *pazValue are both set to NULL.
766**
767** SQLITE_DONE means that the virtual machine has finished
768** executing. sqlite_step() should not be called again on this
769** virtual machine. *pN and *pazColName are set appropriately
770** but *pazValue is set to NULL.
771**
772** SQLITE_ROW means that the virtual machine has generated another
773** row of the result set. *pN is set to the number of columns in
774** the row. *pazColName is set to the names of the columns followed
775** by the column datatypes. *pazValue is set to the values of each
776** column in the row. The value of the i-th column is (*pazValue)[i].
777** The name of the i-th column is (*pazColName)[i] and the datatype
778** of the i-th column is (*pazColName)[i+*pN].
779**
780** SQLITE_ERROR means that a run-time error (such as a constraint
781** violation) has occurred. The details of the error will be returned
782** by the next call to sqlite_finalize(). sqlite_step() should not
783** be called again on the VM.
784**
785** SQLITE_MISUSE means that the this routine was called inappropriately.
786** Perhaps it was called on a virtual machine that had already been
787** finalized or on one that had previously returned SQLITE_ERROR or
788** SQLITE_DONE. Or it could be the case the the same database connection
789** is being used simulataneously by two or more threads.
790*/
791int sqlite_step(
792 sqlite_vm *pVm, /* The virtual machine to execute */
793 int *pN, /* OUT: Number of columns in result */
794 const char ***pazValue, /* OUT: Column data */
795 const char ***pazColName /* OUT: Column names and datatypes */
796){
797 Vdbe *p = (Vdbe*)pVm;
798 sqlite *db;
799 int rc;
800
801 if( p->magic!=VDBE_MAGIC_RUN ){
802 return SQLITE_MISUSE;
803 }
804 db = p->db;
805 if( sqliteSafetyOn(db) ){
806 return SQLITE_MISUSE;
807 }
808 if( p->explain ){
809 rc = sqliteVdbeList(p);
810 }else{
811 rc = sqliteVdbeExec(p);
812 }
813 if( rc==SQLITE_DONE || rc==SQLITE_ROW ){
814 *pazColName = (const char**)p->azColName;
815 *pN = p->nResColumn;
816 }else{
817 *pN = 0;
818 *pazColName = 0;
819 }
820 if( rc==SQLITE_ROW ){
821 *pazValue = (const char**)p->azResColumn;
822 }else{
823 *pazValue = 0;
824 }
825 if( sqliteSafetyOff(db) ){
826 return SQLITE_MISUSE;
827 }
828 return rc;
829}
830
831/*
832** Reset an Agg structure. Delete all its contents.
833**
834** For installable aggregate functions, if the step function has been
835** called, make sure the finalizer function has also been called. The
836** finalizer might need to free memory that was allocated as part of its
837** private context. If the finalizer has not been called yet, call it
838** now.
839*/
840static void AggReset(Agg *pAgg){
841 int i;
842 HashElem *p;
843 for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
844 AggElem *pElem = sqliteHashData(p);
845 assert( pAgg->apFunc!=0 );
846 for(i=0; i<pAgg->nMem; i++){
847 Mem *pMem = &pElem->aMem[i];
848 if( pAgg->apFunc[i] && (pMem->s.flags & STK_AggCtx)!=0 ){
849 sqlite_func ctx;
850 ctx.pFunc = pAgg->apFunc[i];
851 ctx.s.flags = STK_Null;
852 ctx.z = 0;
853 ctx.pAgg = pMem->z;
854 ctx.cnt = pMem->s.i;
855 ctx.isStep = 0;
856 ctx.isError = 0;
857 (*pAgg->apFunc[i]->xFinalize)(&ctx);
858 if( pMem->z!=0 && pMem->z!=pMem->s.z ){
859 sqliteFree(pMem->z);
860 }
861 }else if( pMem->s.flags & STK_Dyn ){
862 sqliteFree(pMem->z);
863 }
864 }
865 sqliteFree(pElem);
866 }
867 sqliteHashClear(&pAgg->hash);
868 sqliteFree(pAgg->apFunc);
869 pAgg->apFunc = 0;
870 pAgg->pCurrent = 0;
871 pAgg->pSearch = 0;
872 pAgg->nMem = 0;
873}
874
875/*
876** Insert a new aggregate element and make it the element that
877** has focus.
878**
879** Return 0 on success and 1 if memory is exhausted.
880*/
881static int AggInsert(Agg *p, char *zKey, int nKey){
882 AggElem *pElem, *pOld;
883 int i;
884 pElem = sqliteMalloc( sizeof(AggElem) + nKey +
885 (p->nMem-1)*sizeof(pElem->aMem[0]) );
886 if( pElem==0 ) return 1;
887 pElem->zKey = (char*)&pElem->aMem[p->nMem];
888 memcpy(pElem->zKey, zKey, nKey);
889 pElem->nKey = nKey;
890 pOld = sqliteHashInsert(&p->hash, pElem->zKey, pElem->nKey, pElem);
891 if( pOld!=0 ){
892 assert( pOld==pElem ); /* Malloc failed on insert */
893 sqliteFree(pOld);
894 return 0;
895 }
896 for(i=0; i<p->nMem; i++){
897 pElem->aMem[i].s.flags = STK_Null;
898 }
899 p->pCurrent = pElem;
900 return 0;
901}
902
903/*
904** Get the AggElem currently in focus
905*/
906#define AggInFocus(P) ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
907static AggElem *_AggInFocus(Agg *p){
908 HashElem *pElem = sqliteHashFirst(&p->hash);
909 if( pElem==0 ){
910 AggInsert(p,"",1);
911 pElem = sqliteHashFirst(&p->hash);
912 }
913 return pElem ? sqliteHashData(pElem) : 0;
914}
915
916/*
917** Convert the given stack entity into a string if it isn't one
918** already.
919*/
920#define Stringify(P,I) if((aStack[I].flags & STK_Str)==0){hardStringify(P,I);}
921static int hardStringify(Vdbe *p, int i){
922 Stack *pStack = &p->aStack[i];
923 int fg = pStack->flags;
924 if( fg & STK_Real ){
925 sprintf(pStack->z,"%.15g",pStack->r);
926 }else if( fg & STK_Int ){
927 sprintf(pStack->z,"%d",pStack->i);
928 }else{
929 pStack->z[0] = 0;
930 }
931 p->zStack[i] = pStack->z;
932 pStack->n = strlen(pStack->z)+1;
933 pStack->flags = STK_Str;
934 return 0;
935}
936
937/*
938** Convert the given stack entity into a string that has been obtained
939** from sqliteMalloc(). This is different from Stringify() above in that
940** Stringify() will use the NBFS bytes of static string space if the string
941** will fit but this routine always mallocs for space.
942** Return non-zero if we run out of memory.
943*/
944#define Dynamicify(P,I) ((aStack[I].flags & STK_Dyn)==0 ? hardDynamicify(P,I):0)
945static int hardDynamicify(Vdbe *p, int i){
946 Stack *pStack = &p->aStack[i];
947 int fg = pStack->flags;
948 char *z;
949 if( (fg & STK_Str)==0 ){
950 hardStringify(p, i);
951 }
952 assert( (fg & STK_Dyn)==0 );
953 z = sqliteMallocRaw( pStack->n );
954 if( z==0 ) return 1;
955 memcpy(z, p->zStack[i], pStack->n);
956 p->zStack[i] = z;
957 pStack->flags |= STK_Dyn;
958 return 0;
959}
960
961/*
962** An ephemeral string value (signified by the STK_Ephem flag) contains
963** a pointer to a dynamically allocated string where some other entity
964** is responsible for deallocating that string. Because the stack entry
965** does not control the string, it might be deleted without the stack
966** entry knowing it.
967**
968** This routine converts an ephemeral string into a dynamically allocated
969** string that the stack entry itself controls. In other words, it
970** converts an STK_Ephem string into an STK_Dyn string.
971*/
972#define Deephemeralize(P,I) \
973 if( ((P)->aStack[I].flags&STK_Ephem)!=0 && hardDeephem(P,I) ){ goto no_mem;}
974static int hardDeephem(Vdbe *p, int i){
975 Stack *pStack = &p->aStack[i];
976 char **pzStack = &p->zStack[i];
977 char *z;
978 assert( (pStack->flags & STK_Ephem)!=0 );
979 z = sqliteMallocRaw( pStack->n );
980 if( z==0 ) return 1;
981 memcpy(z, *pzStack, pStack->n);
982 *pzStack = z;
983 return 0;
984}
985
986/*
987** Release the memory associated with the given stack level
988*/
989#define Release(P,I) if((P)->aStack[I].flags&STK_Dyn){ hardRelease(P,I); }
990static void hardRelease(Vdbe *p, int i){
991 sqliteFree(p->zStack[i]);
992 p->zStack[i] = 0;
993 p->aStack[i].flags &= ~(STK_Str|STK_Dyn|STK_Static|STK_Ephem);
994}
995
996/*
997** Return TRUE if zNum is an integer and write
998** the value of the integer into *pNum.
999**
1000** Under Linux (RedHat 7.2) this routine is much faster than atoi()
1001** for converting strings into integers.
1002*/
1003static int toInt(const char *zNum, int *pNum){
1004 int v = 0;
1005 int neg;
1006 if( *zNum=='-' ){
1007 neg = 1;
1008 zNum++;
1009 }else if( *zNum=='+' ){
1010 neg = 0;
1011 zNum++;
1012 }else{
1013 neg = 0;
1014 }
1015 if( *zNum==0 ) return 0;
1016 while( isdigit(*zNum) ){
1017 v = v*10 + *zNum - '0';
1018 zNum++;
1019 }
1020 *pNum = neg ? -v : v;
1021 return *zNum==0;
1022}
1023
1024/*
1025** Convert the given stack entity into a integer if it isn't one
1026** already.
1027**
1028** Any prior string or real representation is invalidated.
1029** NULLs are converted into 0.
1030*/
1031#define Integerify(P,I) \
1032 if(((P)->aStack[(I)].flags&STK_Int)==0){ hardIntegerify(P,I); }
1033static void hardIntegerify(Vdbe *p, int i){
1034 if( p->aStack[i].flags & STK_Real ){
1035 p->aStack[i].i = (int)p->aStack[i].r;
1036 Release(p, i);
1037 }else if( p->aStack[i].flags & STK_Str ){
1038 toInt(p->zStack[i], &p->aStack[i].i);
1039 Release(p, i);
1040 }else{
1041 p->aStack[i].i = 0;
1042 }
1043 p->aStack[i].flags = STK_Int;
1044}
1045
1046/*
1047** Get a valid Real representation for the given stack element.
1048**
1049** Any prior string or integer representation is retained.
1050** NULLs are converted into 0.0.
1051*/
1052#define Realify(P,I) \
1053 if(((P)->aStack[(I)].flags&STK_Real)==0){ hardRealify(P,I); }
1054static void hardRealify(Vdbe *p, int i){
1055 if( p->aStack[i].flags & STK_Str ){
1056 p->aStack[i].r = atof(p->zStack[i]);
1057 }else if( p->aStack[i].flags & STK_Int ){
1058 p->aStack[i].r = p->aStack[i].i;
1059 }else{
1060 p->aStack[i].r = 0.0;
1061 }
1062 p->aStack[i].flags |= STK_Real;
1063}
1064
1065/*
1066** Pop the stack N times. Free any memory associated with the
1067** popped stack elements.
1068*/
1069static void PopStack(Vdbe *p, int N){
1070 assert( N>=0 );
1071 if( p->zStack==0 ) return;
1072 assert( p->aStack || sqlite_malloc_failed );
1073 if( p->aStack==0 ) return;
1074 while( N-- > 0 ){
1075 if( p->aStack[p->tos].flags & STK_Dyn ){
1076 sqliteFree(p->zStack[p->tos]);
1077 }
1078 p->aStack[p->tos].flags = 0;
1079 p->zStack[p->tos] = 0;
1080 p->tos--;
1081 }
1082}
1083
1084/*
1085** Here is a macro to handle the common case of popping the stack
1086** once. This macro only works from within the sqliteVdbeExec()
1087** function.
1088*/
1089#define POPSTACK \
1090 assert(p->tos>=0); \
1091 if( aStack[p->tos].flags & STK_Dyn ) sqliteFree(zStack[p->tos]); \
1092 p->tos--;
1093
1094/*
1095** Delete a keylist
1096*/
1097static void KeylistFree(Keylist *p){
1098 while( p ){
1099 Keylist *pNext = p->pNext;
1100 sqliteFree(p);
1101 p = pNext;
1102 }
1103}
1104
1105/*
1106** Close a cursor and release all the resources that cursor happens
1107** to hold.
1108*/
1109static void cleanupCursor(Cursor *pCx){
1110 if( pCx->pCursor ){
1111 sqliteBtreeCloseCursor(pCx->pCursor);
1112 }
1113 if( pCx->pBt ){
1114 sqliteBtreeClose(pCx->pBt);
1115 }
1116 sqliteFree(pCx->pData);
1117 memset(pCx, 0, sizeof(Cursor));
1118}
1119
1120/*
1121** Close all cursors
1122*/
1123static void closeAllCursors(Vdbe *p){
1124 int i;
1125 for(i=0; i<p->nCursor; i++){
1126 cleanupCursor(&p->aCsr[i]);
1127 }
1128 sqliteFree(p->aCsr);
1129 p->aCsr = 0;
1130 p->nCursor = 0;
1131}
1132
1133/*
1134** Remove any elements that remain on the sorter for the VDBE given.
1135*/
1136static void SorterReset(Vdbe *p){
1137 while( p->pSort ){
1138 Sorter *pSorter = p->pSort;
1139 p->pSort = pSorter->pNext;
1140 sqliteFree(pSorter->zKey);
1141 sqliteFree(pSorter->pData);
1142 sqliteFree(pSorter);
1143 }
1144}
1145
1146/*
1147** Clean up the VM after execution.
1148**
1149** This routine will automatically close any cursors, lists, and/or
1150** sorters that were left open.
1151*/
1152static void Cleanup(Vdbe *p){
1153 int i;
1154 PopStack(p, p->tos+1);
1155 closeAllCursors(p);
1156 if( p->aMem ){
1157 for(i=0; i<p->nMem; i++){
1158 if( p->aMem[i].s.flags & STK_Dyn ){
1159 sqliteFree(p->aMem[i].z);
1160 }
1161 }
1162 }
1163 sqliteFree(p->aMem);
1164 p->aMem = 0;
1165 p->nMem = 0;
1166 if( p->pList ){
1167 KeylistFree(p->pList);
1168 p->pList = 0;
1169 }
1170 SorterReset(p);
1171 if( p->pFile ){
1172 if( p->pFile!=stdin ) fclose(p->pFile);
1173 p->pFile = 0;
1174 }
1175 if( p->azField ){
1176 sqliteFree(p->azField);
1177 p->azField = 0;
1178 }
1179 p->nField = 0;
1180 if( p->zLine ){
1181 sqliteFree(p->zLine);
1182 p->zLine = 0;
1183 }
1184 p->nLineAlloc = 0;
1185 AggReset(&p->agg);
1186 if( p->aSet ){
1187 for(i=0; i<p->nSet; i++){
1188 sqliteHashClear(&p->aSet[i].hash);
1189 }
1190 }
1191 sqliteFree(p->aSet);
1192 p->aSet = 0;
1193 p->nSet = 0;
1194 if( p->keylistStack ){
1195 int ii;
1196 for(ii = 0; ii < p->keylistStackDepth; ii++){
1197 KeylistFree(p->keylistStack[ii]);
1198 }
1199 sqliteFree(p->keylistStack);
1200 p->keylistStackDepth = 0;
1201 p->keylistStack = 0;
1202 }
1203 sqliteFree(p->zErrMsg);
1204 p->zErrMsg = 0;
1205 p->magic = VDBE_MAGIC_DEAD;
1206}
1207
1208/*
1209** Delete an entire VDBE.
1210*/
1211void sqliteVdbeDelete(Vdbe *p){
1212 int i;
1213 if( p==0 ) return;
1214 Cleanup(p);
1215 if( p->pPrev ){
1216 p->pPrev->pNext = p->pNext;
1217 }else{
1218 assert( p->db->pVdbe==p );
1219 p->db->pVdbe = p->pNext;
1220 }
1221 if( p->pNext ){
1222 p->pNext->pPrev = p->pPrev;
1223 }
1224 p->pPrev = p->pNext = 0;
1225 if( p->nOpAlloc==0 ){
1226 p->aOp = 0;
1227 p->nOp = 0;
1228 }
1229 for(i=0; i<p->nOp; i++){
1230 if( p->aOp[i].p3type==P3_DYNAMIC ){
1231 sqliteFree(p->aOp[i].p3);
1232 }
1233 }
1234 sqliteFree(p->aOp);
1235 sqliteFree(p->aLabel);
1236 sqliteFree(p->aStack);
1237 sqliteFree(p);
1238}
1239
1240/*
1241** Give a listing of the program in the virtual machine.
1242**
1243** The interface is the same as sqliteVdbeExec(). But instead of
1244** running the code, it invokes the callback once for each instruction.
1245** This feature is used to implement "EXPLAIN".
1246*/
1247int sqliteVdbeList(
1248 Vdbe *p /* The VDBE */
1249){
1250 sqlite *db = p->db;
1251 int i;
1252 static char *azColumnNames[] = {
1253 "addr", "opcode", "p1", "p2", "p3",
1254 "int", "text", "int", "int", "text",
1255 0
1256 };
1257
1258 assert( p->popStack==0 );
1259 assert( p->explain );
1260 p->azColName = azColumnNames;
1261 p->azResColumn = p->zStack;
1262 for(i=0; i<5; i++) p->zStack[i] = p->aStack[i].z;
1263 p->rc = SQLITE_OK;
1264 for(i=p->pc; p->rc==SQLITE_OK && i<p->nOp; i++){
1265 if( db->flags & SQLITE_Interrupt ){
1266 db->flags &= ~SQLITE_Interrupt;
1267 if( db->magic!=SQLITE_MAGIC_BUSY ){
1268 p->rc = SQLITE_MISUSE;
1269 }else{
1270 p->rc = SQLITE_INTERRUPT;
1271 }
1272 sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), 0);
1273 break;
1274 }
1275 sprintf(p->zStack[0],"%d",i);
1276 sprintf(p->zStack[2],"%d", p->aOp[i].p1);
1277 sprintf(p->zStack[3],"%d", p->aOp[i].p2);
1278 if( p->aOp[i].p3type==P3_POINTER ){
1279 sprintf(p->aStack[4].z, "ptr(%#x)", (int)p->aOp[i].p3);
1280 p->zStack[4] = p->aStack[4].z;
1281 }else{
1282 p->zStack[4] = p->aOp[i].p3;
1283 }
1284 p->zStack[1] = sqliteOpcodeNames[p->aOp[i].opcode];
1285 if( p->xCallback==0 ){
1286 p->pc = i+1;
1287 p->azResColumn = p->zStack;
1288 p->nResColumn = 5;
1289 return SQLITE_ROW;
1290 }
1291 if( sqliteSafetyOff(db) ){
1292 p->rc = SQLITE_MISUSE;
1293 break;
1294 }
1295 if( p->xCallback(p->pCbArg, 5, p->zStack, p->azColName) ){
1296 p->rc = SQLITE_ABORT;
1297 }
1298 if( sqliteSafetyOn(db) ){
1299 p->rc = SQLITE_MISUSE;
1300 }
1301 }
1302 return p->rc==SQLITE_OK ? SQLITE_DONE : SQLITE_ERROR;
1303}
1304
1305/*
1306** The parameters are pointers to the head of two sorted lists
1307** of Sorter structures. Merge these two lists together and return
1308** a single sorted list. This routine forms the core of the merge-sort
1309** algorithm.
1310**
1311** In the case of a tie, left sorts in front of right.
1312*/
1313static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
1314 Sorter sHead;
1315 Sorter *pTail;
1316 pTail = &sHead;
1317 pTail->pNext = 0;
1318 while( pLeft && pRight ){
1319 int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
1320 if( c<=0 ){
1321 pTail->pNext = pLeft;
1322 pLeft = pLeft->pNext;
1323 }else{
1324 pTail->pNext = pRight;
1325 pRight = pRight->pNext;
1326 }
1327 pTail = pTail->pNext;
1328 }
1329 if( pLeft ){
1330 pTail->pNext = pLeft;
1331 }else if( pRight ){
1332 pTail->pNext = pRight;
1333 }
1334 return sHead.pNext;
1335}
1336
1337/*
1338** Convert an integer in between the native integer format and
1339** the bigEndian format used as the record number for tables.
1340**
1341** The bigEndian format (most significant byte first) is used for
1342** record numbers so that records will sort into the correct order
1343** even though memcmp() is used to compare the keys. On machines
1344** whose native integer format is little endian (ex: i486) the
1345** order of bytes is reversed. On native big-endian machines
1346** (ex: Alpha, Sparc, Motorola) the byte order is the same.
1347**
1348** This function is its own inverse. In other words
1349**
1350** X == byteSwap(byteSwap(X))
1351*/
1352static int byteSwap(int x){
1353 union {
1354 char zBuf[sizeof(int)];
1355 int i;
1356 } ux;
1357 ux.zBuf[3] = x&0xff;
1358 ux.zBuf[2] = (x>>8)&0xff;
1359 ux.zBuf[1] = (x>>16)&0xff;
1360 ux.zBuf[0] = (x>>24)&0xff;
1361 return ux.i;
1362}
1363
1364/*
1365** When converting from the native format to the key format and back
1366** again, in addition to changing the byte order we invert the high-order
1367** bit of the most significant byte. This causes negative numbers to
1368** sort before positive numbers in the memcmp() function.
1369*/
1370#define keyToInt(X) (byteSwap(X) ^ 0x80000000)
1371#define intToKey(X) (byteSwap((X) ^ 0x80000000))
1372
1373/*
1374** Code contained within the VERIFY() macro is not needed for correct
1375** execution. It is there only to catch errors. So when we compile
1376** with NDEBUG=1, the VERIFY() code is omitted.
1377*/
1378#ifdef NDEBUG
1379# define VERIFY(X)
1380#else
1381# define VERIFY(X) X
1382#endif
1383
1384/*
1385** The following routine works like a replacement for the standard
1386** library routine fgets(). The difference is in how end-of-line (EOL)
1387** is handled. Standard fgets() uses LF for EOL under unix, CRLF
1388** under windows, and CR under mac. This routine accepts any of these
1389** character sequences as an EOL mark. The EOL mark is replaced by
1390** a single LF character in zBuf.
1391*/
1392static char *vdbe_fgets(char *zBuf, int nBuf, FILE *in){
1393 int i, c;
1394 for(i=0; i<nBuf-1 && (c=getc(in))!=EOF; i++){
1395 zBuf[i] = c;
1396 if( c=='\r' || c=='\n' ){
1397 if( c=='\r' ){
1398 zBuf[i] = '\n';
1399 c = getc(in);
1400 if( c!=EOF && c!='\n' ) ungetc(c, in);
1401 }
1402 i++;
1403 break;
1404 }
1405 }
1406 zBuf[i] = 0;
1407 return i>0 ? zBuf : 0;
1408}
1409
1410#if !defined(NDEBUG) || defined(VDBE_PROFILE)
1411/*
1412** Print a single opcode. This routine is used for debugging only.
1413*/
1414static void vdbePrintOp(FILE *pOut, int pc, Op *pOp){
1415 char *zP3;
1416 char zPtr[40];
1417 if( pOp->p3type==P3_POINTER ){
1418 sprintf(zPtr, "ptr(%#x)", (int)pOp->p3);
1419 zP3 = zPtr;
1420 }else{
1421 zP3 = pOp->p3;
1422 }
1423 if( pOut==0 ) pOut = stdout;
1424 fprintf(pOut,"%4d %-12s %4d %4d %s\n",
1425 pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
1426 fflush(pOut);
1427}
1428#endif
1429
1430/*
1431** Make sure there is space in the Vdbe structure to hold at least
1432** mxCursor cursors. If there is not currently enough space, then
1433** allocate more.
1434**
1435** If a memory allocation error occurs, return 1. Return 0 if
1436** everything works.
1437*/
1438static int expandCursorArraySize(Vdbe *p, int mxCursor){
1439 if( mxCursor>=p->nCursor ){
1440 Cursor *aCsr = sqliteRealloc( p->aCsr, (mxCursor+1)*sizeof(Cursor) );
1441 if( aCsr==0 ) return 1;
1442 p->aCsr = aCsr;
1443 memset(&p->aCsr[p->nCursor], 0, sizeof(Cursor)*(mxCursor+1-p->nCursor));
1444 p->nCursor = mxCursor+1;
1445 }
1446 return 0;
1447}
1448
1449#ifdef VDBE_PROFILE
1450/*
1451** The following routine only works on pentium-class processors.
1452** It uses the RDTSC opcode to read cycle count value out of the
1453** processor and returns that value. This can be used for high-res
1454** profiling.
1455*/
1456__inline__ unsigned long long int hwtime(void){
1457 unsigned long long int x;
1458 __asm__("rdtsc\n\t"
1459 "mov %%edx, %%ecx\n\t"
1460 :"=A" (x));
1461 return x;
1462}
1463#endif
1464
1465/*
1466** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
1467** sqlite_interrupt() routine has been called. If it has been, then
1468** processing of the VDBE program is interrupted.
1469**
1470** This macro added to every instruction that does a jump in order to
1471** implement a loop. This test used to be on every single instruction,
1472** but that meant we more testing that we needed. By only testing the
1473** flag on jump instructions, we get a (small) speed improvement.
1474*/
1475#define CHECK_FOR_INTERRUPT \
1476 if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
1477
1478
1479/*
1480** Prepare a virtual machine for execution. This involves things such
1481** as allocating stack space and initializing the program counter.
1482** After the VDBE has be prepped, it can be executed by one or more
1483** calls to sqliteVdbeExec().
1484**
1485** The behavior of sqliteVdbeExec() is influenced by the parameters to
1486** this routine. If xCallback is NULL, then sqliteVdbeExec() will return
1487** with SQLITE_ROW whenever there is a row of the result set ready
1488** to be delivered. p->azResColumn will point to the row and
1489** p->nResColumn gives the number of columns in the row. If xCallback
1490** is not NULL, then the xCallback() routine is invoked to process each
1491** row in the result set.
1492*/
1493void sqliteVdbeMakeReady(
1494 Vdbe *p, /* The VDBE */
1495 sqlite_callback xCallback, /* Result callback */
1496 void *pCallbackArg, /* 1st argument to xCallback() */
1497 int isExplain /* True if the EXPLAIN keywords is present */
1498){
1499 int n;
1500#ifdef MEMORY_DEBUG
1501 extern int access(const char*,int);
1502#endif
1503
1504 assert( p!=0 );
1505 assert( p->aStack==0 );
1506 assert( p->magic==VDBE_MAGIC_INIT );
1507
1508 /* Add a HALT instruction to the very end of the program.
1509 */
1510 sqliteVdbeAddOp(p, OP_Halt, 0, 0);
1511
1512 /* No instruction ever pushes more than a single element onto the
1513 ** stack. And the stack never grows on successive executions of the
1514 ** same loop. So the total number of instructions is an upper bound
1515 ** on the maximum stack depth required.
1516 **
1517 ** Allocation all the stack space we will ever need.
1518 */
1519 n = isExplain ? 10 : p->nOp;
1520 p->aStack = sqliteMalloc( n*(sizeof(p->aStack[0]) + 2*sizeof(char*)) );
1521 p->zStack = (char**)&p->aStack[n];
1522 p->azColName = (char**)&p->zStack[n];
1523
1524 sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
1525 p->agg.pSearch = 0;
1526#ifdef MEMORY_DEBUG
1527 if( access("vdbe_trace",0)==0 ){
1528 p->trace = stdout;
1529 }
1530#endif
1531 p->tos = -1;
1532 p->pc = 0;
1533 p->rc = SQLITE_OK;
1534 p->uniqueCnt = 0;
1535 p->returnDepth = 0;
1536 p->errorAction = OE_Abort;
1537 p->undoTransOnError = 0;
1538 p->xCallback = xCallback;
1539 p->pCbArg = pCallbackArg;
1540 p->popStack = 0;
1541 p->explain = isExplain;
1542 p->magic = VDBE_MAGIC_RUN;
1543#ifdef VDBE_PROFILE
1544 for(i=0; i<p->nOp; i++){
1545 p->aOp[i].cnt = 0;
1546 p->aOp[i].cycles = 0;
1547 }
1548#endif
1549}
1550
1551/*
1552** Execute as much of a VDBE program as we can then return.
1553**
1554** sqliteVdbeMakeReady() must be called before this routine in order to
1555** close the program with a final OP_Halt and to set up the callbacks
1556** and the error message pointer.
1557**
1558** Whenever a row or result data is available, this routine will either
1559** invoke the result callback (if there is one) or return with
1560** SQLITE_ROW.
1561**
1562** If an attempt is made to open a locked database, then this routine
1563** will either invoke the busy callback (if there is one) or it will
1564** return SQLITE_BUSY.
1565**
1566** If an error occurs, an error message is written to memory obtained
1567** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
1568** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
1569**
1570** If the callback ever returns non-zero, then the program exits
1571** immediately. There will be no error message but the p->rc field is
1572** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
1573**
1574** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
1575** routine to return SQLITE_ERROR.
1576**
1577** Other fatal errors return SQLITE_ERROR.
1578**
1579** After this routine has finished, sqliteVdbeFinalize() should be
1580** used to clean up the mess that was left behind.
1581*/
1582int sqliteVdbeExec(
1583 Vdbe *p /* The VDBE */
1584){
1585 int pc; /* The program counter */
1586 Op *pOp; /* Current operation */
1587 int rc = SQLITE_OK; /* Value to return */
1588 sqlite *db = p->db; /* The database */
1589 char **zStack = p->zStack; /* Text stack */
1590 Stack *aStack = p->aStack; /* Additional stack information */
1591 char zBuf[100]; /* Space to sprintf() an integer */
1592#ifdef VDBE_PROFILE
1593 unsigned long long start; /* CPU clock count at start of opcode */
1594 int origPc; /* Program counter at start of opcode */
1595#endif
1596
1597 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
1598 assert( db->magic==SQLITE_MAGIC_BUSY );
1599 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
1600 p->rc = SQLITE_OK;
1601 assert( p->explain==0 );
1602 if( sqlite_malloc_failed ) goto no_mem;
1603 if( p->popStack ){
1604 PopStack(p, p->popStack);
1605 p->popStack = 0;
1606 }
1607 for(pc=p->pc; rc==SQLITE_OK; pc++){
1608 assert( pc>=0 && pc<p->nOp );
1609#ifdef VDBE_PROFILE
1610 origPc = pc;
1611 start = hwtime();
1612#endif
1613 pOp = &p->aOp[pc];
1614
1615 /* Only allow tracing if NDEBUG is not defined.
1616 */
1617#ifndef NDEBUG
1618 if( p->trace ){
1619 vdbePrintOp(p->trace, pc, pOp);
1620 }
1621#endif
1622
1623 switch( pOp->opcode ){
1624
1625/*****************************************************************************
1626** What follows is a massive switch statement where each case implements a
1627** separate instruction in the virtual machine. If we follow the usual
1628** indentation conventions, each case should be indented by 6 spaces. But
1629** that is a lot of wasted space on the left margin. So the code within
1630** the switch statement will break with convention and be flush-left. Another
1631** big comment (similar to this one) will mark the point in the code where
1632** we transition back to normal indentation.
1633**
1634** The formatting of each case is important. The makefile for SQLite
1635** generates two C files "opcodes.h" and "opcodes.c" by scanning this
1636** file looking for lines that begin with "case OP_". The opcodes.h files
1637** will be filled with #defines that give unique integer values to each
1638** opcode and the opcodes.c file is filled with an array of strings where
1639** each string is the symbolic name for the corresponding opcode.
1640**
1641** Documentation about VDBE opcodes is generated by scanning this file
1642** for lines of that contain "Opcode:". That line and all subsequent
1643** comment lines are used in the generation of the opcode.html documentation
1644** file.
1645**
1646** SUMMARY:
1647**
1648** Formatting is important to scripts that scan this file.
1649** Do not deviate from the formatting style currently in use.
1650**
1651*****************************************************************************/
1652
1653/* Opcode: Goto * P2 *
1654**
1655** An unconditional jump to address P2.
1656** The next instruction executed will be
1657** the one at index P2 from the beginning of
1658** the program.
1659*/
1660case OP_Goto: {
1661 CHECK_FOR_INTERRUPT;
1662 pc = pOp->p2 - 1;
1663 break;
1664}
1665
1666/* Opcode: Gosub * P2 *
1667**
1668** Push the current address plus 1 onto the return address stack
1669** and then jump to address P2.
1670**
1671** The return address stack is of limited depth. If too many
1672** OP_Gosub operations occur without intervening OP_Returns, then
1673** the return address stack will fill up and processing will abort
1674** with a fatal error.
1675*/
1676case OP_Gosub: {
1677 if( p->returnDepth>=sizeof(p->returnStack)/sizeof(p->returnStack[0]) ){
1678 sqliteSetString(&p->zErrMsg, "return address stack overflow", 0);
1679 p->rc = SQLITE_INTERNAL;
1680 return SQLITE_ERROR;
1681 }
1682 p->returnStack[p->returnDepth++] = pc+1;
1683 pc = pOp->p2 - 1;
1684 break;
1685}
1686
1687/* Opcode: Return * * *
1688**
1689** Jump immediately to the next instruction after the last unreturned
1690** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
1691** processing aborts with a fatal error.
1692*/
1693case OP_Return: {
1694 if( p->returnDepth<=0 ){
1695 sqliteSetString(&p->zErrMsg, "return address stack underflow", 0);
1696 p->rc = SQLITE_INTERNAL;
1697 return SQLITE_ERROR;
1698 }
1699 p->returnDepth--;
1700 pc = p->returnStack[p->returnDepth] - 1;
1701 break;
1702}
1703
1704/* Opcode: Halt P1 P2 *
1705**
1706** Exit immediately. All open cursors, Lists, Sorts, etc are closed
1707** automatically.
1708**
1709** P1 is the result code returned by sqlite_exec(). For a normal
1710** halt, this should be SQLITE_OK (0). For errors, it can be some
1711** other value. If P1!=0 then P2 will determine whether or not to
1712** rollback the current transaction. Do not rollback if P2==OE_Fail.
1713** Do the rollback if P2==OE_Rollback. If P2==OE_Abort, then back
1714** out all changes that have occurred during this execution of the
1715** VDBE, but do not rollback the transaction.
1716**
1717** There is an implied "Halt 0 0 0" instruction inserted at the very end of
1718** every program. So a jump past the last instruction of the program
1719** is the same as executing Halt.
1720*/
1721case OP_Halt: {
1722 p->magic = VDBE_MAGIC_HALT;
1723 if( pOp->p1!=SQLITE_OK ){
1724 p->rc = pOp->p1;
1725 p->errorAction = pOp->p2;
1726 if( pOp->p3 ){
1727 sqliteSetString(&p->zErrMsg, pOp->p3, 0);
1728 }
1729 return SQLITE_ERROR;
1730 }else{
1731 p->rc = SQLITE_OK;
1732 return SQLITE_DONE;
1733 }
1734}
1735
1736/* Opcode: Integer P1 * P3
1737**
1738** The integer value P1 is pushed onto the stack. If P3 is not zero
1739** then it is assumed to be a string representation of the same integer.
1740*/
1741case OP_Integer: {
1742 int i = ++p->tos;
1743 aStack[i].i = pOp->p1;
1744 aStack[i].flags = STK_Int;
1745 if( pOp->p3 ){
1746 zStack[i] = pOp->p3;
1747 aStack[i].flags |= STK_Str | STK_Static;
1748 aStack[i].n = strlen(pOp->p3)+1;
1749 }
1750 break;
1751}
1752
1753/* Opcode: String * * P3
1754**
1755** The string value P3 is pushed onto the stack. If P3==0 then a
1756** NULL is pushed onto the stack.
1757*/
1758case OP_String: {
1759 int i = ++p->tos;
1760 char *z;
1761 z = pOp->p3;
1762 if( z==0 ){
1763 zStack[i] = 0;
1764 aStack[i].n = 0;
1765 aStack[i].flags = STK_Null;
1766 }else{
1767 zStack[i] = z;
1768 aStack[i].n = strlen(z) + 1;
1769 aStack[i].flags = STK_Str | STK_Static;
1770 }
1771 break;
1772}
1773
1774/* Opcode: Pop P1 * *
1775**
1776** P1 elements are popped off of the top of stack and discarded.
1777*/
1778case OP_Pop: {
1779 assert( p->tos+1>=pOp->p1 );
1780 PopStack(p, pOp->p1);
1781 break;
1782}
1783
1784/* Opcode: Dup P1 P2 *
1785**
1786** A copy of the P1-th element of the stack
1787** is made and pushed onto the top of the stack.
1788** The top of the stack is element 0. So the
1789** instruction "Dup 0 0 0" will make a copy of the
1790** top of the stack.
1791**
1792** If the content of the P1-th element is a dynamically
1793** allocated string, then a new copy of that string
1794** is made if P2==0. If P2!=0, then just a pointer
1795** to the string is copied.
1796**
1797** Also see the Pull instruction.
1798*/
1799case OP_Dup: {
1800 int i = p->tos - pOp->p1;
1801 int j = ++p->tos;
1802 VERIFY( if( i<0 ) goto not_enough_stack; )
1803 memcpy(&aStack[j], &aStack[i], sizeof(aStack[i])-NBFS);
1804 if( aStack[j].flags & STK_Str ){
1805 int isStatic = (aStack[j].flags & STK_Static)!=0;
1806 if( pOp->p2 || isStatic ){
1807 zStack[j] = zStack[i];
1808 aStack[j].flags &= ~STK_Dyn;
1809 if( !isStatic ) aStack[j].flags |= STK_Ephem;
1810 }else if( aStack[i].n<=NBFS ){
1811 memcpy(aStack[j].z, zStack[i], aStack[j].n);
1812 zStack[j] = aStack[j].z;
1813 aStack[j].flags &= ~(STK_Static|STK_Dyn|STK_Ephem);
1814 }else{
1815 zStack[j] = sqliteMallocRaw( aStack[j].n );
1816 if( zStack[j]==0 ) goto no_mem;
1817 memcpy(zStack[j], zStack[i], aStack[j].n);
1818 aStack[j].flags &= ~(STK_Static|STK_Ephem);
1819 aStack[j].flags |= STK_Dyn;
1820 }
1821 }
1822 break;
1823}
1824
1825/* Opcode: Pull P1 * *
1826**
1827** The P1-th element is removed from its current location on
1828** the stack and pushed back on top of the stack. The
1829** top of the stack is element 0, so "Pull 0 0 0" is
1830** a no-op. "Pull 1 0 0" swaps the top two elements of
1831** the stack.
1832**
1833** See also the Dup instruction.
1834*/
1835case OP_Pull: {
1836 int from = p->tos - pOp->p1;
1837 int to = p->tos;
1838 int i;
1839 Stack ts;
1840 char *tz;
1841 VERIFY( if( from<0 ) goto not_enough_stack; )
1842 ts = aStack[from];
1843 tz = zStack[from];
1844 Deephemeralize(p, to);
1845 for(i=from; i<to; i++){
1846 Deephemeralize(p, i);
1847 aStack[i] = aStack[i+1];
1848 assert( (aStack[i].flags & STK_Ephem)==0 );
1849 if( aStack[i].flags & (STK_Dyn|STK_Static) ){
1850 zStack[i] = zStack[i+1];
1851 }else{
1852 zStack[i] = aStack[i].z;
1853 }
1854 }
1855 aStack[to] = ts;
1856 assert( (aStack[to].flags & STK_Ephem)==0 );
1857 if( aStack[to].flags & (STK_Dyn|STK_Static) ){
1858 zStack[to] = tz;
1859 }else{
1860 zStack[to] = aStack[to].z;
1861 }
1862 break;
1863}
1864
1865/* Opcode: Push P1 * *
1866**
1867** Overwrite the value of the P1-th element down on the
1868** stack (P1==0 is the top of the stack) with the value
1869** of the top of the stack. Then pop the top of the stack.
1870*/
1871case OP_Push: {
1872 int from = p->tos;
1873 int to = p->tos - pOp->p1;
1874
1875 VERIFY( if( to<0 ) goto not_enough_stack; )
1876 if( aStack[to].flags & STK_Dyn ){
1877 sqliteFree(zStack[to]);
1878 }
1879 Deephemeralize(p, from);
1880 aStack[to] = aStack[from];
1881 if( aStack[to].flags & (STK_Dyn|STK_Static|STK_Ephem) ){
1882 zStack[to] = zStack[from];
1883 }else{
1884 zStack[to] = aStack[to].z;
1885 }
1886 aStack[from].flags = 0;
1887 p->tos--;
1888 break;
1889}
1890
1891/* Opcode: ColumnName P1 * P3
1892**
1893** P3 becomes the P1-th column name (first is 0). An array of pointers
1894** to all column names is passed as the 4th parameter to the callback.
1895*/
1896case OP_ColumnName: {
1897 assert( pOp->p1>=0 && pOp->p1<p->nOp );
1898 p->azColName[pOp->p1] = pOp->p3;
1899 p->nCallback = 0;
1900 break;
1901}
1902
1903/* Opcode: Callback P1 * *
1904**
1905** Pop P1 values off the stack and form them into an array. Then
1906** invoke the callback function using the newly formed array as the
1907** 3rd parameter.
1908*/
1909case OP_Callback: {
1910 int i = p->tos - pOp->p1 + 1;
1911 int j;
1912 VERIFY( if( i<0 ) goto not_enough_stack; )
1913 for(j=i; j<=p->tos; j++){
1914 if( aStack[j].flags & STK_Null ){
1915 zStack[j] = 0;
1916 }else{
1917 Stringify(p, j);
1918 }
1919 }
1920 zStack[p->tos+1] = 0;
1921 if( p->xCallback==0 ){
1922 p->azResColumn = &zStack[i];
1923 p->nResColumn = pOp->p1;
1924 p->popStack = pOp->p1;
1925 p->pc = pc + 1;
1926 return SQLITE_ROW;
1927 }
1928 if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
1929 if( p->xCallback(p->pCbArg, pOp->p1, &zStack[i], p->azColName)!=0 ){
1930 rc = SQLITE_ABORT;
1931 }
1932 if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
1933 p->nCallback++;
1934 PopStack(p, pOp->p1);
1935 if( sqlite_malloc_failed ) goto no_mem;
1936 break;
1937}
1938
1939/* Opcode: NullCallback P1 * *
1940**
1941** Invoke the callback function once with the 2nd argument (the
1942** number of columns) equal to P1 and with the 4th argument (the
1943** names of the columns) set according to prior OP_ColumnName
1944** instructions. This is all like the regular
1945** OP_Callback or OP_SortCallback opcodes. But the 3rd argument
1946** which normally contains a pointer to an array of pointers to
1947** data is NULL.
1948**
1949** The callback is only invoked if there have been no prior calls
1950** to OP_Callback or OP_SortCallback.
1951**
1952** This opcode is used to report the number and names of columns
1953** in cases where the result set is empty.
1954*/
1955case OP_NullCallback: {
1956 if( p->nCallback==0 && p->xCallback!=0 ){
1957 if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
1958 if( p->xCallback(p->pCbArg, pOp->p1, 0, p->azColName)!=0 ){
1959 rc = SQLITE_ABORT;
1960 }
1961 if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
1962 p->nCallback++;
1963 if( sqlite_malloc_failed ) goto no_mem;
1964 }
1965 p->nResColumn = pOp->p1;
1966 break;
1967}
1968
1969/* Opcode: Concat P1 P2 P3
1970**
1971** Look at the first P1 elements of the stack. Append them all
1972** together with the lowest element first. Use P3 as a separator.
1973** Put the result on the top of the stack. The original P1 elements
1974** are popped from the stack if P2==0 and retained if P2==1. If
1975** any element of the stack is NULL, then the result is NULL.
1976**
1977** If P3 is NULL, then use no separator. When P1==1, this routine
1978** makes a copy of the top stack element into memory obtained
1979** from sqliteMalloc().
1980*/
1981case OP_Concat: {
1982 char *zNew;
1983 int nByte;
1984 int nField;
1985 int i, j;
1986 char *zSep;
1987 int nSep;
1988
1989 nField = pOp->p1;
1990 zSep = pOp->p3;
1991 if( zSep==0 ) zSep = "";
1992 nSep = strlen(zSep);
1993 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
1994 nByte = 1 - nSep;
1995 for(i=p->tos-nField+1; i<=p->tos; i++){
1996 if( aStack[i].flags & STK_Null ){
1997 nByte = -1;
1998 break;
1999 }else{
2000 Stringify(p, i);
2001 nByte += aStack[i].n - 1 + nSep;
2002 }
2003 }
2004 if( nByte<0 ){
2005 if( pOp->p2==0 ) PopStack(p, nField);
2006 p->tos++;
2007 aStack[p->tos].flags = STK_Null;
2008 zStack[p->tos] = 0;
2009 break;
2010 }
2011 zNew = sqliteMallocRaw( nByte );
2012 if( zNew==0 ) goto no_mem;
2013 j = 0;
2014 for(i=p->tos-nField+1; i<=p->tos; i++){
2015 if( (aStack[i].flags & STK_Null)==0 ){
2016 memcpy(&zNew[j], zStack[i], aStack[i].n-1);
2017 j += aStack[i].n-1;
2018 }
2019 if( nSep>0 && i<p->tos ){
2020 memcpy(&zNew[j], zSep, nSep);
2021 j += nSep;
2022 }
2023 }
2024 zNew[j] = 0;
2025 if( pOp->p2==0 ) PopStack(p, nField);
2026 p->tos++;
2027 aStack[p->tos].n = nByte;
2028 aStack[p->tos].flags = STK_Str|STK_Dyn;
2029 zStack[p->tos] = zNew;
2030 break;
2031}
2032
2033/* Opcode: Add * * *
2034**
2035** Pop the top two elements from the stack, add them together,
2036** and push the result back onto the stack. If either element
2037** is a string then it is converted to a double using the atof()
2038** function before the addition.
2039** If either operand is NULL, the result is NULL.
2040*/
2041/* Opcode: Multiply * * *
2042**
2043** Pop the top two elements from the stack, multiply them together,
2044** and push the result back onto the stack. If either element
2045** is a string then it is converted to a double using the atof()
2046** function before the multiplication.
2047** If either operand is NULL, the result is NULL.
2048*/
2049/* Opcode: Subtract * * *
2050**
2051** Pop the top two elements from the stack, subtract the
2052** first (what was on top of the stack) from the second (the
2053** next on stack)
2054** and push the result back onto the stack. If either element
2055** is a string then it is converted to a double using the atof()
2056** function before the subtraction.
2057** If either operand is NULL, the result is NULL.
2058*/
2059/* Opcode: Divide * * *
2060**
2061** Pop the top two elements from the stack, divide the
2062** first (what was on top of the stack) from the second (the
2063** next on stack)
2064** and push the result back onto the stack. If either element
2065** is a string then it is converted to a double using the atof()
2066** function before the division. Division by zero returns NULL.
2067** If either operand is NULL, the result is NULL.
2068*/
2069/* Opcode: Remainder * * *
2070**
2071** Pop the top two elements from the stack, divide the
2072** first (what was on top of the stack) from the second (the
2073** next on stack)
2074** and push the remainder after division onto the stack. If either element
2075** is a string then it is converted to a double using the atof()
2076** function before the division. Division by zero returns NULL.
2077** If either operand is NULL, the result is NULL.
2078*/
2079case OP_Add:
2080case OP_Subtract:
2081case OP_Multiply:
2082case OP_Divide:
2083case OP_Remainder: {
2084 int tos = p->tos;
2085 int nos = tos - 1;
2086 VERIFY( if( nos<0 ) goto not_enough_stack; )
2087 if( ((aStack[tos].flags | aStack[nos].flags) & STK_Null)!=0 ){
2088 POPSTACK;
2089 Release(p, nos);
2090 aStack[nos].flags = STK_Null;
2091 }else if( (aStack[tos].flags & aStack[nos].flags & STK_Int)==STK_Int ){
2092 int a, b;
2093 a = aStack[tos].i;
2094 b = aStack[nos].i;
2095 switch( pOp->opcode ){
2096 case OP_Add: b += a; break;
2097 case OP_Subtract: b -= a; break;
2098 case OP_Multiply: b *= a; break;
2099 case OP_Divide: {
2100 if( a==0 ) goto divide_by_zero;
2101 b /= a;
2102 break;
2103 }
2104 default: {
2105 if( a==0 ) goto divide_by_zero;
2106 b %= a;
2107 break;
2108 }
2109 }
2110 POPSTACK;
2111 Release(p, nos);
2112 aStack[nos].i = b;
2113 aStack[nos].flags = STK_Int;
2114 }else{
2115 double a, b;
2116 Realify(p, tos);
2117 Realify(p, nos);
2118 a = aStack[tos].r;
2119 b = aStack[nos].r;
2120 switch( pOp->opcode ){
2121 case OP_Add: b += a; break;
2122 case OP_Subtract: b -= a; break;
2123 case OP_Multiply: b *= a; break;
2124 case OP_Divide: {
2125 if( a==0.0 ) goto divide_by_zero;
2126 b /= a;
2127 break;
2128 }
2129 default: {
2130 int ia = (int)a;
2131 int ib = (int)b;
2132 if( ia==0.0 ) goto divide_by_zero;
2133 b = ib % ia;
2134 break;
2135 }
2136 }
2137 POPSTACK;
2138 Release(p, nos);
2139 aStack[nos].r = b;
2140 aStack[nos].flags = STK_Real;
2141 }
2142 break;
2143
2144divide_by_zero:
2145 PopStack(p, 2);
2146 p->tos = nos;
2147 aStack[nos].flags = STK_Null;
2148 break;
2149}
2150
2151/* Opcode: Function P1 * P3
2152**
2153** Invoke a user function (P3 is a pointer to a Function structure that
2154** defines the function) with P1 string arguments taken from the stack.
2155** Pop all arguments from the stack and push back the result.
2156**
2157** See also: AggFunc
2158*/
2159case OP_Function: {
2160 int n, i;
2161 sqlite_func ctx;
2162
2163 n = pOp->p1;
2164 VERIFY( if( n<0 ) goto bad_instruction; )
2165 VERIFY( if( p->tos+1<n ) goto not_enough_stack; )
2166 for(i=p->tos-n+1; i<=p->tos; i++){
2167 if( aStack[i].flags & STK_Null ){
2168 zStack[i] = 0;
2169 }else{
2170 Stringify(p, i);
2171 }
2172 }
2173 ctx.pFunc = (FuncDef*)pOp->p3;
2174 ctx.s.flags = STK_Null;
2175 ctx.z = 0;
2176 ctx.isError = 0;
2177 ctx.isStep = 0;
2178 (*ctx.pFunc->xFunc)(&ctx, n, (const char**)&zStack[p->tos-n+1]);
2179 PopStack(p, n);
2180 p->tos++;
2181 aStack[p->tos] = ctx.s;
2182 if( ctx.s.flags & STK_Dyn ){
2183 zStack[p->tos] = ctx.z;
2184 }else if( ctx.s.flags & STK_Str ){
2185 zStack[p->tos] = aStack[p->tos].z;
2186 }else{
2187 zStack[p->tos] = 0;
2188 }
2189 if( ctx.isError ){
2190 sqliteSetString(&p->zErrMsg,
2191 zStack[p->tos] ? zStack[p->tos] : "user function error", 0);
2192 rc = SQLITE_ERROR;
2193 }
2194 break;
2195}
2196
2197/* Opcode: BitAnd * * *
2198**
2199** Pop the top two elements from the stack. Convert both elements
2200** to integers. Push back onto the stack the bit-wise AND of the
2201** two elements.
2202** If either operand is NULL, the result is NULL.
2203*/
2204/* Opcode: BitOr * * *
2205**
2206** Pop the top two elements from the stack. Convert both elements
2207** to integers. Push back onto the stack the bit-wise OR of the
2208** two elements.
2209** If either operand is NULL, the result is NULL.
2210*/
2211/* Opcode: ShiftLeft * * *
2212**
2213** Pop the top two elements from the stack. Convert both elements
2214** to integers. Push back onto the stack the top element shifted
2215** left by N bits where N is the second element on the stack.
2216** If either operand is NULL, the result is NULL.
2217*/
2218/* Opcode: ShiftRight * * *
2219**
2220** Pop the top two elements from the stack. Convert both elements
2221** to integers. Push back onto the stack the top element shifted
2222** right by N bits where N is the second element on the stack.
2223** If either operand is NULL, the result is NULL.
2224*/
2225case OP_BitAnd:
2226case OP_BitOr:
2227case OP_ShiftLeft:
2228case OP_ShiftRight: {
2229 int tos = p->tos;
2230 int nos = tos - 1;
2231 int a, b;
2232 VERIFY( if( nos<0 ) goto not_enough_stack; )
2233 if( (aStack[tos].flags | aStack[nos].flags) & STK_Null ){
2234 POPSTACK;
2235 Release(p,nos);
2236 aStack[nos].flags = STK_Null;
2237 break;
2238 }
2239 Integerify(p, tos);
2240 Integerify(p, nos);
2241 a = aStack[tos].i;
2242 b = aStack[nos].i;
2243 switch( pOp->opcode ){
2244 case OP_BitAnd: a &= b; break;
2245 case OP_BitOr: a |= b; break;
2246 case OP_ShiftLeft: a <<= b; break;
2247 case OP_ShiftRight: a >>= b; break;
2248 default: /* CANT HAPPEN */ break;
2249 }
2250 POPSTACK;
2251 Release(p, nos);
2252 aStack[nos].i = a;
2253 aStack[nos].flags = STK_Int;
2254 break;
2255}
2256
2257/* Opcode: AddImm P1 * *
2258**
2259** Add the value P1 to whatever is on top of the stack. The result
2260** is always an integer.
2261**
2262** To force the top of the stack to be an integer, just add 0.
2263*/
2264case OP_AddImm: {
2265 int tos = p->tos;
2266 VERIFY( if( tos<0 ) goto not_enough_stack; )
2267 Integerify(p, tos);
2268 aStack[tos].i += pOp->p1;
2269 break;
2270}
2271
2272/* Opcode: MustBeInt P1 P2 *
2273**
2274** Force the top of the stack to be an integer. If the top of the
2275** stack is not an integer and cannot be converted into an integer
2276** with out data loss, then jump immediately to P2, or if P2==0
2277** raise an SQLITE_MISMATCH exception.
2278**
2279** If the top of the stack is not an integer and P2 is not zero and
2280** P1 is 1, then the stack is popped. In all other cases, the depth
2281** of the stack is unchanged.
2282*/
2283case OP_MustBeInt: {
2284 int tos = p->tos;
2285 VERIFY( if( tos<0 ) goto not_enough_stack; )
2286 if( aStack[tos].flags & STK_Int ){
2287 /* Do nothing */
2288 }else if( aStack[tos].flags & STK_Real ){
2289 int i = aStack[tos].r;
2290 double r = i;
2291 if( r!=aStack[tos].r ){
2292 goto mismatch;
2293 }
2294 aStack[tos].i = i;
2295 }else if( aStack[tos].flags & STK_Str ){
2296 int v;
2297 if( !toInt(zStack[tos], &v) ){
2298 goto mismatch;
2299 }
2300 p->aStack[tos].i = v;
2301 }else{
2302 goto mismatch;
2303 }
2304 Release(p, tos);
2305 p->aStack[tos].flags = STK_Int;
2306 break;
2307
2308mismatch:
2309 if( pOp->p2==0 ){
2310 rc = SQLITE_MISMATCH;
2311 goto abort_due_to_error;
2312 }else{
2313 if( pOp->p1 ) POPSTACK;
2314 pc = pOp->p2 - 1;
2315 }
2316 break;
2317}
2318
2319/* Opcode: Eq P1 P2 *
2320**
2321** Pop the top two elements from the stack. If they are equal, then
2322** jump to instruction P2. Otherwise, continue to the next instruction.
2323**
2324** If either operand is NULL (and thus if the result is unknown) then
2325** take the jump if P1 is true.
2326**
2327** If both values are numeric, they are converted to doubles using atof()
2328** and compared for equality that way. Otherwise the strcmp() library
2329** routine is used for the comparison. For a pure text comparison
2330** use OP_StrEq.
2331**
2332** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2333** stack if the jump would have been taken, or a 0 if not. Push a
2334** NULL if either operand was NULL.
2335*/
2336/* Opcode: Ne P1 P2 *
2337**
2338** Pop the top two elements from the stack. If they are not equal, then
2339** jump to instruction P2. Otherwise, continue to the next instruction.
2340**
2341** If either operand is NULL (and thus if the result is unknown) then
2342** take the jump if P1 is true.
2343**
2344** If both values are numeric, they are converted to doubles using atof()
2345** and compared in that format. Otherwise the strcmp() library
2346** routine is used for the comparison. For a pure text comparison
2347** use OP_StrNe.
2348**
2349** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2350** stack if the jump would have been taken, or a 0 if not. Push a
2351** NULL if either operand was NULL.
2352*/
2353/* Opcode: Lt P1 P2 *
2354**
2355** Pop the top two elements from the stack. If second element (the
2356** next on stack) is less than the first (the top of stack), then
2357** jump to instruction P2. Otherwise, continue to the next instruction.
2358** In other words, jump if NOS<TOS.
2359**
2360** If either operand is NULL (and thus if the result is unknown) then
2361** take the jump if P1 is true.
2362**
2363** If both values are numeric, they are converted to doubles using atof()
2364** and compared in that format. Numeric values are always less than
2365** non-numeric values. If both operands are non-numeric, the strcmp() library
2366** routine is used for the comparison. For a pure text comparison
2367** use OP_StrLt.
2368**
2369** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2370** stack if the jump would have been taken, or a 0 if not. Push a
2371** NULL if either operand was NULL.
2372*/
2373/* Opcode: Le P1 P2 *
2374**
2375** Pop the top two elements from the stack. If second element (the
2376** next on stack) is less than or equal to the first (the top of stack),
2377** then jump to instruction P2. In other words, jump if NOS<=TOS.
2378**
2379** If either operand is NULL (and thus if the result is unknown) then
2380** take the jump if P1 is true.
2381**
2382** If both values are numeric, they are converted to doubles using atof()
2383** and compared in that format. Numeric values are always less than
2384** non-numeric values. If both operands are non-numeric, the strcmp() library
2385** routine is used for the comparison. For a pure text comparison
2386** use OP_StrLe.
2387**
2388** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2389** stack if the jump would have been taken, or a 0 if not. Push a
2390** NULL if either operand was NULL.
2391*/
2392/* Opcode: Gt P1 P2 *
2393**
2394** Pop the top two elements from the stack. If second element (the
2395** next on stack) is greater than the first (the top of stack),
2396** then jump to instruction P2. In other words, jump if NOS>TOS.
2397**
2398** If either operand is NULL (and thus if the result is unknown) then
2399** take the jump if P1 is true.
2400**
2401** If both values are numeric, they are converted to doubles using atof()
2402** and compared in that format. Numeric values are always less than
2403** non-numeric values. If both operands are non-numeric, the strcmp() library
2404** routine is used for the comparison. For a pure text comparison
2405** use OP_StrGt.
2406**
2407** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2408** stack if the jump would have been taken, or a 0 if not. Push a
2409** NULL if either operand was NULL.
2410*/
2411/* Opcode: Ge P1 P2 *
2412**
2413** Pop the top two elements from the stack. If second element (the next
2414** on stack) is greater than or equal to the first (the top of stack),
2415** then jump to instruction P2. In other words, jump if NOS>=TOS.
2416**
2417** If either operand is NULL (and thus if the result is unknown) then
2418** take the jump if P1 is true.
2419**
2420** If both values are numeric, they are converted to doubles using atof()
2421** and compared in that format. Numeric values are always less than
2422** non-numeric values. If both operands are non-numeric, the strcmp() library
2423** routine is used for the comparison. For a pure text comparison
2424** use OP_StrGe.
2425**
2426** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2427** stack if the jump would have been taken, or a 0 if not. Push a
2428** NULL if either operand was NULL.
2429*/
2430case OP_Eq:
2431case OP_Ne:
2432case OP_Lt:
2433case OP_Le:
2434case OP_Gt:
2435case OP_Ge: {
2436 int tos = p->tos;
2437 int nos = tos - 1;
2438 int c, v;
2439 int ft, fn;
2440 VERIFY( if( nos<0 ) goto not_enough_stack; )
2441 ft = aStack[tos].flags;
2442 fn = aStack[nos].flags;
2443 if( (ft | fn) & STK_Null ){
2444 POPSTACK;
2445 POPSTACK;
2446 if( pOp->p2 ){
2447 if( pOp->p1 ) pc = pOp->p2-1;
2448 }else{
2449 p->tos++;
2450 aStack[nos].flags = STK_Null;
2451 }
2452 break;
2453 }else if( (ft & fn & STK_Int)==STK_Int ){
2454 c = aStack[nos].i - aStack[tos].i;
2455 }else if( (ft & STK_Int)!=0 && (fn & STK_Str)!=0 && toInt(zStack[nos],&v) ){
2456 Release(p, nos);
2457 aStack[nos].i = v;
2458 aStack[nos].flags = STK_Int;
2459 c = aStack[nos].i - aStack[tos].i;
2460 }else if( (fn & STK_Int)!=0 && (ft & STK_Str)!=0 && toInt(zStack[tos],&v) ){
2461 Release(p, tos);
2462 aStack[tos].i = v;
2463 aStack[tos].flags = STK_Int;
2464 c = aStack[nos].i - aStack[tos].i;
2465 }else{
2466 Stringify(p, tos);
2467 Stringify(p, nos);
2468 c = sqliteCompare(zStack[nos], zStack[tos]);
2469 }
2470 switch( pOp->opcode ){
2471 case OP_Eq: c = c==0; break;
2472 case OP_Ne: c = c!=0; break;
2473 case OP_Lt: c = c<0; break;
2474 case OP_Le: c = c<=0; break;
2475 case OP_Gt: c = c>0; break;
2476 default: c = c>=0; break;
2477 }
2478 POPSTACK;
2479 POPSTACK;
2480 if( pOp->p2 ){
2481 if( c ) pc = pOp->p2-1;
2482 }else{
2483 p->tos++;
2484 aStack[nos].flags = STK_Int;
2485 aStack[nos].i = c;
2486 }
2487 break;
2488}
2489/* INSERT NO CODE HERE!
2490**
2491** The opcode numbers are extracted from this source file by doing
2492**
2493** grep '^case OP_' vdbe.c | ... >opcodes.h
2494**
2495** The opcodes are numbered in the order that they appear in this file.
2496** But in order for the expression generating code to work right, the
2497** string comparison operators that follow must be numbered exactly 6
2498** greater than the numeric comparison opcodes above. So no other
2499** cases can appear between the two.
2500*/
2501/* Opcode: StrEq P1 P2 *
2502**
2503** Pop the top two elements from the stack. If they are equal, then
2504** jump to instruction P2. Otherwise, continue to the next instruction.
2505**
2506** If either operand is NULL (and thus if the result is unknown) then
2507** take the jump if P1 is true.
2508**
2509** The strcmp() library routine is used for the comparison. For a
2510** numeric comparison, use OP_Eq.
2511**
2512** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2513** stack if the jump would have been taken, or a 0 if not. Push a
2514** NULL if either operand was NULL.
2515*/
2516/* Opcode: StrNe P1 P2 *
2517**
2518** Pop the top two elements from the stack. If they are not equal, then
2519** jump to instruction P2. Otherwise, continue to the next instruction.
2520**
2521** If either operand is NULL (and thus if the result is unknown) then
2522** take the jump if P1 is true.
2523**
2524** The strcmp() library routine is used for the comparison. For a
2525** numeric comparison, use OP_Ne.
2526**
2527** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2528** stack if the jump would have been taken, or a 0 if not. Push a
2529** NULL if either operand was NULL.
2530*/
2531/* Opcode: StrLt P1 P2 *
2532**
2533** Pop the top two elements from the stack. If second element (the
2534** next on stack) is less than the first (the top of stack), then
2535** jump to instruction P2. Otherwise, continue to the next instruction.
2536** In other words, jump if NOS<TOS.
2537**
2538** If either operand is NULL (and thus if the result is unknown) then
2539** take the jump if P1 is true.
2540**
2541** The strcmp() library routine is used for the comparison. For a
2542** numeric comparison, use OP_Lt.
2543**
2544** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2545** stack if the jump would have been taken, or a 0 if not. Push a
2546** NULL if either operand was NULL.
2547*/
2548/* Opcode: StrLe P1 P2 *
2549**
2550** Pop the top two elements from the stack. If second element (the
2551** next on stack) is less than or equal to the first (the top of stack),
2552** then jump to instruction P2. In other words, jump if NOS<=TOS.
2553**
2554** If either operand is NULL (and thus if the result is unknown) then
2555** take the jump if P1 is true.
2556**
2557** The strcmp() library routine is used for the comparison. For a
2558** numeric comparison, use OP_Le.
2559**
2560** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2561** stack if the jump would have been taken, or a 0 if not. Push a
2562** NULL if either operand was NULL.
2563*/
2564/* Opcode: StrGt P1 P2 *
2565**
2566** Pop the top two elements from the stack. If second element (the
2567** next on stack) is greater than the first (the top of stack),
2568** then jump to instruction P2. In other words, jump if NOS>TOS.
2569**
2570** If either operand is NULL (and thus if the result is unknown) then
2571** take the jump if P1 is true.
2572**
2573** The strcmp() library routine is used for the comparison. For a
2574** numeric comparison, use OP_Gt.
2575**
2576** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2577** stack if the jump would have been taken, or a 0 if not. Push a
2578** NULL if either operand was NULL.
2579*/
2580/* Opcode: StrGe P1 P2 *
2581**
2582** Pop the top two elements from the stack. If second element (the next
2583** on stack) is greater than or equal to the first (the top of stack),
2584** then jump to instruction P2. In other words, jump if NOS>=TOS.
2585**
2586** If either operand is NULL (and thus if the result is unknown) then
2587** take the jump if P1 is true.
2588**
2589** The strcmp() library routine is used for the comparison. For a
2590** numeric comparison, use OP_Ge.
2591**
2592** If P2 is zero, do not jump. Instead, push an integer 1 onto the
2593** stack if the jump would have been taken, or a 0 if not. Push a
2594** NULL if either operand was NULL.
2595*/
2596case OP_StrEq:
2597case OP_StrNe:
2598case OP_StrLt:
2599case OP_StrLe:
2600case OP_StrGt:
2601case OP_StrGe: {
2602 int tos = p->tos;
2603 int nos = tos - 1;
2604 int c;
2605 VERIFY( if( nos<0 ) goto not_enough_stack; )
2606 if( (aStack[nos].flags | aStack[tos].flags) & STK_Null ){
2607 POPSTACK;
2608 POPSTACK;
2609 if( pOp->p2 ){
2610 if( pOp->p1 ) pc = pOp->p2-1;
2611 }else{
2612 p->tos++;
2613 aStack[nos].flags = STK_Null;
2614 }
2615 break;
2616 }else{
2617 Stringify(p, tos);
2618 Stringify(p, nos);
2619 c = strcmp(zStack[nos], zStack[tos]);
2620 }
2621 /* The asserts on each case of the following switch are there to verify
2622 ** that string comparison opcodes are always exactly 6 greater than the
2623 ** corresponding numeric comparison opcodes. The code generator depends
2624 ** on this fact.
2625 */
2626 switch( pOp->opcode ){
2627 case OP_StrEq: c = c==0; assert( pOp->opcode-6==OP_Eq ); break;
2628 case OP_StrNe: c = c!=0; assert( pOp->opcode-6==OP_Ne ); break;
2629 case OP_StrLt: c = c<0; assert( pOp->opcode-6==OP_Lt ); break;
2630 case OP_StrLe: c = c<=0; assert( pOp->opcode-6==OP_Le ); break;
2631 case OP_StrGt: c = c>0; assert( pOp->opcode-6==OP_Gt ); break;
2632 default: c = c>=0; assert( pOp->opcode-6==OP_Ge ); break;
2633 }
2634 POPSTACK;
2635 POPSTACK;
2636 if( pOp->p2 ){
2637 if( c ) pc = pOp->p2-1;
2638 }else{
2639 p->tos++;
2640 aStack[nos].flags = STK_Int;
2641 aStack[nos].i = c;
2642 }
2643 break;
2644}
2645
2646/* Opcode: And * * *
2647**
2648** Pop two values off the stack. Take the logical AND of the
2649** two values and push the resulting boolean value back onto the
2650** stack.
2651*/
2652/* Opcode: Or * * *
2653**
2654** Pop two values off the stack. Take the logical OR of the
2655** two values and push the resulting boolean value back onto the
2656** stack.
2657*/
2658case OP_And:
2659case OP_Or: {
2660 int tos = p->tos;
2661 int nos = tos - 1;
2662 int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
2663
2664 VERIFY( if( nos<0 ) goto not_enough_stack; )
2665 if( aStack[tos].flags & STK_Null ){
2666 v1 = 2;
2667 }else{
2668 Integerify(p, tos);
2669 v1 = aStack[tos].i==0;
2670 }
2671 if( aStack[nos].flags & STK_Null ){
2672 v2 = 2;
2673 }else{
2674 Integerify(p, nos);
2675 v2 = aStack[nos].i==0;
2676 }
2677 if( pOp->opcode==OP_And ){
2678 static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
2679 v1 = and_logic[v1*3+v2];
2680 }else{
2681 static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
2682 v1 = or_logic[v1*3+v2];
2683 }
2684 POPSTACK;
2685 Release(p, nos);
2686 if( v1==2 ){
2687 aStack[nos].flags = STK_Null;
2688 }else{
2689 aStack[nos].i = v1==0;
2690 aStack[nos].flags = STK_Int;
2691 }
2692 break;
2693}
2694
2695/* Opcode: Negative * * *
2696**
2697** Treat the top of the stack as a numeric quantity. Replace it
2698** with its additive inverse. If the top of the stack is NULL
2699** its value is unchanged.
2700*/
2701/* Opcode: AbsValue * * *
2702**
2703** Treat the top of the stack as a numeric quantity. Replace it
2704** with its absolute value. If the top of the stack is NULL
2705** its value is unchanged.
2706*/
2707case OP_Negative:
2708case OP_AbsValue: {
2709 int tos = p->tos;
2710 VERIFY( if( tos<0 ) goto not_enough_stack; )
2711 if( aStack[tos].flags & STK_Real ){
2712 Release(p, tos);
2713 if( pOp->opcode==OP_Negative || aStack[tos].r<0.0 ){
2714 aStack[tos].r = -aStack[tos].r;
2715 }
2716 aStack[tos].flags = STK_Real;
2717 }else if( aStack[tos].flags & STK_Int ){
2718 Release(p, tos);
2719 if( pOp->opcode==OP_Negative || aStack[tos].i<0 ){
2720 aStack[tos].i = -aStack[tos].i;
2721 }
2722 aStack[tos].flags = STK_Int;
2723 }else if( aStack[tos].flags & STK_Null ){
2724 /* Do nothing */
2725 }else{
2726 Realify(p, tos);
2727 Release(p, tos);
2728 if( pOp->opcode==OP_Negative || aStack[tos].r<0.0 ){
2729 aStack[tos].r = -aStack[tos].r;
2730 }
2731 aStack[tos].flags = STK_Real;
2732 }
2733 break;
2734}
2735
2736/* Opcode: Not * * *
2737**
2738** Interpret the top of the stack as a boolean value. Replace it
2739** with its complement. If the top of the stack is NULL its value
2740** is unchanged.
2741*/
2742case OP_Not: {
2743 int tos = p->tos;
2744 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
2745 if( aStack[tos].flags & STK_Null ) break; /* Do nothing to NULLs */
2746 Integerify(p, tos);
2747 Release(p, tos);
2748 aStack[tos].i = !aStack[tos].i;
2749 aStack[tos].flags = STK_Int;
2750 break;
2751}
2752
2753/* Opcode: BitNot * * *
2754**
2755** Interpret the top of the stack as an value. Replace it
2756** with its ones-complement. If the top of the stack is NULL its
2757** value is unchanged.
2758*/
2759case OP_BitNot: {
2760 int tos = p->tos;
2761 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
2762 if( aStack[tos].flags & STK_Null ) break; /* Do nothing to NULLs */
2763 Integerify(p, tos);
2764 Release(p, tos);
2765 aStack[tos].i = ~aStack[tos].i;
2766 aStack[tos].flags = STK_Int;
2767 break;
2768}
2769
2770/* Opcode: Noop * * *
2771**
2772** Do nothing. This instruction is often useful as a jump
2773** destination.
2774*/
2775case OP_Noop: {
2776 break;
2777}
2778
2779/* Opcode: If P1 P2 *
2780**
2781** Pop a single boolean from the stack. If the boolean popped is
2782** true, then jump to p2. Otherwise continue to the next instruction.
2783** An integer is false if zero and true otherwise. A string is
2784** false if it has zero length and true otherwise.
2785**
2786** If the value popped of the stack is NULL, then take the jump if P1
2787** is true and fall through if P1 is false.
2788*/
2789/* Opcode: IfNot P1 P2 *
2790**
2791** Pop a single boolean from the stack. If the boolean popped is
2792** false, then jump to p2. Otherwise continue to the next instruction.
2793** An integer is false if zero and true otherwise. A string is
2794** false if it has zero length and true otherwise.
2795**
2796** If the value popped of the stack is NULL, then take the jump if P1
2797** is true and fall through if P1 is false.
2798*/
2799case OP_If:
2800case OP_IfNot: {
2801 int c;
2802 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
2803 if( aStack[p->tos].flags & STK_Null ){
2804 c = pOp->p1;
2805 }else{
2806 Integerify(p, p->tos);
2807 c = aStack[p->tos].i;
2808 if( pOp->opcode==OP_IfNot ) c = !c;
2809 }
2810 POPSTACK;
2811 if( c ) pc = pOp->p2-1;
2812 break;
2813}
2814
2815/* Opcode: IsNull P1 P2 *
2816**
2817** If any of the top abs(P1) values on the stack are NULL, then jump
2818** to P2. The stack is popped P1 times if P1>0. If P1<0 then all values
2819** are left unchanged on the stack.
2820*/
2821case OP_IsNull: {
2822 int i, cnt;
2823 cnt = pOp->p1;
2824 if( cnt<0 ) cnt = -cnt;
2825 VERIFY( if( p->tos+1-cnt<0 ) goto not_enough_stack; )
2826 for(i=0; i<cnt; i++){
2827 if( aStack[p->tos-i].flags & STK_Null ){
2828 pc = pOp->p2-1;
2829 break;
2830 }
2831 }
2832 if( pOp->p1>0 ) PopStack(p, cnt);
2833 break;
2834}
2835
2836/* Opcode: NotNull P1 P2 *
2837**
2838** Jump to P2 if the top value on the stack is not NULL. Pop the
2839** stack if P1 is greater than zero. If P1 is less than or equal to
2840** zero then leave the value on the stack.
2841*/
2842case OP_NotNull: {
2843 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
2844 if( (aStack[p->tos].flags & STK_Null)==0 ) pc = pOp->p2-1;
2845 if( pOp->p1>0 ){ POPSTACK; }
2846 break;
2847}
2848
2849/* Opcode: MakeRecord P1 P2 *
2850**
2851** Convert the top P1 entries of the stack into a single entry
2852** suitable for use as a data record in a database table. The
2853** details of the format are irrelavant as long as the OP_Column
2854** opcode can decode the record later. Refer to source code
2855** comments for the details of the record format.
2856**
2857** If P2 is true (non-zero) and one or more of the P1 entries
2858** that go into building the record is NULL, then add some extra
2859** bytes to the record to make it distinct for other entries created
2860** during the same run of the VDBE. The extra bytes added are a
2861** counter that is reset with each run of the VDBE, so records
2862** created this way will not necessarily be distinct across runs.
2863** But they should be distinct for transient tables (created using
2864** OP_OpenTemp) which is what they are intended for.
2865**
2866** (Later:) The P2==1 option was intended to make NULLs distinct
2867** for the UNION operator. But I have since discovered that NULLs
2868** are indistinct for UNION. So this option is never used.
2869*/
2870case OP_MakeRecord: {
2871 char *zNewRecord;
2872 int nByte;
2873 int nField;
2874 int i, j;
2875 int idxWidth;
2876 u32 addr;
2877 int addUnique = 0; /* True to cause bytes to be added to make the
2878 ** generated record distinct */
2879 char zTemp[NBFS]; /* Temp space for small records */
2880
2881 /* Assuming the record contains N fields, the record format looks
2882 ** like this:
2883 **
2884 ** -------------------------------------------------------------------
2885 ** | idx0 | idx1 | ... | idx(N-1) | idx(N) | data0 | ... | data(N-1) |
2886 ** -------------------------------------------------------------------
2887 **
2888 ** All data fields are converted to strings before being stored and
2889 ** are stored with their null terminators. NULL entries omit the
2890 ** null terminator. Thus an empty string uses 1 byte and a NULL uses
2891 ** zero bytes. Data(0) is taken from the lowest element of the stack
2892 ** and data(N-1) is the top of the stack.
2893 **
2894 ** Each of the idx() entries is either 1, 2, or 3 bytes depending on
2895 ** how big the total record is. Idx(0) contains the offset to the start
2896 ** of data(0). Idx(k) contains the offset to the start of data(k).
2897 ** Idx(N) contains the total number of bytes in the record.
2898 */
2899 nField = pOp->p1;
2900 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
2901 nByte = 0;
2902 for(i=p->tos-nField+1; i<=p->tos; i++){
2903 if( (aStack[i].flags & STK_Null) ){
2904 addUnique = pOp->p2;
2905 }else{
2906 Stringify(p, i);
2907 nByte += aStack[i].n;
2908 }
2909 }
2910 if( addUnique ) nByte += sizeof(p->uniqueCnt);
2911 if( nByte + nField + 1 < 256 ){
2912 idxWidth = 1;
2913 }else if( nByte + 2*nField + 2 < 65536 ){
2914 idxWidth = 2;
2915 }else{
2916 idxWidth = 3;
2917 }
2918 nByte += idxWidth*(nField + 1);
2919 if( nByte>MAX_BYTES_PER_ROW ){
2920 rc = SQLITE_TOOBIG;
2921 goto abort_due_to_error;
2922 }
2923 if( nByte<=NBFS ){
2924 zNewRecord = zTemp;
2925 }else{
2926 zNewRecord = sqliteMallocRaw( nByte );
2927 if( zNewRecord==0 ) goto no_mem;
2928 }
2929 j = 0;
2930 addr = idxWidth*(nField+1) + addUnique*sizeof(p->uniqueCnt);
2931 for(i=p->tos-nField+1; i<=p->tos; i++){
2932 zNewRecord[j++] = addr & 0xff;
2933 if( idxWidth>1 ){
2934 zNewRecord[j++] = (addr>>8)&0xff;
2935 if( idxWidth>2 ){
2936 zNewRecord[j++] = (addr>>16)&0xff;
2937 }
2938 }
2939 if( (aStack[i].flags & STK_Null)==0 ){
2940 addr += aStack[i].n;
2941 }
2942 }
2943 zNewRecord[j++] = addr & 0xff;
2944 if( idxWidth>1 ){
2945 zNewRecord[j++] = (addr>>8)&0xff;
2946 if( idxWidth>2 ){
2947 zNewRecord[j++] = (addr>>16)&0xff;
2948 }
2949 }
2950 if( addUnique ){
2951 memcpy(&zNewRecord[j], &p->uniqueCnt, sizeof(p->uniqueCnt));
2952 p->uniqueCnt++;
2953 j += sizeof(p->uniqueCnt);
2954 }
2955 for(i=p->tos-nField+1; i<=p->tos; i++){
2956 if( (aStack[i].flags & STK_Null)==0 ){
2957 memcpy(&zNewRecord[j], zStack[i], aStack[i].n);
2958 j += aStack[i].n;
2959 }
2960 }
2961 PopStack(p, nField);
2962 p->tos++;
2963 aStack[p->tos].n = nByte;
2964 if( nByte<=NBFS ){
2965 assert( zNewRecord==zTemp );
2966 memcpy(aStack[p->tos].z, zTemp, nByte);
2967 zStack[p->tos] = aStack[p->tos].z;
2968 aStack[p->tos].flags = STK_Str;
2969 }else{
2970 assert( zNewRecord!=zTemp );
2971 aStack[p->tos].flags = STK_Str | STK_Dyn;
2972 zStack[p->tos] = zNewRecord;
2973 }
2974 break;
2975}
2976
2977/* Opcode: MakeKey P1 P2 P3
2978**
2979** Convert the top P1 entries of the stack into a single entry suitable
2980** for use as the key in an index. The top P1 records are
2981** converted to strings and merged. The null-terminators
2982** are retained and used as separators.
2983** The lowest entry in the stack is the first field and the top of the
2984** stack becomes the last.
2985**
2986** If P2 is not zero, then the original entries remain on the stack
2987** and the new key is pushed on top. If P2 is zero, the original
2988** data is popped off the stack first then the new key is pushed
2989** back in its place.
2990**
2991** P3 is a string that is P1 characters long. Each character is either
2992** an 'n' or a 't' to indicates if the argument should be numeric or
2993** text. The first character corresponds to the lowest element on the
2994** stack. If P3 is NULL then all arguments are assumed to be numeric.
2995**
2996** The key is a concatenation of fields. Each field is terminated by
2997** a single 0x00 character. A NULL field is introduced by an 'a' and
2998** is followed immediately by its 0x00 terminator. A numeric field is
2999** introduced by a single character 'b' and is followed by a sequence
3000** of characters that represent the number such that a comparison of
3001** the character string using memcpy() sorts the numbers in numerical
3002** order. The character strings for numbers are generated using the
3003** sqliteRealToSortable() function. A text field is introduced by a
3004** 'c' character and is followed by the exact text of the field. The
3005** use of an 'a', 'b', or 'c' character at the beginning of each field
3006** guarantees that NULL sort before numbers and that numbers sort
3007** before text. 0x00 characters do not occur except as separators
3008** between fields.
3009**
3010** See also: MakeIdxKey, SortMakeKey
3011*/
3012/* Opcode: MakeIdxKey P1 P2 P3
3013**
3014** Convert the top P1 entries of the stack into a single entry suitable
3015** for use as the key in an index. In addition, take one additional integer
3016** off of the stack, treat that integer as a four-byte record number, and
3017** append the four bytes to the key. Thus a total of P1+1 entries are
3018** popped from the stack for this instruction and a single entry is pushed
3019** back. The first P1 entries that are popped are strings and the last
3020** entry (the lowest on the stack) is an integer record number.
3021**
3022** The converstion of the first P1 string entries occurs just like in
3023** MakeKey. Each entry is separated from the others by a null.
3024** The entire concatenation is null-terminated. The lowest entry
3025** in the stack is the first field and the top of the stack becomes the
3026** last.
3027**
3028** If P2 is not zero and one or more of the P1 entries that go into the
3029** generated key is NULL, then jump to P2 after the new key has been
3030** pushed on the stack. In other words, jump to P2 if the key is
3031** guaranteed to be unique. This jump can be used to skip a subsequent
3032** uniqueness test.
3033**
3034** P3 is a string that is P1 characters long. Each character is either
3035** an 'n' or a 't' to indicates if the argument should be numeric or
3036** text. The first character corresponds to the lowest element on the
3037** stack. If P3 is null then all arguments are assumed to be numeric.
3038**
3039** See also: MakeKey, SortMakeKey
3040*/
3041case OP_MakeIdxKey:
3042case OP_MakeKey: {
3043 char *zNewKey;
3044 int nByte;
3045 int nField;
3046 int addRowid;
3047 int i, j;
3048 int containsNull = 0;
3049 char zTemp[NBFS];
3050
3051 addRowid = pOp->opcode==OP_MakeIdxKey;
3052 nField = pOp->p1;
3053 VERIFY( if( p->tos+1+addRowid<nField ) goto not_enough_stack; )
3054 nByte = 0;
3055 for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
3056 int flags = aStack[i].flags;
3057 int len;
3058 char *z;
3059 if( flags & STK_Null ){
3060 nByte += 2;
3061 containsNull = 1;
3062 }else if( pOp->p3 && pOp->p3[j]=='t' ){
3063 Stringify(p, i);
3064 aStack[i].flags &= ~(STK_Int|STK_Real);
3065 nByte += aStack[i].n+1;
3066 }else if( (flags & (STK_Real|STK_Int))!=0 || sqliteIsNumber(zStack[i]) ){
3067 if( (flags & (STK_Real|STK_Int))==STK_Int ){
3068 aStack[i].r = aStack[i].i;
3069 }else if( (flags & (STK_Real|STK_Int))==0 ){
3070 aStack[i].r = atof(zStack[i]);
3071 }
3072 Release(p, i);
3073 z = aStack[i].z;
3074 sqliteRealToSortable(aStack[i].r, z);
3075 len = strlen(z);
3076 zStack[i] = 0;
3077 aStack[i].flags = STK_Real;
3078 aStack[i].n = len+1;
3079 nByte += aStack[i].n+1;
3080 }else{
3081 nByte += aStack[i].n+1;
3082 }
3083 }
3084 if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
3085 rc = SQLITE_TOOBIG;
3086 goto abort_due_to_error;
3087 }
3088 if( addRowid ) nByte += sizeof(u32);
3089 if( nByte<=NBFS ){
3090 zNewKey = zTemp;
3091 }else{
3092 zNewKey = sqliteMallocRaw( nByte );
3093 if( zNewKey==0 ) goto no_mem;
3094 }
3095 j = 0;
3096 for(i=p->tos-nField+1; i<=p->tos; i++){
3097 if( aStack[i].flags & STK_Null ){
3098 zNewKey[j++] = 'a';
3099 zNewKey[j++] = 0;
3100 }else{
3101 if( aStack[i].flags & (STK_Int|STK_Real) ){
3102 zNewKey[j++] = 'b';
3103 }else{
3104 zNewKey[j++] = 'c';
3105 }
3106 memcpy(&zNewKey[j], zStack[i] ? zStack[i] : aStack[i].z, aStack[i].n);
3107 j += aStack[i].n;
3108 }
3109 }
3110 if( addRowid ){
3111 u32 iKey;
3112 Integerify(p, p->tos-nField);
3113 iKey = intToKey(aStack[p->tos-nField].i);
3114 memcpy(&zNewKey[j], &iKey, sizeof(u32));
3115 PopStack(p, nField+1);
3116 if( pOp->p2 && containsNull ) pc = pOp->p2 - 1;
3117 }else{
3118 if( pOp->p2==0 ) PopStack(p, nField+addRowid);
3119 }
3120 p->tos++;
3121 aStack[p->tos].n = nByte;
3122 if( nByte<=NBFS ){
3123 assert( zNewKey==zTemp );
3124 zStack[p->tos] = aStack[p->tos].z;
3125 memcpy(zStack[p->tos], zTemp, nByte);
3126 aStack[p->tos].flags = STK_Str;
3127 }else{
3128 aStack[p->tos].flags = STK_Str|STK_Dyn;
3129 zStack[p->tos] = zNewKey;
3130 }
3131 break;
3132}
3133
3134/* Opcode: IncrKey * * *
3135**
3136** The top of the stack should contain an index key generated by
3137** The MakeKey opcode. This routine increases the least significant
3138** byte of that key by one. This is used so that the MoveTo opcode
3139** will move to the first entry greater than the key rather than to
3140** the key itself.
3141*/
3142case OP_IncrKey: {
3143 int tos = p->tos;
3144
3145 VERIFY( if( tos<0 ) goto bad_instruction );
3146 Stringify(p, tos);
3147 if( aStack[tos].flags & (STK_Static|STK_Ephem) ){
3148 /* CANT HAPPEN. The IncrKey opcode is only applied to keys
3149 ** generated by MakeKey or MakeIdxKey and the results of those
3150 ** operands are always dynamic strings.
3151 */
3152 goto abort_due_to_error;
3153 }
3154 zStack[tos][aStack[tos].n-1]++;
3155 break;
3156}
3157
3158/* Opcode: Checkpoint P1 * *
3159**
3160** Begin a checkpoint. A checkpoint is the beginning of a operation that
3161** is part of a larger transaction but which might need to be rolled back
3162** itself without effecting the containing transaction. A checkpoint will
3163** be automatically committed or rollback when the VDBE halts.
3164**
3165** The checkpoint is begun on the database file with index P1. The main
3166** database file has an index of 0 and the file used for temporary tables
3167** has an index of 1.
3168*/
3169case OP_Checkpoint: {
3170 int i = pOp->p1;
3171 if( i>=0 && i<db->nDb && db->aDb[i].pBt && db->aDb[i].inTrans==1 ){
3172 rc = sqliteBtreeBeginCkpt(db->aDb[i].pBt);
3173 if( rc==SQLITE_OK ) db->aDb[i].inTrans = 2;
3174 }
3175 break;
3176}
3177
3178/* Opcode: Transaction P1 * *
3179**
3180** Begin a transaction. The transaction ends when a Commit or Rollback
3181** opcode is encountered. Depending on the ON CONFLICT setting, the
3182** transaction might also be rolled back if an error is encountered.
3183**
3184** P1 is the index of the database file on which the transaction is
3185** started. Index 0 is the main database file and index 1 is the
3186** file used for temporary tables.
3187**
3188** A write lock is obtained on the database file when a transaction is
3189** started. No other process can read or write the file while the
3190** transaction is underway. Starting a transaction also creates a
3191** rollback journal. A transaction must be started before any changes
3192** can be made to the database.
3193*/
3194case OP_Transaction: {
3195 int busy = 1;
3196 int i = pOp->p1;
3197 assert( i>=0 && i<db->nDb );
3198 if( db->aDb[i].inTrans ) break;
3199 while( db->aDb[i].pBt!=0 && busy ){
3200 rc = sqliteBtreeBeginTrans(db->aDb[i].pBt);
3201 switch( rc ){
3202 case SQLITE_BUSY: {
3203 if( db->xBusyCallback==0 ){
3204 p->pc = pc;
3205 p->undoTransOnError = 1;
3206 p->rc = SQLITE_BUSY;
3207 return SQLITE_BUSY;
3208 }else if( (*db->xBusyCallback)(db->pBusyArg, "", busy++)==0 ){
3209 sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
3210 busy = 0;
3211 }
3212 break;
3213 }
3214 case SQLITE_READONLY: {
3215 rc = SQLITE_OK;
3216 /* Fall thru into the next case */
3217 }
3218 case SQLITE_OK: {
3219 p->inTempTrans = 0;
3220 busy = 0;
3221 break;
3222 }
3223 default: {
3224 goto abort_due_to_error;
3225 }
3226 }
3227 }
3228 db->aDb[i].inTrans = 1;
3229 p->undoTransOnError = 1;
3230 break;
3231}
3232
3233/* Opcode: Commit * * *
3234**
3235** Cause all modifications to the database that have been made since the
3236** last Transaction to actually take effect. No additional modifications
3237** are allowed until another transaction is started. The Commit instruction
3238** deletes the journal file and releases the write lock on the database.
3239** A read lock continues to be held if there are still cursors open.
3240*/
3241case OP_Commit: {
3242 int i;
3243 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
3244 if( db->aDb[i].inTrans ){
3245 rc = sqliteBtreeCommit(db->aDb[i].pBt);
3246 db->aDb[i].inTrans = 0;
3247 }
3248 }
3249 if( rc==SQLITE_OK ){
3250 sqliteCommitInternalChanges(db);
3251 }else{
3252 sqliteRollbackAll(db);
3253 }
3254 break;
3255}
3256
3257/* Opcode: Rollback P1 * *
3258**
3259** Cause all modifications to the database that have been made since the
3260** last Transaction to be undone. The database is restored to its state
3261** before the Transaction opcode was executed. No additional modifications
3262** are allowed until another transaction is started.
3263**
3264** P1 is the index of the database file that is committed. An index of 0
3265** is used for the main database and an index of 1 is used for the file used
3266** to hold temporary tables.
3267**
3268** This instruction automatically closes all cursors and releases both
3269** the read and write locks on the indicated database.
3270*/
3271case OP_Rollback: {
3272 sqliteRollbackAll(db);
3273 break;
3274}
3275
3276/* Opcode: ReadCookie P1 P2 *
3277**
3278** Read cookie number P2 from database P1 and push it onto the stack.
3279** P2==0 is the schema version. P2==1 is the database format.
3280** P2==2 is the recommended pager cache size, and so forth. P1==0 is
3281** the main database file and P1==1 is the database file used to store
3282** temporary tables.
3283**
3284** There must be a read-lock on the database (either a transaction
3285** must be started or there must be an open cursor) before
3286** executing this instruction.
3287*/
3288case OP_ReadCookie: {
3289 int i = ++p->tos;
3290 int aMeta[SQLITE_N_BTREE_META];
3291 assert( pOp->p2<SQLITE_N_BTREE_META );
3292 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3293 assert( db->aDb[pOp->p1].pBt!=0 );
3294 rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
3295 aStack[i].i = aMeta[1+pOp->p2];
3296 aStack[i].flags = STK_Int;
3297 break;
3298}
3299
3300/* Opcode: SetCookie P1 P2 *
3301**
3302** Write the top of the stack into cookie number P2 of database P1.
3303** P2==0 is the schema version. P2==1 is the database format.
3304** P2==2 is the recommended pager cache size, and so forth. P1==0 is
3305** the main database file and P1==1 is the database file used to store
3306** temporary tables.
3307**
3308** A transaction must be started before executing this opcode.
3309*/
3310case OP_SetCookie: {
3311 int aMeta[SQLITE_N_BTREE_META];
3312 assert( pOp->p2<SQLITE_N_BTREE_META );
3313 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3314 assert( db->aDb[pOp->p1].pBt!=0 );
3315 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
3316 Integerify(p, p->tos)
3317 rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
3318 if( rc==SQLITE_OK ){
3319 aMeta[1+pOp->p2] = aStack[p->tos].i;
3320 rc = sqliteBtreeUpdateMeta(db->aDb[pOp->p1].pBt, aMeta);
3321 }
3322 POPSTACK;
3323 break;
3324}
3325
3326/* Opcode: VerifyCookie P1 P2 *
3327**
3328** Check the value of global database parameter number 0 (the
3329** schema version) and make sure it is equal to P2.
3330** P1 is the database number which is 0 for the main database file
3331** and 1 for the file holding temporary tables and some higher number
3332** for auxiliary databases.
3333**
3334** The cookie changes its value whenever the database schema changes.
3335** This operation is used to detect when that the cookie has changed
3336** and that the current process needs to reread the schema.
3337**
3338** Either a transaction needs to have been started or an OP_Open needs
3339** to be executed (to establish a read lock) before this opcode is
3340** invoked.
3341*/
3342case OP_VerifyCookie: {
3343 int aMeta[SQLITE_N_BTREE_META];
3344 assert( pOp->p1>=0 && pOp->p1<db->nDb );
3345 rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
3346 if( rc==SQLITE_OK && aMeta[1]!=pOp->p2 ){
3347 sqliteSetString(&p->zErrMsg, "database schema has changed", 0);
3348 rc = SQLITE_SCHEMA;
3349 }
3350 break;
3351}
3352
3353/* Opcode: OpenRead P1 P2 P3
3354**
3355** Open a read-only cursor for the database table whose root page is
3356** P2 in a database file. The database file is determined by an
3357** integer from the top of the stack. 0 means the main database and
3358** 1 means the database used for temporary tables. Give the new
3359** cursor an identifier of P1. The P1 values need not be contiguous
3360** but all P1 values should be small integers. It is an error for
3361** P1 to be negative.
3362**
3363** If P2==0 then take the root page number from the next of the stack.
3364**
3365** There will be a read lock on the database whenever there is an
3366** open cursor. If the database was unlocked prior to this instruction
3367** then a read lock is acquired as part of this instruction. A read
3368** lock allows other processes to read the database but prohibits
3369** any other process from modifying the database. The read lock is
3370** released when all cursors are closed. If this instruction attempts
3371** to get a read lock but fails, the script terminates with an
3372** SQLITE_BUSY error code.
3373**
3374** The P3 value is the name of the table or index being opened.
3375** The P3 value is not actually used by this opcode and may be
3376** omitted. But the code generator usually inserts the index or
3377** table name into P3 to make the code easier to read.
3378**
3379** See also OpenWrite.
3380*/
3381/* Opcode: OpenWrite P1 P2 P3
3382**
3383** Open a read/write cursor named P1 on the table or index whose root
3384** page is P2. If P2==0 then take the root page number from the stack.
3385**
3386** The P3 value is the name of the table or index being opened.
3387** The P3 value is not actually used by this opcode and may be
3388** omitted. But the code generator usually inserts the index or
3389** table name into P3 to make the code easier to read.
3390**
3391** This instruction works just like OpenRead except that it opens the cursor
3392** in read/write mode. For a given table, there can be one or more read-only
3393** cursors or a single read/write cursor but not both.
3394**
3395** See also OpenRead.
3396*/
3397case OP_OpenRead:
3398case OP_OpenWrite: {
3399 int busy = 0;
3400 int i = pOp->p1;
3401 int tos = p->tos;
3402 int p2 = pOp->p2;
3403 int wrFlag;
3404 Btree *pX;
3405 int iDb;
3406
3407 VERIFY( if( tos<0 ) goto not_enough_stack; );
3408 Integerify(p, tos);
3409 iDb = p->aStack[tos].i;
3410 tos--;
3411 VERIFY( if( iDb<0 || iDb>=db->nDb ) goto bad_instruction; );
3412 VERIFY( if( db->aDb[iDb].pBt==0 ) goto bad_instruction; );
3413 pX = db->aDb[iDb].pBt;
3414 wrFlag = pOp->opcode==OP_OpenWrite;
3415 if( p2<=0 ){
3416 VERIFY( if( tos<0 ) goto not_enough_stack; );
3417 Integerify(p, tos);
3418 p2 = p->aStack[tos].i;
3419 POPSTACK;
3420 if( p2<2 ){
3421 sqliteSetString(&p->zErrMsg, "root page number less than 2", 0);
3422 rc = SQLITE_INTERNAL;
3423 break;
3424 }
3425 }
3426 VERIFY( if( i<0 ) goto bad_instruction; )
3427 if( expandCursorArraySize(p, i) ) goto no_mem;
3428 cleanupCursor(&p->aCsr[i]);
3429 memset(&p->aCsr[i], 0, sizeof(Cursor));
3430 p->aCsr[i].nullRow = 1;
3431 if( pX==0 ) break;
3432 do{
3433 rc = sqliteBtreeCursor(pX, p2, wrFlag, &p->aCsr[i].pCursor);
3434 switch( rc ){
3435 case SQLITE_BUSY: {
3436 if( db->xBusyCallback==0 ){
3437 p->pc = pc;
3438 p->rc = SQLITE_BUSY;
3439 return SQLITE_BUSY;
3440 }else if( (*db->xBusyCallback)(db->pBusyArg, pOp->p3, ++busy)==0 ){
3441 sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), 0);
3442 busy = 0;
3443 }
3444 break;
3445 }
3446 case SQLITE_OK: {
3447 busy = 0;
3448 break;
3449 }
3450 default: {
3451 goto abort_due_to_error;
3452 }
3453 }
3454 }while( busy );
3455 if( p2<=0 ){
3456 POPSTACK;
3457 }
3458 POPSTACK;
3459 break;
3460}
3461
3462/* Opcode: OpenTemp P1 P2 *
3463**
3464** Open a new cursor to a transient table.
3465** The transient cursor is always opened read/write even if
3466** the main database is read-only. The transient table is deleted
3467** automatically when the cursor is closed.
3468**
3469** The cursor points to a BTree table if P2==0 and to a BTree index
3470** if P2==1. A BTree table must have an integer key and can have arbitrary
3471** data. A BTree index has no data but can have an arbitrary key.
3472**
3473** This opcode is used for tables that exist for the duration of a single
3474** SQL statement only. Tables created using CREATE TEMPORARY TABLE
3475** are opened using OP_OpenRead or OP_OpenWrite. "Temporary" in the
3476** context of this opcode means for the duration of a single SQL statement
3477** whereas "Temporary" in the context of CREATE TABLE means for the duration
3478** of the connection to the database. Same word; different meanings.
3479*/
3480case OP_OpenTemp: {
3481 int i = pOp->p1;
3482 Cursor *pCx;
3483 VERIFY( if( i<0 ) goto bad_instruction; )
3484 if( expandCursorArraySize(p, i) ) goto no_mem;
3485 pCx = &p->aCsr[i];
3486 cleanupCursor(pCx);
3487 memset(pCx, 0, sizeof(*pCx));
3488 pCx->nullRow = 1;
3489 rc = sqliteBtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
3490
3491 if( rc==SQLITE_OK ){
3492 rc = sqliteBtreeBeginTrans(pCx->pBt);
3493 }
3494 if( rc==SQLITE_OK ){
3495 if( pOp->p2 ){
3496 int pgno;
3497 rc = sqliteBtreeCreateIndex(pCx->pBt, &pgno);
3498 if( rc==SQLITE_OK ){
3499 rc = sqliteBtreeCursor(pCx->pBt, pgno, 1, &pCx->pCursor);
3500 }
3501 }else{
3502 rc = sqliteBtreeCursor(pCx->pBt, 2, 1, &pCx->pCursor);
3503 }
3504 }
3505 break;
3506}
3507
3508/* Opcode: OpenPseudo P1 * *
3509**
3510** Open a new cursor that points to a fake table that contains a single
3511** row of data. Any attempt to write a second row of data causes the
3512** first row to be deleted. All data is deleted when the cursor is
3513** closed.
3514**
3515** A pseudo-table created by this opcode is useful for holding the
3516** NEW or OLD tables in a trigger.
3517*/
3518case OP_OpenPseudo: {
3519 int i = pOp->p1;
3520 Cursor *pCx;
3521 VERIFY( if( i<0 ) goto bad_instruction; )
3522 if( expandCursorArraySize(p, i) ) goto no_mem;
3523 pCx = &p->aCsr[i];
3524 cleanupCursor(pCx);
3525 memset(pCx, 0, sizeof(*pCx));
3526 pCx->nullRow = 1;
3527 pCx->pseudoTable = 1;
3528 break;
3529}
3530
3531/* Opcode: Close P1 * *
3532**
3533** Close a cursor previously opened as P1. If P1 is not
3534** currently open, this instruction is a no-op.
3535*/
3536case OP_Close: {
3537 int i = pOp->p1;
3538 if( i>=0 && i<p->nCursor ){
3539 cleanupCursor(&p->aCsr[i]);
3540 }
3541 break;
3542}
3543
3544/* Opcode: MoveTo P1 P2 *
3545**
3546** Pop the top of the stack and use its value as a key. Reposition
3547** cursor P1 so that it points to an entry with a matching key. If
3548** the table contains no record with a matching key, then the cursor
3549** is left pointing at the first record that is greater than the key.
3550** If there are no records greater than the key and P2 is not zero,
3551** then an immediate jump to P2 is made.
3552**
3553** See also: Found, NotFound, Distinct, MoveLt
3554*/
3555/* Opcode: MoveLt P1 P2 *
3556**
3557** Pop the top of the stack and use its value as a key. Reposition
3558** cursor P1 so that it points to the entry with the largest key that is
3559** less than the key popped from the stack.
3560** If there are no records less than than the key and P2
3561** is not zero then an immediate jump to P2 is made.
3562**
3563** See also: MoveTo
3564*/
3565case OP_MoveLt:
3566case OP_MoveTo: {
3567 int i = pOp->p1;
3568 int tos = p->tos;
3569 Cursor *pC;
3570
3571 VERIFY( if( tos<0 ) goto not_enough_stack; )
3572 assert( i>=0 && i<p->nCursor );
3573 pC = &p->aCsr[i];
3574 if( pC->pCursor!=0 ){
3575 int res, oc;
3576 if( aStack[tos].flags & STK_Int ){
3577 int iKey = intToKey(aStack[tos].i);
3578 sqliteBtreeMoveto(pC->pCursor, (char*)&iKey, sizeof(int), &res);
3579 pC->lastRecno = aStack[tos].i;
3580 pC->recnoIsValid = res==0;
3581 }else{
3582 Stringify(p, tos);
3583 sqliteBtreeMoveto(pC->pCursor, zStack[tos], aStack[tos].n, &res);
3584 pC->recnoIsValid = 0;
3585 }
3586 pC->nullRow = 0;
3587 sqlite_search_count++;
3588 oc = pOp->opcode;
3589 if( oc==OP_MoveTo && res<0 ){
3590 sqliteBtreeNext(pC->pCursor, &res);
3591 pC->recnoIsValid = 0;
3592 if( res && pOp->p2>0 ){
3593 pc = pOp->p2 - 1;
3594 }
3595 }else if( oc==OP_MoveLt ){
3596 if( res>=0 ){
3597 sqliteBtreePrevious(pC->pCursor, &res);
3598 pC->recnoIsValid = 0;
3599 }else{
3600 /* res might be negative because the table is empty. Check to
3601 ** see if this is the case.
3602 */
3603 int keysize;
3604 res = sqliteBtreeKeySize(pC->pCursor,&keysize)!=0 || keysize==0;
3605 }
3606 if( res && pOp->p2>0 ){
3607 pc = pOp->p2 - 1;
3608 }
3609 }
3610 }
3611 POPSTACK;
3612 break;
3613}
3614
3615/* Opcode: Distinct P1 P2 *
3616**
3617** Use the top of the stack as a string key. If a record with that key does
3618** not exist in the table of cursor P1, then jump to P2. If the record
3619** does already exist, then fall thru. The cursor is left pointing
3620** at the record if it exists. The key is not popped from the stack.
3621**
3622** This operation is similar to NotFound except that this operation
3623** does not pop the key from the stack.
3624**
3625** See also: Found, NotFound, MoveTo, IsUnique, NotExists
3626*/
3627/* Opcode: Found P1 P2 *
3628**
3629** Use the top of the stack as a string key. If a record with that key
3630** does exist in table of P1, then jump to P2. If the record
3631** does not exist, then fall thru. The cursor is left pointing
3632** to the record if it exists. The key is popped from the stack.
3633**
3634** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
3635*/
3636/* Opcode: NotFound P1 P2 *
3637**
3638** Use the top of the stack as a string key. If a record with that key
3639** does not exist in table of P1, then jump to P2. If the record
3640** does exist, then fall thru. The cursor is left pointing to the
3641** record if it exists. The key is popped from the stack.
3642**
3643** The difference between this operation and Distinct is that
3644** Distinct does not pop the key from the stack.
3645**
3646** See also: Distinct, Found, MoveTo, NotExists, IsUnique
3647*/
3648case OP_Distinct:
3649case OP_NotFound:
3650case OP_Found: {
3651 int i = pOp->p1;
3652 int tos = p->tos;
3653 int alreadyExists = 0;
3654 Cursor *pC;
3655 VERIFY( if( tos<0 ) goto not_enough_stack; )
3656 if( VERIFY( i>=0 && i<p->nCursor && ) (pC = &p->aCsr[i])->pCursor!=0 ){
3657 int res, rx;
3658 Stringify(p, tos);
3659 rx = sqliteBtreeMoveto(pC->pCursor, zStack[tos], aStack[tos].n, &res);
3660 alreadyExists = rx==SQLITE_OK && res==0;
3661 }
3662 if( pOp->opcode==OP_Found ){
3663 if( alreadyExists ) pc = pOp->p2 - 1;
3664 }else{
3665 if( !alreadyExists ) pc = pOp->p2 - 1;
3666 }
3667 if( pOp->opcode!=OP_Distinct ){
3668 POPSTACK;
3669 }
3670 break;
3671}
3672
3673/* Opcode: IsUnique P1 P2 *
3674**
3675** The top of the stack is an integer record number. Call this
3676** record number R. The next on the stack is an index key created
3677** using MakeIdxKey. Call it K. This instruction pops R from the
3678** stack but it leaves K unchanged.
3679**
3680** P1 is an index. So all but the last four bytes of K are an
3681** index string. The last four bytes of K are a record number.
3682**
3683** This instruction asks if there is an entry in P1 where the
3684** index string matches K but the record number is different
3685** from R. If there is no such entry, then there is an immediate
3686** jump to P2. If any entry does exist where the index string
3687** matches K but the record number is not R, then the record
3688** number for that entry is pushed onto the stack and control
3689** falls through to the next instruction.
3690**
3691** See also: Distinct, NotFound, NotExists, Found
3692*/
3693case OP_IsUnique: {
3694 int i = pOp->p1;
3695 int tos = p->tos;
3696 int nos = tos-1;
3697 BtCursor *pCrsr;
3698 int R;
3699
3700 /* Pop the value R off the top of the stack
3701 */
3702 VERIFY( if( nos<0 ) goto not_enough_stack; )
3703 Integerify(p, tos);
3704 R = aStack[tos].i;
3705 POPSTACK;
3706 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
3707 int res, rc;
3708 int v; /* The record number on the P1 entry that matches K */
3709 char *zKey; /* The value of K */
3710 int nKey; /* Number of bytes in K */
3711
3712 /* Make sure K is a string and make zKey point to K
3713 */
3714 Stringify(p, nos);
3715 zKey = zStack[nos];
3716 nKey = aStack[nos].n;
3717 assert( nKey >= 4 );
3718
3719 /* Search for an entry in P1 where all but the last four bytes match K.
3720 ** If there is no such entry, jump immediately to P2.
3721 */
3722 rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
3723 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3724 if( res<0 ){
3725 rc = sqliteBtreeNext(pCrsr, &res);
3726 if( res ){
3727 pc = pOp->p2 - 1;
3728 break;
3729 }
3730 }
3731 rc = sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &res);
3732 if( rc!=SQLITE_OK ) goto abort_due_to_error;
3733 if( res>0 ){
3734 pc = pOp->p2 - 1;
3735 break;
3736 }
3737
3738 /* At this point, pCrsr is pointing to an entry in P1 where all but
3739 ** the last for bytes of the key match K. Check to see if the last
3740 ** four bytes of the key are different from R. If the last four
3741 ** bytes equal R then jump immediately to P2.
3742 */
3743 sqliteBtreeKey(pCrsr, nKey - 4, 4, (char*)&v);
3744 v = keyToInt(v);
3745 if( v==R ){
3746 pc = pOp->p2 - 1;
3747 break;
3748 }
3749
3750 /* The last four bytes of the key are different from R. Convert the
3751 ** last four bytes of the key into an integer and push it onto the
3752 ** stack. (These bytes are the record number of an entry that
3753 ** violates a UNIQUE constraint.)
3754 */
3755 p->tos++;
3756 aStack[tos].i = v;
3757 aStack[tos].flags = STK_Int;
3758 }
3759 break;
3760}
3761
3762/* Opcode: NotExists P1 P2 *
3763**
3764** Use the top of the stack as a integer key. If a record with that key
3765** does not exist in table of P1, then jump to P2. If the record
3766** does exist, then fall thru. The cursor is left pointing to the
3767** record if it exists. The integer key is popped from the stack.
3768**
3769** The difference between this operation and NotFound is that this
3770** operation assumes the key is an integer and NotFound assumes it
3771** is a string.
3772**
3773** See also: Distinct, Found, MoveTo, NotFound, IsUnique
3774*/
3775case OP_NotExists: {
3776 int i = pOp->p1;
3777 int tos = p->tos;
3778 BtCursor *pCrsr;
3779 VERIFY( if( tos<0 ) goto not_enough_stack; )
3780 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
3781 int res, rx, iKey;
3782 assert( aStack[tos].flags & STK_Int );
3783 iKey = intToKey(aStack[tos].i);
3784 rx = sqliteBtreeMoveto(pCrsr, (char*)&iKey, sizeof(int), &res);
3785 p->aCsr[i].lastRecno = aStack[tos].i;
3786 p->aCsr[i].recnoIsValid = res==0;
3787 p->aCsr[i].nullRow = 0;
3788 if( rx!=SQLITE_OK || res!=0 ){
3789 pc = pOp->p2 - 1;
3790 p->aCsr[i].recnoIsValid = 0;
3791 }
3792 }
3793 POPSTACK;
3794 break;
3795}
3796
3797/* Opcode: NewRecno P1 * *
3798**
3799** Get a new integer record number used as the key to a table.
3800** The record number is not previously used as a key in the database
3801** table that cursor P1 points to. The new record number is pushed
3802** onto the stack.
3803*/
3804case OP_NewRecno: {
3805 int i = pOp->p1;
3806 int v = 0;
3807 Cursor *pC;
3808 if( VERIFY( i<0 || i>=p->nCursor || ) (pC = &p->aCsr[i])->pCursor==0 ){
3809 v = 0;
3810 }else{
3811 /* The next rowid or record number (different terms for the same
3812 ** thing) is obtained in a two-step algorithm.
3813 **
3814 ** First we attempt to find the largest existing rowid and add one
3815 ** to that. But if the largest existing rowid is already the maximum
3816 ** positive integer, we have to fall through to the second
3817 ** probabilistic algorithm
3818 **
3819 ** The second algorithm is to select a rowid at random and see if
3820 ** it already exists in the table. If it does not exist, we have
3821 ** succeeded. If the random rowid does exist, we select a new one
3822 ** and try again, up to 1000 times.
3823 **
3824 ** For a table with less than 2 billion entries, the probability
3825 ** of not finding a unused rowid is about 1.0e-300. This is a
3826 ** non-zero probability, but it is still vanishingly small and should
3827 ** never cause a problem. You are much, much more likely to have a
3828 ** hardware failure than for this algorithm to fail.
3829 **
3830 ** The analysis in the previous paragraph assumes that you have a good
3831 ** source of random numbers. Is a library function like lrand48()
3832 ** good enough? Maybe. Maybe not. It's hard to know whether there
3833 ** might be subtle bugs is some implementations of lrand48() that
3834 ** could cause problems. To avoid uncertainty, SQLite uses its own
3835 ** random number generator based on the RC4 algorithm.
3836 **
3837 ** To promote locality of reference for repetitive inserts, the
3838 ** first few attempts at chosing a random rowid pick values just a little
3839 ** larger than the previous rowid. This has been shown experimentally
3840 ** to double the speed of the COPY operation.
3841 */
3842 int res, rx, cnt, x;
3843 cnt = 0;
3844 if( !pC->useRandomRowid ){
3845 if( pC->nextRowidValid ){
3846 v = pC->nextRowid;
3847 }else{
3848 rx = sqliteBtreeLast(pC->pCursor, &res);
3849 if( res ){
3850 v = 1;
3851 }else{
3852 sqliteBtreeKey(pC->pCursor, 0, sizeof(v), (void*)&v);
3853 v = keyToInt(v);
3854 if( v==0x7fffffff ){
3855 pC->useRandomRowid = 1;
3856 }else{
3857 v++;
3858 }
3859 }
3860 }
3861 if( v<0x7fffffff ){
3862 pC->nextRowidValid = 1;
3863 pC->nextRowid = v+1;
3864 }else{
3865 pC->nextRowidValid = 0;
3866 }
3867 }
3868 if( pC->useRandomRowid ){
3869 v = db->priorNewRowid;
3870 cnt = 0;
3871 do{
3872 if( v==0 || cnt>2 ){
3873 v = sqliteRandomInteger();
3874 if( cnt<5 ) v &= 0xffffff;
3875 }else{
3876 v += sqliteRandomByte() + 1;
3877 }
3878 if( v==0 ) continue;
3879 x = intToKey(v);
3880 rx = sqliteBtreeMoveto(pC->pCursor, &x, sizeof(int), &res);
3881 cnt++;
3882 }while( cnt<1000 && rx==SQLITE_OK && res==0 );
3883 db->priorNewRowid = v;
3884 if( rx==SQLITE_OK && res==0 ){
3885 rc = SQLITE_FULL;
3886 goto abort_due_to_error;
3887 }
3888 }
3889 pC->recnoIsValid = 0;
3890 }
3891 p->tos++;
3892 aStack[p->tos].i = v;
3893 aStack[p->tos].flags = STK_Int;
3894 break;
3895}
3896
3897/* Opcode: PutIntKey P1 P2 *
3898**
3899** Write an entry into the table of cursor P1. A new entry is
3900** created if it doesn't already exist or the data for an existing
3901** entry is overwritten. The data is the value on the top of the
3902** stack. The key is the next value down on the stack. The key must
3903** be an integer. The stack is popped twice by this instruction.
3904**
3905** If P2==1 then the row change count is incremented. If P2==0 the
3906** row change count is unmodified. The rowid is stored for subsequent
3907** return by the sqlite_last_insert_rowid() function if P2 is 1.
3908*/
3909/* Opcode: PutStrKey P1 * *
3910**
3911** Write an entry into the table of cursor P1. A new entry is
3912** created if it doesn't already exist or the data for an existing
3913** entry is overwritten. The data is the value on the top of the
3914** stack. The key is the next value down on the stack. The key must
3915** be a string. The stack is popped twice by this instruction.
3916**
3917** P1 may not be a pseudo-table opened using the OpenPseudo opcode.
3918*/
3919case OP_PutIntKey:
3920case OP_PutStrKey: {
3921 int tos = p->tos;
3922 int nos = p->tos-1;
3923 int i = pOp->p1;
3924 Cursor *pC;
3925 VERIFY( if( nos<0 ) goto not_enough_stack; )
3926 if( VERIFY( i>=0 && i<p->nCursor && )
3927 ((pC = &p->aCsr[i])->pCursor!=0 || pC->pseudoTable) ){
3928 char *zKey;
3929 int nKey, iKey;
3930 if( pOp->opcode==OP_PutStrKey ){
3931 Stringify(p, nos);
3932 nKey = aStack[nos].n;
3933 zKey = zStack[nos];
3934 }else{
3935 assert( aStack[nos].flags & STK_Int );
3936 nKey = sizeof(int);
3937 iKey = intToKey(aStack[nos].i);
3938 zKey = (char*)&iKey;
3939 if( pOp->p2 ){
3940 db->nChange++;
3941 db->lastRowid = aStack[nos].i;
3942 }
3943 if( pC->nextRowidValid && aStack[nos].i>=pC->nextRowid ){
3944 pC->nextRowidValid = 0;
3945 }
3946 }
3947 if( pC->pseudoTable ){
3948 /* PutStrKey does not work for pseudo-tables.
3949 ** The following assert makes sure we are not trying to use
3950 ** PutStrKey on a pseudo-table
3951 */
3952 assert( pOp->opcode==OP_PutIntKey );
3953 sqliteFree(pC->pData);
3954 pC->iKey = iKey;
3955 pC->nData = aStack[tos].n;
3956 if( aStack[tos].flags & STK_Dyn ){
3957 pC->pData = zStack[tos];
3958 zStack[tos] = 0;
3959 aStack[tos].flags = STK_Null;
3960 }else{
3961 pC->pData = sqliteMallocRaw( pC->nData );
3962 if( pC->pData ){
3963 memcpy(pC->pData, zStack[tos], pC->nData);
3964 }
3965 }
3966 pC->nullRow = 0;
3967 }else{
3968 rc = sqliteBtreeInsert(pC->pCursor, zKey, nKey,
3969 zStack[tos], aStack[tos].n);
3970 }
3971 pC->recnoIsValid = 0;
3972 }
3973 POPSTACK;
3974 POPSTACK;
3975 break;
3976}
3977
3978/* Opcode: Delete P1 P2 *
3979**
3980** Delete the record at which the P1 cursor is currently pointing.
3981**
3982** The cursor will be left pointing at either the next or the previous
3983** record in the table. If it is left pointing at the next record, then
3984** the next Next instruction will be a no-op. Hence it is OK to delete
3985** a record from within an Next loop.
3986**
3987** The row change counter is incremented if P2==1 and is unmodified
3988** if P2==0.
3989**
3990** If P1 is a pseudo-table, then this instruction is a no-op.
3991*/
3992case OP_Delete: {
3993 int i = pOp->p1;
3994 Cursor *pC;
3995 assert( i>=0 && i<p->nCursor );
3996 pC = &p->aCsr[i];
3997 if( pC->pCursor!=0 ){
3998 rc = sqliteBtreeDelete(pC->pCursor);
3999 pC->nextRowidValid = 0;
4000 }
4001 if( pOp->p2 ) db->nChange++;
4002 break;
4003}
4004
4005/* Opcode: KeyAsData P1 P2 *
4006**
4007** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
4008** off (if P2==0). In key-as-data mode, the OP_Column opcode pulls
4009** data off of the key rather than the data. This is used for
4010** processing compound selects.
4011*/
4012case OP_KeyAsData: {
4013 int i = pOp->p1;
4014 assert( i>=0 && i<p->nCursor );
4015 p->aCsr[i].keyAsData = pOp->p2;
4016 break;
4017}
4018
4019/* Opcode: RowData P1 * *
4020**
4021** Push onto the stack the complete row data for cursor P1.
4022** There is no interpretation of the data. It is just copied
4023** onto the stack exactly as it is found in the database file.
4024**
4025** If the cursor is not pointing to a valid row, a NULL is pushed
4026** onto the stack.
4027*/
4028case OP_RowData: {
4029 int i = pOp->p1;
4030 int tos = ++p->tos;
4031 Cursor *pC;
4032 int n;
4033
4034 assert( i>=0 && i<p->nCursor );
4035 pC = &p->aCsr[i];
4036 if( pC->nullRow ){
4037 aStack[tos].flags = STK_Null;
4038 }else if( pC->pCursor!=0 ){
4039 BtCursor *pCrsr = pC->pCursor;
4040 if( pC->nullRow ){
4041 aStack[tos].flags = STK_Null;
4042 break;
4043 }else if( pC->keyAsData ){
4044 sqliteBtreeKeySize(pCrsr, &n);
4045 }else{
4046 sqliteBtreeDataSize(pCrsr, &n);
4047 }
4048 aStack[tos].n = n;
4049 if( n<=NBFS ){
4050 aStack[tos].flags = STK_Str;
4051 zStack[tos] = aStack[tos].z;
4052 }else{
4053 char *z = sqliteMallocRaw( n );
4054 if( z==0 ) goto no_mem;
4055 aStack[tos].flags = STK_Str | STK_Dyn;
4056 zStack[tos] = z;
4057 }
4058 if( pC->keyAsData ){
4059 sqliteBtreeKey(pCrsr, 0, n, zStack[tos]);
4060 }else{
4061 sqliteBtreeData(pCrsr, 0, n, zStack[tos]);
4062 }
4063 }else if( pC->pseudoTable ){
4064 aStack[tos].n = pC->nData;
4065 zStack[tos] = pC->pData;
4066 aStack[tos].flags = STK_Str|STK_Ephem;
4067 }else{
4068 aStack[tos].flags = STK_Null;
4069 }
4070 break;
4071}
4072
4073/* Opcode: Column P1 P2 *
4074**
4075** Interpret the data that cursor P1 points to as
4076** a structure built using the MakeRecord instruction.
4077** (See the MakeRecord opcode for additional information about
4078** the format of the data.)
4079** Push onto the stack the value of the P2-th column contained
4080** in the data.
4081**
4082** If the KeyAsData opcode has previously executed on this cursor,
4083** then the field might be extracted from the key rather than the
4084** data.
4085**
4086** If P1 is negative, then the record is stored on the stack rather
4087** than in a table. For P1==-1, the top of the stack is used.
4088** For P1==-2, the next on the stack is used. And so forth. The
4089** value pushed is always just a pointer into the record which is
4090** stored further down on the stack. The column value is not copied.
4091*/
4092case OP_Column: {
4093 int amt, offset, end, payloadSize;
4094 int i = pOp->p1;
4095 int p2 = pOp->p2;
4096 int tos = p->tos+1;
4097 Cursor *pC;
4098 char *zRec;
4099 BtCursor *pCrsr;
4100 int idxWidth;
4101 unsigned char aHdr[10];
4102
4103 assert( i<p->nCursor );
4104 if( i<0 ){
4105 VERIFY( if( tos+i<0 ) goto bad_instruction; )
4106 VERIFY( if( (aStack[tos+i].flags & STK_Str)==0 ) goto bad_instruction; )
4107 zRec = zStack[tos+i];
4108 payloadSize = aStack[tos+i].n;
4109 }else if( (pC = &p->aCsr[i])->pCursor!=0 ){
4110 zRec = 0;
4111 pCrsr = pC->pCursor;
4112 if( pC->nullRow ){
4113 payloadSize = 0;
4114 }else if( pC->keyAsData ){
4115 sqliteBtreeKeySize(pCrsr, &payloadSize);
4116 }else{
4117 sqliteBtreeDataSize(pCrsr, &payloadSize);
4118 }
4119 }else if( pC->pseudoTable ){
4120 payloadSize = pC->nData;
4121 zRec = pC->pData;
4122 assert( payloadSize==0 || zRec!=0 );
4123 }else{
4124 payloadSize = 0;
4125 }
4126
4127 /* Figure out how many bytes in the column data and where the column
4128 ** data begins.
4129 */
4130 if( payloadSize==0 ){
4131 aStack[tos].flags = STK_Null;
4132 p->tos = tos;
4133 break;
4134 }else if( payloadSize<256 ){
4135 idxWidth = 1;
4136 }else if( payloadSize<65536 ){
4137 idxWidth = 2;
4138 }else{
4139 idxWidth = 3;
4140 }
4141
4142 /* Figure out where the requested column is stored and how big it is.
4143 */
4144 if( payloadSize < idxWidth*(p2+1) ){
4145 rc = SQLITE_CORRUPT;
4146 goto abort_due_to_error;
4147 }
4148 if( zRec ){
4149 memcpy(aHdr, &zRec[idxWidth*p2], idxWidth*2);
4150 }else if( pC->keyAsData ){
4151 sqliteBtreeKey(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
4152 }else{
4153 sqliteBtreeData(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
4154 }
4155 offset = aHdr[0];
4156 end = aHdr[idxWidth];
4157 if( idxWidth>1 ){
4158 offset |= aHdr[1]<<8;
4159 end |= aHdr[idxWidth+1]<<8;
4160 if( idxWidth>2 ){
4161 offset |= aHdr[2]<<16;
4162 end |= aHdr[idxWidth+2]<<16;
4163 }
4164 }
4165 amt = end - offset;
4166 if( amt<0 || offset<0 || end>payloadSize ){
4167 rc = SQLITE_CORRUPT;
4168 goto abort_due_to_error;
4169 }
4170
4171 /* amt and offset now hold the offset to the start of data and the
4172 ** amount of data. Go get the data and put it on the stack.
4173 */
4174 if( amt==0 ){
4175 aStack[tos].flags = STK_Null;
4176 }else if( zRec ){
4177 aStack[tos].flags = STK_Str | STK_Ephem;
4178 aStack[tos].n = amt;
4179 zStack[tos] = &zRec[offset];
4180 }else{
4181 if( amt<=NBFS ){
4182 aStack[tos].flags = STK_Str;
4183 zStack[tos] = aStack[tos].z;
4184 aStack[tos].n = amt;
4185 }else{
4186 char *z = sqliteMallocRaw( amt );
4187 if( z==0 ) goto no_mem;
4188 aStack[tos].flags = STK_Str | STK_Dyn;
4189 zStack[tos] = z;
4190 aStack[tos].n = amt;
4191 }
4192 if( pC->keyAsData ){
4193 sqliteBtreeKey(pCrsr, offset, amt, zStack[tos]);
4194 }else{
4195 sqliteBtreeData(pCrsr, offset, amt, zStack[tos]);
4196 }
4197 }
4198 p->tos = tos;
4199 break;
4200}
4201
4202/* Opcode: Recno P1 * *
4203**
4204** Push onto the stack an integer which is the first 4 bytes of the
4205** the key to the current entry in a sequential scan of the database
4206** file P1. The sequential scan should have been started using the
4207** Next opcode.
4208*/
4209case OP_Recno: {
4210 int i = pOp->p1;
4211 int tos = ++p->tos;
4212 Cursor *pC;
4213 int v;
4214
4215 assert( i>=0 && i<p->nCursor );
4216 if( (pC = &p->aCsr[i])->recnoIsValid ){
4217 v = pC->lastRecno;
4218 }else if( pC->nullRow ){
4219 aStack[tos].flags = STK_Null;
4220 break;
4221 }else if( pC->pseudoTable ){
4222 v = keyToInt(pC->iKey);
4223 }else{
4224 assert( pC->pCursor!=0 );
4225 sqliteBtreeKey(pC->pCursor, 0, sizeof(u32), (char*)&v);
4226 v = keyToInt(v);
4227 }
4228 aStack[tos].i = v;
4229 aStack[tos].flags = STK_Int;
4230 break;
4231}
4232
4233/* Opcode: FullKey P1 * *
4234**
4235** Extract the complete key from the record that cursor P1 is currently
4236** pointing to and push the key onto the stack as a string.
4237**
4238** Compare this opcode to Recno. The Recno opcode extracts the first
4239** 4 bytes of the key and pushes those bytes onto the stack as an
4240** integer. This instruction pushes the entire key as a string.
4241**
4242** This opcode may not be used on a pseudo-table.
4243*/
4244case OP_FullKey: {
4245 int i = pOp->p1;
4246 int tos = ++p->tos;
4247 BtCursor *pCrsr;
4248
4249 VERIFY( if( !p->aCsr[i].keyAsData ) goto bad_instruction; )
4250 VERIFY( if( p->aCsr[i].pseudoTable ) goto bad_instruction; )
4251 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
4252 int amt;
4253 char *z;
4254
4255 sqliteBtreeKeySize(pCrsr, &amt);
4256 if( amt<=0 ){
4257 rc = SQLITE_CORRUPT;
4258 goto abort_due_to_error;
4259 }
4260 if( amt>NBFS ){
4261 z = sqliteMallocRaw( amt );
4262 if( z==0 ) goto no_mem;
4263 aStack[tos].flags = STK_Str | STK_Dyn;
4264 }else{
4265 z = aStack[tos].z;
4266 aStack[tos].flags = STK_Str;
4267 }
4268 sqliteBtreeKey(pCrsr, 0, amt, z);
4269 zStack[tos] = z;
4270 aStack[tos].n = amt;
4271 }
4272 break;
4273}
4274
4275/* Opcode: NullRow P1 * *
4276**
4277** Move the cursor P1 to a null row. Any OP_Column operations
4278** that occur while the cursor is on the null row will always push
4279** a NULL onto the stack.
4280*/
4281case OP_NullRow: {
4282 int i = pOp->p1;
4283
4284 assert( i>=0 && i<p->nCursor );
4285 p->aCsr[i].nullRow = 1;
4286 p->aCsr[i].recnoIsValid = 0;
4287 break;
4288}
4289
4290/* Opcode: Last P1 P2 *
4291**
4292** The next use of the Recno or Column or Next instruction for P1
4293** will refer to the last entry in the database table or index.
4294** If the table or index is empty and P2>0, then jump immediately to P2.
4295** If P2 is 0 or if the table or index is not empty, fall through
4296** to the following instruction.
4297*/
4298case OP_Last: {
4299 int i = pOp->p1;
4300 Cursor *pC;
4301 BtCursor *pCrsr;
4302
4303 assert( i>=0 && i<p->nCursor );
4304 pC = &p->aCsr[i];
4305 if( (pCrsr = pC->pCursor)!=0 ){
4306 int res;
4307 rc = sqliteBtreeLast(pCrsr, &res);
4308 p->aCsr[i].nullRow = res;
4309 if( res && pOp->p2>0 ){
4310 pc = pOp->p2 - 1;
4311 }
4312 }else{
4313 pC->nullRow = 0;
4314 }
4315 break;
4316}
4317
4318/* Opcode: Rewind P1 P2 *
4319**
4320** The next use of the Recno or Column or Next instruction for P1
4321** will refer to the first entry in the database table or index.
4322** If the table or index is empty and P2>0, then jump immediately to P2.
4323** If P2 is 0 or if the table or index is not empty, fall through
4324** to the following instruction.
4325*/
4326case OP_Rewind: {
4327 int i = pOp->p1;
4328 Cursor *pC;
4329 BtCursor *pCrsr;
4330
4331 assert( i>=0 && i<p->nCursor );
4332 pC = &p->aCsr[i];
4333 if( (pCrsr = pC->pCursor)!=0 ){
4334 int res;
4335 rc = sqliteBtreeFirst(pCrsr, &res);
4336 pC->atFirst = res==0;
4337 pC->nullRow = res;
4338 if( res && pOp->p2>0 ){
4339 pc = pOp->p2 - 1;
4340 }
4341 }else{
4342 pC->nullRow = 0;
4343 }
4344 break;
4345}
4346
4347/* Opcode: Next P1 P2 *
4348**
4349** Advance cursor P1 so that it points to the next key/data pair in its
4350** table or index. If there are no more key/value pairs then fall through
4351** to the following instruction. But if the cursor advance was successful,
4352** jump immediately to P2.
4353**
4354** See also: Prev
4355*/
4356/* Opcode: Prev P1 P2 *
4357**
4358** Back up cursor P1 so that it points to the previous key/data pair in its
4359** table or index. If there is no previous key/value pairs then fall through
4360** to the following instruction. But if the cursor backup was successful,
4361** jump immediately to P2.
4362*/
4363case OP_Prev:
4364case OP_Next: {
4365 Cursor *pC;
4366 BtCursor *pCrsr;
4367
4368 CHECK_FOR_INTERRUPT;
4369 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
4370 pC = &p->aCsr[pOp->p1];
4371 if( (pCrsr = pC->pCursor)!=0 ){
4372 int res;
4373 if( pC->nullRow ){
4374 res = 1;
4375 }else{
4376 rc = pOp->opcode==OP_Next ? sqliteBtreeNext(pCrsr, &res) :
4377 sqliteBtreePrevious(pCrsr, &res);
4378 pC->nullRow = res;
4379 }
4380 if( res==0 ){
4381 pc = pOp->p2 - 1;
4382 sqlite_search_count++;
4383 }
4384 }else{
4385 pC->nullRow = 1;
4386 }
4387 pC->recnoIsValid = 0;
4388 break;
4389}
4390
4391/* Opcode: IdxPut P1 P2 P3
4392**
4393** The top of the stack holds a SQL index key made using the
4394** MakeIdxKey instruction. This opcode writes that key into the
4395** index P1. Data for the entry is nil.
4396**
4397** If P2==1, then the key must be unique. If the key is not unique,
4398** the program aborts with a SQLITE_CONSTRAINT error and the database
4399** is rolled back. If P3 is not null, then it becomes part of the
4400** error message returned with the SQLITE_CONSTRAINT.
4401*/
4402case OP_IdxPut: {
4403 int i = pOp->p1;
4404 int tos = p->tos;
4405 BtCursor *pCrsr;
4406 VERIFY( if( tos<0 ) goto not_enough_stack; )
4407 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
4408 int nKey = aStack[tos].n;
4409 const char *zKey = zStack[tos];
4410 if( pOp->p2 ){
4411 int res, n;
4412 assert( aStack[tos].n >= 4 );
4413 rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
4414 if( rc!=SQLITE_OK ) goto abort_due_to_error;
4415 while( res!=0 ){
4416 int c;
4417 sqliteBtreeKeySize(pCrsr, &n);
4418 if( n==nKey
4419 && sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &c)==SQLITE_OK
4420 && c==0
4421 ){
4422 rc = SQLITE_CONSTRAINT;
4423 if( pOp->p3 && pOp->p3[0] ){
4424 sqliteSetString(&p->zErrMsg, pOp->p3, 0);
4425 }
4426 goto abort_due_to_error;
4427 }
4428 if( res<0 ){
4429 sqliteBtreeNext(pCrsr, &res);
4430 res = +1;
4431 }else{
4432 break;
4433 }
4434 }
4435 }
4436 rc = sqliteBtreeInsert(pCrsr, zKey, nKey, "", 0);
4437 }
4438 POPSTACK;
4439 break;
4440}
4441
4442/* Opcode: IdxDelete P1 * *
4443**
4444** The top of the stack is an index key built using the MakeIdxKey opcode.
4445** This opcode removes that entry from the index.
4446*/
4447case OP_IdxDelete: {
4448 int i = pOp->p1;
4449 int tos = p->tos;
4450 BtCursor *pCrsr;
4451 VERIFY( if( tos<0 ) goto not_enough_stack; )
4452 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
4453 int rx, res;
4454 rx = sqliteBtreeMoveto(pCrsr, zStack[tos], aStack[tos].n, &res);
4455 if( rx==SQLITE_OK && res==0 ){
4456 rc = sqliteBtreeDelete(pCrsr);
4457 }
4458 }
4459 POPSTACK;
4460 break;
4461}
4462
4463/* Opcode: IdxRecno P1 * *
4464**
4465** Push onto the stack an integer which is the last 4 bytes of the
4466** the key to the current entry in index P1. These 4 bytes should
4467** be the record number of the table entry to which this index entry
4468** points.
4469**
4470** See also: Recno, MakeIdxKey.
4471*/
4472case OP_IdxRecno: {
4473 int i = pOp->p1;
4474 int tos = ++p->tos;
4475 BtCursor *pCrsr;
4476
4477 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
4478 int v;
4479 int sz;
4480 sqliteBtreeKeySize(pCrsr, &sz);
4481 if( sz<sizeof(u32) ){
4482 aStack[tos].flags = STK_Null;
4483 }else{
4484 sqliteBtreeKey(pCrsr, sz - sizeof(u32), sizeof(u32), (char*)&v);
4485 v = keyToInt(v);
4486 aStack[tos].i = v;
4487 aStack[tos].flags = STK_Int;
4488 }
4489 }
4490 break;
4491}
4492
4493/* Opcode: IdxGT P1 P2 *
4494**
4495** Compare the top of the stack against the key on the index entry that
4496** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
4497** index entry. If the index entry is greater than the top of the stack
4498** then jump to P2. Otherwise fall through to the next instruction.
4499** In either case, the stack is popped once.
4500*/
4501/* Opcode: IdxGE P1 P2 *
4502**
4503** Compare the top of the stack against the key on the index entry that
4504** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
4505** index entry. If the index entry is greater than or equal to
4506** the top of the stack
4507** then jump to P2. Otherwise fall through to the next instruction.
4508** In either case, the stack is popped once.
4509*/
4510/* Opcode: IdxLT P1 P2 *
4511**
4512** Compare the top of the stack against the key on the index entry that
4513** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
4514** index entry. If the index entry is less than the top of the stack
4515** then jump to P2. Otherwise fall through to the next instruction.
4516** In either case, the stack is popped once.
4517*/
4518case OP_IdxLT:
4519case OP_IdxGT:
4520case OP_IdxGE: {
4521 int i= pOp->p1;
4522 int tos = p->tos;
4523 BtCursor *pCrsr;
4524
4525 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
4526 int res, rc;
4527
4528 Stringify(p, tos);
4529 rc = sqliteBtreeKeyCompare(pCrsr, zStack[tos], aStack[tos].n, 4, &res);
4530 if( rc!=SQLITE_OK ){
4531 break;
4532 }
4533 if( pOp->opcode==OP_IdxLT ){
4534 res = -res;
4535 }else if( pOp->opcode==OP_IdxGE ){
4536 res++;
4537 }
4538 if( res>0 ){
4539 pc = pOp->p2 - 1 ;
4540 }
4541 }
4542 POPSTACK;
4543 break;
4544}
4545
4546/* Opcode: Destroy P1 P2 *
4547**
4548** Delete an entire database table or index whose root page in the database
4549** file is given by P1.
4550**
4551** The table being destroyed is in the main database file if P2==0. If
4552** P2==1 then the table to be clear is in the auxiliary database file
4553** that is used to store tables create using CREATE TEMPORARY TABLE.
4554**
4555** See also: Clear
4556*/
4557case OP_Destroy: {
4558 rc = sqliteBtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1);
4559 break;
4560}
4561
4562/* Opcode: Clear P1 P2 *
4563**
4564** Delete all contents of the database table or index whose root page
4565** in the database file is given by P1. But, unlike Destroy, do not
4566** remove the table or index from the database file.
4567**
4568** The table being clear is in the main database file if P2==0. If
4569** P2==1 then the table to be clear is in the auxiliary database file
4570** that is used to store tables create using CREATE TEMPORARY TABLE.
4571**
4572** See also: Destroy
4573*/
4574case OP_Clear: {
4575 rc = sqliteBtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
4576 break;
4577}
4578
4579/* Opcode: CreateTable * P2 P3
4580**
4581** Allocate a new table in the main database file if P2==0 or in the
4582** auxiliary database file if P2==1. Push the page number
4583** for the root page of the new table onto the stack.
4584**
4585** The root page number is also written to a memory location that P3
4586** points to. This is the mechanism is used to write the root page
4587** number into the parser's internal data structures that describe the
4588** new table.
4589**
4590** The difference between a table and an index is this: A table must
4591** have a 4-byte integer key and can have arbitrary data. An index
4592** has an arbitrary key but no data.
4593**
4594** See also: CreateIndex
4595*/
4596/* Opcode: CreateIndex * P2 P3
4597**
4598** Allocate a new index in the main database file if P2==0 or in the
4599** auxiliary database file if P2==1. Push the page number of the
4600** root page of the new index onto the stack.
4601**
4602** See documentation on OP_CreateTable for additional information.
4603*/
4604case OP_CreateIndex:
4605case OP_CreateTable: {
4606 int i = ++p->tos;
4607 int pgno;
4608 assert( pOp->p3!=0 && pOp->p3type==P3_POINTER );
4609 assert( pOp->p2>=0 && pOp->p2<db->nDb );
4610 assert( db->aDb[pOp->p2].pBt!=0 );
4611 if( pOp->opcode==OP_CreateTable ){
4612 rc = sqliteBtreeCreateTable(db->aDb[pOp->p2].pBt, &pgno);
4613 }else{
4614 rc = sqliteBtreeCreateIndex(db->aDb[pOp->p2].pBt, &pgno);
4615 }
4616 if( rc==SQLITE_OK ){
4617 aStack[i].i = pgno;
4618 aStack[i].flags = STK_Int;
4619 *(u32*)pOp->p3 = pgno;
4620 pOp->p3 = 0;
4621 }
4622 break;
4623}
4624
4625/* Opcode: IntegrityCk P1 P2 *
4626**
4627** Do an analysis of the currently open database. Push onto the
4628** stack the text of an error message describing any problems.
4629** If there are no errors, push a "ok" onto the stack.
4630**
4631** P1 is the index of a set that contains the root page numbers
4632** for all tables and indices in the main database file.
4633**
4634** If P2 is not zero, the check is done on the auxiliary database
4635** file, not the main database file.
4636**
4637** This opcode is used for testing purposes only.
4638*/
4639case OP_IntegrityCk: {
4640 int nRoot;
4641 int *aRoot;
4642 int tos = ++p->tos;
4643 int iSet = pOp->p1;
4644 Set *pSet;
4645 int j;
4646 HashElem *i;
4647 char *z;
4648
4649 VERIFY( if( iSet<0 || iSet>=p->nSet ) goto bad_instruction; )
4650 pSet = &p->aSet[iSet];
4651 nRoot = sqliteHashCount(&pSet->hash);
4652 aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
4653 if( aRoot==0 ) goto no_mem;
4654 for(j=0, i=sqliteHashFirst(&pSet->hash); i; i=sqliteHashNext(i), j++){
4655 toInt((char*)sqliteHashKey(i), &aRoot[j]);
4656 }
4657 aRoot[j] = 0;
4658 z = sqliteBtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
4659 if( z==0 || z[0]==0 ){
4660 if( z ) sqliteFree(z);
4661 zStack[tos] = "ok";
4662 aStack[tos].n = 3;
4663 aStack[tos].flags = STK_Str | STK_Static;
4664 }else{
4665 zStack[tos] = z;
4666 aStack[tos].n = strlen(z) + 1;
4667 aStack[tos].flags = STK_Str | STK_Dyn;
4668 }
4669 sqliteFree(aRoot);
4670 break;
4671}
4672
4673/* Opcode: ListWrite * * *
4674**
4675** Write the integer on the top of the stack
4676** into the temporary storage list.
4677*/
4678case OP_ListWrite: {
4679 Keylist *pKeylist;
4680 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
4681 pKeylist = p->pList;
4682 if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
4683 pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
4684 if( pKeylist==0 ) goto no_mem;
4685 pKeylist->nKey = 1000;
4686 pKeylist->nRead = 0;
4687 pKeylist->nUsed = 0;
4688 pKeylist->pNext = p->pList;
4689 p->pList = pKeylist;
4690 }
4691 Integerify(p, p->tos);
4692 pKeylist->aKey[pKeylist->nUsed++] = aStack[p->tos].i;
4693 POPSTACK;
4694 break;
4695}
4696
4697/* Opcode: ListRewind * * *
4698**
4699** Rewind the temporary buffer back to the beginning. This is
4700** now a no-op.
4701*/
4702case OP_ListRewind: {
4703 /* This is now a no-op */
4704 break;
4705}
4706
4707/* Opcode: ListRead * P2 *
4708**
4709** Attempt to read an integer from the temporary storage buffer
4710** and push it onto the stack. If the storage buffer is empty,
4711** push nothing but instead jump to P2.
4712*/
4713case OP_ListRead: {
4714 Keylist *pKeylist;
4715 CHECK_FOR_INTERRUPT;
4716 pKeylist = p->pList;
4717 if( pKeylist!=0 ){
4718 VERIFY(
4719 if( pKeylist->nRead<0
4720 || pKeylist->nRead>=pKeylist->nUsed
4721 || pKeylist->nRead>=pKeylist->nKey ) goto bad_instruction;
4722 )
4723 p->tos++;
4724 aStack[p->tos].i = pKeylist->aKey[pKeylist->nRead++];
4725 aStack[p->tos].flags = STK_Int;
4726 zStack[p->tos] = 0;
4727 if( pKeylist->nRead>=pKeylist->nUsed ){
4728 p->pList = pKeylist->pNext;
4729 sqliteFree(pKeylist);
4730 }
4731 }else{
4732 pc = pOp->p2 - 1;
4733 }
4734 break;
4735}
4736
4737/* Opcode: ListReset * * *
4738**
4739** Reset the temporary storage buffer so that it holds nothing.
4740*/
4741case OP_ListReset: {
4742 if( p->pList ){
4743 KeylistFree(p->pList);
4744 p->pList = 0;
4745 }
4746 break;
4747}
4748
4749/* Opcode: ListPush * * *
4750**
4751** Save the current Vdbe list such that it can be restored by a ListPop
4752** opcode. The list is empty after this is executed.
4753*/
4754case OP_ListPush: {
4755 p->keylistStackDepth++;
4756 assert(p->keylistStackDepth > 0);
4757 p->keylistStack = sqliteRealloc(p->keylistStack,
4758 sizeof(Keylist *) * p->keylistStackDepth);
4759 if( p->keylistStack==0 ) goto no_mem;
4760 p->keylistStack[p->keylistStackDepth - 1] = p->pList;
4761 p->pList = 0;
4762 break;
4763}
4764
4765/* Opcode: ListPop * * *
4766**
4767** Restore the Vdbe list to the state it was in when ListPush was last
4768** executed.
4769*/
4770case OP_ListPop: {
4771 assert(p->keylistStackDepth > 0);
4772 p->keylistStackDepth--;
4773 KeylistFree(p->pList);
4774 p->pList = p->keylistStack[p->keylistStackDepth];
4775 p->keylistStack[p->keylistStackDepth] = 0;
4776 if( p->keylistStackDepth == 0 ){
4777 sqliteFree(p->keylistStack);
4778 p->keylistStack = 0;
4779 }
4780 break;
4781}
4782
4783/* Opcode: SortPut * * *
4784**
4785** The TOS is the key and the NOS is the data. Pop both from the stack
4786** and put them on the sorter. The key and data should have been
4787** made using SortMakeKey and SortMakeRec, respectively.
4788*/
4789case OP_SortPut: {
4790 int tos = p->tos;
4791 int nos = tos - 1;
4792 Sorter *pSorter;
4793 VERIFY( if( tos<1 ) goto not_enough_stack; )
4794 if( Dynamicify(p, tos) || Dynamicify(p, nos) ) goto no_mem;
4795 pSorter = sqliteMallocRaw( sizeof(Sorter) );
4796 if( pSorter==0 ) goto no_mem;
4797 pSorter->pNext = p->pSort;
4798 p->pSort = pSorter;
4799 assert( aStack[tos].flags & STK_Dyn );
4800 pSorter->nKey = aStack[tos].n;
4801 pSorter->zKey = zStack[tos];
4802 pSorter->nData = aStack[nos].n;
4803 if( aStack[nos].flags & STK_Dyn ){
4804 pSorter->pData = zStack[nos];
4805 }else{
4806 pSorter->pData = sqliteStrDup(zStack[nos]);
4807 }
4808 aStack[tos].flags = 0;
4809 aStack[nos].flags = 0;
4810 zStack[tos] = 0;
4811 zStack[nos] = 0;
4812 p->tos -= 2;
4813 break;
4814}
4815
4816/* Opcode: SortMakeRec P1 * *
4817**
4818** The top P1 elements are the arguments to a callback. Form these
4819** elements into a single data entry that can be stored on a sorter
4820** using SortPut and later fed to a callback using SortCallback.
4821*/
4822case OP_SortMakeRec: {
4823 char *z;
4824 char **azArg;
4825 int nByte;
4826 int nField;
4827 int i, j;
4828
4829 nField = pOp->p1;
4830 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
4831 nByte = 0;
4832 for(i=p->tos-nField+1; i<=p->tos; i++){
4833 if( (aStack[i].flags & STK_Null)==0 ){
4834 Stringify(p, i);
4835 nByte += aStack[i].n;
4836 }
4837 }
4838 nByte += sizeof(char*)*(nField+1);
4839 azArg = sqliteMallocRaw( nByte );
4840 if( azArg==0 ) goto no_mem;
4841 z = (char*)&azArg[nField+1];
4842 for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
4843 if( aStack[i].flags & STK_Null ){
4844 azArg[j] = 0;
4845 }else{
4846 azArg[j] = z;
4847 strcpy(z, zStack[i]);
4848 z += aStack[i].n;
4849 }
4850 }
4851 PopStack(p, nField);
4852 p->tos++;
4853 aStack[p->tos].n = nByte;
4854 zStack[p->tos] = (char*)azArg;
4855 aStack[p->tos].flags = STK_Str|STK_Dyn;
4856 break;
4857}
4858
4859/* Opcode: SortMakeKey * * P3
4860**
4861** Convert the top few entries of the stack into a sort key. The
4862** number of stack entries consumed is the number of characters in
4863** the string P3. One character from P3 is prepended to each entry.
4864** The first character of P3 is prepended to the element lowest in
4865** the stack and the last character of P3 is prepended to the top of
4866** the stack. All stack entries are separated by a \000 character
4867** in the result. The whole key is terminated by two \000 characters
4868** in a row.
4869**
4870** "N" is substituted in place of the P3 character for NULL values.
4871**
4872** See also the MakeKey and MakeIdxKey opcodes.
4873*/
4874case OP_SortMakeKey: {
4875 char *zNewKey;
4876 int nByte;
4877 int nField;
4878 int i, j, k;
4879
4880 nField = strlen(pOp->p3);
4881 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
4882 nByte = 1;
4883 for(i=p->tos-nField+1; i<=p->tos; i++){
4884 if( (aStack[i].flags & STK_Null)!=0 ){
4885 nByte += 2;
4886 }else{
4887 Stringify(p, i);
4888 nByte += aStack[i].n+2;
4889 }
4890 }
4891 zNewKey = sqliteMallocRaw( nByte );
4892 if( zNewKey==0 ) goto no_mem;
4893 j = 0;
4894 k = 0;
4895 for(i=p->tos-nField+1; i<=p->tos; i++){
4896 if( (aStack[i].flags & STK_Null)!=0 ){
4897 zNewKey[j++] = 'N';
4898 zNewKey[j++] = 0;
4899 k++;
4900 }else{
4901 zNewKey[j++] = pOp->p3[k++];
4902 memcpy(&zNewKey[j], zStack[i], aStack[i].n-1);
4903 j += aStack[i].n-1;
4904 zNewKey[j++] = 0;
4905 }
4906 }
4907 zNewKey[j] = 0;
4908 assert( j<nByte );
4909 PopStack(p, nField);
4910 p->tos++;
4911 aStack[p->tos].n = nByte;
4912 aStack[p->tos].flags = STK_Str|STK_Dyn;
4913 zStack[p->tos] = zNewKey;
4914 break;
4915}
4916
4917/* Opcode: Sort * * *
4918**
4919** Sort all elements on the sorter. The algorithm is a
4920** mergesort.
4921*/
4922case OP_Sort: {
4923 int i;
4924 Sorter *pElem;
4925 Sorter *apSorter[NSORT];
4926 for(i=0; i<NSORT; i++){
4927 apSorter[i] = 0;
4928 }
4929 while( p->pSort ){
4930 pElem = p->pSort;
4931 p->pSort = pElem->pNext;
4932 pElem->pNext = 0;
4933 for(i=0; i<NSORT-1; i++){
4934 if( apSorter[i]==0 ){
4935 apSorter[i] = pElem;
4936 break;
4937 }else{
4938 pElem = Merge(apSorter[i], pElem);
4939 apSorter[i] = 0;
4940 }
4941 }
4942 if( i>=NSORT-1 ){
4943 apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
4944 }
4945 }
4946 pElem = 0;
4947 for(i=0; i<NSORT; i++){
4948 pElem = Merge(apSorter[i], pElem);
4949 }
4950 p->pSort = pElem;
4951 break;
4952}
4953
4954/* Opcode: SortNext * P2 *
4955**
4956** Push the data for the topmost element in the sorter onto the
4957** stack, then remove the element from the sorter. If the sorter
4958** is empty, push nothing on the stack and instead jump immediately
4959** to instruction P2.
4960*/
4961case OP_SortNext: {
4962 Sorter *pSorter = p->pSort;
4963 CHECK_FOR_INTERRUPT;
4964 if( pSorter!=0 ){
4965 p->pSort = pSorter->pNext;
4966 p->tos++;
4967 zStack[p->tos] = pSorter->pData;
4968 aStack[p->tos].n = pSorter->nData;
4969 aStack[p->tos].flags = STK_Str|STK_Dyn;
4970 sqliteFree(pSorter->zKey);
4971 sqliteFree(pSorter);
4972 }else{
4973 pc = pOp->p2 - 1;
4974 }
4975 break;
4976}
4977
4978/* Opcode: SortCallback P1 * *
4979**
4980** The top of the stack contains a callback record built using
4981** the SortMakeRec operation with the same P1 value as this
4982** instruction. Pop this record from the stack and invoke the
4983** callback on it.
4984*/
4985case OP_SortCallback: {
4986 int i = p->tos;
4987 VERIFY( if( i<0 ) goto not_enough_stack; )
4988 if( p->xCallback==0 ){
4989 p->pc = pc+1;
4990 p->azResColumn = (char**)zStack[i];
4991 p->nResColumn = pOp->p1;
4992 p->popStack = 1;
4993 return SQLITE_ROW;
4994 }else{
4995 if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
4996 if( p->xCallback(p->pCbArg, pOp->p1, (char**)zStack[i], p->azColName)!=0 ){
4997 rc = SQLITE_ABORT;
4998 }
4999 if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
5000 p->nCallback++;
5001 }
5002 POPSTACK;
5003 if( sqlite_malloc_failed ) goto no_mem;
5004 break;
5005}
5006
5007/* Opcode: SortReset * * *
5008**
5009** Remove any elements that remain on the sorter.
5010*/
5011case OP_SortReset: {
5012 SorterReset(p);
5013 break;
5014}
5015
5016/* Opcode: FileOpen * * P3
5017**
5018** Open the file named by P3 for reading using the FileRead opcode.
5019** If P3 is "stdin" then open standard input for reading.
5020*/
5021case OP_FileOpen: {
5022 VERIFY( if( pOp->p3==0 ) goto bad_instruction; )
5023 if( p->pFile ){
5024 if( p->pFile!=stdin ) fclose(p->pFile);
5025 p->pFile = 0;
5026 }
5027 if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
5028 p->pFile = stdin;
5029 }else{
5030 p->pFile = fopen(pOp->p3, "r");
5031 }
5032 if( p->pFile==0 ){
5033 sqliteSetString(&p->zErrMsg,"unable to open file: ", pOp->p3, 0);
5034 rc = SQLITE_ERROR;
5035 }
5036 break;
5037}
5038
5039/* Opcode: FileRead P1 P2 P3
5040**
5041** Read a single line of input from the open file (the file opened using
5042** FileOpen). If we reach end-of-file, jump immediately to P2. If
5043** we are able to get another line, split the line apart using P3 as
5044** a delimiter. There should be P1 fields. If the input line contains
5045** more than P1 fields, ignore the excess. If the input line contains
5046** fewer than P1 fields, assume the remaining fields contain NULLs.
5047**
5048** Input ends if a line consists of just "\.". A field containing only
5049** "\N" is a null field. The backslash \ character can be used be used
5050** to escape newlines or the delimiter.
5051*/
5052case OP_FileRead: {
5053 int n, eol, nField, i, c, nDelim;
5054 char *zDelim, *z;
5055 CHECK_FOR_INTERRUPT;
5056 if( p->pFile==0 ) goto fileread_jump;
5057 nField = pOp->p1;
5058 if( nField<=0 ) goto fileread_jump;
5059 if( nField!=p->nField || p->azField==0 ){
5060 char **azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
5061 if( azField==0 ){ goto no_mem; }
5062 p->azField = azField;
5063 p->nField = nField;
5064 }
5065 n = 0;
5066 eol = 0;
5067 while( eol==0 ){
5068 if( p->zLine==0 || n+200>p->nLineAlloc ){
5069 char *zLine;
5070 p->nLineAlloc = p->nLineAlloc*2 + 300;
5071 zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
5072 if( zLine==0 ){
5073 p->nLineAlloc = 0;
5074 sqliteFree(p->zLine);
5075 p->zLine = 0;
5076 goto no_mem;
5077 }
5078 p->zLine = zLine;
5079 }
5080