xref: /titanic_50/usr/src/lib/libsqlite/src/vdbeInt.h (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2003 September 6
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** This is the header file for information that is private to the
16 ** VDBE.  This information used to all be at the top of the single
17 ** source code file "vdbe.c".  When that file became too big (over
18 ** 6000 lines long) it was split up into several smaller files and
19 ** this header information was factored out.
20 */
21 
22 /*
23 ** When converting from the native format to the key format and back
24 ** again, in addition to changing the byte order we invert the high-order
25 ** bit of the most significant byte.  This causes negative numbers to
26 ** sort before positive numbers in the memcmp() function.
27 */
28 #define keyToInt(X)   (sqliteVdbeByteSwap(X) ^ 0x80000000)
29 #define intToKey(X)   (sqliteVdbeByteSwap((X) ^ 0x80000000))
30 
31 /*
32 ** The makefile scans this source file and creates the following
33 ** array of string constants which are the names of all VDBE opcodes.
34 ** This array is defined in a separate source code file named opcode.c
35 ** which is automatically generated by the makefile.
36 */
37 extern char *sqliteOpcodeNames[];
38 
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 */
44 typedef struct VdbeOp Op;
45 
46 /*
47 ** Boolean values
48 */
49 typedef unsigned char Bool;
50 
51 /*
52 ** A cursor is a pointer into a single BTree within a database file.
53 ** The cursor can seek to a BTree entry with a particular key, or
54 ** loop over all entries of the Btree.  You can also insert new BTree
55 ** entries or retrieve the key or data from the entry that the cursor
56 ** is currently pointing to.
57 **
58 ** Every cursor that the virtual machine has open is represented by an
59 ** instance of the following structure.
60 **
61 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
62 ** really a single row that represents the NEW or OLD pseudo-table of
63 ** a row trigger.  The data for the row is stored in Cursor.pData and
64 ** the rowid is in Cursor.iKey.
65 */
66 struct Cursor {
67   BtCursor *pCursor;    /* The cursor structure of the backend */
68   int lastRecno;        /* Last recno from a Next or NextIdx operation */
69   int nextRowid;        /* Next rowid returned by OP_NewRowid */
70   Bool recnoIsValid;    /* True if lastRecno is valid */
71   Bool keyAsData;       /* The OP_Column command works on key instead of data */
72   Bool atFirst;         /* True if pointing to first entry */
73   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
74   Bool nullRow;         /* True if pointing to a row with no data */
75   Bool nextRowidValid;  /* True if the nextRowid field is valid */
76   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
77   Bool deferredMoveto;  /* A call to sqliteBtreeMoveto() is needed */
78   int movetoTarget;     /* Argument to the deferred sqliteBtreeMoveto() */
79   Btree *pBt;           /* Separate file holding temporary table */
80   int nData;            /* Number of bytes in pData */
81   char *pData;          /* Data for a NEW or OLD pseudo-table */
82   int iKey;             /* Key for the NEW or OLD pseudo-table row */
83 };
84 typedef struct Cursor Cursor;
85 
86 /*
87 ** A sorter builds a list of elements to be sorted.  Each element of
88 ** the list is an instance of the following structure.
89 */
90 typedef struct Sorter Sorter;
91 struct Sorter {
92   int nKey;           /* Number of bytes in the key */
93   char *zKey;         /* The key by which we will sort */
94   int nData;          /* Number of bytes in the data */
95   char *pData;        /* The data associated with this key */
96   Sorter *pNext;      /* Next in the list */
97 };
98 
99 /*
100 ** Number of buckets used for merge-sort.
101 */
102 #define NSORT 30
103 
104 /*
105 ** Number of bytes of string storage space available to each stack
106 ** layer without having to malloc.  NBFS is short for Number of Bytes
107 ** For Strings.
108 */
109 #define NBFS 32
110 
111 /*
112 ** A single level of the stack or a single memory cell
113 ** is an instance of the following structure.
114 */
115 struct Mem {
116   int i;              /* Integer value */
117   int n;              /* Number of characters in string value, including '\0' */
118   int flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
119   double r;           /* Real value */
120   char *z;            /* String value */
121   char zShort[NBFS];  /* Space for short strings */
122 };
123 typedef struct Mem Mem;
124 
125 /*
126 ** Allowed values for Mem.flags
127 */
128 #define MEM_Null      0x0001   /* Value is NULL */
129 #define MEM_Str       0x0002   /* Value is a string */
130 #define MEM_Int       0x0004   /* Value is an integer */
131 #define MEM_Real      0x0008   /* Value is a real number */
132 #define MEM_Dyn       0x0010   /* Need to call sqliteFree() on Mem.z */
133 #define MEM_Static    0x0020   /* Mem.z points to a static string */
134 #define MEM_Ephem     0x0040   /* Mem.z points to an ephemeral string */
135 #define MEM_Short     0x0080   /* Mem.z points to Mem.zShort */
136 
137 /* The following MEM_ value appears only in AggElem.aMem.s.flag fields.
138 ** It indicates that the corresponding AggElem.aMem.z points to a
139 ** aggregate function context that needs to be finalized.
140 */
141 #define MEM_AggCtx    0x0100   /* Mem.z points to an agg function context */
142 
143 /*
144 ** The "context" argument for a installable function.  A pointer to an
145 ** instance of this structure is the first argument to the routines used
146 ** implement the SQL functions.
147 **
148 ** There is a typedef for this structure in sqlite.h.  So all routines,
149 ** even the public interface to SQLite, can use a pointer to this structure.
150 ** But this file is the only place where the internal details of this
151 ** structure are known.
152 **
153 ** This structure is defined inside of vdbe.c because it uses substructures
154 ** (Mem) which are only defined there.
155 */
156 struct sqlite_func {
157   FuncDef *pFunc;   /* Pointer to function information.  MUST BE FIRST */
158   Mem s;            /* The return value is stored here */
159   void *pAgg;       /* Aggregate context */
160   u8 isError;       /* Set to true for an error */
161   u8 isStep;        /* Current in the step function */
162   int cnt;          /* Number of times that the step function has been called */
163 };
164 
165 /*
166 ** An Agg structure describes an Aggregator.  Each Agg consists of
167 ** zero or more Aggregator elements (AggElem).  Each AggElem contains
168 ** a key and one or more values.  The values are used in processing
169 ** aggregate functions in a SELECT.  The key is used to implement
170 ** the GROUP BY clause of a select.
171 */
172 typedef struct Agg Agg;
173 typedef struct AggElem AggElem;
174 struct Agg {
175   int nMem;            /* Number of values stored in each AggElem */
176   AggElem *pCurrent;   /* The AggElem currently in focus */
177   HashElem *pSearch;   /* The hash element for pCurrent */
178   Hash hash;           /* Hash table of all aggregate elements */
179   FuncDef **apFunc;    /* Information about aggregate functions */
180 };
181 struct AggElem {
182   char *zKey;          /* The key to this AggElem */
183   int nKey;            /* Number of bytes in the key, including '\0' at end */
184   Mem aMem[1];         /* The values for this AggElem */
185 };
186 
187 /*
188 ** A Set structure is used for quick testing to see if a value
189 ** is part of a small set.  Sets are used to implement code like
190 ** this:
191 **            x.y IN ('hi','hoo','hum')
192 */
193 typedef struct Set Set;
194 struct Set {
195   Hash hash;             /* A set is just a hash table */
196   HashElem *prev;        /* Previously accessed hash elemen */
197 };
198 
199 /*
200 ** A Keylist is a bunch of keys into a table.  The keylist can
201 ** grow without bound.  The keylist stores the ROWIDs of database
202 ** records that need to be deleted or updated.
203 */
204 typedef struct Keylist Keylist;
205 struct Keylist {
206   int nKey;         /* Number of slots in aKey[] */
207   int nUsed;        /* Next unwritten slot in aKey[] */
208   int nRead;        /* Next unread slot in aKey[] */
209   Keylist *pNext;   /* Next block of keys */
210   int aKey[1];      /* One or more keys.  Extra space allocated as needed */
211 };
212 
213 /*
214 ** A Context stores the last insert rowid, the last statement change count,
215 ** and the current statement change count (i.e. changes since last statement).
216 ** Elements of Context structure type make up the ContextStack, which is
217 ** updated by the ContextPush and ContextPop opcodes (used by triggers)
218 */
219 typedef struct Context Context;
220 struct Context {
221   int lastRowid;    /* Last insert rowid (from db->lastRowid) */
222   int lsChange;     /* Last statement change count (from db->lsChange) */
223   int csChange;     /* Current statement change count (from db->csChange) */
224 };
225 
226 /*
227 ** An instance of the virtual machine.  This structure contains the complete
228 ** state of the virtual machine.
229 **
230 ** The "sqlite_vm" structure pointer that is returned by sqlite_compile()
231 ** is really a pointer to an instance of this structure.
232 */
233 struct Vdbe {
234   sqlite *db;         /* The whole database */
235   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
236   FILE *trace;        /* Write an execution trace here, if not NULL */
237   int nOp;            /* Number of instructions in the program */
238   int nOpAlloc;       /* Number of slots allocated for aOp[] */
239   Op *aOp;            /* Space to hold the virtual machine's program */
240   int nLabel;         /* Number of labels used */
241   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
242   int *aLabel;        /* Space to hold the labels */
243   Mem *aStack;        /* The operand stack, except string values */
244   Mem *pTos;          /* Top entry in the operand stack */
245   char **zArgv;       /* Text values used by the callback */
246   char **azColName;   /* Becomes the 4th parameter to callbacks */
247   int nCursor;        /* Number of slots in aCsr[] */
248   Cursor *aCsr;       /* One element of this array for each open cursor */
249   Sorter *pSort;      /* A linked list of objects to be sorted */
250   FILE *pFile;        /* At most one open file handler */
251   int nField;         /* Number of file fields */
252   char **azField;     /* Data for each file field */
253   int nVar;           /* Number of entries in azVariable[] */
254   char **azVar;       /* Values for the OP_Variable opcode */
255   int *anVar;         /* Length of each value in azVariable[] */
256   u8 *abVar;          /* TRUE if azVariable[i] needs to be sqliteFree()ed */
257   char *zLine;            /* A single line from the input file */
258   int nLineAlloc;         /* Number of spaces allocated for zLine */
259   int magic;              /* Magic number for sanity checking */
260   int nMem;               /* Number of memory locations currently allocated */
261   Mem *aMem;              /* The memory locations */
262   Agg agg;                /* Aggregate information */
263   int nSet;               /* Number of sets allocated */
264   Set *aSet;              /* An array of sets */
265   int nCallback;          /* Number of callbacks invoked so far */
266   Keylist *pList;         /* A list of ROWIDs */
267   int keylistStackDepth;  /* The size of the "keylist" stack */
268   Keylist **keylistStack; /* The stack used by opcodes ListPush & ListPop */
269   int contextStackDepth;  /* The size of the "context" stack */
270   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
271   int pc;                 /* The program counter */
272   int rc;                 /* Value to return */
273   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
274   int errorAction;        /* Recovery action to do in case of an error */
275   int undoTransOnError;   /* If error, either ROLLBACK or COMMIT */
276   int inTempTrans;        /* True if temp database is transactioned */
277   int returnStack[100];   /* Return address stack for OP_Gosub & OP_Return */
278   int returnDepth;        /* Next unused element in returnStack[] */
279   int nResColumn;         /* Number of columns in one row of the result set */
280   char **azResColumn;     /* Values for one row of result */
281   int popStack;           /* Pop the stack this much on entry to VdbeExec() */
282   char *zErrMsg;          /* Error message written here */
283   u8 explain;             /* True if EXPLAIN present on SQL command */
284 };
285 
286 /*
287 ** The following are allowed values for Vdbe.magic
288 */
289 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
290 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
291 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
292 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
293 
294 /*
295 ** Function prototypes
296 */
297 void sqliteVdbeCleanupCursor(Cursor*);
298 void sqliteVdbeSorterReset(Vdbe*);
299 void sqliteVdbeAggReset(Agg*);
300 void sqliteVdbeKeylistFree(Keylist*);
301 void sqliteVdbePopStack(Vdbe*,int);
302 int sqliteVdbeCursorMoveto(Cursor*);
303 int sqliteVdbeByteSwap(int);
304 #if !defined(NDEBUG) || defined(VDBE_PROFILE)
305 void sqliteVdbePrintOp(FILE*, int, Op*);
306 #endif
307