blob: cbdae741b097d1aee7234946360720e49e1494c8 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
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
drhb19a2bc2001-09-16 00:13:26 +000024** 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.
drh75897232000-05-29 14:26:00 +000027**
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**
drhb19a2bc2001-09-16 00:13:26 +000033** $Id: vdbe.c,v 1.70 2001/09/16 00:13:27 drh Exp $
drh75897232000-05-29 14:26:00 +000034*/
35#include "sqliteInt.h"
drh7c68d602000-10-11 19:28:51 +000036#include <ctype.h>
drh5edc3122001-09-13 21:53:09 +000037#include <unistd.h>
drh75897232000-05-29 14:26:00 +000038
39/*
40** SQL is translated into a sequence of instructions to be
41** executed by a virtual machine. Each instruction is an instance
42** of the following structure.
43*/
44typedef struct VdbeOp Op;
45
46/*
drh5e00f6c2001-09-13 13:46:56 +000047** Boolean values
48*/
49typedef unsigned char Bool;
50
51/*
drh967e8b72000-06-21 13:59:10 +000052** A cursor is a pointer into a database file. The database file
53** can represent either an SQL table or an SQL index. Each file is
54** a bag of key/data pairs. The cursor can loop over all key/data
55** pairs (in an arbitrary order) or it can retrieve a particular
56** key/data pair given a copy of the key.
57**
58** Every cursor that the virtual machine has open is represented by an
drh75897232000-05-29 14:26:00 +000059** instance of the following structure.
60*/
drh967e8b72000-06-21 13:59:10 +000061struct Cursor {
drh5e00f6c2001-09-13 13:46:56 +000062 BtCursor *pCursor; /* The cursor structure of the backend */
63 int lastRecno; /* Last recno from a Next or NextIdx operation */
64 Bool recnoIsValid; /* True if lastRecno is valid */
65 Bool keyAsData; /* The OP_Column command works on key instead of data */
66 Bool atFirst; /* True if pointing to first entry */
67 Btree *pBt; /* Separate file holding temporary table */
68 char *zKey; /* Key used in BeginIdx and NextIdx operators */
69 int nKey; /* Number of bytes in zKey[] */
70 char *zBuf; /* Buffer space used to hold a copy of zKey[] */
drh75897232000-05-29 14:26:00 +000071};
drh967e8b72000-06-21 13:59:10 +000072typedef struct Cursor Cursor;
drh75897232000-05-29 14:26:00 +000073
74/*
75** A sorter builds a list of elements to be sorted. Each element of
76** the list is an instance of the following structure.
77*/
78typedef struct Sorter Sorter;
79struct Sorter {
80 int nKey; /* Number of bytes in the key */
81 char *zKey; /* The key by which we will sort */
82 int nData; /* Number of bytes in the data */
83 char *pData; /* The data associated with this key */
84 Sorter *pNext; /* Next in the list */
85};
86
87/*
88** Number of buckets used for merge-sort.
89*/
90#define NSORT 30
91
92/*
drhc61053b2000-06-04 12:58:36 +000093** A single level of the stack is an instance of the following
94** structure. Except, string values are stored on a separate
95** list of of pointers to character. The reason for storing
96** strings separately is so that they can be easily passed
97** to the callback function.
98*/
99struct Stack {
100 int i; /* Integer value */
101 int n; /* Number of characters in string value, including '\0' */
102 int flags; /* Some combination of STK_Null, STK_Str, STK_Dyn, etc. */
drh19a775c2000-06-05 18:54:46 +0000103 double r; /* Real value */
drhc61053b2000-06-04 12:58:36 +0000104};
105typedef struct Stack Stack;
106
107/*
drh19a775c2000-06-05 18:54:46 +0000108** Memory cells use the same structure as the stack except that space
109** for an arbitrary string is added.
110*/
111struct Mem {
112 Stack s; /* All values of the memory cell besides string */
113 char *z; /* String value for this memory cell */
114};
115typedef struct Mem Mem;
116
117/*
drhfef52082000-06-06 01:50:43 +0000118** Allowed values for Stack.flags
119*/
120#define STK_Null 0x0001 /* Value is NULL */
121#define STK_Str 0x0002 /* Value is a string */
122#define STK_Int 0x0004 /* Value is an integer */
123#define STK_Real 0x0008 /* Value is a real number */
124#define STK_Dyn 0x0010 /* Need to call sqliteFree() on zStack[*] */
125
126/*
drh967e8b72000-06-21 13:59:10 +0000127** An Agg structure describes an Aggregator. Each Agg consists of
drh600b1b22000-06-05 21:39:48 +0000128** zero or more Aggregator elements (AggElem). Each AggElem contains
129** a key and one or more values. The values are used in processing
130** aggregate functions in a SELECT. The key is used to implement
131** the GROUP BY clause of a select.
132*/
133typedef struct Agg Agg;
134typedef struct AggElem AggElem;
135struct Agg {
136 int nMem; /* Number of values stored in each AggElem */
137 AggElem *pCurrent; /* The AggElem currently in focus */
138 int nElem; /* The number of AggElems */
139 int nHash; /* Number of slots in apHash[] */
drh967e8b72000-06-21 13:59:10 +0000140 AggElem **apHash; /* A hash array for looking up AggElems by zKey */
drh600b1b22000-06-05 21:39:48 +0000141 AggElem *pFirst; /* A list of all AggElems */
142};
143struct AggElem {
144 char *zKey; /* The key to this AggElem */
145 AggElem *pHash; /* Next AggElem with the same hash on zKey */
146 AggElem *pNext; /* Next AggElem in a list of them all */
147 Mem aMem[1]; /* The values for this AggElem */
148};
149
150/*
drhfef52082000-06-06 01:50:43 +0000151** A Set structure is used for quick testing to see if a value
152** is part of a small set. Sets are used to implement code like
153** this:
154** x.y IN ('hi','hoo','hum')
drhc61053b2000-06-04 12:58:36 +0000155*/
drhfef52082000-06-06 01:50:43 +0000156typedef struct Set Set;
157typedef struct SetElem SetElem;
158struct Set {
159 SetElem *pAll; /* All elements of this set */
drh967e8b72000-06-21 13:59:10 +0000160 SetElem *apHash[41]; /* A hash array for all elements in this set */
drhfef52082000-06-06 01:50:43 +0000161};
162struct SetElem {
163 SetElem *pHash; /* Next element with the same hash on zKey */
164 SetElem *pNext; /* Next element in a list of them all */
165 char zKey[1]; /* Value of this key */
166};
drhc61053b2000-06-04 12:58:36 +0000167
168/*
drh0353ced2001-03-20 22:05:00 +0000169** A Keylist is a bunch of keys into a table. The keylist can
170** grow without bound. The keylist stores the keys of database
171** records that need to be deleted.
172*/
173typedef struct Keylist Keylist;
174struct Keylist {
175 int nKey; /* Number of slots in aKey[] */
176 int nUsed; /* Next unwritten slot in aKey[] */
177 int nRead; /* Next unread slot in aKey[] */
178 Keylist *pNext; /* Next block of keys */
179 int aKey[1]; /* One or more keys. Extra space allocated as needed */
180};
181
182/*
drh75897232000-05-29 14:26:00 +0000183** An instance of the virtual machine
184*/
185struct Vdbe {
drh4c504392000-10-16 22:06:40 +0000186 sqlite *db; /* The whole database */
drhbe0072d2001-09-13 14:46:09 +0000187 Btree *pBt; /* Opaque context structure used by DB backend */
drh75897232000-05-29 14:26:00 +0000188 FILE *trace; /* Write an execution trace here, if not NULL */
189 int nOp; /* Number of instructions in the program */
190 int nOpAlloc; /* Number of slots allocated for aOp[] */
191 Op *aOp; /* Space to hold the virtual machine's program */
192 int nLabel; /* Number of labels used */
193 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
194 int *aLabel; /* Space to hold the labels */
195 int tos; /* Index of top of stack */
196 int nStackAlloc; /* Size of the stack */
drhc61053b2000-06-04 12:58:36 +0000197 Stack *aStack; /* The operand stack, except string values */
drh75897232000-05-29 14:26:00 +0000198 char **zStack; /* Text or binary values of the stack */
199 char **azColName; /* Becomes the 4th parameter to callbacks */
drh967e8b72000-06-21 13:59:10 +0000200 int nCursor; /* Number of slots in aCsr[] */
201 Cursor *aCsr; /* On element of this array for each open cursor */
drh75897232000-05-29 14:26:00 +0000202 int nList; /* Number of slots in apList[] */
drh0353ced2001-03-20 22:05:00 +0000203 Keylist **apList; /* For each Keylist */
drh75897232000-05-29 14:26:00 +0000204 int nSort; /* Number of slots in apSort[] */
205 Sorter **apSort; /* An open sorter list */
drh982cef72000-05-30 16:27:03 +0000206 FILE *pFile; /* At most one open file handler */
207 int nField; /* Number of file fields */
208 char **azField; /* Data for each file field */
209 char *zLine; /* A single line from the input file */
210 int nLineAlloc; /* Number of spaces allocated for zLine */
drh19a775c2000-06-05 18:54:46 +0000211 int nMem; /* Number of memory locations currently allocated */
212 Mem *aMem; /* The memory locations */
drh600b1b22000-06-05 21:39:48 +0000213 Agg agg; /* Aggregate information */
drhfef52082000-06-06 01:50:43 +0000214 int nSet; /* Number of sets allocated */
215 Set *aSet; /* An array of sets */
drh5e00f6c2001-09-13 13:46:56 +0000216 int *pTableRoot; /* Write root page no. for new tables to this addr */
217 int *pIndexRoot; /* Write root page no. for new indices to this addr */
drh0bdaf622000-06-11 23:50:13 +0000218 int nFetch; /* Number of OP_Fetch instructions executed */
drh75897232000-05-29 14:26:00 +0000219};
220
221/*
222** Create a new virtual database engine.
223*/
drh4c504392000-10-16 22:06:40 +0000224Vdbe *sqliteVdbeCreate(sqlite *db){
drh75897232000-05-29 14:26:00 +0000225 Vdbe *p;
drh75897232000-05-29 14:26:00 +0000226 p = sqliteMalloc( sizeof(Vdbe) );
drhdaffd0e2001-04-11 14:28:42 +0000227 if( p==0 ) return 0;
drhbe0072d2001-09-13 14:46:09 +0000228 p->pBt = db->pBe;
drh4c504392000-10-16 22:06:40 +0000229 p->db = db;
drh75897232000-05-29 14:26:00 +0000230 return p;
231}
232
233/*
234** Turn tracing on or off
235*/
236void sqliteVdbeTrace(Vdbe *p, FILE *trace){
237 p->trace = trace;
238}
239
240/*
drh5e00f6c2001-09-13 13:46:56 +0000241** Cause the next OP_CreateTable or OP_CreateIndex instruction that executes
242** to write the page number of the root page for the new table or index it
243** creates into the memory location *pAddr.
244**
245** The pointer to the place to write the page number is cleared after
246** the OP_Create* statement. If OP_Create* is executed and the pointer
247** is NULL, an error results. Hence the address can only be used once.
248** If the root address fields are set but OP_Create* operations never
249** execute, that too is an error.
250*/
251void sqliteVdbeTableRootAddr(Vdbe *p, int *pAddr){
252 p->pTableRoot = pAddr;
253}
254void sqliteVdbeIndexRootAddr(Vdbe *p, int *pAddr){
255 p->pIndexRoot = pAddr;
256}
257
258/*
drh75897232000-05-29 14:26:00 +0000259** Add a new instruction to the list of instructions current in the
260** VDBE. Return the address of the new instruction.
261**
262** Parameters:
263**
264** p Pointer to the VDBE
265**
266** op The opcode for this instruction
267**
268** p1, p2, p3 Three operands.
269**
270** lbl A symbolic label for this instruction.
271**
272** Symbolic labels are negative numbers that stand for the address
273** of instructions that have yet to be coded. When the instruction
274** is coded, its real address is substituted in the p2 field of
275** prior and subsequent instructions that have the lbl value in
276** their p2 fields.
277*/
278int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2, const char *p3, int lbl){
279 int i, j;
280
281 i = p->nOp;
282 p->nOp++;
283 if( i>=p->nOpAlloc ){
284 int oldSize = p->nOpAlloc;
285 p->nOpAlloc = p->nOpAlloc*2 + 10;
286 p->aOp = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
287 if( p->aOp==0 ){
288 p->nOp = 0;
289 p->nOpAlloc = 0;
290 return 0;
291 }
292 memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
293 }
294 p->aOp[i].opcode = op;
295 p->aOp[i].p1 = p1;
296 if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
297 p2 = p->aLabel[-1-p2];
298 }
299 p->aOp[i].p2 = p2;
300 if( p3 && p3[0] ){
drh6e142f52000-06-08 13:36:40 +0000301 p->aOp[i].p3 = sqliteStrDup(p3);
drh75897232000-05-29 14:26:00 +0000302 }else{
303 p->aOp[i].p3 = 0;
304 }
305 if( lbl<0 && (-lbl)<=p->nLabel ){
306 p->aLabel[-1-lbl] = i;
307 for(j=0; j<i; j++){
308 if( p->aOp[j].p2==lbl ) p->aOp[j].p2 = i;
309 }
310 }
311 return i;
312}
313
314/*
315** Resolve label "x" to be the address of the next instruction to
316** be inserted.
317*/
318void sqliteVdbeResolveLabel(Vdbe *p, int x){
319 int j;
320 if( x<0 && (-x)<=p->nLabel ){
321 p->aLabel[-1-x] = p->nOp;
322 for(j=0; j<p->nOp; j++){
323 if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
324 }
325 }
326}
327
328/*
329** Return the address of the next instruction to be inserted.
330*/
331int sqliteVdbeCurrentAddr(Vdbe *p){
332 return p->nOp;
333}
334
335/*
336** Add a whole list of operations to the operation stack. Return the
337** address of the first operation added.
338*/
339int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOp const *aOp){
340 int addr;
341 if( p->nOp + nOp >= p->nOpAlloc ){
342 int oldSize = p->nOpAlloc;
343 p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
344 p->aOp = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
345 if( p->aOp==0 ){
346 p->nOp = 0;
347 p->nOpAlloc = 0;
348 return 0;
349 }
350 memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
351 }
352 addr = p->nOp;
353 if( nOp>0 ){
354 int i;
355 for(i=0; i<nOp; i++){
356 int p2 = aOp[i].p2;
357 if( p2<0 ) p2 = addr + ADDR(p2);
358 sqliteVdbeAddOp(p, aOp[i].opcode, aOp[i].p1, p2, aOp[i].p3, 0);
359 }
360 }
361 return addr;
362}
363
364/*
drh5e00f6c2001-09-13 13:46:56 +0000365** Change the value of the P1 operand for a specific instruction.
366** This routine is useful when a large program is loaded from a
367** static array using sqliteVdbeAddOpList but we want to make a
368** few minor changes to the program.
369*/
370void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
371 if( p && addr>=0 && p->nOp>addr ){
372 p->aOp[addr].p1 = val;
373 }
374}
375
376/*
drh75897232000-05-29 14:26:00 +0000377** Change the value of the P3 operand for a specific instruction.
378** This routine is useful when a large program is loaded from a
379** static array using sqliteVdbeAddOpList but we want to make a
380** few minor changes to the program.
381*/
382void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
383 if( p && addr>=0 && p->nOp>addr && zP3 ){
384 sqliteSetNString(&p->aOp[addr].p3, zP3, n, 0);
385 }
386}
387
388/*
389** If the P3 operand to the specified instruction appears
390** to be a quoted string token, then this procedure removes
391** the quotes.
392**
393** The quoting operator can be either a grave ascent (ASCII 0x27)
394** or a double quote character (ASCII 0x22). Two quotes in a row
395** resolve to be a single actual quote character within the string.
396*/
397void sqliteVdbeDequoteP3(Vdbe *p, int addr){
drh75897232000-05-29 14:26:00 +0000398 char *z;
399 if( addr<0 || addr>=p->nOp ) return;
400 z = p->aOp[addr].p3;
drhdaffd0e2001-04-11 14:28:42 +0000401 if( z ) sqliteDequote(z);
drh75897232000-05-29 14:26:00 +0000402}
403
404/*
drhe1b6a5b2000-07-29 13:06:59 +0000405** On the P3 argument of the given instruction, change all
406** strings of whitespace characters into a single space and
407** delete leading and trailing whitespace.
408*/
409void sqliteVdbeCompressSpace(Vdbe *p, int addr){
410 char *z;
411 int i, j;
412 if( addr<0 || addr>=p->nOp ) return;
413 z = p->aOp[addr].p3;
drhdaffd0e2001-04-11 14:28:42 +0000414 if( z==0 ) return;
drhe1b6a5b2000-07-29 13:06:59 +0000415 i = j = 0;
416 while( isspace(z[i]) ){ i++; }
417 while( z[i] ){
418 if( isspace(z[i]) ){
419 z[j++] = ' ';
420 while( isspace(z[++i]) ){}
421 }else{
422 z[j++] = z[i++];
423 }
424 }
425 while( i>0 && isspace(z[i-1]) ){
426 z[i-1] = 0;
427 i--;
428 }
429}
430
431/*
drh75897232000-05-29 14:26:00 +0000432** Create a new symbolic label for an instruction that has yet to be
433** coded. The symbolic label is really just a negative number. The
434** label can be used as the P2 value of an operation. Later, when
435** the label is resolved to a specific address, the VDBE will scan
436** through its operation list and change all values of P2 which match
437** the label into the resolved address.
438**
439** The VDBE knows that a P2 value is a label because labels are
440** always negative and P2 values are suppose to be non-negative.
441** Hence, a negative P2 value is a label that has yet to be resolved.
442*/
443int sqliteVdbeMakeLabel(Vdbe *p){
444 int i;
445 i = p->nLabel++;
446 if( i>=p->nLabelAlloc ){
447 p->nLabelAlloc = p->nLabelAlloc*2 + 10;
drh092d0352001-09-15 13:15:12 +0000448 p->aLabel = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
drh75897232000-05-29 14:26:00 +0000449 }
450 if( p->aLabel==0 ){
451 p->nLabel = 0;
452 p->nLabelAlloc = 0;
453 return 0;
454 }
455 p->aLabel[i] = -1;
456 return -1-i;
457}
458
459/*
drh600b1b22000-06-05 21:39:48 +0000460** Reset an Agg structure. Delete all its contents.
461*/
462static void AggReset(Agg *p){
463 int i;
464 while( p->pFirst ){
465 AggElem *pElem = p->pFirst;
466 p->pFirst = pElem->pNext;
467 for(i=0; i<p->nMem; i++){
468 if( pElem->aMem[i].s.flags & STK_Dyn ){
469 sqliteFree(pElem->aMem[i].z);
470 }
471 }
472 sqliteFree(pElem);
473 }
474 sqliteFree(p->apHash);
475 memset(p, 0, sizeof(*p));
476}
477
478/*
drh967e8b72000-06-21 13:59:10 +0000479** Add the given AggElem to the hash array
drh600b1b22000-06-05 21:39:48 +0000480*/
481static void AggEnhash(Agg *p, AggElem *pElem){
482 int h = sqliteHashNoCase(pElem->zKey, 0) % p->nHash;
483 pElem->pHash = p->apHash[h];
484 p->apHash[h] = pElem;
485}
486
487/*
drh967e8b72000-06-21 13:59:10 +0000488** Change the size of the hash array to the amount given.
drh600b1b22000-06-05 21:39:48 +0000489*/
490static void AggRehash(Agg *p, int nHash){
491 int size;
492 AggElem *pElem;
493 if( p->nHash==nHash ) return;
494 size = nHash * sizeof(AggElem*);
495 p->apHash = sqliteRealloc(p->apHash, size );
drhdaffd0e2001-04-11 14:28:42 +0000496 if( p->apHash==0 ){
497 AggReset(p);
498 return;
499 }
drh600b1b22000-06-05 21:39:48 +0000500 memset(p->apHash, 0, size);
501 p->nHash = nHash;
502 for(pElem=p->pFirst; pElem; pElem=pElem->pNext){
503 AggEnhash(p, pElem);
504 }
505}
506
507/*
508** Insert a new element and make it the current element.
509**
510** Return 0 on success and 1 if memory is exhausted.
511*/
512static int AggInsert(Agg *p, char *zKey){
513 AggElem *pElem;
drh22827922000-06-06 17:27:05 +0000514 int i;
515 if( p->nHash <= p->nElem*2 ){
drhc837e702000-06-08 16:26:24 +0000516 AggRehash(p, p->nElem*2 + 19);
drh600b1b22000-06-05 21:39:48 +0000517 }
518 if( p->nHash==0 ) return 1;
519 pElem = sqliteMalloc( sizeof(AggElem) + strlen(zKey) + 1 +
520 (p->nMem-1)*sizeof(pElem->aMem[0]) );
521 if( pElem==0 ) return 1;
522 pElem->zKey = (char*)&pElem->aMem[p->nMem];
523 strcpy(pElem->zKey, zKey);
524 AggEnhash(p, pElem);
525 pElem->pNext = p->pFirst;
526 p->pFirst = pElem;
527 p->nElem++;
528 p->pCurrent = pElem;
drh22827922000-06-06 17:27:05 +0000529 for(i=0; i<p->nMem; i++){
530 pElem->aMem[i].s.flags = STK_Null;
531 }
drh600b1b22000-06-05 21:39:48 +0000532 return 0;
533}
534
535/*
536** Get the AggElem currently in focus
537*/
538#define AggInFocus(P) ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
539static AggElem *_AggInFocus(Agg *p){
540 AggElem *pFocus = p->pFirst;
541 if( pFocus ){
542 p->pCurrent = pFocus;
543 }else{
544 AggInsert(p,"");
drh22827922000-06-06 17:27:05 +0000545 pFocus = p->pCurrent = p->pFirst;
drh600b1b22000-06-05 21:39:48 +0000546 }
547 return pFocus;
548}
549
550/*
drhfef52082000-06-06 01:50:43 +0000551** Erase all information from a Set
552*/
553static void SetClear(Set *p){
554 SetElem *pElem, *pNext;
555 for(pElem=p->pAll; pElem; pElem=pNext){
556 pNext = pElem->pNext;
557 sqliteFree(pElem);
558 }
559 memset(p, 0, sizeof(*p));
560}
561
562/*
563** Insert a new element into the set
564*/
565static void SetInsert(Set *p, char *zKey){
566 SetElem *pElem;
567 int h = sqliteHashNoCase(zKey, 0) % ArraySize(p->apHash);
568 for(pElem=p->apHash[h]; pElem; pElem=pElem->pHash){
569 if( strcmp(pElem->zKey, zKey)==0 ) return;
570 }
drhcfab11b2000-06-06 03:31:22 +0000571 pElem = sqliteMalloc( sizeof(*pElem) + strlen(zKey) );
drhdaffd0e2001-04-11 14:28:42 +0000572 if( pElem==0 ){
573 SetClear(p);
574 return;
575 }
drhfef52082000-06-06 01:50:43 +0000576 strcpy(pElem->zKey, zKey);
577 pElem->pNext = p->pAll;
578 p->pAll = pElem;
579 pElem->pHash = p->apHash[h];
580 p->apHash[h] = pElem;
581}
582
583/*
584** Return TRUE if an element is in the set. Return FALSE if not.
585*/
586static int SetTest(Set *p, char *zKey){
587 SetElem *pElem;
588 int h = sqliteHashNoCase(zKey, 0) % ArraySize(p->apHash);
589 for(pElem=p->apHash[h]; pElem; pElem=pElem->pHash){
590 if( strcmp(pElem->zKey, zKey)==0 ) return 1;
591 }
592 return 0;
593}
594
595/*
drhc61053b2000-06-04 12:58:36 +0000596** Convert the given stack entity into a string if it isn't one
597** already. Return non-zero if we run out of memory.
598**
599** NULLs are converted into an empty string.
600*/
601#define Stringify(P,I) \
602 ((P->aStack[I].flags & STK_Str)==0 ? hardStringify(P,I) : 0)
603static int hardStringify(Vdbe *p, int i){
drhefa4e172000-10-19 14:42:04 +0000604 Stack *pStack = &p->aStack[i];
605 char **pzStack = &p->zStack[i];
drhc61053b2000-06-04 12:58:36 +0000606 char zBuf[30];
drhefa4e172000-10-19 14:42:04 +0000607 int fg = pStack->flags;
drhc61053b2000-06-04 12:58:36 +0000608 if( fg & STK_Real ){
drhefa4e172000-10-19 14:42:04 +0000609 sprintf(zBuf,"%.15g",pStack->r);
drhc61053b2000-06-04 12:58:36 +0000610 }else if( fg & STK_Int ){
drhefa4e172000-10-19 14:42:04 +0000611 sprintf(zBuf,"%d",pStack->i);
drhc61053b2000-06-04 12:58:36 +0000612 }else{
613 p->zStack[i] = "";
drhefa4e172000-10-19 14:42:04 +0000614 pStack->n = 1;
615 pStack->flags |= STK_Str;
drhc61053b2000-06-04 12:58:36 +0000616 return 0;
617 }
drhefa4e172000-10-19 14:42:04 +0000618 *pzStack = sqliteStrDup(zBuf);
619 if( *pzStack==0 ) return 1;
620 pStack->n = strlen(*pzStack)+1;
621 pStack->flags |= STK_Str|STK_Dyn;
drhc61053b2000-06-04 12:58:36 +0000622 return 0;
623}
624
625/*
626** Release the memory associated with the given stack level
627*/
628#define Release(P,I) if((P)->aStack[I].flags&STK_Dyn){ hardRelease(P,I); }
629static void hardRelease(Vdbe *p, int i){
630 sqliteFree(p->zStack[i]);
631 p->zStack[i] = 0;
632 p->aStack[i].flags &= ~(STK_Str|STK_Dyn);
633}
634
635/*
636** Convert the given stack entity into a integer if it isn't one
637** already.
638**
639** Any prior string or real representation is invalidated.
640** NULLs are converted into 0.
641*/
642#define Integerify(P,I) \
643 if(((P)->aStack[(I)].flags&STK_Int)==0){ hardIntegerify(P,I); }
644static void hardIntegerify(Vdbe *p, int i){
645 if( p->aStack[i].flags & STK_Real ){
646 p->aStack[i].i = p->aStack[i].r;
647 Release(p, i);
648 }else if( p->aStack[i].flags & STK_Str ){
649 p->aStack[i].i = atoi(p->zStack[i]);
650 Release(p, i);
651 }else{
652 p->aStack[i].i = 0;
653 }
654 p->aStack[i].flags = STK_Int;
655}
656
657/*
658** Get a valid Real representation for the given stack element.
659**
660** Any prior string or integer representation is retained.
661** NULLs are converted into 0.0.
662*/
663#define Realify(P,I) \
664 if(((P)->aStack[(I)].flags&STK_Real)==0){ hardRealify(P,I); }
665static void hardRealify(Vdbe *p, int i){
666 if( p->aStack[i].flags & STK_Str ){
667 p->aStack[i].r = atof(p->zStack[i]);
668 }else if( p->aStack[i].flags & STK_Int ){
669 p->aStack[i].r = p->aStack[i].i;
670 }else{
671 p->aStack[i].r = 0.0;
672 }
673 p->aStack[i].flags |= STK_Real;
674}
675
676/*
drh75897232000-05-29 14:26:00 +0000677** Pop the stack N times. Free any memory associated with the
678** popped stack elements.
679*/
680static void PopStack(Vdbe *p, int N){
drhefa4e172000-10-19 14:42:04 +0000681 char **pzStack;
682 Stack *pStack;
drh75897232000-05-29 14:26:00 +0000683 if( p->zStack==0 ) return;
drhefa4e172000-10-19 14:42:04 +0000684 pStack = &p->aStack[p->tos];
685 pzStack = &p->zStack[p->tos];
686 p->tos -= N;
687 while( N-- > 0 ){
688 if( pStack->flags & STK_Dyn ){
689 sqliteFree(*pzStack);
690 }
691 pStack->flags = 0;
692 *pzStack = 0;
693 pStack--;
694 pzStack--;
695 }
drh75897232000-05-29 14:26:00 +0000696}
697
698/*
drh8c82b352000-12-10 18:23:50 +0000699** Here is a macro to handle the common case of popping the stack
700** once. This macro only works from within the sqliteVdbeExec()
701** function.
702*/
703#define POPSTACK \
704 if( aStack[p->tos].flags & STK_Dyn ) sqliteFree(zStack[p->tos]); \
705 p->tos--;
706
707/*
drhc61053b2000-06-04 12:58:36 +0000708** Make sure space has been allocated to hold at least N
709** stack elements. Allocate additional stack space if
710** necessary.
711**
712** Return 0 on success and non-zero if there are memory
713** allocation errors.
714*/
715#define NeedStack(P,N) (((P)->nStackAlloc<=(N)) ? hardNeedStack(P,N) : 0)
716static int hardNeedStack(Vdbe *p, int N){
717 int oldAlloc;
718 int i;
719 if( N>=p->nStackAlloc ){
720 oldAlloc = p->nStackAlloc;
721 p->nStackAlloc = N + 20;
722 p->aStack = sqliteRealloc(p->aStack, p->nStackAlloc*sizeof(p->aStack[0]));
723 p->zStack = sqliteRealloc(p->zStack, p->nStackAlloc*sizeof(char*));
724 if( p->aStack==0 || p->zStack==0 ){
725 sqliteFree(p->aStack);
726 sqliteFree(p->zStack);
727 p->aStack = 0;
728 p->zStack = 0;
729 p->nStackAlloc = 0;
730 return 1;
731 }
732 for(i=oldAlloc; i<p->nStackAlloc; i++){
733 p->zStack[i] = 0;
734 p->aStack[i].flags = 0;
735 }
736 }
737 return 0;
738}
739
740/*
drh0353ced2001-03-20 22:05:00 +0000741** Delete a keylist
742*/
743static void KeylistFree(Keylist *p){
744 while( p ){
745 Keylist *pNext = p->pNext;
746 sqliteFree(p);
747 p = pNext;
748 }
749}
750
751/*
drh50e5dad2001-09-15 00:57:28 +0000752** Close a cursor and release all the resources that cursor happens
753** to hold.
754*/
755static void cleanupCursor(Cursor *pCx){
756 if( pCx->pCursor ){
757 sqliteBtreeCloseCursor(pCx->pCursor);
758 }
759 if( pCx->zKey ){
760 sqliteFree(pCx->zKey);
761 }
762 if( pCx->pBt ){
763 sqliteBtreeClose(pCx->pBt);
764 }
765 memset(pCx, 0, sizeof(Cursor));
766}
767
768/*
drh75897232000-05-29 14:26:00 +0000769** Clean up the VM after execution.
770**
drh5e00f6c2001-09-13 13:46:56 +0000771** This routine will automatically close any cursors, lists, and/or
drh75897232000-05-29 14:26:00 +0000772** sorters that were left open.
773*/
774static void Cleanup(Vdbe *p){
775 int i;
776 PopStack(p, p->tos+1);
777 sqliteFree(p->azColName);
778 p->azColName = 0;
drh967e8b72000-06-21 13:59:10 +0000779 for(i=0; i<p->nCursor; i++){
drh50e5dad2001-09-15 00:57:28 +0000780 cleanupCursor(&p->aCsr[i]);
drh75897232000-05-29 14:26:00 +0000781 }
drh967e8b72000-06-21 13:59:10 +0000782 sqliteFree(p->aCsr);
783 p->aCsr = 0;
784 p->nCursor = 0;
drh19a775c2000-06-05 18:54:46 +0000785 for(i=0; i<p->nMem; i++){
786 if( p->aMem[i].s.flags & STK_Dyn ){
787 sqliteFree(p->aMem[i].z);
788 }
789 }
790 sqliteFree(p->aMem);
791 p->aMem = 0;
792 p->nMem = 0;
drh75897232000-05-29 14:26:00 +0000793 for(i=0; i<p->nList; i++){
drh0353ced2001-03-20 22:05:00 +0000794 KeylistFree(p->apList[i]);
795 p->apList[i] = 0;
drh75897232000-05-29 14:26:00 +0000796 }
797 sqliteFree(p->apList);
798 p->apList = 0;
799 p->nList = 0;
800 for(i=0; i<p->nSort; i++){
801 Sorter *pSorter;
802 while( (pSorter = p->apSort[i])!=0 ){
803 p->apSort[i] = pSorter->pNext;
804 sqliteFree(pSorter->zKey);
805 sqliteFree(pSorter->pData);
806 sqliteFree(pSorter);
807 }
808 }
809 sqliteFree(p->apSort);
810 p->apSort = 0;
811 p->nSort = 0;
drh982cef72000-05-30 16:27:03 +0000812 if( p->pFile ){
813 if( p->pFile!=stdin ) fclose(p->pFile);
814 p->pFile = 0;
815 }
816 if( p->azField ){
817 sqliteFree(p->azField);
818 p->azField = 0;
819 }
820 p->nField = 0;
821 if( p->zLine ){
822 sqliteFree(p->zLine);
823 p->zLine = 0;
824 }
825 p->nLineAlloc = 0;
drh600b1b22000-06-05 21:39:48 +0000826 AggReset(&p->agg);
drhfef52082000-06-06 01:50:43 +0000827 for(i=0; i<p->nSet; i++){
828 SetClear(&p->aSet[i]);
829 }
830 sqliteFree(p->aSet);
831 p->aSet = 0;
832 p->nSet = 0;
drh5e00f6c2001-09-13 13:46:56 +0000833 p->pTableRoot = 0;
834 p->pIndexRoot = 0;
drh75897232000-05-29 14:26:00 +0000835}
836
837/*
838** Delete an entire VDBE.
839*/
840void sqliteVdbeDelete(Vdbe *p){
841 int i;
842 if( p==0 ) return;
843 Cleanup(p);
844 if( p->nOpAlloc==0 ){
845 p->aOp = 0;
846 p->nOp = 0;
847 }
848 for(i=0; i<p->nOp; i++){
849 sqliteFree(p->aOp[i].p3);
850 }
851 sqliteFree(p->aOp);
852 sqliteFree(p->aLabel);
drhc61053b2000-06-04 12:58:36 +0000853 sqliteFree(p->aStack);
drh75897232000-05-29 14:26:00 +0000854 sqliteFree(p->zStack);
855 sqliteFree(p);
856}
857
858/*
859** A translation from opcode numbers to opcode names. Used for testing
860** and debugging only.
861**
862** If any of the numeric OP_ values for opcodes defined in sqliteVdbe.h
863** change, be sure to change this array to match. You can use the
864** "opNames.awk" awk script which is part of the source tree to regenerate
865** this array, then copy and paste it into this file, if you want.
866*/
867static char *zOpName[] = { 0,
drh50e5dad2001-09-15 00:57:28 +0000868 "Transaction", "Commit", "Rollback", "ReadCookie",
869 "SetCookie", "VerifyCookie", "Open", "OpenTemp",
870 "Close", "MoveTo", "Fcnt", "NewRecno",
871 "Put", "Distinct", "Found", "NotFound",
872 "Delete", "Column", "KeyAsData", "Recno",
873 "FullKey", "Rewind", "Next", "Destroy",
874 "Clear", "CreateIndex", "CreateTable", "Reorganize",
875 "BeginIdx", "NextIdx", "PutIdx", "DeleteIdx",
876 "MemLoad", "MemStore", "ListOpen", "ListWrite",
877 "ListRewind", "ListRead", "ListClose", "SortOpen",
878 "SortPut", "SortMakeRec", "SortMakeKey", "Sort",
879 "SortNext", "SortKey", "SortCallback", "SortClose",
880 "FileOpen", "FileRead", "FileColumn", "FileClose",
881 "AggReset", "AggFocus", "AggIncr", "AggNext",
882 "AggSet", "AggGet", "SetInsert", "SetFound",
883 "SetNotFound", "SetClear", "MakeRecord", "MakeKey",
884 "MakeIdxKey", "Goto", "If", "Halt",
885 "ColumnCount", "ColumnName", "Callback", "Integer",
886 "String", "Null", "Pop", "Dup",
887 "Pull", "Add", "AddImm", "Subtract",
888 "Multiply", "Divide", "Min", "Max",
889 "Like", "Glob", "Eq", "Ne",
890 "Lt", "Le", "Gt", "Ge",
891 "IsNull", "NotNull", "Negative", "And",
892 "Or", "Not", "Concat", "Noop",
893 "Strlen", "Substr",
drh75897232000-05-29 14:26:00 +0000894};
895
896/*
897** Given the name of an opcode, return its number. Return 0 if
898** there is no match.
899**
900** This routine is used for testing and debugging.
901*/
902int sqliteVdbeOpcode(const char *zName){
903 int i;
904 for(i=1; i<=OP_MAX; i++){
905 if( sqliteStrICmp(zName, zOpName[i])==0 ) return i;
906 }
907 return 0;
908}
909
910/*
911** Give a listing of the program in the virtual machine.
912**
913** The interface is the same as sqliteVdbeExec(). But instead of
914** running the code, it invokes the callback once for each instruction.
915** This feature is used to implement "EXPLAIN".
916*/
917int sqliteVdbeList(
918 Vdbe *p, /* The VDBE */
919 sqlite_callback xCallback, /* The callback */
920 void *pArg, /* 1st argument to callback */
921 char **pzErrMsg /* Error msg written here */
922){
923 int i, rc;
drh967e8b72000-06-21 13:59:10 +0000924 char *azValue[6];
drh75897232000-05-29 14:26:00 +0000925 char zAddr[20];
926 char zP1[20];
927 char zP2[20];
928 static char *azColumnNames[] = {
929 "addr", "opcode", "p1", "p2", "p3", 0
930 };
931
932 if( xCallback==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000933 azValue[0] = zAddr;
934 azValue[2] = zP1;
935 azValue[3] = zP2;
936 azValue[5] = 0;
drh58b95762000-06-02 01:17:37 +0000937 rc = SQLITE_OK;
drh4794b982000-06-06 13:54:14 +0000938 /* if( pzErrMsg ){ *pzErrMsg = 0; } */
drh58b95762000-06-02 01:17:37 +0000939 for(i=0; rc==SQLITE_OK && i<p->nOp; i++){
drh4c504392000-10-16 22:06:40 +0000940 if( p->db->flags & SQLITE_Interrupt ){
941 p->db->flags &= ~SQLITE_Interrupt;
942 sqliteSetString(pzErrMsg, "interrupted", 0);
943 rc = SQLITE_INTERRUPT;
944 break;
945 }
drh75897232000-05-29 14:26:00 +0000946 sprintf(zAddr,"%d",i);
947 sprintf(zP1,"%d", p->aOp[i].p1);
948 sprintf(zP2,"%d", p->aOp[i].p2);
drh967e8b72000-06-21 13:59:10 +0000949 azValue[4] = p->aOp[i].p3;
950 azValue[1] = zOpName[p->aOp[i].opcode];
951 if( xCallback(pArg, 5, azValue, azColumnNames) ){
drh58b95762000-06-02 01:17:37 +0000952 rc = SQLITE_ABORT;
953 }
drh75897232000-05-29 14:26:00 +0000954 }
955 return rc;
956}
957
958/*
drh75897232000-05-29 14:26:00 +0000959** The parameters are pointers to the head of two sorted lists
960** of Sorter structures. Merge these two lists together and return
961** a single sorted list. This routine forms the core of the merge-sort
962** algorithm.
963**
964** In the case of a tie, left sorts in front of right.
965*/
966static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
967 Sorter sHead;
968 Sorter *pTail;
969 pTail = &sHead;
970 pTail->pNext = 0;
971 while( pLeft && pRight ){
972 int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
973 if( c<=0 ){
974 pTail->pNext = pLeft;
975 pLeft = pLeft->pNext;
976 }else{
977 pTail->pNext = pRight;
978 pRight = pRight->pNext;
979 }
980 pTail = pTail->pNext;
981 }
982 if( pLeft ){
983 pTail->pNext = pLeft;
984 }else if( pRight ){
985 pTail->pNext = pRight;
986 }
987 return sHead.pNext;
988}
989
drh75897232000-05-29 14:26:00 +0000990/*
drh76634482000-10-23 01:07:59 +0000991** Code contained within the VERIFY() macro is not needed for correct
992** execution. It is there only to catch errors. So when we compile
993** with NDEBUG=1, the VERIFY() code is omitted.
994*/
995#ifdef NDEBUG
996# define VERIFY(X)
997#else
998# define VERIFY(X) X
999#endif
1000
1001/*
drh75897232000-05-29 14:26:00 +00001002** Execute the program in the VDBE.
1003**
1004** If an error occurs, an error message is written to memory obtained
1005** from sqliteMalloc() and *pzErrMsg is made to point to that memory.
1006** The return parameter is the number of errors.
1007**
1008** If the callback every returns non-zero, then the program exits
drh58b95762000-06-02 01:17:37 +00001009** immediately. No error message but the function does return SQLITE_ABORT.
1010**
1011** A memory allocation error causes this routine to return SQLITE_NOMEM
1012** and abandon furture processing.
1013**
1014** Other fatal errors return SQLITE_ERROR.
1015**
1016** If a database file could not be opened because it is locked by
drh2dfbbca2000-07-28 14:32:48 +00001017** another database instance, then the xBusy() callback is invoked
1018** with pBusyArg as its first argument, the name of the table as the
1019** second argument, and the number of times the open has been attempted
1020** as the third argument. The xBusy() callback will typically wait
1021** for the database file to be openable, then return. If xBusy()
1022** returns non-zero, another attempt is made to open the file. If
1023** xBusy() returns zero, or if xBusy is NULL, then execution halts
1024** and this routine returns SQLITE_BUSY.
drh75897232000-05-29 14:26:00 +00001025*/
1026int sqliteVdbeExec(
1027 Vdbe *p, /* The VDBE */
1028 sqlite_callback xCallback, /* The callback */
1029 void *pArg, /* 1st argument to callback */
drh2dfbbca2000-07-28 14:32:48 +00001030 char **pzErrMsg, /* Error msg written here */
1031 void *pBusyArg, /* 1st argument to the busy callback */
1032 int (*xBusy)(void*,const char*,int) /* Called when a file is busy */
drh75897232000-05-29 14:26:00 +00001033){
1034 int pc; /* The program counter */
1035 Op *pOp; /* Current operation */
1036 int rc; /* Value to return */
drhbe0072d2001-09-13 14:46:09 +00001037 Btree *pBt = p->pBt; /* The backend driver */
drh76634482000-10-23 01:07:59 +00001038 sqlite *db = p->db; /* The database */
drh5e00f6c2001-09-13 13:46:56 +00001039 char **zStack; /* Text stack */
1040 Stack *aStack; /* Additional stack information */
1041 char zBuf[100]; /* Space to sprintf() an integer */
drh75897232000-05-29 14:26:00 +00001042
drh76634482000-10-23 01:07:59 +00001043
1044 /* No instruction ever pushes more than a single element onto the
1045 ** stack. And the stack never grows on successive executions of the
1046 ** same loop. So the total number of instructions is an upper bound
1047 ** on the maximum stack depth required.
1048 **
1049 ** Allocation all the stack space we will ever need.
1050 */
1051 NeedStack(p, p->nOp);
drh8c3052c2000-10-23 13:16:31 +00001052 zStack = p->zStack;
1053 aStack = p->aStack;
drh75897232000-05-29 14:26:00 +00001054 p->tos = -1;
drh76634482000-10-23 01:07:59 +00001055
drh58b95762000-06-02 01:17:37 +00001056 rc = SQLITE_OK;
drhd1dedb82000-06-05 02:07:04 +00001057#ifdef MEMORY_DEBUG
1058 if( access("vdbe_trace",0)==0 ){
drh3fc190c2001-09-14 03:24:23 +00001059 p->trace = stdout;
drhd1dedb82000-06-05 02:07:04 +00001060 }
1061#endif
drh4794b982000-06-06 13:54:14 +00001062 /* if( pzErrMsg ){ *pzErrMsg = 0; } */
drhdaffd0e2001-04-11 14:28:42 +00001063 if( sqlite_malloc_failed ) rc = SQLITE_NOMEM;
drh76634482000-10-23 01:07:59 +00001064 for(pc=0; rc==SQLITE_OK && pc<p->nOp VERIFY(&& pc>=0); pc++){
drh75897232000-05-29 14:26:00 +00001065 pOp = &p->aOp[pc];
drh6e142f52000-06-08 13:36:40 +00001066
drh4c504392000-10-16 22:06:40 +00001067 /* Interrupt processing if requested.
1068 */
drh76634482000-10-23 01:07:59 +00001069 if( db->flags & SQLITE_Interrupt ){
1070 db->flags &= ~SQLITE_Interrupt;
drh4c504392000-10-16 22:06:40 +00001071 rc = SQLITE_INTERRUPT;
1072 sqliteSetString(pzErrMsg, "interrupted", 0);
1073 break;
1074 }
1075
drh6e142f52000-06-08 13:36:40 +00001076 /* Only allow tracing if NDEBUG is not defined.
1077 */
1078#ifndef NDEBUG
drh75897232000-05-29 14:26:00 +00001079 if( p->trace ){
1080 fprintf(p->trace,"%4d %-12s %4d %4d %s\n",
1081 pc, zOpName[pOp->opcode], pOp->p1, pOp->p2,
1082 pOp->p3 ? pOp->p3 : "");
drh3fc190c2001-09-14 03:24:23 +00001083 fflush(p->trace);
drh75897232000-05-29 14:26:00 +00001084 }
drh6e142f52000-06-08 13:36:40 +00001085#endif
1086
drh75897232000-05-29 14:26:00 +00001087 switch( pOp->opcode ){
drh75897232000-05-29 14:26:00 +00001088
drh5e00f6c2001-09-13 13:46:56 +00001089/*****************************************************************************
1090** What follows is a massive switch statement where each case implements a
1091** separate instruction in the virtual machine. If we follow the usual
1092** indentation conventions, each case should be indented by 6 spaces. But
1093** that is a lot of wasted space on the left margin. So the code within
1094** the switch statement will break with convention and be flush-left. Another
1095** big comment (similar to this one) will mark the point in the code where
1096** we transition back to normal indentation.
1097*****************************************************************************/
drh75897232000-05-29 14:26:00 +00001098
drh5e00f6c2001-09-13 13:46:56 +00001099/* Opcode: Goto P2 * *
1100**
1101** An unconditional jump to address P2.
1102** The next instruction executed will be
1103** the one at index P2 from the beginning of
1104** the program.
1105*/
1106case OP_Goto: {
1107 pc = pOp->p2 - 1;
1108 break;
1109}
drh75897232000-05-29 14:26:00 +00001110
drh5e00f6c2001-09-13 13:46:56 +00001111/* Opcode: Halt * * *
1112**
drhb19a2bc2001-09-16 00:13:26 +00001113** Exit immediately. All open cursors, Lists, Sorts, etc are closed
drh5e00f6c2001-09-13 13:46:56 +00001114** automatically.
drhb19a2bc2001-09-16 00:13:26 +00001115**
1116** There is an implied Halt instruction inserted at the very end of
1117** every program. So a jump past the last instruction of the program
1118** is the same as executing Halt.
drh5e00f6c2001-09-13 13:46:56 +00001119*/
1120case OP_Halt: {
1121 pc = p->nOp-1;
1122 break;
1123}
drhc61053b2000-06-04 12:58:36 +00001124
drh5e00f6c2001-09-13 13:46:56 +00001125/* Opcode: Integer P1 * *
1126**
1127** The integer value P1 is pushed onto the stack.
1128*/
1129case OP_Integer: {
1130 int i = ++p->tos;
1131 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
1132 aStack[i].i = pOp->p1;
1133 aStack[i].flags = STK_Int;
1134 break;
1135}
drh75897232000-05-29 14:26:00 +00001136
drh5e00f6c2001-09-13 13:46:56 +00001137/* Opcode: String * * P3
1138**
1139** The string value P3 is pushed onto the stack.
1140*/
1141case OP_String: {
1142 int i = ++p->tos;
1143 char *z;
1144 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
1145 z = pOp->p3;
1146 if( z==0 ) z = "";
1147 zStack[i] = z;
1148 aStack[i].n = strlen(z) + 1;
1149 aStack[i].flags = STK_Str;
1150 break;
1151}
drh75897232000-05-29 14:26:00 +00001152
drh5e00f6c2001-09-13 13:46:56 +00001153/* Opcode: Null * * *
1154**
1155** Push a NULL value onto the stack.
1156*/
1157case OP_Null: {
1158 int i = ++p->tos;
1159 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
1160 zStack[i] = 0;
1161 aStack[i].flags = STK_Null;
1162 break;
1163}
drh75897232000-05-29 14:26:00 +00001164
drh5e00f6c2001-09-13 13:46:56 +00001165/* Opcode: Pop P1 * *
1166**
1167** P1 elements are popped off of the top of stack and discarded.
1168*/
1169case OP_Pop: {
1170 PopStack(p, pOp->p1);
1171 break;
1172}
drh75897232000-05-29 14:26:00 +00001173
drh5e00f6c2001-09-13 13:46:56 +00001174/* Opcode: Dup P1 * *
1175**
1176** A copy of the P1-th element of the stack
1177** is made and pushed onto the top of the stack.
1178** The top of the stack is element 0. So the
1179** instruction "Dup 0 0 0" will make a copy of the
1180** top of the stack.
drhb19a2bc2001-09-16 00:13:26 +00001181**
1182** Also see the Pull instruction.
drh5e00f6c2001-09-13 13:46:56 +00001183*/
1184case OP_Dup: {
1185 int i = p->tos - pOp->p1;
1186 int j = ++p->tos;
1187 VERIFY( if( i<0 ) goto not_enough_stack; )
1188 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
1189 aStack[j] = aStack[i];
1190 if( aStack[i].flags & STK_Dyn ){
1191 zStack[j] = sqliteMalloc( aStack[j].n );
1192 if( zStack[j]==0 ) goto no_mem;
1193 memcpy(zStack[j], zStack[i], aStack[j].n);
1194 }else{
1195 zStack[j] = zStack[i];
1196 }
1197 break;
1198}
drh75897232000-05-29 14:26:00 +00001199
drh5e00f6c2001-09-13 13:46:56 +00001200/* Opcode: Pull P1 * *
1201**
1202** The P1-th element is removed from its current location on
1203** the stack and pushed back on top of the stack. The
1204** top of the stack is element 0, so "Pull 0 0 0" is
drhb19a2bc2001-09-16 00:13:26 +00001205** a no-op. "Pull 1 0 0" swaps the top two elements of
1206** the stack.
1207**
1208** See also the Dup instruction.
drh5e00f6c2001-09-13 13:46:56 +00001209*/
1210case OP_Pull: {
1211 int from = p->tos - pOp->p1;
1212 int to = p->tos;
1213 int i;
1214 Stack ts;
1215 char *tz;
1216 VERIFY( if( from<0 ) goto not_enough_stack; )
1217 ts = aStack[from];
1218 tz = zStack[from];
1219 for(i=from; i<to; i++){
1220 aStack[i] = aStack[i+1];
1221 zStack[i] = zStack[i+1];
1222 }
1223 aStack[to] = ts;
1224 zStack[to] = tz;
1225 break;
1226}
drh75897232000-05-29 14:26:00 +00001227
drh5e00f6c2001-09-13 13:46:56 +00001228/* Opcode: ColumnCount P1 * *
1229**
1230** Specify the number of column values that will appear in the
1231** array passed as the 4th parameter to the callback. No checking
1232** is done. If this value is wrong, a coredump can result.
1233*/
1234case OP_ColumnCount: {
1235 p->azColName = sqliteRealloc(p->azColName, (pOp->p1+1)*sizeof(char*));
1236 if( p->azColName==0 ) goto no_mem;
1237 p->azColName[pOp->p1] = 0;
1238 break;
1239}
drh75897232000-05-29 14:26:00 +00001240
drh5e00f6c2001-09-13 13:46:56 +00001241/* Opcode: ColumnName P1 * P3
1242**
1243** P3 becomes the P1-th column name (first is 0). An array of pointers
1244** to all column names is passed as the 4th parameter to the callback.
1245** The ColumnCount opcode must be executed first to allocate space to
1246** hold the column names. Failure to do this will likely result in
1247** a coredump.
1248*/
1249case OP_ColumnName: {
1250 p->azColName[pOp->p1] = pOp->p3 ? pOp->p3 : "";
1251 break;
1252}
drhc61053b2000-06-04 12:58:36 +00001253
drh5e00f6c2001-09-13 13:46:56 +00001254/* Opcode: Callback P1 * *
1255**
1256** Pop P1 values off the stack and form them into an array. Then
1257** invoke the callback function using the newly formed array as the
1258** 3rd parameter.
1259*/
1260case OP_Callback: {
1261 int i = p->tos - pOp->p1 + 1;
1262 int j;
1263 VERIFY( if( i<0 ) goto not_enough_stack; )
1264 VERIFY( if( NeedStack(p, p->tos+2) ) goto no_mem; )
1265 for(j=i; j<=p->tos; j++){
1266 if( (aStack[j].flags & STK_Null)==0 ){
1267 if( Stringify(p, j) ) goto no_mem;
1268 }
1269 }
1270 zStack[p->tos+1] = 0;
1271 if( xCallback!=0 ){
1272 if( xCallback(pArg, pOp->p1, &zStack[i], p->azColName)!=0 ){
1273 rc = SQLITE_ABORT;
1274 }
1275 }
1276 PopStack(p, pOp->p1);
1277 break;
1278}
drh75897232000-05-29 14:26:00 +00001279
drh5e00f6c2001-09-13 13:46:56 +00001280/* Opcode: Concat P1 P2 P3
1281**
1282** Look at the first P1 elements of the stack. Append them all
1283** together with the lowest element first. Use P3 as a separator.
1284** Put the result on the top of the stack. The original P1 elements
1285** are popped from the stack if P2==0 and retained if P2==1.
1286**
1287** If P3 is NULL, then use no separator. When P1==1, this routine
1288** makes a copy of the top stack element into memory obtained
1289** from sqliteMalloc().
1290*/
1291case OP_Concat: {
1292 char *zNew;
1293 int nByte;
1294 int nField;
1295 int i, j;
1296 char *zSep;
1297 int nSep;
drh22827922000-06-06 17:27:05 +00001298
drh5e00f6c2001-09-13 13:46:56 +00001299 nField = pOp->p1;
1300 zSep = pOp->p3;
1301 if( zSep==0 ) zSep = "";
1302 nSep = strlen(zSep);
1303 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
1304 nByte = 1 - nSep;
1305 for(i=p->tos-nField+1; i<=p->tos; i++){
1306 if( aStack[i].flags & STK_Null ){
1307 nByte += nSep;
1308 }else{
1309 if( Stringify(p, i) ) goto no_mem;
1310 nByte += aStack[i].n - 1 + nSep;
1311 }
1312 }
1313 zNew = sqliteMalloc( nByte );
1314 if( zNew==0 ) goto no_mem;
1315 j = 0;
1316 for(i=p->tos-nField+1; i<=p->tos; i++){
1317 if( (aStack[i].flags & STK_Null)==0 ){
1318 memcpy(&zNew[j], zStack[i], aStack[i].n-1);
1319 j += aStack[i].n-1;
1320 }
1321 if( nSep>0 && i<p->tos ){
1322 memcpy(&zNew[j], zSep, nSep);
1323 j += nSep;
1324 }
1325 }
1326 zNew[j] = 0;
1327 if( pOp->p2==0 ) PopStack(p, nField);
1328 VERIFY( NeedStack(p, p->tos+1); )
1329 p->tos++;
1330 aStack[p->tos].n = nByte;
1331 aStack[p->tos].flags = STK_Str|STK_Dyn;
1332 zStack[p->tos] = zNew;
1333 break;
1334}
drh75897232000-05-29 14:26:00 +00001335
drh5e00f6c2001-09-13 13:46:56 +00001336/* Opcode: Add * * *
1337**
1338** Pop the top two elements from the stack, add them together,
1339** and push the result back onto the stack. If either element
1340** is a string then it is converted to a double using the atof()
1341** function before the addition.
1342*/
1343/* Opcode: Multiply * * *
1344**
1345** Pop the top two elements from the stack, multiply them together,
1346** and push the result back onto the stack. If either element
1347** is a string then it is converted to a double using the atof()
1348** function before the multiplication.
1349*/
1350/* Opcode: Subtract * * *
1351**
1352** Pop the top two elements from the stack, subtract the
1353** first (what was on top of the stack) from the second (the
1354** next on stack)
1355** and push the result back onto the stack. If either element
1356** is a string then it is converted to a double using the atof()
1357** function before the subtraction.
1358*/
1359/* Opcode: Divide * * *
1360**
1361** Pop the top two elements from the stack, divide the
1362** first (what was on top of the stack) from the second (the
1363** next on stack)
1364** and push the result back onto the stack. If either element
1365** is a string then it is converted to a double using the atof()
1366** function before the division. Division by zero returns NULL.
1367*/
1368case OP_Add:
1369case OP_Subtract:
1370case OP_Multiply:
1371case OP_Divide: {
1372 int tos = p->tos;
1373 int nos = tos - 1;
1374 VERIFY( if( nos<0 ) goto not_enough_stack; )
1375 if( (aStack[tos].flags & aStack[nos].flags & STK_Int)==STK_Int ){
1376 int a, b;
1377 a = aStack[tos].i;
1378 b = aStack[nos].i;
1379 switch( pOp->opcode ){
1380 case OP_Add: b += a; break;
1381 case OP_Subtract: b -= a; break;
1382 case OP_Multiply: b *= a; break;
drh75897232000-05-29 14:26:00 +00001383 default: {
drh5e00f6c2001-09-13 13:46:56 +00001384 if( a==0 ) goto divide_by_zero;
1385 b /= a;
drh75897232000-05-29 14:26:00 +00001386 break;
1387 }
1388 }
drh5e00f6c2001-09-13 13:46:56 +00001389 POPSTACK;
1390 Release(p, nos);
1391 aStack[nos].i = b;
1392 aStack[nos].flags = STK_Int;
1393 }else{
1394 double a, b;
1395 Realify(p, tos);
1396 Realify(p, nos);
1397 a = aStack[tos].r;
1398 b = aStack[nos].r;
1399 switch( pOp->opcode ){
1400 case OP_Add: b += a; break;
1401 case OP_Subtract: b -= a; break;
1402 case OP_Multiply: b *= a; break;
1403 default: {
1404 if( a==0.0 ) goto divide_by_zero;
1405 b /= a;
1406 break;
1407 }
1408 }
1409 POPSTACK;
1410 Release(p, nos);
1411 aStack[nos].r = b;
1412 aStack[nos].flags = STK_Real;
1413 }
1414 break;
1415
1416divide_by_zero:
1417 PopStack(p, 2);
1418 p->tos = nos;
1419 aStack[nos].flags = STK_Null;
1420 break;
1421}
1422
1423/* Opcode: Max * * *
1424**
1425** Pop the top two elements from the stack then push back the
1426** largest of the two.
1427*/
1428case OP_Max: {
1429 int tos = p->tos;
1430 int nos = tos - 1;
1431 int ft, fn;
1432 int copy = 0;
1433 VERIFY( if( nos<0 ) goto not_enough_stack; )
1434 ft = aStack[tos].flags;
1435 fn = aStack[nos].flags;
1436 if( fn & STK_Null ){
1437 copy = 1;
1438 }else if( (ft & fn & STK_Int)==STK_Int ){
1439 copy = aStack[nos].i<aStack[tos].i;
1440 }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
1441 Realify(p, tos);
1442 Realify(p, nos);
1443 copy = aStack[tos].r>aStack[nos].r;
1444 }else{
1445 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
1446 copy = sqliteCompare(zStack[tos],zStack[nos])>0;
1447 }
1448 if( copy ){
1449 Release(p, nos);
1450 aStack[nos] = aStack[tos];
1451 zStack[nos] = zStack[tos];
1452 zStack[tos] = 0;
1453 aStack[tos].flags = 0;
1454 }else{
1455 Release(p, tos);
1456 }
1457 p->tos = nos;
1458 break;
1459}
1460
1461/* Opcode: Min * * *
1462**
1463** Pop the top two elements from the stack then push back the
1464** smaller of the two.
1465*/
1466case OP_Min: {
1467 int tos = p->tos;
1468 int nos = tos - 1;
1469 int ft, fn;
1470 int copy = 0;
1471 VERIFY( if( nos<0 ) goto not_enough_stack; )
1472 ft = aStack[tos].flags;
1473 fn = aStack[nos].flags;
1474 if( fn & STK_Null ){
1475 copy = 1;
1476 }else if( ft & STK_Null ){
1477 copy = 0;
1478 }else if( (ft & fn & STK_Int)==STK_Int ){
1479 copy = aStack[nos].i>aStack[tos].i;
1480 }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
1481 Realify(p, tos);
1482 Realify(p, nos);
1483 copy = aStack[tos].r<aStack[nos].r;
1484 }else{
1485 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
1486 copy = sqliteCompare(zStack[tos],zStack[nos])<0;
1487 }
1488 if( copy ){
1489 Release(p, nos);
1490 aStack[nos] = aStack[tos];
1491 zStack[nos] = zStack[tos];
1492 zStack[tos] = 0;
1493 aStack[tos].flags = 0;
1494 }else{
1495 Release(p, tos);
1496 }
1497 p->tos = nos;
1498 break;
1499}
1500
1501/* Opcode: AddImm P1 * *
1502**
1503** Add the value P1 to whatever is on top of the stack.
1504*/
1505case OP_AddImm: {
1506 int tos = p->tos;
1507 VERIFY( if( tos<0 ) goto not_enough_stack; )
1508 Integerify(p, tos);
1509 aStack[tos].i += pOp->p1;
1510 break;
1511}
1512
1513/* Opcode: Eq * P2 *
1514**
1515** Pop the top two elements from the stack. If they are equal, then
1516** jump to instruction P2. Otherwise, continue to the next instruction.
1517*/
1518/* Opcode: Ne * P2 *
1519**
1520** Pop the top two elements from the stack. If they are not equal, then
1521** jump to instruction P2. Otherwise, continue to the next instruction.
1522*/
1523/* Opcode: Lt * P2 *
1524**
1525** Pop the top two elements from the stack. If second element (the
1526** next on stack) is less than the first (the top of stack), then
1527** jump to instruction P2. Otherwise, continue to the next instruction.
1528** In other words, jump if NOS<TOS.
1529*/
1530/* Opcode: Le * P2 *
1531**
1532** Pop the top two elements from the stack. If second element (the
1533** next on stack) is less than or equal to the first (the top of stack),
1534** then jump to instruction P2. In other words, jump if NOS<=TOS.
1535*/
1536/* Opcode: Gt * P2 *
1537**
1538** Pop the top two elements from the stack. If second element (the
1539** next on stack) is greater than the first (the top of stack),
1540** then jump to instruction P2. In other words, jump if NOS>TOS.
1541*/
1542/* Opcode: Ge * P2 *
1543**
1544** Pop the top two elements from the stack. If second element (the next
1545** on stack) is greater than or equal to the first (the top of stack),
1546** then jump to instruction P2. In other words, jump if NOS>=TOS.
1547*/
1548case OP_Eq:
1549case OP_Ne:
1550case OP_Lt:
1551case OP_Le:
1552case OP_Gt:
1553case OP_Ge: {
1554 int tos = p->tos;
1555 int nos = tos - 1;
1556 int c;
1557 int ft, fn;
1558 VERIFY( if( nos<0 ) goto not_enough_stack; )
1559 ft = aStack[tos].flags;
1560 fn = aStack[nos].flags;
1561 if( (ft & fn)==STK_Int ){
1562 c = aStack[nos].i - aStack[tos].i;
1563 }else{
1564 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
1565 c = sqliteCompare(zStack[nos], zStack[tos]);
1566 }
1567 switch( pOp->opcode ){
1568 case OP_Eq: c = c==0; break;
1569 case OP_Ne: c = c!=0; break;
1570 case OP_Lt: c = c<0; break;
1571 case OP_Le: c = c<=0; break;
1572 case OP_Gt: c = c>0; break;
1573 default: c = c>=0; break;
1574 }
1575 POPSTACK;
1576 POPSTACK;
1577 if( c ) pc = pOp->p2-1;
1578 break;
1579}
1580
1581/* Opcode: Like P1 P2 *
1582**
1583** Pop the top two elements from the stack. The top-most is a
1584** "like" pattern -- the right operand of the SQL "LIKE" operator.
1585** The lower element is the string to compare against the like
1586** pattern. Jump to P2 if the two compare, and fall through without
1587** jumping if they do not. The '%' in the top-most element matches
1588** any sequence of zero or more characters in the lower element. The
1589** '_' character in the topmost matches any single character of the
1590** lower element. Case is ignored for this comparison.
1591**
1592** If P1 is not zero, the sense of the test is inverted and we
1593** have a "NOT LIKE" operator. The jump is made if the two values
1594** are different.
1595*/
1596case OP_Like: {
1597 int tos = p->tos;
1598 int nos = tos - 1;
1599 int c;
1600 VERIFY( if( nos<0 ) goto not_enough_stack; )
1601 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
1602 c = sqliteLikeCompare(zStack[tos], zStack[nos]);
1603 POPSTACK;
1604 POPSTACK;
1605 if( pOp->p1 ) c = !c;
1606 if( c ) pc = pOp->p2-1;
1607 break;
1608}
1609
1610/* Opcode: Glob P1 P2 *
1611**
1612** Pop the top two elements from the stack. The top-most is a
1613** "glob" pattern. The lower element is the string to compare
1614** against the glob pattern.
1615**
1616** Jump to P2 if the two compare, and fall through without
1617** jumping if they do not. The '*' in the top-most element matches
1618** any sequence of zero or more characters in the lower element. The
1619** '?' character in the topmost matches any single character of the
1620** lower element. [...] matches a range of characters. [^...]
1621** matches any character not in the range. Case is significant
1622** for globs.
1623**
1624** If P1 is not zero, the sense of the test is inverted and we
1625** have a "NOT GLOB" operator. The jump is made if the two values
1626** are different.
1627*/
1628case OP_Glob: {
1629 int tos = p->tos;
1630 int nos = tos - 1;
1631 int c;
1632 VERIFY( if( nos<0 ) goto not_enough_stack; )
1633 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
1634 c = sqliteGlobCompare(zStack[tos], zStack[nos]);
1635 POPSTACK;
1636 POPSTACK;
1637 if( pOp->p1 ) c = !c;
1638 if( c ) pc = pOp->p2-1;
1639 break;
1640}
1641
1642/* Opcode: And * * *
1643**
1644** Pop two values off the stack. Take the logical AND of the
1645** two values and push the resulting boolean value back onto the
1646** stack.
1647*/
1648/* Opcode: Or * * *
1649**
1650** Pop two values off the stack. Take the logical OR of the
1651** two values and push the resulting boolean value back onto the
1652** stack.
1653*/
1654case OP_And:
1655case OP_Or: {
1656 int tos = p->tos;
1657 int nos = tos - 1;
1658 int c;
1659 VERIFY( if( nos<0 ) goto not_enough_stack; )
1660 Integerify(p, tos);
1661 Integerify(p, nos);
1662 if( pOp->opcode==OP_And ){
1663 c = aStack[tos].i && aStack[nos].i;
1664 }else{
1665 c = aStack[tos].i || aStack[nos].i;
1666 }
1667 POPSTACK;
1668 Release(p, nos);
1669 aStack[nos].i = c;
1670 aStack[nos].flags = STK_Int;
1671 break;
1672}
1673
1674/* Opcode: Negative * * *
1675**
1676** Treat the top of the stack as a numeric quantity. Replace it
1677** with its additive inverse.
1678*/
1679case OP_Negative: {
1680 int tos = p->tos;
1681 VERIFY( if( tos<0 ) goto not_enough_stack; )
1682 if( aStack[tos].flags & STK_Real ){
1683 Release(p, tos);
1684 aStack[tos].r = -aStack[tos].r;
1685 aStack[tos].flags = STK_Real;
1686 }else if( aStack[tos].flags & STK_Int ){
1687 Release(p, tos);
1688 aStack[tos].i = -aStack[tos].i;
1689 aStack[tos].flags = STK_Int;
1690 }else{
1691 Realify(p, tos);
1692 Release(p, tos);
1693 aStack[tos].r = -aStack[tos].r;
1694 aStack[tos].flags = STK_Real;
1695 }
1696 break;
1697}
1698
1699/* Opcode: Not * * *
1700**
1701** Interpret the top of the stack as a boolean value. Replace it
1702** with its complement.
1703*/
1704case OP_Not: {
1705 int tos = p->tos;
1706 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
1707 Integerify(p, tos);
1708 Release(p, tos);
1709 aStack[tos].i = !aStack[tos].i;
1710 aStack[tos].flags = STK_Int;
1711 break;
1712}
1713
1714/* Opcode: Noop * * *
1715**
1716** Do nothing. This instruction is often useful as a jump
1717** destination.
1718*/
1719case OP_Noop: {
1720 break;
1721}
1722
1723/* Opcode: If * P2 *
1724**
1725** Pop a single boolean from the stack. If the boolean popped is
1726** true, then jump to p2. Otherwise continue to the next instruction.
1727** An integer is false if zero and true otherwise. A string is
1728** false if it has zero length and true otherwise.
1729*/
1730case OP_If: {
1731 int c;
1732 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
1733 Integerify(p, p->tos);
1734 c = aStack[p->tos].i;
1735 POPSTACK;
1736 if( c ) pc = pOp->p2-1;
1737 break;
1738}
1739
1740/* Opcode: IsNull * P2 *
1741**
1742** Pop a single value from the stack. If the value popped is NULL
1743** then jump to p2. Otherwise continue to the next
1744** instruction.
1745*/
1746case OP_IsNull: {
1747 int c;
1748 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
1749 c = (aStack[p->tos].flags & STK_Null)!=0;
1750 POPSTACK;
1751 if( c ) pc = pOp->p2-1;
1752 break;
1753}
1754
1755/* Opcode: NotNull * P2 *
1756**
1757** Pop a single value from the stack. If the value popped is not an
1758** empty string, then jump to p2. Otherwise continue to the next
1759** instruction.
1760*/
1761case OP_NotNull: {
1762 int c;
1763 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
1764 c = (aStack[p->tos].flags & STK_Null)==0;
1765 POPSTACK;
1766 if( c ) pc = pOp->p2-1;
1767 break;
1768}
1769
1770/* Opcode: MakeRecord P1 * *
1771**
1772** Convert the top P1 entries of the stack into a single entry
1773** suitable for use as a data record in a database table. To do this
1774** all entries (except NULLs) are converted to strings and
drh092d0352001-09-15 13:15:12 +00001775** concatenated. The null-terminators are included on all string
1776** except for NULL columns which are represented by zero bytes.
1777** The lowest entry
drh5e00f6c2001-09-13 13:46:56 +00001778** on the stack is the first in the concatenation and the top of
1779** the stack is the last. After all columns are concatenated, an
drh092d0352001-09-15 13:15:12 +00001780** index header is added. The index header consists of P1 16-bit integers
drh5e00f6c2001-09-13 13:46:56 +00001781** which hold the offset of the beginning of each column data from the
drh092d0352001-09-15 13:15:12 +00001782** beginning of the completed record including the header.
1783**
drhb19a2bc2001-09-16 00:13:26 +00001784** The Column opcode is used to unpack a record manufactured with
drh092d0352001-09-15 13:15:12 +00001785** the opcode.
drh5e00f6c2001-09-13 13:46:56 +00001786*/
1787case OP_MakeRecord: {
1788 char *zNewRecord;
1789 int nByte;
1790 int nField;
1791 int i, j;
drh092d0352001-09-15 13:15:12 +00001792 u16 addr;
drh5e00f6c2001-09-13 13:46:56 +00001793
1794 nField = pOp->p1;
1795 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
1796 nByte = 0;
1797 for(i=p->tos-nField+1; i<=p->tos; i++){
1798 if( (aStack[i].flags & STK_Null)==0 ){
1799 if( Stringify(p, i) ) goto no_mem;
1800 nByte += aStack[i].n;
1801 }
1802 }
drh092d0352001-09-15 13:15:12 +00001803 nByte += sizeof(addr)*nField;
drh872ff862001-09-15 14:43:39 +00001804 if( nByte>MAX_BYTES_PER_ROW ){
drh092d0352001-09-15 13:15:12 +00001805 rc = SQLITE_TOOBIG;
1806 goto abort_due_to_error;
1807 }
drh5e00f6c2001-09-13 13:46:56 +00001808 zNewRecord = sqliteMalloc( nByte );
1809 if( zNewRecord==0 ) goto no_mem;
1810 j = 0;
drh092d0352001-09-15 13:15:12 +00001811 addr = sizeof(addr)*nField;
drh5e00f6c2001-09-13 13:46:56 +00001812 for(i=p->tos-nField+1; i<=p->tos; i++){
drh092d0352001-09-15 13:15:12 +00001813 memcpy(&zNewRecord[j], (char*)&addr, sizeof(addr));
1814 j += sizeof(addr);
drh5e00f6c2001-09-13 13:46:56 +00001815 if( (aStack[i].flags & STK_Null)==0 ){
1816 addr += aStack[i].n;
1817 }
drh5e00f6c2001-09-13 13:46:56 +00001818 }
1819 for(i=p->tos-nField+1; i<=p->tos; i++){
1820 if( (aStack[i].flags & STK_Null)==0 ){
1821 memcpy(&zNewRecord[j], zStack[i], aStack[i].n);
1822 j += aStack[i].n;
1823 }
1824 }
1825 PopStack(p, nField);
1826 VERIFY( NeedStack(p, p->tos+1); )
1827 p->tos++;
1828 aStack[p->tos].n = nByte;
1829 aStack[p->tos].flags = STK_Str | STK_Dyn;
1830 zStack[p->tos] = zNewRecord;
1831 break;
1832}
1833
1834/* Opcode: MakeKey P1 P2 *
1835**
1836** Convert the top P1 entries of the stack into a single entry suitable
drhb19a2bc2001-09-16 00:13:26 +00001837** for use as the key in an index. The top P1 records are
1838** converted to strings and merged. The null-terminators
1839** are retained and used as separators.
drh872ff862001-09-15 14:43:39 +00001840** The lowest entry in the stack is the first field and the top of the
drh5e00f6c2001-09-13 13:46:56 +00001841** stack becomes the last.
1842**
1843** If P2 is not zero, then the original entries remain on the stack
1844** and the new key is pushed on top. If P2 is zero, the original
1845** data is popped off the stack first then the new key is pushed
1846** back in its place.
1847**
1848** See also: MakeIdxKey, SortMakeKey
1849*/
1850case OP_MakeKey: {
1851 char *zNewKey;
1852 int nByte;
1853 int nField;
1854 int i, j;
1855
1856 nField = pOp->p1;
1857 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
1858 nByte = 0;
1859 for(i=p->tos-nField+1; i<=p->tos; i++){
1860 if( aStack[i].flags & STK_Null ){
1861 nByte++;
1862 }else{
1863 if( Stringify(p, i) ) goto no_mem;
1864 nByte += aStack[i].n;
1865 }
1866 }
drh872ff862001-09-15 14:43:39 +00001867 if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
1868 rc = SQLITE_TOOBIG;
1869 goto abort_due_to_error;
1870 }
drh5e00f6c2001-09-13 13:46:56 +00001871 zNewKey = sqliteMalloc( nByte );
1872 if( zNewKey==0 ) goto no_mem;
1873 j = 0;
1874 for(i=p->tos-nField+1; i<=p->tos; i++){
drh872ff862001-09-15 14:43:39 +00001875 if( aStack[i].flags & STK_Null ){
1876 zNewKey[j++] = 0;
1877 }else{
1878 memcpy(&zNewKey[j], zStack[i], aStack[i].n);
1879 j += aStack[i].n;
drh5e00f6c2001-09-13 13:46:56 +00001880 }
drh5e00f6c2001-09-13 13:46:56 +00001881 }
drh5e00f6c2001-09-13 13:46:56 +00001882 if( pOp->p2==0 ) PopStack(p, nField);
1883 VERIFY( NeedStack(p, p->tos+1); )
1884 p->tos++;
1885 aStack[p->tos].n = nByte;
1886 aStack[p->tos].flags = STK_Str|STK_Dyn;
1887 zStack[p->tos] = zNewKey;
1888 break;
1889}
1890
1891/* Opcode: MakeIdxKey P1 * *
1892**
1893** Convert the top P1 entries of the stack into a single entry suitable
1894** for use as the key in an index. In addition, take one additional integer
1895** off of the stack, treat that integer as a four-byte record number, and
1896** append the four bytes to the key. Thus a total of P1+1 entries are
1897** popped from the stack for this instruction and a single entry is pushed
1898** back. The first P1 entries that are popped are strings and the last
1899** entry (the lowest on the stack) is an integer record number.
1900**
1901** The converstion of the first P1 string entries occurs just like in
drh872ff862001-09-15 14:43:39 +00001902** MakeKey. Each entry is separated from the others by a null.
drh5e00f6c2001-09-13 13:46:56 +00001903** The entire concatenation is null-terminated. The lowest entry
1904** in the stack is the first field and the top of the stack becomes the
1905** last.
1906**
1907** See also: MakeKey, SortMakeKey
1908*/
1909case OP_MakeIdxKey: {
1910 char *zNewKey;
1911 int nByte;
1912 int nField;
1913 int i, j;
1914
1915 nField = pOp->p1;
1916 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
drh092d0352001-09-15 13:15:12 +00001917 nByte = sizeof(u32);
drh5e00f6c2001-09-13 13:46:56 +00001918 for(i=p->tos-nField+1; i<=p->tos; i++){
1919 if( aStack[i].flags & STK_Null ){
1920 nByte++;
1921 }else{
1922 if( Stringify(p, i) ) goto no_mem;
1923 nByte += aStack[i].n;
1924 }
1925 }
drh872ff862001-09-15 14:43:39 +00001926 if( nByte>MAX_BYTES_PER_ROW ){
1927 rc = SQLITE_TOOBIG;
1928 goto abort_due_to_error;
1929 }
drh5e00f6c2001-09-13 13:46:56 +00001930 zNewKey = sqliteMalloc( nByte );
1931 if( zNewKey==0 ) goto no_mem;
1932 j = 0;
1933 for(i=p->tos-nField+1; i<=p->tos; i++){
drh872ff862001-09-15 14:43:39 +00001934 if( aStack[i].flags & STK_Null ){
1935 zNewKey[j++] = 0;
1936 }else{
1937 memcpy(&zNewKey[j], zStack[i], aStack[i].n);
1938 j += aStack[i].n;
drh5e00f6c2001-09-13 13:46:56 +00001939 }
drh5e00f6c2001-09-13 13:46:56 +00001940 }
drh5e00f6c2001-09-13 13:46:56 +00001941 Integerify(p, p->tos-nField);
drh092d0352001-09-15 13:15:12 +00001942 memcpy(&zNewKey[j], &aStack[p->tos-nField].i, sizeof(u32));
drh5e00f6c2001-09-13 13:46:56 +00001943 PopStack(p, nField+1);
1944 VERIFY( NeedStack(p, p->tos+1); )
1945 p->tos++;
1946 aStack[p->tos].n = nByte;
1947 aStack[p->tos].flags = STK_Str|STK_Dyn;
1948 zStack[p->tos] = zNewKey;
1949 break;
1950}
1951
1952/* Opcode: Transaction * * *
1953**
1954** Begin a transaction. The transaction ends when a Commit or Rollback
1955** opcode is encountered or whenever there is an execution error that causes
drhb19a2bc2001-09-16 00:13:26 +00001956** a script to abort. A transaction is not ended by a Halt.
drh5e00f6c2001-09-13 13:46:56 +00001957**
drhb19a2bc2001-09-16 00:13:26 +00001958** A write lock is obtained on the database file when a transaction is
1959** started. No other process can read or write the file while the
1960** transaction is underway. Starting a transaction also creates a
1961** rollback journal.
drh5e00f6c2001-09-13 13:46:56 +00001962** A transaction must be started before any changes can be made to the
1963** database.
1964*/
1965case OP_Transaction: {
drhbe0072d2001-09-13 14:46:09 +00001966 rc = sqliteBtreeBeginTrans(pBt);
drh5e00f6c2001-09-13 13:46:56 +00001967 break;
1968}
1969
1970/* Opcode: Commit * * *
1971**
1972** Cause all modifications to the database that have been made since the
1973** last Transaction to actually take effect. No additional modifications
drhb19a2bc2001-09-16 00:13:26 +00001974** are allowed until another transaction is started. The Commit instruction
1975** deletes the journal file and releases the write lock on the database.
1976** A read lock continues to be held if there are still cursors open.
drh5e00f6c2001-09-13 13:46:56 +00001977*/
1978case OP_Commit: {
drhbe0072d2001-09-13 14:46:09 +00001979 rc = sqliteBtreeCommit(pBt);
drh5e00f6c2001-09-13 13:46:56 +00001980 if( rc==SQLITE_OK ){
1981 sqliteCommitInternalChanges(db);
1982 }else{
1983 sqliteRollbackInternalChanges(db);
1984 }
1985 break;
1986}
1987
1988/* Opcode: Rollback * * *
1989**
1990** Cause all modifications to the database that have been made since the
1991** last Transaction to be undone. The database is restored to its state
1992** before the Transaction opcode was executed. No additional modifications
1993** are allowed until another transaction is started.
drhb19a2bc2001-09-16 00:13:26 +00001994**
1995** This instruction automatically closes all cursors and releases both
1996** the read and write locks on the database.
drh5e00f6c2001-09-13 13:46:56 +00001997*/
1998case OP_Rollback: {
drhbe0072d2001-09-13 14:46:09 +00001999 rc = sqliteBtreeRollback(pBt);
drh5e00f6c2001-09-13 13:46:56 +00002000 sqliteRollbackInternalChanges(db);
2001 break;
2002}
2003
drh50e5dad2001-09-15 00:57:28 +00002004/* Opcode: ReadCookie * * *
2005**
drhb19a2bc2001-09-16 00:13:26 +00002006** Read the schema cookie from the database file and push it onto the
2007** stack. The schema cookie is an integer that is used like a version
drh50e5dad2001-09-15 00:57:28 +00002008** number for the database schema. Everytime the schema changes, the
2009** cookie changes to a new random value. This opcode is used during
2010** initialization to read the initial cookie value so that subsequent
2011** database accesses can verify that the cookie has not changed.
2012**
2013** There must be a read-lock on the database (either a transaction
drhb19a2bc2001-09-16 00:13:26 +00002014** must be started or there must be an open cursor) before
drh50e5dad2001-09-15 00:57:28 +00002015** executing this instruction.
2016*/
2017case OP_ReadCookie: {
2018 int i = ++p->tos;
2019 int aMeta[SQLITE_N_BTREE_META];
2020 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2021 rc = sqliteBtreeGetMeta(pBt, aMeta);
2022 aStack[i].i = aMeta[1];
2023 aStack[i].flags = STK_Int;
2024 break;
2025}
2026
2027/* Opcode: SetCookie P1 * *
2028**
drhb19a2bc2001-09-16 00:13:26 +00002029** This operation changes the value of the schema cookie on the database.
drh50e5dad2001-09-15 00:57:28 +00002030** The new value is P1.
2031**
drhb19a2bc2001-09-16 00:13:26 +00002032** The schema cookie changes its value whenever the database schema changes.
drh50e5dad2001-09-15 00:57:28 +00002033** That way, other processes can recognize when the schema has changed
2034** and reread it.
2035**
2036** A transaction must be started before executing this opcode.
2037*/
2038case OP_SetCookie: {
2039 int aMeta[SQLITE_N_BTREE_META];
2040 rc = sqliteBtreeGetMeta(pBt, aMeta);
2041 if( rc==SQLITE_OK ){
2042 aMeta[1] = pOp->p1;
2043 rc = sqliteBtreeUpdateMeta(pBt, aMeta);
2044 }
2045 break;
2046}
2047
2048/* Opcode: VerifyCookie P1 * *
2049**
drhb19a2bc2001-09-16 00:13:26 +00002050** Check the current value of the schema cookie and make sure it is
drh50e5dad2001-09-15 00:57:28 +00002051** equal to P1. If it is not, abort with an SQLITE_SCHEMA error.
2052**
2053** The cookie changes its value whenever the database schema changes.
drhb19a2bc2001-09-16 00:13:26 +00002054** This operation is used to detect when that the cookie has changed
drh50e5dad2001-09-15 00:57:28 +00002055** and that the current process needs to reread the schema.
2056**
2057** Either a transaction needs to have been started or an OP_Open needs
2058** to be executed (to establish a read lock) before this opcode is
2059** invoked.
2060*/
2061case OP_VerifyCookie: {
2062 int aMeta[SQLITE_N_BTREE_META];
2063 rc = sqliteBtreeGetMeta(pBt, aMeta);
2064 if( rc==SQLITE_OK && aMeta[1]!=pOp->p1 ){
2065 sqliteSetString(pzErrMsg, "database schema has changed", 0);
2066 rc = SQLITE_SCHEMA;
2067 }
2068 break;
2069}
2070
drh5e00f6c2001-09-13 13:46:56 +00002071/* Opcode: Open P1 P2 P3
2072**
2073** Open a new cursor for the database table whose root page is
2074** P2 in the main database file. Give the new cursor an identifier
2075** of P1. The P1 values need not be contiguous but all P1 values
2076** should be small integers. It is an error for P1 to be negative.
2077**
drh5edc3122001-09-13 21:53:09 +00002078** If P2==0 then take the root page number from the top of the stack.
2079**
drhb19a2bc2001-09-16 00:13:26 +00002080** There will be a read lock on the database whenever there is an
2081** open cursor. If the database was unlocked prior to this instruction
2082** then a read lock is acquired as part of this instruction. A read
2083** lock allows other processes to read the database but prohibits
2084** any other process from modifying the database. The read lock is
2085** released when all cursors are closed. If this instruction attempts
2086** to get a read lock but fails, the script terminates with an
2087** SQLITE_BUSY error code.
2088**
drh5e00f6c2001-09-13 13:46:56 +00002089** The P3 value is the name of the table or index being opened.
2090** The P3 value is not actually used by this opcode and may be
2091** omitted. But the code generator usually inserts the index or
2092** table name into P3 to make the code easier to read.
2093*/
2094case OP_Open: {
2095 int busy = 0;
2096 int i = pOp->p1;
drh5edc3122001-09-13 21:53:09 +00002097 int tos = p->tos;
2098 int p2 = pOp->p2;
2099 if( p2<=0 ){
2100 if( tos<0 ) goto not_enough_stack;
2101 Integerify(p, tos);
2102 p2 = p->aStack[tos].i;
2103 POPSTACK;
2104 if( p2<2 ){
2105 sqliteSetString(pzErrMsg, "root page number less than 2", 0);
2106 rc = SQLITE_INTERNAL;
2107 goto cleanup;
2108 }
2109 }
drh5e00f6c2001-09-13 13:46:56 +00002110 VERIFY( if( i<0 ) goto bad_instruction; )
2111 if( i>=p->nCursor ){
2112 int j;
2113 p->aCsr = sqliteRealloc( p->aCsr, (i+1)*sizeof(Cursor) );
2114 if( p->aCsr==0 ){ p->nCursor = 0; goto no_mem; }
drha1b351a2001-09-14 16:42:12 +00002115 for(j=p->nCursor; j<=i; j++){
2116 memset(&p->aCsr[j], 0, sizeof(Cursor));
2117 }
drh5e00f6c2001-09-13 13:46:56 +00002118 p->nCursor = i+1;
drh5e00f6c2001-09-13 13:46:56 +00002119 }
drh50e5dad2001-09-15 00:57:28 +00002120 cleanupCursor(&p->aCsr[i]);
drh5e00f6c2001-09-13 13:46:56 +00002121 memset(&p->aCsr[i], 0, sizeof(Cursor));
drhbe0072d2001-09-13 14:46:09 +00002122 do{
drh5edc3122001-09-13 21:53:09 +00002123 rc = sqliteBtreeCursor(pBt, p2, &p->aCsr[i].pCursor);
drh5e00f6c2001-09-13 13:46:56 +00002124 switch( rc ){
2125 case SQLITE_BUSY: {
2126 if( xBusy==0 || (*xBusy)(pBusyArg, pOp->p3, ++busy)==0 ){
2127 sqliteSetString(pzErrMsg, sqliteErrStr(rc), 0);
2128 busy = 0;
2129 }
2130 break;
2131 }
2132 case SQLITE_OK: {
2133 busy = 0;
2134 break;
2135 }
2136 default: {
2137 goto abort_due_to_error;
2138 }
2139 }
2140 }while( busy );
2141 break;
2142}
2143
2144/* Opcode: OpenTemp P1 * *
2145**
2146** Open a new cursor that points to a table in a temporary database
drhb19a2bc2001-09-16 00:13:26 +00002147** file. The temporary file is opened read/write even if the main
drh5e00f6c2001-09-13 13:46:56 +00002148** database is read-only. The temporary file is deleted when the
2149** cursor is closed.
2150*/
2151case OP_OpenTemp: {
drh5e00f6c2001-09-13 13:46:56 +00002152 int i = pOp->p1;
2153 Cursor *pCx;
2154 VERIFY( if( i<0 ) goto bad_instruction; )
2155 if( i>=p->nCursor ){
2156 int j;
2157 p->aCsr = sqliteRealloc( p->aCsr, (i+1)*sizeof(Cursor) );
2158 if( p->aCsr==0 ){ p->nCursor = 0; goto no_mem; }
drha1b351a2001-09-14 16:42:12 +00002159 for(j=p->nCursor; j<=i; j++){
2160 memset(&p->aCsr[j], 0, sizeof(Cursor));
2161 }
drh5e00f6c2001-09-13 13:46:56 +00002162 p->nCursor = i+1;
drh5e00f6c2001-09-13 13:46:56 +00002163 }
2164 pCx = &p->aCsr[i];
drh50e5dad2001-09-15 00:57:28 +00002165 cleanupCursor(pCx);
drh5e00f6c2001-09-13 13:46:56 +00002166 memset(pCx, 0, sizeof(*pCx));
drha1b351a2001-09-14 16:42:12 +00002167 rc = sqliteBtreeOpen(0, 0, TEMP_PAGES, &pCx->pBt);
drh5e00f6c2001-09-13 13:46:56 +00002168 if( rc==SQLITE_OK ){
drhbe0072d2001-09-13 14:46:09 +00002169 rc = sqliteBtreeCursor(pCx->pBt, 2, &pCx->pCursor);
drh5e00f6c2001-09-13 13:46:56 +00002170 }
2171 if( rc==SQLITE_OK ){
2172 rc = sqliteBtreeBeginTrans(pCx->pBt);
2173 }
2174 break;
2175}
2176
2177/* Opcode: Close P1 * *
2178**
2179** Close a cursor previously opened as P1. If P1 is not
2180** currently open, this instruction is a no-op.
2181*/
2182case OP_Close: {
2183 int i = pOp->p1;
2184 if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
drh50e5dad2001-09-15 00:57:28 +00002185 cleanupCursor(&p->aCsr[i]);
drh5e00f6c2001-09-13 13:46:56 +00002186 }
2187 break;
2188}
2189
2190/* Opcode: MoveTo P1 * *
2191**
2192** Pop the top of the stack and use its value as a key. Reposition
2193** cursor P1 so that it points to an entry with a matching key. If
2194** the table contains no record with a matching key, then the cursor
2195** is left pointing at a nearby record.
drhb19a2bc2001-09-16 00:13:26 +00002196**
2197** See also: Found, NotFound, Distinct
drh5e00f6c2001-09-13 13:46:56 +00002198*/
2199case OP_MoveTo: {
2200 int i = pOp->p1;
2201 int tos = p->tos;
2202 VERIFY( if( tos<0 ) goto not_enough_stack; )
2203 if( i>=0 && i<p->nCursor && p->aCsr[i].pCursor ){
2204 int res;
2205 if( aStack[tos].flags & STK_Int ){
drhbe0072d2001-09-13 14:46:09 +00002206 sqliteBtreeMoveto(p->aCsr[i].pCursor,
2207 (char*)&aStack[tos].i, sizeof(int), &res);
drh5e00f6c2001-09-13 13:46:56 +00002208 p->aCsr[i].lastRecno = aStack[tos].i;
2209 p->aCsr[i].recnoIsValid = 1;
2210 }else{
2211 if( Stringify(p, tos) ) goto no_mem;
drhbe0072d2001-09-13 14:46:09 +00002212 sqliteBtreeMoveto(p->aCsr[i].pCursor, zStack[tos], aStack[tos].n, &res);
drh5e00f6c2001-09-13 13:46:56 +00002213 p->aCsr[i].recnoIsValid = 0;
2214 }
2215 p->nFetch++;
2216 }
2217 POPSTACK;
2218 break;
2219}
2220
2221/* Opcode: Fcnt * * *
2222**
2223** Push an integer onto the stack which is the total number of
drhb19a2bc2001-09-16 00:13:26 +00002224** MoveTo opcodes that have been executed by this virtual machine.
drh5e00f6c2001-09-13 13:46:56 +00002225**
2226** This instruction is used to implement the special fcnt() function
2227** in the SQL dialect that SQLite understands. fcnt() is used for
2228** testing purposes.
2229*/
2230case OP_Fcnt: {
2231 int i = ++p->tos;
2232 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2233 aStack[i].i = p->nFetch;
2234 aStack[i].flags = STK_Int;
2235 break;
2236}
2237
2238/* Opcode: Distinct P1 P2 *
2239**
drhb19a2bc2001-09-16 00:13:26 +00002240** Use the top of the stack as a key. If a record with that key does
2241** not exist in the table of cursor P1, then jump to P2. If the record
drh3fc190c2001-09-14 03:24:23 +00002242** does already exist, then fall thru. The cursor is left pointing
2243** at the record if it exists. The key is not popped from the stack.
drh5e00f6c2001-09-13 13:46:56 +00002244**
2245** This operation is similar to NotFound except that this operation
2246** does not pop the key from the stack.
drhb19a2bc2001-09-16 00:13:26 +00002247**
2248** See also: Found, NotFound, MoveTo
drh5e00f6c2001-09-13 13:46:56 +00002249*/
2250/* Opcode: Found P1 P2 *
2251**
2252** Use the top of the stack as a key. If a record with that key
drhb19a2bc2001-09-16 00:13:26 +00002253** does exist in table of P1, then jump to P2. If the record
drh3fc190c2001-09-14 03:24:23 +00002254** does not exist, then fall thru. The cursor is left pointing
2255** to the record if it exists. The key is popped from the stack.
drhb19a2bc2001-09-16 00:13:26 +00002256**
2257** See also: Distinct, NotFound, MoveTo
drh5e00f6c2001-09-13 13:46:56 +00002258*/
2259/* Opcode: NotFound P1 P2 *
2260**
2261** Use the top of the stack as a key. If a record with that key
drhb19a2bc2001-09-16 00:13:26 +00002262** does not exist in table of P1, then jump to P2. If the record
drh3fc190c2001-09-14 03:24:23 +00002263** does exist, then fall thru. The cursor is left pointing to the
2264** record if it exists. The key is popped from the stack.
drh5e00f6c2001-09-13 13:46:56 +00002265**
2266** The difference between this operation and Distinct is that
2267** Distinct does not pop the key from the stack.
drhb19a2bc2001-09-16 00:13:26 +00002268**
2269** See also: Distinct, Found, MoveTo
drh5e00f6c2001-09-13 13:46:56 +00002270*/
2271case OP_Distinct:
2272case OP_NotFound:
2273case OP_Found: {
2274 int i = pOp->p1;
2275 int tos = p->tos;
2276 int alreadyExists = 0;
2277 VERIFY( if( tos<0 ) goto not_enough_stack; )
2278 if( VERIFY( i>=0 && i<p->nCursor && ) p->aCsr[i].pCursor ){
2279 int res, rx;
2280 if( aStack[tos].flags & STK_Int ){
drhbe0072d2001-09-13 14:46:09 +00002281 rx = sqliteBtreeMoveto(p->aCsr[i].pCursor,
2282 (char*)&aStack[tos].i, sizeof(int), &res);
drh5e00f6c2001-09-13 13:46:56 +00002283 }else{
2284 if( Stringify(p, tos) ) goto no_mem;
drhbe0072d2001-09-13 14:46:09 +00002285 rx = sqliteBtreeMoveto(p->aCsr[i].pCursor,
2286 zStack[tos], aStack[tos].n, &res);
drh5e00f6c2001-09-13 13:46:56 +00002287 }
2288 alreadyExists = rx==SQLITE_OK && res==0;
2289 }
2290 if( pOp->opcode==OP_Found ){
2291 if( alreadyExists ) pc = pOp->p2 - 1;
2292 }else{
2293 if( !alreadyExists ) pc = pOp->p2 - 1;
2294 }
2295 if( pOp->opcode!=OP_Distinct ){
2296 POPSTACK;
2297 }
2298 break;
2299}
2300
2301/* Opcode: NewRecno P1 * *
2302**
2303** Get a new integer record number used as the key to a table.
drhb19a2bc2001-09-16 00:13:26 +00002304** The record number is not previously used as a key in the database
2305** table that cursor P1 points to. The new record number pushed
drh5e00f6c2001-09-13 13:46:56 +00002306** onto the stack.
2307*/
2308case OP_NewRecno: {
2309 int i = pOp->p1;
drha1b351a2001-09-14 16:42:12 +00002310 int v = 0;
drh5e00f6c2001-09-13 13:46:56 +00002311 if( VERIFY( i<0 || i>=p->nCursor || ) p->aCsr[i].pCursor==0 ){
2312 v = 0;
2313 }else{
2314 int res, rx, cnt;
drha1b351a2001-09-14 16:42:12 +00002315 static int x = 0;
2316 union {
2317 char zBuf[sizeof(int)];
2318 int i;
2319 } ux;
drh5e00f6c2001-09-13 13:46:56 +00002320 cnt = 0;
2321 do{
drha1b351a2001-09-14 16:42:12 +00002322 if( x==0 || cnt>5 ){
2323 x = sqliteRandomInteger();
drh3fc190c2001-09-14 03:24:23 +00002324 }else{
drha1b351a2001-09-14 16:42:12 +00002325 x += sqliteRandomByte() + 1;
drh3fc190c2001-09-14 03:24:23 +00002326 }
drha1b351a2001-09-14 16:42:12 +00002327 if( x==0 ) continue;
2328 ux.zBuf[3] = x&0xff;
2329 ux.zBuf[2] = (x>>8)&0xff;
2330 ux.zBuf[1] = (x>>16)&0xff;
2331 ux.zBuf[0] = (x>>24)&0xff;
2332 v = ux.i;
drhbe0072d2001-09-13 14:46:09 +00002333 rx = sqliteBtreeMoveto(p->aCsr[i].pCursor, &v, sizeof(v), &res);
drh5e00f6c2001-09-13 13:46:56 +00002334 cnt++;
2335 }while( cnt<10 && rx==SQLITE_OK && res==0 );
2336 }
2337 VERIFY( NeedStack(p, p->tos+1); )
2338 p->tos++;
2339 aStack[p->tos].i = v;
2340 aStack[p->tos].flags = STK_Int;
2341 break;
2342}
2343
2344/* Opcode: Put P1 * *
2345**
2346** Write an entry into the database file P1. A new entry is
drhb19a2bc2001-09-16 00:13:26 +00002347** created if it doesn't already exist or the data for an existing
drh5e00f6c2001-09-13 13:46:56 +00002348** entry is overwritten. The data is the value on the top of the
2349** stack. The key is the next value down on the stack. The stack
2350** is popped twice by this instruction.
2351*/
2352case OP_Put: {
2353 int tos = p->tos;
2354 int nos = p->tos-1;
2355 int i = pOp->p1;
2356 VERIFY( if( nos<0 ) goto not_enough_stack; )
2357 if( VERIFY( i>=0 && i<p->nCursor && ) p->aCsr[i].pCursor!=0 ){
2358 char *zKey;
2359 int nKey;
2360 if( (aStack[nos].flags & STK_Int)==0 ){
2361 if( Stringify(p, nos) ) goto no_mem;
2362 nKey = aStack[nos].n;
2363 zKey = zStack[nos];
2364 }else{
2365 nKey = sizeof(int);
2366 zKey = (char*)&aStack[nos].i;
2367 }
drhbe0072d2001-09-13 14:46:09 +00002368 rc = sqliteBtreeInsert(p->aCsr[i].pCursor, zKey, nKey,
2369 zStack[tos], aStack[tos].n);
drh5e00f6c2001-09-13 13:46:56 +00002370 }
2371 POPSTACK;
2372 POPSTACK;
2373 break;
2374}
2375
2376/* Opcode: Delete P1 * *
2377**
drh5edc3122001-09-13 21:53:09 +00002378** Delete the record at which the P1 cursor is currently pointing.
2379**
2380** The cursor will be left pointing at either the next or the previous
2381** record in the table. If it is left pointing at the next record, then
drhb19a2bc2001-09-16 00:13:26 +00002382** the next Next instruction will be a no-op. Hence it is OK to delete
2383** a record from within an Next loop.
drh5e00f6c2001-09-13 13:46:56 +00002384*/
2385case OP_Delete: {
drh5e00f6c2001-09-13 13:46:56 +00002386 int i = pOp->p1;
drh5e00f6c2001-09-13 13:46:56 +00002387 if( VERIFY( i>=0 && i<p->nCursor && ) p->aCsr[i].pCursor!=0 ){
drhbe0072d2001-09-13 14:46:09 +00002388 rc = sqliteBtreeDelete(p->aCsr[i].pCursor);
drh5e00f6c2001-09-13 13:46:56 +00002389 }
drh5e00f6c2001-09-13 13:46:56 +00002390 break;
2391}
2392
2393/* Opcode: KeyAsData P1 P2 *
2394**
2395** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
drhb19a2bc2001-09-16 00:13:26 +00002396** off (if P2==0). In key-as-data mode, the Field opcode pulls
drh5e00f6c2001-09-13 13:46:56 +00002397** data off of the key rather than the data. This is useful for
2398** processing compound selects.
2399*/
2400case OP_KeyAsData: {
2401 int i = pOp->p1;
2402 if( VERIFY( i>=0 && i<p->nCursor && ) p->aCsr[i].pCursor!=0 ){
2403 p->aCsr[i].keyAsData = pOp->p2;
2404 }
2405 break;
2406}
2407
2408/* Opcode: Column P1 P2 *
2409**
drh092d0352001-09-15 13:15:12 +00002410** Interpret the data that cursor P1 points to as
2411** a structure built using the MakeRecord instruction.
2412** (See the MakeRecord opcode for additional information about
2413** the format of the data.)
2414** Push onto the stack the value of the P2-th column contained
2415** in the data.
drh5e00f6c2001-09-13 13:46:56 +00002416**
2417** If the KeyAsData opcode has previously executed on this cursor,
2418** then the field might be extracted from the key rather than the
2419** data.
2420*/
2421case OP_Column: {
drh5e00f6c2001-09-13 13:46:56 +00002422 int amt, offset, nCol, payloadSize;
drh092d0352001-09-15 13:15:12 +00002423 u16 aHdr[10];
drhd78eeee2001-09-13 16:18:53 +00002424 static const int mxHdr = sizeof(aHdr)/sizeof(aHdr[0]);
drh5e00f6c2001-09-13 13:46:56 +00002425 int i = pOp->p1;
2426 int p2 = pOp->p2;
drh5edc3122001-09-13 21:53:09 +00002427 int tos = p->tos+1;
drh5e00f6c2001-09-13 13:46:56 +00002428 BtCursor *pCrsr;
2429 char *z;
2430
drh5edc3122001-09-13 21:53:09 +00002431 VERIFY( if( NeedStack(p, tos+1) ) goto no_mem; )
drh5e00f6c2001-09-13 13:46:56 +00002432 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2433 int (*xSize)(BtCursor*, int*);
drhbe0072d2001-09-13 14:46:09 +00002434 int (*xRead)(BtCursor*, int, int, char*);
drh5e00f6c2001-09-13 13:46:56 +00002435
2436 /* Use different access functions depending on whether the information
2437 ** is coming from the key or the data of the record.
2438 */
2439 if( p->aCsr[i].keyAsData ){
2440 xSize = sqliteBtreeKeySize;
2441 xRead = sqliteBtreeKey;
2442 }else{
2443 xSize = sqliteBtreeDataSize;
2444 xRead = sqliteBtreeData;
2445 }
2446
2447 /*
2448 ** The code is complicated by efforts to minimize the number
2449 ** of invocations of xRead() since that call can be expensive.
2450 ** For the common case where P2 is small, xRead() is invoked
2451 ** twice. For larger values of P2, it has to be called
2452 ** three times.
2453 */
2454 (*xSize)(pCrsr, &payloadSize);
drh092d0352001-09-15 13:15:12 +00002455 if( payloadSize < sizeof(aHdr[0])*(p2+1) ){
drh5e00f6c2001-09-13 13:46:56 +00002456 rc = SQLITE_CORRUPT;
2457 goto abort_due_to_error;
2458 }
2459 if( p2+1<mxHdr ){
drhbe0072d2001-09-13 14:46:09 +00002460 (*xRead)(pCrsr, 0, sizeof(aHdr[0])*(p2+2), (char*)aHdr);
drh5e00f6c2001-09-13 13:46:56 +00002461 nCol = aHdr[0];
drh092d0352001-09-15 13:15:12 +00002462 nCol /= sizeof(aHdr[0]);
drh5e00f6c2001-09-13 13:46:56 +00002463 offset = aHdr[p2];
2464 if( p2 == nCol-1 ){
2465 amt = payloadSize - offset;
2466 }else{
2467 amt = aHdr[p2+1] - offset;
2468 }
2469 }else{
drh092d0352001-09-15 13:15:12 +00002470 sqliteBtreeData(pCrsr, 0, sizeof(aHdr[0]), (char*)aHdr);
2471 nCol = aHdr[0]/sizeof(aHdr[0]);
drh5e00f6c2001-09-13 13:46:56 +00002472 if( p2 == nCol-1 ){
drh092d0352001-09-15 13:15:12 +00002473 (*xRead)(pCrsr, sizeof(aHdr[0])*p2, sizeof(aHdr[0]), (char*)aHdr);
2474 offset = aHdr[0];
drh5e00f6c2001-09-13 13:46:56 +00002475 amt = payloadSize - offset;
2476 }else{
drh092d0352001-09-15 13:15:12 +00002477 (*xRead)(pCrsr, sizeof(aHdr[0])*p2, sizeof(aHdr[0])*2, (char*)aHdr);
drh5e00f6c2001-09-13 13:46:56 +00002478 offset = aHdr[0];
2479 amt = aHdr[1] - offset;
2480 }
2481 }
2482 if( payloadSize < nCol || amt<0 || offset<0 ){
2483 rc = SQLITE_CORRUPT;
2484 goto abort_due_to_error;
2485 }
drh092d0352001-09-15 13:15:12 +00002486
2487 /* amt and offset now hold the offset to the start of data and the
2488 ** amount of data. Go get the data and put it on the stack.
2489 */
drh5e00f6c2001-09-13 13:46:56 +00002490 if( amt==0 ){
2491 aStack[tos].flags = STK_Null;
2492 }else{
2493 z = sqliteMalloc( amt );
2494 if( z==0 ) goto no_mem;
2495 (*xRead)(pCrsr, offset, amt, z);
2496 aStack[tos].flags = STK_Str | STK_Dyn;
2497 zStack[tos] = z;
2498 aStack[tos].n = amt;
2499 }
drh5edc3122001-09-13 21:53:09 +00002500 p->tos = tos;
drh5e00f6c2001-09-13 13:46:56 +00002501 }
2502 break;
2503}
2504
2505/* Opcode: Recno P1 * *
2506**
2507** Push onto the stack an integer which is the first 4 bytes of the
2508** the key to the current entry in a sequential scan of the database
2509** file P1. The sequential scan should have been started using the
2510** Next opcode.
2511*/
2512case OP_Recno: {
2513 int i = pOp->p1;
2514 int tos = ++p->tos;
2515 BtCursor *pCrsr;
2516
2517 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2518 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2519 int v;
2520 if( p->aCsr[i].recnoIsValid ){
2521 v = p->aCsr[i].lastRecno;
2522 }else{
drh092d0352001-09-15 13:15:12 +00002523 sqliteBtreeKey(pCrsr, 0, sizeof(u32), (char*)&v);
drh5e00f6c2001-09-13 13:46:56 +00002524 }
2525 aStack[tos].i = v;
2526 aStack[tos].flags = STK_Int;
2527 }
2528 break;
2529}
2530
2531/* Opcode: FullKey P1 * *
2532**
drhb19a2bc2001-09-16 00:13:26 +00002533** Extract the complete key from the record that cursor P1 is currently
2534** pointing to and push the key onto the stack as a string.
2535**
2536** Compare this opcode to Recno. The Recno opcode extracts the first
2537** 4 bytes of the key and pushes those bytes onto the stack as an
2538** integer. This instruction pushes the entire key as a string.
drh5e00f6c2001-09-13 13:46:56 +00002539*/
2540case OP_FullKey: {
2541 int i = pOp->p1;
2542 int tos = ++p->tos;
2543 BtCursor *pCrsr;
2544
2545 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2546 VERIFY( if( !p->aCsr[i].keyAsData ) goto bad_instruction; )
2547 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2548 int amt;
2549 char *z;
2550
2551 sqliteBtreeKeySize(pCrsr, &amt);
2552 if( amt<=0 ){
2553 rc = SQLITE_CORRUPT;
2554 goto abort_due_to_error;
2555 }
2556 z = sqliteMalloc( amt );
2557 sqliteBtreeKey(pCrsr, 0, amt, z);
2558 zStack[tos] = z;
2559 aStack[tos].flags = STK_Str | STK_Dyn;
2560 aStack[tos].n = amt;
2561 }
2562 break;
2563}
2564
2565/* Opcode: Rewind P1 * *
2566**
2567** The next use of the Recno or Column or Next instruction for P1
2568** will refer to the first entry in the database file.
2569*/
2570case OP_Rewind: {
2571 int i = pOp->p1;
2572 BtCursor *pCrsr;
2573
2574 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2575 int res;
2576 sqliteBtreeFirst(pCrsr, &res);
2577 p->aCsr[i].atFirst = res==0;
2578 }
2579 break;
2580}
2581
2582/* Opcode: Next P1 P2 *
2583**
2584** Advance cursor P1 so that it points to the next key/data pair in its
2585** table. Or, if there are no more key/data pairs, jump to location P2.
2586*/
2587case OP_Next: {
2588 int i = pOp->p1;
2589 BtCursor *pCrsr;
2590
2591 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2592 if( !p->aCsr[i].atFirst ){
2593 int res;
2594 sqliteBtreeNext(pCrsr, &res);
2595 if( res ){
2596 pc = pOp->p2 - 1;
2597 }else{
2598 p->nFetch++;
2599 }
2600 }
2601 p->aCsr[i].atFirst = 0;
2602 p->aCsr[i].recnoIsValid = 0;
2603 }
2604 break;
2605}
2606
2607/* Opcode: BeginIdx P1 * *
2608**
2609** Begin searching an index for records with the key found on the
2610** top of the stack. The key on the top of the stack should be built
2611** using the MakeKey opcode. Subsequent calls to NextIdx will push
2612** record numbers onto the stack until all records with the same key
2613** have been returned.
2614**
2615** Note that the key for this opcode should be built using MakeKey
2616** but the key used for PutIdx and DeleteIdx should be built using
2617** MakeIdxKey. The difference is that MakeIdxKey adds a 4-bytes
2618** record number to the end of the key in order to specify a particular
drh872ff862001-09-15 14:43:39 +00002619** entry in the index. MakeKey omits the 4-byte record number.
2620** The search that this BeginIdx instruction initiates will span all
2621** entries in the index where the MakeKey generated key matches all
2622** but the last four bytes of the MakeIdxKey generated key.
drh5e00f6c2001-09-13 13:46:56 +00002623*/
2624case OP_BeginIdx: {
2625 int i = pOp->p1;
2626 int tos = p->tos;
2627 int res, rx;
2628 Cursor *pCrsr;
2629 VERIFY( if( tos<0 ) goto not_enough_stack; )
2630 if( i>=0 && i<p->nCursor && (pCrsr = &p->aCsr[i])->pCursor!=0 ){
2631 if( Stringify(p, tos) ) goto no_mem;
drh50e5dad2001-09-15 00:57:28 +00002632 if( pCrsr->zKey ) sqliteFree(pCrsr->zKey);
drh5e00f6c2001-09-13 13:46:56 +00002633 pCrsr->nKey = aStack[tos].n;
drh872ff862001-09-15 14:43:39 +00002634 pCrsr->zKey = sqliteMalloc( 2*pCrsr->nKey );
drh5e00f6c2001-09-13 13:46:56 +00002635 if( pCrsr->zKey==0 ) goto no_mem;
drh872ff862001-09-15 14:43:39 +00002636 pCrsr->zBuf = &pCrsr->zKey[pCrsr->nKey];
2637 memcpy(pCrsr->zKey, zStack[tos], aStack[tos].n);
drh5e00f6c2001-09-13 13:46:56 +00002638 pCrsr->zKey[aStack[tos].n] = 0;
drhbe0072d2001-09-13 14:46:09 +00002639 rx = sqliteBtreeMoveto(pCrsr->pCursor, zStack[tos], aStack[tos].n, &res);
drh5e00f6c2001-09-13 13:46:56 +00002640 pCrsr->atFirst = rx==SQLITE_OK && res>0;
2641 pCrsr->recnoIsValid = 0;
2642 }
2643 POPSTACK;
2644 break;
2645}
2646
2647/* Opcode: NextIdx P1 P2 *
2648**
2649** The P1 cursor points to an SQL index for which a BeginIdx operation
drh872ff862001-09-15 14:43:39 +00002650** has been issued. This operation retrieves the next record from that
drhb19a2bc2001-09-16 00:13:26 +00002651** cursor and verifies that the key on the record minus the last 4 bytes
2652** matches the key that was pulled from the stack by the BeginIdx instruction.
2653** If they match, then the last 4 bytes of the key on the record hold a record
drh872ff862001-09-15 14:43:39 +00002654** number and that record number is extracted and pushed on the stack.
2655** If the keys do not match, there is an immediate jump to instruction P2.
drh5e00f6c2001-09-13 13:46:56 +00002656*/
2657case OP_NextIdx: {
2658 int i = pOp->p1;
2659 int tos = ++p->tos;
2660 Cursor *pCrsr;
drhbe0072d2001-09-13 14:46:09 +00002661 BtCursor *pCur;
drh5e00f6c2001-09-13 13:46:56 +00002662 int rx, res, size;
2663
2664 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2665 zStack[tos] = 0;
drhbe0072d2001-09-13 14:46:09 +00002666 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = &p->aCsr[i])->pCursor!=0 ){
drh5e00f6c2001-09-13 13:46:56 +00002667 pCur = pCrsr->pCursor;
drh5edc3122001-09-13 21:53:09 +00002668 if( pCrsr->atFirst ){
2669 pCrsr->atFirst = 0;
2670 res = 0;
2671 }else{
2672 rx = sqliteBtreeNext(pCur, &res);
2673 if( rx!=SQLITE_OK ) goto abort_due_to_error;
2674 }
drhbe0072d2001-09-13 14:46:09 +00002675 sqliteBtreeKeySize(pCur, &size);
drh092d0352001-09-15 13:15:12 +00002676 if( res>0 || size!=pCrsr->nKey+sizeof(u32) ||
drh5e00f6c2001-09-13 13:46:56 +00002677 sqliteBtreeKey(pCur, 0, pCrsr->nKey, pCrsr->zBuf)!=pCrsr->nKey ||
drh872ff862001-09-15 14:43:39 +00002678 memcmp(pCrsr->zKey, pCrsr->zBuf, pCrsr->nKey)!=0
drh5e00f6c2001-09-13 13:46:56 +00002679 ){
2680 pc = pOp->p2 - 1;
2681 POPSTACK;
2682 }else{
2683 int recno;
drh092d0352001-09-15 13:15:12 +00002684 sqliteBtreeKey(pCur, pCrsr->nKey, sizeof(u32), (char*)&recno);
drh5e00f6c2001-09-13 13:46:56 +00002685 p->aCsr[i].lastRecno = aStack[tos].i = recno;
2686 p->aCsr[i].recnoIsValid = 1;
2687 aStack[tos].flags = STK_Int;
2688 }
2689 }
2690 break;
2691}
2692
2693/* Opcode: PutIdx P1 * *
2694**
2695** The top of the stack hold an SQL index key made using the
2696** MakeIdxKey instruction. This opcode writes that key into the
2697** index P1. Data for the entry is nil.
2698*/
2699case OP_PutIdx: {
2700 int i = pOp->p1;
2701 int tos = p->tos;
2702 BtCursor *pCrsr;
2703 VERIFY( if( tos<0 ) goto not_enough_stack; )
2704 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
drhbe0072d2001-09-13 14:46:09 +00002705 sqliteBtreeInsert(pCrsr, zStack[tos], aStack[tos].n, "", 0);
drh5e00f6c2001-09-13 13:46:56 +00002706 }
2707 POPSTACK;
2708 break;
2709}
2710
2711/* Opcode: DeleteIdx P1 * *
2712**
2713** The top of the stack is an index key built using the MakeIdxKey opcode.
2714** This opcode removes that entry from the index.
2715*/
2716case OP_DeleteIdx: {
2717 int i = pOp->p1;
2718 int tos = p->tos;
2719 BtCursor *pCrsr;
2720 VERIFY( if( tos<0 ) goto not_enough_stack; )
2721 if( VERIFY( i>=0 && i<p->nCursor && ) (pCrsr = p->aCsr[i].pCursor)!=0 ){
2722 int rx, res;
drhbe0072d2001-09-13 14:46:09 +00002723 rx = sqliteBtreeMoveto(pCrsr, zStack[tos], aStack[tos].n, &res);
drh5e00f6c2001-09-13 13:46:56 +00002724 if( rx==SQLITE_OK && res==0 ){
2725 sqliteBtreeDelete(pCrsr);
2726 }
2727 }
2728 POPSTACK;
2729 break;
2730}
2731
2732/* Opcode: Destroy P1 * *
2733**
2734** Delete an entire database table or index whose root page in the database
2735** file is given by P1.
drhb19a2bc2001-09-16 00:13:26 +00002736**
2737** See also: Clear
drh5e00f6c2001-09-13 13:46:56 +00002738*/
2739case OP_Destroy: {
drhbe0072d2001-09-13 14:46:09 +00002740 sqliteBtreeDropTable(pBt, pOp->p1);
drh5e00f6c2001-09-13 13:46:56 +00002741 break;
2742}
2743
drh5edc3122001-09-13 21:53:09 +00002744/* Opcode: Clear P1 * *
2745**
2746** Delete all contents of the database table or index whose root page
drhb19a2bc2001-09-16 00:13:26 +00002747** in the database file is given by P1. But, unlike Destroy, do not
drh5edc3122001-09-13 21:53:09 +00002748** remove the table or index from the database file.
drhb19a2bc2001-09-16 00:13:26 +00002749**
2750** See also: Destroy
drh5edc3122001-09-13 21:53:09 +00002751*/
2752case OP_Clear: {
2753 sqliteBtreeClearTable(pBt, pOp->p1);
2754 break;
2755}
2756
drh5b2fd562001-09-13 15:21:31 +00002757/* Opcode: CreateTable * * *
2758**
2759** Allocate a new table in the main database file. Push the page number
2760** for the root page of the new table onto the stack.
2761**
2762** The root page number is also written to a memory location which has
2763** be set up by the parser. The difference between CreateTable and
2764** CreateIndex is that each writes its root page number into a different
2765** memory location. This writing of the page number into a memory location
2766** is used by the SQL parser to record the page number in its internal
2767** data structures.
drhb19a2bc2001-09-16 00:13:26 +00002768**
2769** See also: CreateIndex
drh5b2fd562001-09-13 15:21:31 +00002770*/
2771case OP_CreateTable: {
2772 int i = ++p->tos;
2773 int pgno;
2774 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2775 if( p->pTableRoot==0 ){
2776 rc = SQLITE_INTERNAL;
2777 goto abort_due_to_error;
2778 }
2779 rc = sqliteBtreeCreateTable(pBt, &pgno);
2780 if( rc==SQLITE_OK ){
2781 aStack[i].i = pgno;
2782 aStack[i].flags = STK_Int;
2783 *p->pTableRoot = pgno;
2784 p->pTableRoot = 0;
2785 }
2786 break;
2787}
2788
drhb19a2bc2001-09-16 00:13:26 +00002789/* Opcode: CreateIndex P1 * *
drh5b2fd562001-09-13 15:21:31 +00002790**
2791** Allocate a new Index in the main database file. Push the page number
2792** for the root page of the new table onto the stack.
2793**
2794** The root page number is also written to a memory location which has
2795** be set up by the parser. The difference between CreateTable and
2796** CreateIndex is that each writes its root page number into a different
2797** memory location. This writing of the page number into a memory location
2798** is used by the SQL parser to record the page number in its internal
2799** data structures.
drhb19a2bc2001-09-16 00:13:26 +00002800**
2801** See also: CreateTable
drh5b2fd562001-09-13 15:21:31 +00002802*/
2803case OP_CreateIndex: {
2804 int i = ++p->tos;
2805 int pgno;
2806 VERIFY( if( NeedStack(p, p->tos) ) goto no_mem; )
2807 if( p->pIndexRoot==0 ){
2808 rc = SQLITE_INTERNAL;
2809 goto abort_due_to_error;
2810 }
2811 rc = sqliteBtreeCreateTable(pBt, &pgno);
2812 if( rc==SQLITE_OK ){
2813 aStack[i].i = pgno;
2814 aStack[i].flags = STK_Int;
2815 *p->pIndexRoot = pgno;
2816 p->pIndexRoot = 0;
2817 }
2818 break;
2819}
2820
drh5e00f6c2001-09-13 13:46:56 +00002821/* Opcode: Reorganize P1 * *
2822**
2823** Compress, optimize, and tidy up table or index whose root page in the
2824** database file is P1.
drhb19a2bc2001-09-16 00:13:26 +00002825**
2826** In the current implementation, this is a no-op.
drh5e00f6c2001-09-13 13:46:56 +00002827*/
2828case OP_Reorganize: {
2829 /* This is currently a no-op */
2830 break;
2831}
2832
2833/* Opcode: ListOpen P1 * *
2834**
2835** Open a "List" structure used for temporary storage of integer
drhb19a2bc2001-09-16 00:13:26 +00002836** record numbers. P1 will server as a handle to this list for future
drh5e00f6c2001-09-13 13:46:56 +00002837** interactions. If another list with the P1 handle is
2838** already opened, the prior list is closed and a new one opened
2839** in its place.
2840*/
2841case OP_ListOpen: {
2842 int i = pOp->p1;
2843 VERIFY( if( i<0 ) goto bad_instruction; )
2844 if( i>=p->nList ){
2845 int j;
2846 p->apList = sqliteRealloc( p->apList, (i+1)*sizeof(Keylist*) );
2847 if( p->apList==0 ){ p->nList = 0; goto no_mem; }
2848 for(j=p->nList; j<=i; j++) p->apList[j] = 0;
2849 p->nList = i+1;
2850 }else if( p->apList[i] ){
2851 KeylistFree(p->apList[i]);
2852 p->apList[i] = 0;
2853 }
2854 break;
2855}
2856
2857/* Opcode: ListWrite P1 * *
2858**
2859** Write the integer on the top of the stack
2860** into the temporary storage list P1.
2861*/
2862case OP_ListWrite: {
2863 int i = pOp->p1;
2864 Keylist *pKeylist;
2865 VERIFY( if( i<0 || i>=p->nList ) goto bad_instruction; )
2866 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
2867 pKeylist = p->apList[i];
2868 if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
drh092d0352001-09-15 13:15:12 +00002869 pKeylist = sqliteMalloc( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
drh5e00f6c2001-09-13 13:46:56 +00002870 if( pKeylist==0 ) goto no_mem;
2871 pKeylist->nKey = 1000;
2872 pKeylist->nRead = 0;
2873 pKeylist->nUsed = 0;
2874 pKeylist->pNext = p->apList[i];
2875 p->apList[i] = pKeylist;
2876 }
2877 Integerify(p, p->tos);
2878 pKeylist->aKey[pKeylist->nUsed++] = aStack[p->tos].i;
2879 POPSTACK;
2880 break;
2881}
2882
2883/* Opcode: ListRewind P1 * *
2884**
2885** Rewind the temporary buffer P1 back to the beginning.
2886*/
2887case OP_ListRewind: {
2888 int i = pOp->p1;
2889 VERIFY( if( i<0 ) goto bad_instruction; )
2890 /* This is now a no-op */
2891 break;
2892}
2893
2894/* Opcode: ListRead P1 P2 *
2895**
2896** Attempt to read an integer from temporary storage buffer P1
2897** and push it onto the stack. If the storage buffer is empty,
2898** push nothing but instead jump to P2.
2899*/
2900case OP_ListRead: {
2901 int i = pOp->p1;
2902 Keylist *pKeylist;
2903 VERIFY(if( i<0 || i>=p->nList ) goto bad_instruction;)
2904 pKeylist = p->apList[i];
2905 if( pKeylist!=0 ){
2906 VERIFY(
2907 if( pKeylist->nRead<0
2908 || pKeylist->nRead>=pKeylist->nUsed
2909 || pKeylist->nRead>=pKeylist->nKey ) goto bad_instruction;
2910 )
2911 p->tos++;
2912 if( NeedStack(p, p->tos) ) goto no_mem;
2913 aStack[p->tos].i = pKeylist->aKey[pKeylist->nRead++];
2914 aStack[p->tos].flags = STK_Int;
2915 zStack[p->tos] = 0;
2916 if( pKeylist->nRead>=pKeylist->nUsed ){
2917 p->apList[i] = pKeylist->pNext;
2918 sqliteFree(pKeylist);
2919 }
2920 }else{
2921 pc = pOp->p2 - 1;
2922 }
2923 break;
2924}
2925
2926/* Opcode: ListClose P1 * *
2927**
2928** Close the temporary storage buffer and discard its contents.
2929*/
2930case OP_ListClose: {
2931 int i = pOp->p1;
2932 VERIFY( if( i<0 ) goto bad_instruction; )
2933 VERIFY( if( i>=p->nList ) goto bad_instruction; )
2934 KeylistFree(p->apList[i]);
2935 p->apList[i] = 0;
2936 break;
2937}
2938
2939/* Opcode: SortOpen P1 * *
2940**
2941** Create a new sorter with index P1
2942*/
2943case OP_SortOpen: {
2944 int i = pOp->p1;
2945 VERIFY( if( i<0 ) goto bad_instruction; )
2946 if( i>=p->nSort ){
2947 int j;
2948 p->apSort = sqliteRealloc( p->apSort, (i+1)*sizeof(Sorter*) );
2949 if( p->apSort==0 ){ p->nSort = 0; goto no_mem; }
2950 for(j=p->nSort; j<=i; j++) p->apSort[j] = 0;
2951 p->nSort = i+1;
2952 }
2953 break;
2954}
2955
2956/* Opcode: SortPut P1 * *
2957**
2958** The TOS is the key and the NOS is the data. Pop both from the stack
2959** and put them on the sorter.
2960*/
2961case OP_SortPut: {
2962 int i = pOp->p1;
2963 int tos = p->tos;
2964 int nos = tos - 1;
2965 Sorter *pSorter;
2966 VERIFY( if( i<0 || i>=p->nSort ) goto bad_instruction; )
2967 VERIFY( if( tos<1 ) goto not_enough_stack; )
2968 if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
2969 pSorter = sqliteMalloc( sizeof(Sorter) );
2970 if( pSorter==0 ) goto no_mem;
2971 pSorter->pNext = p->apSort[i];
2972 p->apSort[i] = pSorter;
2973 pSorter->nKey = aStack[tos].n;
2974 pSorter->zKey = zStack[tos];
2975 pSorter->nData = aStack[nos].n;
2976 pSorter->pData = zStack[nos];
2977 aStack[tos].flags = 0;
2978 aStack[nos].flags = 0;
2979 zStack[tos] = 0;
2980 zStack[nos] = 0;
2981 p->tos -= 2;
2982 break;
2983}
2984
2985/* Opcode: SortMakeRec P1 * *
2986**
2987** The top P1 elements are the arguments to a callback. Form these
2988** elements into a single data entry that can be stored on a sorter
2989** using SortPut and later fed to a callback using SortCallback.
2990*/
2991case OP_SortMakeRec: {
2992 char *z;
2993 char **azArg;
2994 int nByte;
2995 int nField;
2996 int i, j;
2997
2998 nField = pOp->p1;
2999 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
3000 nByte = 0;
3001 for(i=p->tos-nField+1; i<=p->tos; i++){
3002 if( (aStack[i].flags & STK_Null)==0 ){
3003 if( Stringify(p, i) ) goto no_mem;
3004 nByte += aStack[i].n;
3005 }
3006 }
3007 nByte += sizeof(char*)*(nField+1);
3008 azArg = sqliteMalloc( nByte );
3009 if( azArg==0 ) goto no_mem;
3010 z = (char*)&azArg[nField+1];
3011 for(j=0, i=p->tos-nField+1; i<=p->tos; i++, j++){
3012 if( aStack[i].flags & STK_Null ){
3013 azArg[j] = 0;
3014 }else{
3015 azArg[j] = z;
3016 strcpy(z, zStack[i]);
3017 z += aStack[i].n;
3018 }
3019 }
3020 PopStack(p, nField);
3021 VERIFY( NeedStack(p, p->tos+1); )
3022 p->tos++;
3023 aStack[p->tos].n = nByte;
3024 zStack[p->tos] = (char*)azArg;
3025 aStack[p->tos].flags = STK_Str|STK_Dyn;
3026 break;
3027}
3028
3029/* Opcode: SortMakeKey P1 * P3
3030**
3031** Convert the top few entries of the stack into a sort key. The
3032** number of stack entries consumed is the number of characters in
3033** the string P3. One character from P3 is prepended to each entry.
3034** The first character of P3 is prepended to the element lowest in
3035** the stack and the last character of P3 is appended to the top of
3036** the stack. All stack entries are separated by a \000 character
3037** in the result. The whole key is terminated by two \000 characters
3038** in a row.
3039**
drhb19a2bc2001-09-16 00:13:26 +00003040** See also the MakeKey and MakeIdxKey opcodes.
drh5e00f6c2001-09-13 13:46:56 +00003041*/
3042case OP_SortMakeKey: {
3043 char *zNewKey;
3044 int nByte;
3045 int nField;
3046 int i, j, k;
3047
3048 nField = strlen(pOp->p3);
3049 VERIFY( if( p->tos+1<nField ) goto not_enough_stack; )
3050 nByte = 1;
3051 for(i=p->tos-nField+1; i<=p->tos; i++){
3052 if( Stringify(p, i) ) goto no_mem;
3053 nByte += aStack[i].n+2;
3054 }
3055 zNewKey = sqliteMalloc( nByte );
3056 if( zNewKey==0 ) goto no_mem;
3057 j = 0;
3058 k = 0;
3059 for(i=p->tos-nField+1; i<=p->tos; i++){
3060 zNewKey[j++] = pOp->p3[k++];
3061 memcpy(&zNewKey[j], zStack[i], aStack[i].n-1);
3062 j += aStack[i].n-1;
3063 zNewKey[j++] = 0;
3064 }
3065 zNewKey[j] = 0;
3066 PopStack(p, nField);
3067 VERIFY( NeedStack(p, p->tos+1); )
3068 p->tos++;
3069 aStack[p->tos].n = nByte;
3070 aStack[p->tos].flags = STK_Str|STK_Dyn;
3071 zStack[p->tos] = zNewKey;
3072 break;
3073}
3074
3075/* Opcode: Sort P1 * *
3076**
3077** Sort all elements on the given sorter. The algorithm is a
3078** mergesort.
3079*/
3080case OP_Sort: {
3081 int j;
3082 j = pOp->p1;
3083 VERIFY( if( j<0 ) goto bad_instruction; )
3084 if( j<p->nSort ){
3085 int i;
3086 Sorter *pElem;
3087 Sorter *apSorter[NSORT];
3088 for(i=0; i<NSORT; i++){
3089 apSorter[i] = 0;
3090 }
3091 while( p->apSort[j] ){
3092 pElem = p->apSort[j];
3093 p->apSort[j] = pElem->pNext;
3094 pElem->pNext = 0;
3095 for(i=0; i<NSORT-1; i++){
3096 if( apSorter[i]==0 ){
3097 apSorter[i] = pElem;
3098 break;
3099 }else{
3100 pElem = Merge(apSorter[i], pElem);
3101 apSorter[i] = 0;
3102 }
3103 }
3104 if( i>=NSORT-1 ){
3105 apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
3106 }
3107 }
3108 pElem = 0;
3109 for(i=0; i<NSORT; i++){
3110 pElem = Merge(apSorter[i], pElem);
3111 }
3112 p->apSort[j] = pElem;
3113 }
3114 break;
3115}
3116
3117/* Opcode: SortNext P1 P2 *
3118**
3119** Push the data for the topmost element in the given sorter onto the
3120** stack, then remove the element from the sorter.
3121*/
3122case OP_SortNext: {
3123 int i = pOp->p1;
3124 VERIFY( if( i<0 ) goto bad_instruction; )
3125 if( VERIFY( i<p->nSort && ) p->apSort[i]!=0 ){
3126 Sorter *pSorter = p->apSort[i];
3127 p->apSort[i] = pSorter->pNext;
3128 p->tos++;
3129 VERIFY( NeedStack(p, p->tos); )
3130 zStack[p->tos] = pSorter->pData;
3131 aStack[p->tos].n = pSorter->nData;
3132 aStack[p->tos].flags = STK_Str|STK_Dyn;
3133 sqliteFree(pSorter->zKey);
3134 sqliteFree(pSorter);
3135 }else{
3136 pc = pOp->p2 - 1;
3137 }
3138 break;
3139}
3140
3141/* Opcode: SortKey P1 * *
3142**
3143** Push the key for the topmost element of the sorter onto the stack.
3144** But don't change the sorter an any other way.
3145*/
3146case OP_SortKey: {
3147 int i = pOp->p1;
3148 VERIFY( if( i<0 ) goto bad_instruction; )
3149 if( i<p->nSort && p->apSort[i]!=0 ){
3150 Sorter *pSorter = p->apSort[i];
3151 p->tos++;
3152 VERIFY( NeedStack(p, p->tos); )
3153 sqliteSetString(&zStack[p->tos], pSorter->zKey, 0);
3154 aStack[p->tos].n = pSorter->nKey;
3155 aStack[p->tos].flags = STK_Str|STK_Dyn;
3156 }
3157 break;
3158}
3159
3160/* Opcode: SortCallback P1 P2 *
3161**
3162** The top of the stack contains a callback record built using
3163** the SortMakeRec operation with the same P1 value as this
3164** instruction. Pop this record from the stack and invoke the
3165** callback on it.
3166*/
3167case OP_SortCallback: {
3168 int i = p->tos;
3169 VERIFY( if( i<0 ) goto not_enough_stack; )
3170 if( xCallback!=0 ){
3171 if( xCallback(pArg, pOp->p1, (char**)zStack[i], p->azColName) ){
3172 rc = SQLITE_ABORT;
3173 }
3174 }
3175 POPSTACK;
3176 break;
3177}
3178
3179/* Opcode: SortClose P1 * *
3180**
3181** Close the given sorter and remove all its elements.
3182*/
3183case OP_SortClose: {
3184 Sorter *pSorter;
3185 int i = pOp->p1;
3186 VERIFY( if( i<0 ) goto bad_instruction; )
3187 if( i<p->nSort ){
3188 while( (pSorter = p->apSort[i])!=0 ){
3189 p->apSort[i] = pSorter->pNext;
3190 sqliteFree(pSorter->zKey);
3191 sqliteFree(pSorter->pData);
3192 sqliteFree(pSorter);
3193 }
3194 }
3195 break;
3196}
3197
3198/* Opcode: FileOpen * * P3
3199**
3200** Open the file named by P3 for reading using the FileRead opcode.
3201** If P3 is "stdin" then open standard input for reading.
3202*/
3203case OP_FileOpen: {
3204 VERIFY( if( pOp->p3==0 ) goto bad_instruction; )
3205 if( p->pFile ){
3206 if( p->pFile!=stdin ) fclose(p->pFile);
3207 p->pFile = 0;
3208 }
3209 if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
3210 p->pFile = stdin;
3211 }else{
3212 p->pFile = fopen(pOp->p3, "r");
3213 }
3214 if( p->pFile==0 ){
3215 sqliteSetString(pzErrMsg,"unable to open file: ", pOp->p3, 0);
3216 rc = SQLITE_ERROR;
3217 goto cleanup;
3218 }
3219 break;
3220}
3221
3222/* Opcode: FileClose * * *
3223**
3224** Close a file previously opened using FileOpen. This is a no-op
3225** if there is no prior FileOpen call.
3226*/
3227case OP_FileClose: {
3228 if( p->pFile ){
3229 if( p->pFile!=stdin ) fclose(p->pFile);
3230 p->pFile = 0;
3231 }
3232 if( p->azField ){
3233 sqliteFree(p->azField);
3234 p->azField = 0;
3235 }
3236 p->nField = 0;
3237 if( p->zLine ){
3238 sqliteFree(p->zLine);
3239 p->zLine = 0;
3240 }
3241 p->nLineAlloc = 0;
3242 break;
3243}
3244
3245/* Opcode: FileRead P1 P2 P3
3246**
3247** Read a single line of input from the open file (the file opened using
3248** FileOpen). If we reach end-of-file, jump immediately to P2. If
3249** we are able to get another line, split the line apart using P3 as
3250** a delimiter. There should be P1 fields. If the input line contains
3251** more than P1 fields, ignore the excess. If the input line contains
3252** fewer than P1 fields, assume the remaining fields contain an
drhb19a2bc2001-09-16 00:13:26 +00003253** empty strings.
drh5e00f6c2001-09-13 13:46:56 +00003254*/
3255case OP_FileRead: {
3256 int n, eol, nField, i, c, nDelim;
3257 char *zDelim, *z;
3258 if( p->pFile==0 ) goto fileread_jump;
3259 nField = pOp->p1;
3260 if( nField<=0 ) goto fileread_jump;
3261 if( nField!=p->nField || p->azField==0 ){
3262 p->azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
3263 if( p->azField==0 ){
3264 p->nField = 0;
3265 goto fileread_jump;
3266 }
3267 p->nField = nField;
3268 }
3269 n = 0;
3270 eol = 0;
3271 while( eol==0 ){
3272 if( p->zLine==0 || n+200>p->nLineAlloc ){
3273 p->nLineAlloc = p->nLineAlloc*2 + 300;
3274 p->zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
3275 if( p->zLine==0 ){
3276 p->nLineAlloc = 0;
3277 goto fileread_jump;
3278 }
3279 }
3280 if( fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
3281 eol = 1;
3282 p->zLine[n] = 0;
3283 }else{
3284 while( p->zLine[n] ){ n++; }
3285 if( n>0 && p->zLine[n-1]=='\n' ){
3286 n--;
3287 p->zLine[n] = 0;
3288 eol = 1;
3289 }
3290 }
3291 }
3292 if( n==0 ) goto fileread_jump;
3293 z = p->zLine;
3294 if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
3295 goto fileread_jump;
3296 }
3297 zDelim = pOp->p3;
3298 if( zDelim==0 ) zDelim = "\t";
3299 c = zDelim[0];
3300 nDelim = strlen(zDelim);
3301 p->azField[0] = z;
3302 for(i=1; *z!=0 && i<=nField; i++){
3303 int from, to;
3304 from = to = 0;
3305 while( z[from] ){
3306 if( z[from]=='\\' && z[from+1]!=0 ){
3307 z[to++] = z[from+1];
3308 from += 2;
3309 continue;
3310 }
3311 if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
3312 z[to++] = z[from++];
3313 }
3314 if( z[from] ){
3315 z[to] = 0;
3316 z += from + nDelim;
3317 if( i<nField ) p->azField[i] = z;
3318 }else{
3319 z[to] = 0;
3320 z = "";
3321 }
3322 }
3323 while( i<nField ){
3324 p->azField[i++] = "";
3325 }
3326 break;
3327
3328 /* If we reach end-of-file, or if anything goes wrong, jump here.
3329 ** This code will cause a jump to P2 */
3330fileread_jump:
3331 pc = pOp->p2 - 1;
3332 break;
3333}
3334
drhbe0072d2001-09-13 14:46:09 +00003335/* Opcode: FileColumn P1 * *
drh5e00f6c2001-09-13 13:46:56 +00003336**
drhb19a2bc2001-09-16 00:13:26 +00003337** Push onto the stack the P1-th column of the most recently read line
drh5e00f6c2001-09-13 13:46:56 +00003338** from the input file.
3339*/
drhbe0072d2001-09-13 14:46:09 +00003340case OP_FileColumn: {
drh5e00f6c2001-09-13 13:46:56 +00003341 int i = pOp->p1;
3342 char *z;
3343 VERIFY( if( NeedStack(p, p->tos+1) ) goto no_mem; )
3344 if( VERIFY( i>=0 && i<p->nField && ) p->azField ){
3345 z = p->azField[i];
3346 }else{
3347 z = 0;
3348 }
3349 if( z==0 ) z = "";
3350 p->tos++;
3351 aStack[p->tos].n = strlen(z) + 1;
3352 zStack[p->tos] = z;
3353 aStack[p->tos].flags = STK_Str;
3354 break;
3355}
3356
3357/* Opcode: MemStore P1 * *
3358**
3359** Pop a single value of the stack and store that value into memory
3360** location P1. P1 should be a small integer since space is allocated
3361** for all memory locations between 0 and P1 inclusive.
3362*/
3363case OP_MemStore: {
3364 int i = pOp->p1;
3365 int tos = p->tos;
3366 Mem *pMem;
3367 char *zOld;
3368 VERIFY( if( tos<0 ) goto not_enough_stack; )
3369 if( i>=p->nMem ){
3370 int nOld = p->nMem;
3371 p->nMem = i + 5;
3372 p->aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
3373 if( p->aMem==0 ) goto no_mem;
3374 if( nOld<p->nMem ){
3375 memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
3376 }
3377 }
3378 pMem = &p->aMem[i];
3379 if( pMem->s.flags & STK_Dyn ){
3380 zOld = pMem->z;
3381 }else{
3382 zOld = 0;
3383 }
3384 pMem->s = aStack[tos];
3385 if( pMem->s.flags & STK_Str ){
3386 pMem->z = sqliteStrNDup(zStack[tos], pMem->s.n);
3387 pMem->s.flags |= STK_Dyn;
3388 }
3389 if( zOld ) sqliteFree(zOld);
3390 POPSTACK;
3391 break;
3392}
3393
3394/* Opcode: MemLoad P1 * *
3395**
3396** Push a copy of the value in memory location P1 onto the stack.
3397*/
3398case OP_MemLoad: {
3399 int tos = ++p->tos;
3400 int i = pOp->p1;
3401 VERIFY( if( NeedStack(p, tos) ) goto no_mem; )
3402 if( i<0 || i>=p->nMem ){
3403 aStack[tos].flags = STK_Null;
3404 zStack[tos] = 0;
3405 }else{
3406 aStack[tos] = p->aMem[i].s;
3407 if( aStack[tos].flags & STK_Str ){
3408 char *z = sqliteMalloc(aStack[tos].n);
3409 if( z==0 ) goto no_mem;
3410 memcpy(z, p->aMem[i].z, aStack[tos].n);
3411 zStack[tos] = z;
3412 aStack[tos].flags |= STK_Dyn;
3413 }
3414 }
3415 break;
3416}
3417
3418/* Opcode: AggReset * P2 *
3419**
3420** Reset the aggregator so that it no longer contains any data.
3421** Future aggregator elements will contain P2 values each.
3422*/
3423case OP_AggReset: {
3424 AggReset(&p->agg);
3425 p->agg.nMem = pOp->p2;
3426 break;
3427}
3428
3429/* Opcode: AggFocus * P2 *
3430**
3431** Pop the top of the stack and use that as an aggregator key. If
3432** an aggregator with that same key already exists, then make the
3433** aggregator the current aggregator and jump to P2. If no aggregator
3434** with the given key exists, create one and make it current but
3435** do not jump.
3436**
3437** The order of aggregator opcodes is important. The order is:
3438** AggReset AggFocus AggNext. In other words, you must execute
3439** AggReset first, then zero or more AggFocus operations, then
3440** zero or more AggNext operations. You must not execute an AggFocus
3441** in between an AggNext and an AggReset.
3442*/
3443case OP_AggFocus: {
3444 int tos = p->tos;
3445 AggElem *pElem;
3446 char *zKey;
3447 int nKey;
3448
3449 VERIFY( if( tos<0 ) goto not_enough_stack; )
3450 if( Stringify(p, tos) ) goto no_mem;
3451 zKey = zStack[tos];
3452 nKey = aStack[tos].n;
3453 if( p->agg.nHash<=0 ){
3454 pElem = 0;
3455 }else{
3456 int h = sqliteHashNoCase(zKey, nKey-1) % p->agg.nHash;
3457 for(pElem=p->agg.apHash[h]; pElem; pElem=pElem->pHash){
3458 if( strcmp(pElem->zKey, zKey)==0 ) break;
3459 }
3460 }
3461 if( pElem ){
3462 p->agg.pCurrent = pElem;
3463 pc = pOp->p2 - 1;
3464 }else{
3465 AggInsert(&p->agg, zKey);
3466 if( sqlite_malloc_failed ) goto no_mem;
3467 }
3468 POPSTACK;
3469 break;
3470}
3471
3472/* Opcode: AggIncr P1 P2 *
3473**
3474** Increase the integer value in the P2-th field of the aggregate
3475** element current in focus by an amount P1.
3476*/
3477case OP_AggIncr: {
3478 AggElem *pFocus = AggInFocus(p->agg);
3479 int i = pOp->p2;
3480 if( pFocus==0 ) goto no_mem;
3481 if( i>=0 && i<p->agg.nMem ){
3482 Mem *pMem = &pFocus->aMem[i];
3483 if( pMem->s.flags!=STK_Int ){
3484 if( pMem->s.flags & STK_Int ){
3485 /* Do nothing */
3486 }else if( pMem->s.flags & STK_Real ){
3487 pMem->s.i = pMem->s.r;
3488 }else if( pMem->s.flags & STK_Str ){
3489 pMem->s.i = atoi(pMem->z);
3490 }else{
3491 pMem->s.i = 0;
3492 }
3493 if( pMem->s.flags & STK_Dyn ) sqliteFree(pMem->z);
3494 pMem->z = 0;
3495 pMem->s.flags = STK_Int;
3496 }
3497 pMem->s.i += pOp->p1;
3498 }
3499 break;
3500}
3501
3502/* Opcode: AggSet * P2 *
3503**
3504** Move the top of the stack into the P2-th field of the current
3505** aggregate. String values are duplicated into new memory.
3506*/
3507case OP_AggSet: {
3508 AggElem *pFocus = AggInFocus(p->agg);
3509 int i = pOp->p2;
3510 int tos = p->tos;
3511 VERIFY( if( tos<0 ) goto not_enough_stack; )
3512 if( pFocus==0 ) goto no_mem;
3513 if( VERIFY( i>=0 && ) i<p->agg.nMem ){
3514 Mem *pMem = &pFocus->aMem[i];
3515 char *zOld;
3516 if( pMem->s.flags & STK_Dyn ){
3517 zOld = pMem->z;
3518 }else{
3519 zOld = 0;
3520 }
3521 pMem->s = aStack[tos];
3522 if( pMem->s.flags & STK_Str ){
3523 pMem->z = sqliteMalloc( aStack[tos].n );
3524 if( pMem->z==0 ) goto no_mem;
3525 memcpy(pMem->z, zStack[tos], pMem->s.n);
3526 pMem->s.flags |= STK_Str|STK_Dyn;
3527 }
3528 if( zOld ) sqliteFree(zOld);
3529 }
3530 POPSTACK;
3531 break;
3532}
3533
3534/* Opcode: AggGet * P2 *
3535**
3536** Push a new entry onto the stack which is a copy of the P2-th field
3537** of the current aggregate. Strings are not duplicated so
3538** string values will be ephemeral.
3539*/
3540case OP_AggGet: {
3541 AggElem *pFocus = AggInFocus(p->agg);
3542 int i = pOp->p2;
3543 int tos = ++p->tos;
3544 VERIFY( if( NeedStack(p, tos) ) goto no_mem; )
3545 if( pFocus==0 ) goto no_mem;
3546 if( VERIFY( i>=0 && ) i<p->agg.nMem ){
3547 Mem *pMem = &pFocus->aMem[i];
3548 aStack[tos] = pMem->s;
3549 zStack[tos] = pMem->z;
3550 aStack[tos].flags &= ~STK_Dyn;
3551 }
3552 break;
3553}
3554
3555/* Opcode: AggNext * P2 *
3556**
3557** Make the next aggregate value the current aggregate. The prior
3558** aggregate is deleted. If all aggregate values have been consumed,
3559** jump to P2.
3560**
3561** The order of aggregator opcodes is important. The order is:
3562** AggReset AggFocus AggNext. In other words, you must execute
3563** AggReset first, then zero or more AggFocus operations, then
3564** zero or more AggNext operations. You must not execute an AggFocus
3565** in between an AggNext and an AggReset.
3566*/
3567case OP_AggNext: {
3568 if( p->agg.nHash ){
3569 p->agg.nHash = 0;
3570 sqliteFree(p->agg.apHash);
3571 p->agg.apHash = 0;
3572 p->agg.pCurrent = p->agg.pFirst;
3573 }else if( p->agg.pCurrent==p->agg.pFirst && p->agg.pCurrent!=0 ){
3574 int i;
3575 AggElem *pElem = p->agg.pCurrent;
3576 for(i=0; i<p->agg.nMem; i++){
3577 if( pElem->aMem[i].s.flags & STK_Dyn ){
3578 sqliteFree(pElem->aMem[i].z);
3579 }
3580 }
3581 p->agg.pCurrent = p->agg.pFirst = pElem->pNext;
3582 sqliteFree(pElem);
3583 p->agg.nElem--;
3584 }
3585 if( p->agg.pCurrent==0 ){
3586 pc = pOp->p2-1;
3587 }
3588 break;
3589}
3590
3591/* Opcode: SetClear P1 * *
3592**
3593** Remove all elements from the P1-th Set.
3594*/
3595case OP_SetClear: {
3596 int i = pOp->p1;
3597 if( i>=0 && i<p->nSet ){
3598 SetClear(&p->aSet[i]);
3599 }
3600 break;
3601}
3602
3603/* Opcode: SetInsert P1 * P3
3604**
3605** If Set P1 does not exist then create it. Then insert value
3606** P3 into that set. If P3 is NULL, then insert the top of the
3607** stack into the set.
3608*/
3609case OP_SetInsert: {
3610 int i = pOp->p1;
3611 if( p->nSet<=i ){
3612 p->aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
3613 if( p->aSet==0 ) goto no_mem;
3614 memset(&p->aSet[p->nSet], 0, sizeof(p->aSet[0])*(i+1 - p->nSet));
3615 p->nSet = i+1;
3616 }
3617 if( pOp->p3 ){
3618 SetInsert(&p->aSet[i], pOp->p3);
3619 }else{
3620 int tos = p->tos;
3621 if( tos<0 ) goto not_enough_stack;
3622 if( Stringify(p, tos) ) goto no_mem;
3623 SetInsert(&p->aSet[i], zStack[tos]);
3624 POPSTACK;
3625 }
3626 if( sqlite_malloc_failed ) goto no_mem;
3627 break;
3628}
3629
3630/* Opcode: SetFound P1 P2 *
3631**
3632** Pop the stack once and compare the value popped off with the
3633** contents of set P1. If the element popped exists in set P1,
3634** then jump to P2. Otherwise fall through.
3635*/
3636case OP_SetFound: {
3637 int i = pOp->p1;
3638 int tos = p->tos;
3639 VERIFY( if( tos<0 ) goto not_enough_stack; )
3640 if( Stringify(p, tos) ) goto no_mem;
3641 if( VERIFY( i>=0 && i<p->nSet &&) SetTest(&p->aSet[i], zStack[tos])){
3642 pc = pOp->p2 - 1;
3643 }
3644 POPSTACK;
3645 break;
3646}
3647
3648/* Opcode: SetNotFound P1 P2 *
3649**
3650** Pop the stack once and compare the value popped off with the
3651** contents of set P1. If the element popped does not exists in
3652** set P1, then jump to P2. Otherwise fall through.
3653*/
3654case OP_SetNotFound: {
3655 int i = pOp->p1;
3656 int tos = p->tos;
3657 VERIFY( if( tos<0 ) goto not_enough_stack; )
3658 if( Stringify(p, tos) ) goto no_mem;
3659 if(VERIFY( i>=0 && i<p->nSet &&) !SetTest(&p->aSet[i], zStack[tos])){
3660 pc = pOp->p2 - 1;
3661 }
3662 POPSTACK;
3663 break;
3664}
3665
3666/* Opcode: Strlen * * *
3667**
3668** Interpret the top of the stack as a string. Replace the top of
3669** stack with an integer which is the length of the string.
3670*/
3671case OP_Strlen: {
3672 int tos = p->tos;
3673 int len;
3674 VERIFY( if( tos<0 ) goto not_enough_stack; )
3675 if( Stringify(p, tos) ) goto no_mem;
3676#ifdef SQLITE_UTF8
3677 {
3678 char *z = zStack[tos];
3679 for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
3680 }
3681#else
3682 len = aStack[tos].n-1;
3683#endif
3684 POPSTACK;
3685 p->tos++;
3686 aStack[tos].i = len;
3687 aStack[tos].flags = STK_Int;
3688 break;
3689}
3690
3691/* Opcode: Substr P1 P2 *
3692**
3693** This operation pops between 1 and 3 elements from the stack and
3694** pushes back a single element. The bottom-most element popped from
3695** the stack is a string and the element pushed back is also a string.
3696** The other two elements popped are integers. The integers are taken
3697** from the stack only if P1 and/or P2 are 0. When P1 or P2 are
3698** not zero, the value of the operand is used rather than the integer
3699** from the stack. In the sequel, we will use P1 and P2 to describe
3700** the two integers, even if those integers are really taken from the
3701** stack.
3702**
3703** The string pushed back onto the stack is a substring of the string
3704** that was popped. There are P2 characters in the substring. The
3705** first character of the substring is the P1-th character of the
3706** original string where the left-most character is 1 (not 0). If P1
3707** is negative, then counting begins at the right instead of at the
3708** left.
3709*/
3710case OP_Substr: {
3711 int cnt;
3712 int start;
3713 int n;
3714 char *z;
3715
3716 if( pOp->p2==0 ){
3717 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
3718 Integerify(p, p->tos);
3719 cnt = aStack[p->tos].i;
3720 POPSTACK;
3721 }else{
3722 cnt = pOp->p2;
3723 }
3724 if( pOp->p1==0 ){
3725 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
3726 Integerify(p, p->tos);
3727 start = aStack[p->tos].i - 1;
3728 POPSTACK;
3729 }else{
3730 start = pOp->p1 - 1;
3731 }
3732 VERIFY( if( p->tos<0 ) goto not_enough_stack; )
3733 if( Stringify(p, p->tos) ) goto no_mem;
3734
3735 /* "n" will be the number of characters in the input string.
3736 ** For iso8859, the number of characters is the number of bytes.
3737 ** Buf for UTF-8, some characters can use multiple bytes and the
3738 ** situation is more complex.
3739 */
3740#ifdef SQLITE_UTF8
3741 z = zStack[p->tos];
3742 for(n=0; *z; z++){ if( (0xc0&*z)!=0x80 ) n++; }
3743#else
3744 n = aStack[p->tos].n - 1;
3745#endif
3746 if( start<0 ){
3747 start += n + 1;
3748 if( start<0 ){
3749 cnt += start;
3750 start = 0;
3751 }
3752 }
3753 if( start>n ){
3754 start = n;
3755 }
3756 if( cnt<0 ) cnt = 0;
3757 if( cnt > n ){
3758 cnt = n;
3759 }
3760
3761 /* At this point, "start" is the index of the first character to
3762 ** extract and "cnt" is the number of characters to extract. We
3763 ** need to convert units on these variable from characters into
3764 ** bytes. For iso8859, the conversion is a no-op, but for UTF-8
3765 ** we have to do a little work.
3766 */
3767#ifdef SQLITE_UTF8
3768 {
3769 int c_start = start;
3770 int c_cnt = cnt;
3771 int i;
3772 z = zStack[p->tos];
3773 for(start=i=0; i<c_start; i++){
3774 while( (0xc0&z[++start])==0x80 ){}
3775 }
3776 for(cnt=i=0; i<c_cnt; i++){
3777 while( (0xc0&z[(++cnt)+start])==0x80 ){}
3778 }
3779 }
3780#endif
3781 z = sqliteMalloc( cnt+1 );
3782 if( z==0 ) goto no_mem;
3783 strncpy(z, &zStack[p->tos][start], cnt);
3784 z[cnt] = 0;
3785 POPSTACK;
3786 p->tos++;
3787 zStack[p->tos] = z;
3788 aStack[p->tos].n = cnt + 1;
3789 aStack[p->tos].flags = STK_Str|STK_Dyn;
3790 break;
3791}
3792
3793/* An other opcode is illegal...
3794*/
3795default: {
3796 sprintf(zBuf,"%d",pOp->opcode);
3797 sqliteSetString(pzErrMsg, "unknown opcode ", zBuf, 0);
3798 rc = SQLITE_INTERNAL;
3799 break;
3800}
3801
3802/*****************************************************************************
3803** The cases of the switch statement above this line should all be indented
3804** by 6 spaces. But the left-most 6 spaces have been removed to improve the
3805** readability. From this point on down, the normal indentation rules are
3806** restored.
3807*****************************************************************************/
3808 }
drh6e142f52000-06-08 13:36:40 +00003809
3810 /* The following code adds nothing to the actual functionality
3811 ** of the program. It is only here for testing and debugging.
3812 ** On the other hand, it does burn CPU cycles every time through
3813 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
3814 */
3815#ifndef NDEBUG
drh58b95762000-06-02 01:17:37 +00003816 if( pc<-1 || pc>=p->nOp ){
3817 sqliteSetString(pzErrMsg, "jump destination out of range", 0);
3818 rc = SQLITE_INTERNAL;
3819 }
drh75897232000-05-29 14:26:00 +00003820 if( p->trace && p->tos>=0 ){
3821 int i;
3822 fprintf(p->trace, "Stack:");
3823 for(i=p->tos; i>=0 && i>p->tos-5; i--){
drh8c3052c2000-10-23 13:16:31 +00003824 if( aStack[i].flags & STK_Null ){
drhc61053b2000-06-04 12:58:36 +00003825 fprintf(p->trace, " NULL");
drh8c3052c2000-10-23 13:16:31 +00003826 }else if( aStack[i].flags & STK_Int ){
3827 fprintf(p->trace, " i:%d", aStack[i].i);
3828 }else if( aStack[i].flags & STK_Real ){
3829 fprintf(p->trace, " r:%g", aStack[i].r);
3830 }else if( aStack[i].flags & STK_Str ){
drh092d0352001-09-15 13:15:12 +00003831 int j, k;
3832 char zBuf[100];
3833 zBuf[0] = ' ';
3834 zBuf[1] = (aStack[i].flags & STK_Dyn)!=0 ? 'z' : 's';
drh872ff862001-09-15 14:43:39 +00003835 zBuf[2] = '[';
drh092d0352001-09-15 13:15:12 +00003836 k = 3;
drh872ff862001-09-15 14:43:39 +00003837 for(j=0; j<20 && j<aStack[i].n; j++){
drh092d0352001-09-15 13:15:12 +00003838 int c = zStack[i][j];
3839 if( c==0 && j==aStack[i].n-1 ) break;
3840 if( isprint(c) && !isspace(c) ){
3841 zBuf[k++] = c;
3842 }else{
3843 zBuf[k++] = '.';
3844 }
drhc61053b2000-06-04 12:58:36 +00003845 }
drh872ff862001-09-15 14:43:39 +00003846 zBuf[k++] = ']';
drh092d0352001-09-15 13:15:12 +00003847 zBuf[k++] = 0;
3848 fprintf(p->trace, "%s", zBuf);
drh75897232000-05-29 14:26:00 +00003849 }else{
drhc61053b2000-06-04 12:58:36 +00003850 fprintf(p->trace, " ???");
drh75897232000-05-29 14:26:00 +00003851 }
3852 }
3853 fprintf(p->trace,"\n");
3854 }
drh6e142f52000-06-08 13:36:40 +00003855#endif
drh75897232000-05-29 14:26:00 +00003856 }
3857
3858cleanup:
3859 Cleanup(p);
drh5edc3122001-09-13 21:53:09 +00003860 if( (p->pTableRoot || p->pIndexRoot) && rc==SQLITE_OK ){
drh5b2fd562001-09-13 15:21:31 +00003861 rc = SQLITE_INTERNAL;
3862 sqliteSetString(pzErrMsg, "table or index root page not set", 0);
3863 }
drh5e00f6c2001-09-13 13:46:56 +00003864 if( rc!=SQLITE_OK && (db->flags & SQLITE_InTrans)!=0 ){
drhbe0072d2001-09-13 14:46:09 +00003865 sqliteBtreeRollback(pBt);
drh5e00f6c2001-09-13 13:46:56 +00003866 sqliteRollbackInternalChanges(db);
3867 db->flags &= ~SQLITE_InTrans;
3868 }
drh75897232000-05-29 14:26:00 +00003869 return rc;
3870
3871 /* Jump to here if a malloc() fails. It's hard to get a malloc()
3872 ** to fail on a modern VM computer, so this code is untested.
3873 */
3874no_mem:
drh75897232000-05-29 14:26:00 +00003875 sqliteSetString(pzErrMsg, "out or memory", 0);
drh5e00f6c2001-09-13 13:46:56 +00003876 rc = SQLITE_NOMEM;
3877 goto cleanup;
3878
3879 /* Jump to here for any other kind of fatal error. The "rc" variable
3880 ** should hold the error number.
3881 */
drhbe0072d2001-09-13 14:46:09 +00003882abort_due_to_error:
drh5e00f6c2001-09-13 13:46:56 +00003883 sqliteSetString(pzErrMsg, sqliteErrStr(rc), 0);
3884 goto cleanup;
drh75897232000-05-29 14:26:00 +00003885
3886 /* Jump to here if a operator is encountered that requires more stack
3887 ** operands than are currently available on the stack.
3888 */
3889not_enough_stack:
3890 sprintf(zBuf,"%d",pc);
3891 sqliteSetString(pzErrMsg, "too few operands on stack at ", zBuf, 0);
drh58b95762000-06-02 01:17:37 +00003892 rc = SQLITE_INTERNAL;
drh75897232000-05-29 14:26:00 +00003893 goto cleanup;
3894
3895 /* Jump here if an illegal or illformed instruction is executed.
3896 */
3897bad_instruction:
3898 sprintf(zBuf,"%d",pc);
3899 sqliteSetString(pzErrMsg, "illegal operation at ", zBuf, 0);
drh58b95762000-06-02 01:17:37 +00003900 rc = SQLITE_INTERNAL;
drh75897232000-05-29 14:26:00 +00003901 goto cleanup;
drh75897232000-05-29 14:26:00 +00003902}