xref: /sqlite-3.40.0/src/vdbeapi.c (revision 99a21828)
1 /*
2 ** 2004 May 26
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 **
13 ** This file contains code use to implement APIs that are part of the
14 ** VDBE.
15 */
16 #include "sqliteInt.h"
17 #include "vdbeInt.h"
18 
19 #ifndef SQLITE_OMIT_DEPRECATED
20 /*
21 ** Return TRUE (non-zero) of the statement supplied as an argument needs
22 ** to be recompiled.  A statement needs to be recompiled whenever the
23 ** execution environment changes in a way that would alter the program
24 ** that sqlite3_prepare() generates.  For example, if new functions or
25 ** collating sequences are registered or if an authorizer function is
26 ** added or changed.
27 */
28 int sqlite3_expired(sqlite3_stmt *pStmt){
29   Vdbe *p = (Vdbe*)pStmt;
30   return p==0 || p->expired;
31 }
32 #endif
33 
34 /*
35 ** Check on a Vdbe to make sure it has not been finalized.  Log
36 ** an error and return true if it has been finalized (or is otherwise
37 ** invalid).  Return false if it is ok.
38 */
39 static int vdbeSafety(Vdbe *p){
40   if( p->db==0 ){
41     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
42     return 1;
43   }else{
44     return 0;
45   }
46 }
47 static int vdbeSafetyNotNull(Vdbe *p){
48   if( p==0 ){
49     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
50     return 1;
51   }else{
52     return vdbeSafety(p);
53   }
54 }
55 
56 #ifndef SQLITE_OMIT_TRACE
57 /*
58 ** Invoke the profile callback.  This routine is only called if we already
59 ** know that the profile callback is defined and needs to be invoked.
60 */
61 static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
62   sqlite3_int64 iNow;
63   sqlite3_int64 iElapse;
64   assert( p->startTime>0 );
65   assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
66   assert( db->init.busy==0 );
67   assert( p->zSql!=0 );
68   sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
69   iElapse = (iNow - p->startTime)*1000000;
70 #ifndef SQLITE_OMIT_DEPRECATED
71   if( db->xProfile ){
72     db->xProfile(db->pProfileArg, p->zSql, iElapse);
73   }
74 #endif
75   if( db->mTrace & SQLITE_TRACE_PROFILE ){
76     db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
77   }
78   p->startTime = 0;
79 }
80 /*
81 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
82 ** is needed, and it invokes the callback if it is needed.
83 */
84 # define checkProfileCallback(DB,P) \
85    if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
86 #else
87 # define checkProfileCallback(DB,P)  /*no-op*/
88 #endif
89 
90 /*
91 ** The following routine destroys a virtual machine that is created by
92 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
93 ** success/failure code that describes the result of executing the virtual
94 ** machine.
95 **
96 ** This routine sets the error code and string returned by
97 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
98 */
99 int sqlite3_finalize(sqlite3_stmt *pStmt){
100   int rc;
101   if( pStmt==0 ){
102     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
103     ** pointer is a harmless no-op. */
104     rc = SQLITE_OK;
105   }else{
106     Vdbe *v = (Vdbe*)pStmt;
107     sqlite3 *db = v->db;
108     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
109     sqlite3_mutex_enter(db->mutex);
110     checkProfileCallback(db, v);
111     rc = sqlite3VdbeFinalize(v);
112     rc = sqlite3ApiExit(db, rc);
113     sqlite3LeaveMutexAndCloseZombie(db);
114   }
115   return rc;
116 }
117 
118 /*
119 ** Terminate the current execution of an SQL statement and reset it
120 ** back to its starting state so that it can be reused. A success code from
121 ** the prior execution is returned.
122 **
123 ** This routine sets the error code and string returned by
124 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
125 */
126 int sqlite3_reset(sqlite3_stmt *pStmt){
127   int rc;
128   if( pStmt==0 ){
129     rc = SQLITE_OK;
130   }else{
131     Vdbe *v = (Vdbe*)pStmt;
132     sqlite3 *db = v->db;
133     sqlite3_mutex_enter(db->mutex);
134     checkProfileCallback(db, v);
135     rc = sqlite3VdbeReset(v);
136     sqlite3VdbeRewind(v);
137     assert( (rc & (db->errMask))==rc );
138     rc = sqlite3ApiExit(db, rc);
139     sqlite3_mutex_leave(db->mutex);
140   }
141   return rc;
142 }
143 
144 /*
145 ** Set all the parameters in the compiled SQL statement to NULL.
146 */
147 int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
148   int i;
149   int rc = SQLITE_OK;
150   Vdbe *p = (Vdbe*)pStmt;
151 #if SQLITE_THREADSAFE
152   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
153 #endif
154   sqlite3_mutex_enter(mutex);
155   for(i=0; i<p->nVar; i++){
156     sqlite3VdbeMemRelease(&p->aVar[i]);
157     p->aVar[i].flags = MEM_Null;
158   }
159   assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
160   if( p->expmask ){
161     p->expired = 1;
162   }
163   sqlite3_mutex_leave(mutex);
164   return rc;
165 }
166 
167 
168 /**************************** sqlite3_value_  *******************************
169 ** The following routines extract information from a Mem or sqlite3_value
170 ** structure.
171 */
172 const void *sqlite3_value_blob(sqlite3_value *pVal){
173   Mem *p = (Mem*)pVal;
174   if( p->flags & (MEM_Blob|MEM_Str) ){
175     if( ExpandBlob(p)!=SQLITE_OK ){
176       assert( p->flags==MEM_Null && p->z==0 );
177       return 0;
178     }
179     p->flags |= MEM_Blob;
180     return p->n ? p->z : 0;
181   }else{
182     return sqlite3_value_text(pVal);
183   }
184 }
185 int sqlite3_value_bytes(sqlite3_value *pVal){
186   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
187 }
188 int sqlite3_value_bytes16(sqlite3_value *pVal){
189   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
190 }
191 double sqlite3_value_double(sqlite3_value *pVal){
192   return sqlite3VdbeRealValue((Mem*)pVal);
193 }
194 int sqlite3_value_int(sqlite3_value *pVal){
195   return (int)sqlite3VdbeIntValue((Mem*)pVal);
196 }
197 sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
198   return sqlite3VdbeIntValue((Mem*)pVal);
199 }
200 unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
201   Mem *pMem = (Mem*)pVal;
202   return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
203 }
204 void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
205   Mem *p = (Mem*)pVal;
206   if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
207                  (MEM_Null|MEM_Term|MEM_Subtype)
208    && zPType!=0
209    && p->eSubtype=='p'
210    && strcmp(p->u.zPType, zPType)==0
211   ){
212     return (void*)p->z;
213   }else{
214     return 0;
215   }
216 }
217 const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
218   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
219 }
220 #ifndef SQLITE_OMIT_UTF16
221 const void *sqlite3_value_text16(sqlite3_value* pVal){
222   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
223 }
224 const void *sqlite3_value_text16be(sqlite3_value *pVal){
225   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
226 }
227 const void *sqlite3_value_text16le(sqlite3_value *pVal){
228   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
229 }
230 #endif /* SQLITE_OMIT_UTF16 */
231 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
232 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
233 ** point number string BLOB NULL
234 */
235 int sqlite3_value_type(sqlite3_value* pVal){
236   static const u8 aType[] = {
237      SQLITE_BLOB,     /* 0x00 (not possible) */
238      SQLITE_NULL,     /* 0x01 NULL */
239      SQLITE_TEXT,     /* 0x02 TEXT */
240      SQLITE_NULL,     /* 0x03 (not possible) */
241      SQLITE_INTEGER,  /* 0x04 INTEGER */
242      SQLITE_NULL,     /* 0x05 (not possible) */
243      SQLITE_INTEGER,  /* 0x06 INTEGER + TEXT */
244      SQLITE_NULL,     /* 0x07 (not possible) */
245      SQLITE_FLOAT,    /* 0x08 FLOAT */
246      SQLITE_NULL,     /* 0x09 (not possible) */
247      SQLITE_FLOAT,    /* 0x0a FLOAT + TEXT */
248      SQLITE_NULL,     /* 0x0b (not possible) */
249      SQLITE_INTEGER,  /* 0x0c (not possible) */
250      SQLITE_NULL,     /* 0x0d (not possible) */
251      SQLITE_INTEGER,  /* 0x0e (not possible) */
252      SQLITE_NULL,     /* 0x0f (not possible) */
253      SQLITE_BLOB,     /* 0x10 BLOB */
254      SQLITE_NULL,     /* 0x11 (not possible) */
255      SQLITE_TEXT,     /* 0x12 (not possible) */
256      SQLITE_NULL,     /* 0x13 (not possible) */
257      SQLITE_INTEGER,  /* 0x14 INTEGER + BLOB */
258      SQLITE_NULL,     /* 0x15 (not possible) */
259      SQLITE_INTEGER,  /* 0x16 (not possible) */
260      SQLITE_NULL,     /* 0x17 (not possible) */
261      SQLITE_FLOAT,    /* 0x18 FLOAT + BLOB */
262      SQLITE_NULL,     /* 0x19 (not possible) */
263      SQLITE_FLOAT,    /* 0x1a (not possible) */
264      SQLITE_NULL,     /* 0x1b (not possible) */
265      SQLITE_INTEGER,  /* 0x1c (not possible) */
266      SQLITE_NULL,     /* 0x1d (not possible) */
267      SQLITE_INTEGER,  /* 0x1e (not possible) */
268      SQLITE_NULL,     /* 0x1f (not possible) */
269      SQLITE_FLOAT,    /* 0x20 INTREAL */
270      SQLITE_NULL,     /* 0x21 (not possible) */
271      SQLITE_TEXT,     /* 0x22 INTREAL + TEXT */
272      SQLITE_NULL,     /* 0x23 (not possible) */
273      SQLITE_FLOAT,    /* 0x24 (not possible) */
274      SQLITE_NULL,     /* 0x25 (not possible) */
275      SQLITE_FLOAT,    /* 0x26 (not possible) */
276      SQLITE_NULL,     /* 0x27 (not possible) */
277      SQLITE_FLOAT,    /* 0x28 (not possible) */
278      SQLITE_NULL,     /* 0x29 (not possible) */
279      SQLITE_FLOAT,    /* 0x2a (not possible) */
280      SQLITE_NULL,     /* 0x2b (not possible) */
281      SQLITE_FLOAT,    /* 0x2c (not possible) */
282      SQLITE_NULL,     /* 0x2d (not possible) */
283      SQLITE_FLOAT,    /* 0x2e (not possible) */
284      SQLITE_NULL,     /* 0x2f (not possible) */
285      SQLITE_BLOB,     /* 0x30 (not possible) */
286      SQLITE_NULL,     /* 0x31 (not possible) */
287      SQLITE_TEXT,     /* 0x32 (not possible) */
288      SQLITE_NULL,     /* 0x33 (not possible) */
289      SQLITE_FLOAT,    /* 0x34 (not possible) */
290      SQLITE_NULL,     /* 0x35 (not possible) */
291      SQLITE_FLOAT,    /* 0x36 (not possible) */
292      SQLITE_NULL,     /* 0x37 (not possible) */
293      SQLITE_FLOAT,    /* 0x38 (not possible) */
294      SQLITE_NULL,     /* 0x39 (not possible) */
295      SQLITE_FLOAT,    /* 0x3a (not possible) */
296      SQLITE_NULL,     /* 0x3b (not possible) */
297      SQLITE_FLOAT,    /* 0x3c (not possible) */
298      SQLITE_NULL,     /* 0x3d (not possible) */
299      SQLITE_FLOAT,    /* 0x3e (not possible) */
300      SQLITE_NULL,     /* 0x3f (not possible) */
301   };
302 #ifdef SQLITE_DEBUG
303   {
304     int eType = SQLITE_BLOB;
305     if( pVal->flags & MEM_Null ){
306       eType = SQLITE_NULL;
307     }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
308       eType = SQLITE_FLOAT;
309     }else if( pVal->flags & MEM_Int ){
310       eType = SQLITE_INTEGER;
311     }else if( pVal->flags & MEM_Str ){
312       eType = SQLITE_TEXT;
313     }
314     assert( eType == aType[pVal->flags&MEM_AffMask] );
315   }
316 #endif
317   return aType[pVal->flags&MEM_AffMask];
318 }
319 
320 /* Return true if a parameter to xUpdate represents an unchanged column */
321 int sqlite3_value_nochange(sqlite3_value *pVal){
322   return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
323 }
324 
325 /* Return true if a parameter value originated from an sqlite3_bind() */
326 int sqlite3_value_frombind(sqlite3_value *pVal){
327   return (pVal->flags&MEM_FromBind)!=0;
328 }
329 
330 /* Make a copy of an sqlite3_value object
331 */
332 sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
333   sqlite3_value *pNew;
334   if( pOrig==0 ) return 0;
335   pNew = sqlite3_malloc( sizeof(*pNew) );
336   if( pNew==0 ) return 0;
337   memset(pNew, 0, sizeof(*pNew));
338   memcpy(pNew, pOrig, MEMCELLSIZE);
339   pNew->flags &= ~MEM_Dyn;
340   pNew->db = 0;
341   if( pNew->flags&(MEM_Str|MEM_Blob) ){
342     pNew->flags &= ~(MEM_Static|MEM_Dyn);
343     pNew->flags |= MEM_Ephem;
344     if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
345       sqlite3ValueFree(pNew);
346       pNew = 0;
347     }
348   }else if( pNew->flags & MEM_Null ){
349     /* Do not duplicate pointer values */
350     pNew->flags &= ~(MEM_Term|MEM_Subtype);
351   }
352   return pNew;
353 }
354 
355 /* Destroy an sqlite3_value object previously obtained from
356 ** sqlite3_value_dup().
357 */
358 void sqlite3_value_free(sqlite3_value *pOld){
359   sqlite3ValueFree(pOld);
360 }
361 
362 
363 /**************************** sqlite3_result_  *******************************
364 ** The following routines are used by user-defined functions to specify
365 ** the function result.
366 **
367 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
368 ** result as a string or blob.  Appropriate errors are set if the string/blob
369 ** is too big or if an OOM occurs.
370 **
371 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
372 ** on value P is not going to be used and need to be destroyed.
373 */
374 static void setResultStrOrError(
375   sqlite3_context *pCtx,  /* Function context */
376   const char *z,          /* String pointer */
377   int n,                  /* Bytes in string, or negative */
378   u8 enc,                 /* Encoding of z.  0 for BLOBs */
379   void (*xDel)(void*)     /* Destructor function */
380 ){
381   Mem *pOut = pCtx->pOut;
382   int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
383   if( rc ){
384     if( rc==SQLITE_TOOBIG ){
385       sqlite3_result_error_toobig(pCtx);
386     }else{
387       /* The only errors possible from sqlite3VdbeMemSetStr are
388       ** SQLITE_TOOBIG and SQLITE_NOMEM */
389       assert( rc==SQLITE_NOMEM );
390       sqlite3_result_error_nomem(pCtx);
391     }
392     return;
393   }
394   sqlite3VdbeChangeEncoding(pOut, ENC(pOut->db));
395   if( sqlite3VdbeMemTooBig(pOut) ){
396     sqlite3_result_error_toobig(pCtx);
397   }
398 }
399 static int invokeValueDestructor(
400   const void *p,             /* Value to destroy */
401   void (*xDel)(void*),       /* The destructor */
402   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
403 ){
404   assert( xDel!=SQLITE_DYNAMIC );
405   if( xDel==0 ){
406     /* noop */
407   }else if( xDel==SQLITE_TRANSIENT ){
408     /* noop */
409   }else{
410     xDel((void*)p);
411   }
412   sqlite3_result_error_toobig(pCtx);
413   return SQLITE_TOOBIG;
414 }
415 void sqlite3_result_blob(
416   sqlite3_context *pCtx,
417   const void *z,
418   int n,
419   void (*xDel)(void *)
420 ){
421   assert( n>=0 );
422   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
423   setResultStrOrError(pCtx, z, n, 0, xDel);
424 }
425 void sqlite3_result_blob64(
426   sqlite3_context *pCtx,
427   const void *z,
428   sqlite3_uint64 n,
429   void (*xDel)(void *)
430 ){
431   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
432   assert( xDel!=SQLITE_DYNAMIC );
433   if( n>0x7fffffff ){
434     (void)invokeValueDestructor(z, xDel, pCtx);
435   }else{
436     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
437   }
438 }
439 void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
440   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
441   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
442 }
443 void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
444   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
445   pCtx->isError = SQLITE_ERROR;
446   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
447 }
448 #ifndef SQLITE_OMIT_UTF16
449 void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
450   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
451   pCtx->isError = SQLITE_ERROR;
452   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
453 }
454 #endif
455 void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
456   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
457   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
458 }
459 void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
460   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
461   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
462 }
463 void sqlite3_result_null(sqlite3_context *pCtx){
464   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
465   sqlite3VdbeMemSetNull(pCtx->pOut);
466 }
467 void sqlite3_result_pointer(
468   sqlite3_context *pCtx,
469   void *pPtr,
470   const char *zPType,
471   void (*xDestructor)(void*)
472 ){
473   Mem *pOut = pCtx->pOut;
474   assert( sqlite3_mutex_held(pOut->db->mutex) );
475   sqlite3VdbeMemRelease(pOut);
476   pOut->flags = MEM_Null;
477   sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
478 }
479 void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
480   Mem *pOut = pCtx->pOut;
481   assert( sqlite3_mutex_held(pOut->db->mutex) );
482   pOut->eSubtype = eSubtype & 0xff;
483   pOut->flags |= MEM_Subtype;
484 }
485 void sqlite3_result_text(
486   sqlite3_context *pCtx,
487   const char *z,
488   int n,
489   void (*xDel)(void *)
490 ){
491   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
492   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
493 }
494 void sqlite3_result_text64(
495   sqlite3_context *pCtx,
496   const char *z,
497   sqlite3_uint64 n,
498   void (*xDel)(void *),
499   unsigned char enc
500 ){
501   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
502   assert( xDel!=SQLITE_DYNAMIC );
503   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
504   if( n>0x7fffffff ){
505     (void)invokeValueDestructor(z, xDel, pCtx);
506   }else{
507     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
508   }
509 }
510 #ifndef SQLITE_OMIT_UTF16
511 void sqlite3_result_text16(
512   sqlite3_context *pCtx,
513   const void *z,
514   int n,
515   void (*xDel)(void *)
516 ){
517   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
518   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
519 }
520 void sqlite3_result_text16be(
521   sqlite3_context *pCtx,
522   const void *z,
523   int n,
524   void (*xDel)(void *)
525 ){
526   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
527   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
528 }
529 void sqlite3_result_text16le(
530   sqlite3_context *pCtx,
531   const void *z,
532   int n,
533   void (*xDel)(void *)
534 ){
535   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
536   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
537 }
538 #endif /* SQLITE_OMIT_UTF16 */
539 void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
540   Mem *pOut = pCtx->pOut;
541   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
542   sqlite3VdbeMemCopy(pOut, pValue);
543   sqlite3VdbeChangeEncoding(pOut, ENC(pOut->db));
544   if( sqlite3VdbeMemTooBig(pOut) ){
545     sqlite3_result_error_toobig(pCtx);
546   }
547 }
548 void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
549   sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
550 }
551 int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
552   Mem *pOut = pCtx->pOut;
553   assert( sqlite3_mutex_held(pOut->db->mutex) );
554   if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
555     sqlite3_result_error_toobig(pCtx);
556     return SQLITE_TOOBIG;
557   }
558 #ifndef SQLITE_OMIT_INCRBLOB
559   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
560   return SQLITE_OK;
561 #else
562   return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
563 #endif
564 }
565 void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
566   pCtx->isError = errCode ? errCode : -1;
567 #ifdef SQLITE_DEBUG
568   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
569 #endif
570   if( pCtx->pOut->flags & MEM_Null ){
571     setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
572                         SQLITE_STATIC);
573   }
574 }
575 
576 /* Force an SQLITE_TOOBIG error. */
577 void sqlite3_result_error_toobig(sqlite3_context *pCtx){
578   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
579   pCtx->isError = SQLITE_TOOBIG;
580   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
581                        SQLITE_UTF8, SQLITE_STATIC);
582 }
583 
584 /* An SQLITE_NOMEM error. */
585 void sqlite3_result_error_nomem(sqlite3_context *pCtx){
586   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
587   sqlite3VdbeMemSetNull(pCtx->pOut);
588   pCtx->isError = SQLITE_NOMEM_BKPT;
589   sqlite3OomFault(pCtx->pOut->db);
590 }
591 
592 #ifndef SQLITE_UNTESTABLE
593 /* Force the INT64 value currently stored as the result to be
594 ** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL
595 ** test-control.
596 */
597 void sqlite3ResultIntReal(sqlite3_context *pCtx){
598   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
599   if( pCtx->pOut->flags & MEM_Int ){
600     pCtx->pOut->flags &= ~MEM_Int;
601     pCtx->pOut->flags |= MEM_IntReal;
602   }
603 }
604 #endif
605 
606 
607 /*
608 ** This function is called after a transaction has been committed. It
609 ** invokes callbacks registered with sqlite3_wal_hook() as required.
610 */
611 static int doWalCallbacks(sqlite3 *db){
612   int rc = SQLITE_OK;
613 #ifndef SQLITE_OMIT_WAL
614   int i;
615   for(i=0; i<db->nDb; i++){
616     Btree *pBt = db->aDb[i].pBt;
617     if( pBt ){
618       int nEntry;
619       sqlite3BtreeEnter(pBt);
620       nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
621       sqlite3BtreeLeave(pBt);
622       if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
623         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
624       }
625     }
626   }
627 #endif
628   return rc;
629 }
630 
631 
632 /*
633 ** Execute the statement pStmt, either until a row of data is ready, the
634 ** statement is completely executed or an error occurs.
635 **
636 ** This routine implements the bulk of the logic behind the sqlite_step()
637 ** API.  The only thing omitted is the automatic recompile if a
638 ** schema change has occurred.  That detail is handled by the
639 ** outer sqlite3_step() wrapper procedure.
640 */
641 static int sqlite3Step(Vdbe *p){
642   sqlite3 *db;
643   int rc;
644 
645   /* Check that malloc() has not failed. If it has, return early. */
646   db = p->db;
647   if( db->mallocFailed ){
648     p->rc = SQLITE_NOMEM;
649     return SQLITE_NOMEM_BKPT;
650   }
651 
652   assert(p);
653   if( p->eVdbeState!=VDBE_RUN_STATE ){
654     restart_step:
655     if( p->eVdbeState==VDBE_READY_STATE ){
656       if( p->expired ){
657         p->rc = SQLITE_SCHEMA;
658         rc = SQLITE_ERROR;
659         if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
660           /* If this statement was prepared using saved SQL and an
661           ** error has occurred, then return the error code in p->rc to the
662           ** caller. Set the error code in the database handle to the same
663           ** value.
664           */
665           rc = sqlite3VdbeTransferError(p);
666         }
667         goto end_of_step;
668       }
669 
670       /* If there are no other statements currently running, then
671       ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
672       ** from interrupting a statement that has not yet started.
673       */
674       if( db->nVdbeActive==0 ){
675         AtomicStore(&db->u1.isInterrupted, 0);
676       }
677 
678       assert( db->nVdbeWrite>0 || db->autoCommit==0
679           || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
680       );
681 
682 #ifndef SQLITE_OMIT_TRACE
683       if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
684           && !db->init.busy && p->zSql ){
685         sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
686       }else{
687         assert( p->startTime==0 );
688       }
689 #endif
690 
691       db->nVdbeActive++;
692       if( p->readOnly==0 ) db->nVdbeWrite++;
693       if( p->bIsReader ) db->nVdbeRead++;
694       p->pc = 0;
695       p->eVdbeState = VDBE_RUN_STATE;
696     }else
697 
698     if( p->eVdbeState==VDBE_HALT_STATE ){
699       /* We used to require that sqlite3_reset() be called before retrying
700       ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
701       ** with version 3.7.0, we changed this so that sqlite3_reset() would
702       ** be called automatically instead of throwing the SQLITE_MISUSE error.
703       ** This "automatic-reset" change is not technically an incompatibility,
704       ** since any application that receives an SQLITE_MISUSE is broken by
705       ** definition.
706       **
707       ** Nevertheless, some published applications that were originally written
708       ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
709       ** returns, and those were broken by the automatic-reset change.  As a
710       ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
711       ** legacy behavior of returning SQLITE_MISUSE for cases where the
712       ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
713       ** or SQLITE_BUSY error.
714       */
715 #ifdef SQLITE_OMIT_AUTORESET
716       if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
717         sqlite3_reset((sqlite3_stmt*)p);
718       }else{
719         return SQLITE_MISUSE_BKPT;
720       }
721 #else
722       sqlite3_reset((sqlite3_stmt*)p);
723 #endif
724       assert( p->eVdbeState==VDBE_READY_STATE );
725       goto restart_step;
726     }
727   }
728 
729 #ifdef SQLITE_DEBUG
730   p->rcApp = SQLITE_OK;
731 #endif
732 #ifndef SQLITE_OMIT_EXPLAIN
733   if( p->explain ){
734     rc = sqlite3VdbeList(p);
735   }else
736 #endif /* SQLITE_OMIT_EXPLAIN */
737   {
738     db->nVdbeExec++;
739     rc = sqlite3VdbeExec(p);
740     db->nVdbeExec--;
741   }
742 
743   if( rc==SQLITE_ROW ){
744     assert( p->rc==SQLITE_OK );
745     assert( db->mallocFailed==0 );
746     db->errCode = SQLITE_ROW;
747     return SQLITE_ROW;
748   }else{
749 #ifndef SQLITE_OMIT_TRACE
750     /* If the statement completed successfully, invoke the profile callback */
751     checkProfileCallback(db, p);
752 #endif
753 
754     if( rc==SQLITE_DONE && db->autoCommit ){
755       assert( p->rc==SQLITE_OK );
756       p->rc = doWalCallbacks(db);
757       if( p->rc!=SQLITE_OK ){
758         rc = SQLITE_ERROR;
759       }
760     }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
761       /* If this statement was prepared using saved SQL and an
762       ** error has occurred, then return the error code in p->rc to the
763       ** caller. Set the error code in the database handle to the same value.
764       */
765       rc = sqlite3VdbeTransferError(p);
766     }
767   }
768 
769   db->errCode = rc;
770   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
771     p->rc = SQLITE_NOMEM_BKPT;
772     if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
773   }
774 end_of_step:
775   /* There are only a limited number of result codes allowed from the
776   ** statements prepared using the legacy sqlite3_prepare() interface */
777   assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
778        || rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
779        || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
780   );
781   return (rc&db->errMask);
782 }
783 
784 /*
785 ** This is the top-level implementation of sqlite3_step().  Call
786 ** sqlite3Step() to do most of the work.  If a schema error occurs,
787 ** call sqlite3Reprepare() and try again.
788 */
789 int sqlite3_step(sqlite3_stmt *pStmt){
790   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
791   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
792   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
793   sqlite3 *db;             /* The database connection */
794 
795   if( vdbeSafetyNotNull(v) ){
796     return SQLITE_MISUSE_BKPT;
797   }
798   db = v->db;
799   sqlite3_mutex_enter(db->mutex);
800   v->doingRerun = 0;
801   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
802          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
803     int savedPc = v->pc;
804     rc = sqlite3Reprepare(v);
805     if( rc!=SQLITE_OK ){
806       /* This case occurs after failing to recompile an sql statement.
807       ** The error message from the SQL compiler has already been loaded
808       ** into the database handle. This block copies the error message
809       ** from the database handle into the statement and sets the statement
810       ** program counter to 0 to ensure that when the statement is
811       ** finalized or reset the parser error message is available via
812       ** sqlite3_errmsg() and sqlite3_errcode().
813       */
814       const char *zErr = (const char *)sqlite3_value_text(db->pErr);
815       sqlite3DbFree(db, v->zErrMsg);
816       if( !db->mallocFailed ){
817         v->zErrMsg = sqlite3DbStrDup(db, zErr);
818         v->rc = rc = sqlite3ApiExit(db, rc);
819       } else {
820         v->zErrMsg = 0;
821         v->rc = rc = SQLITE_NOMEM_BKPT;
822       }
823       break;
824     }
825     sqlite3_reset(pStmt);
826     if( savedPc>=0 ) v->doingRerun = 1;
827     assert( v->expired==0 );
828   }
829   sqlite3_mutex_leave(db->mutex);
830   return rc;
831 }
832 
833 
834 /*
835 ** Extract the user data from a sqlite3_context structure and return a
836 ** pointer to it.
837 */
838 void *sqlite3_user_data(sqlite3_context *p){
839   assert( p && p->pFunc );
840   return p->pFunc->pUserData;
841 }
842 
843 /*
844 ** Extract the user data from a sqlite3_context structure and return a
845 ** pointer to it.
846 **
847 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
848 ** returns a copy of the pointer to the database connection (the 1st
849 ** parameter) of the sqlite3_create_function() and
850 ** sqlite3_create_function16() routines that originally registered the
851 ** application defined function.
852 */
853 sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
854   assert( p && p->pOut );
855   return p->pOut->db;
856 }
857 
858 /*
859 ** If this routine is invoked from within an xColumn method of a virtual
860 ** table, then it returns true if and only if the the call is during an
861 ** UPDATE operation and the value of the column will not be modified
862 ** by the UPDATE.
863 **
864 ** If this routine is called from any context other than within the
865 ** xColumn method of a virtual table, then the return value is meaningless
866 ** and arbitrary.
867 **
868 ** Virtual table implements might use this routine to optimize their
869 ** performance by substituting a NULL result, or some other light-weight
870 ** value, as a signal to the xUpdate routine that the column is unchanged.
871 */
872 int sqlite3_vtab_nochange(sqlite3_context *p){
873   assert( p );
874   return sqlite3_value_nochange(p->pOut);
875 }
876 
877 /*
878 ** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
879 ** sqlite3_vtab_in_next() (if bNext!=0).
880 */
881 static int valueFromValueList(
882   sqlite3_value *pVal,        /* Pointer to the ValueList object */
883   sqlite3_value **ppOut,      /* Store the next value from the list here */
884   int bNext                   /* 1 for _next(). 0 for _first() */
885 ){
886   int rc;
887   ValueList *pRhs;
888 
889   *ppOut = 0;
890   if( pVal==0 ) return SQLITE_MISUSE;
891   pRhs = (ValueList*)sqlite3_value_pointer(pVal, "ValueList");
892   if( pRhs==0 ) return SQLITE_MISUSE;
893   if( bNext ){
894     rc = sqlite3BtreeNext(pRhs->pCsr, 0);
895   }else{
896     int dummy = 0;
897     rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
898     assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
899     if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
900   }
901   if( rc==SQLITE_OK ){
902     u32 sz;       /* Size of current row in bytes */
903     Mem sMem;     /* Raw content of current row */
904     memset(&sMem, 0, sizeof(sMem));
905     sz = sqlite3BtreePayloadSize(pRhs->pCsr);
906     rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
907     if( rc==SQLITE_OK ){
908       u8 *zBuf = (u8*)sMem.z;
909       u32 iSerial;
910       sqlite3_value *pOut = pRhs->pOut;
911       int iOff = 1 + getVarint32(&zBuf[1], iSerial);
912       sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
913       pOut->enc = ENC(pOut->db);
914       if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
915         rc = SQLITE_NOMEM;
916       }else{
917         *ppOut = pOut;
918       }
919     }
920     sqlite3VdbeMemRelease(&sMem);
921   }
922   return rc;
923 }
924 
925 /*
926 ** Set the iterator value pVal to point to the first value in the set.
927 ** Set (*ppOut) to point to this value before returning.
928 */
929 int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
930   return valueFromValueList(pVal, ppOut, 0);
931 }
932 
933 /*
934 ** Set the iterator value pVal to point to the next value in the set.
935 ** Set (*ppOut) to point to this value before returning.
936 */
937 int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
938   return valueFromValueList(pVal, ppOut, 1);
939 }
940 
941 /*
942 ** Return the current time for a statement.  If the current time
943 ** is requested more than once within the same run of a single prepared
944 ** statement, the exact same time is returned for each invocation regardless
945 ** of the amount of time that elapses between invocations.  In other words,
946 ** the time returned is always the time of the first call.
947 */
948 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
949   int rc;
950 #ifndef SQLITE_ENABLE_STAT4
951   sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
952   assert( p->pVdbe!=0 );
953 #else
954   sqlite3_int64 iTime = 0;
955   sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
956 #endif
957   if( *piTime==0 ){
958     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
959     if( rc ) *piTime = 0;
960   }
961   return *piTime;
962 }
963 
964 /*
965 ** Create a new aggregate context for p and return a pointer to
966 ** its pMem->z element.
967 */
968 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
969   Mem *pMem = p->pMem;
970   assert( (pMem->flags & MEM_Agg)==0 );
971   if( nByte<=0 ){
972     sqlite3VdbeMemSetNull(pMem);
973     pMem->z = 0;
974   }else{
975     sqlite3VdbeMemClearAndResize(pMem, nByte);
976     pMem->flags = MEM_Agg;
977     pMem->u.pDef = p->pFunc;
978     if( pMem->z ){
979       memset(pMem->z, 0, nByte);
980     }
981   }
982   return (void*)pMem->z;
983 }
984 
985 /*
986 ** Allocate or return the aggregate context for a user function.  A new
987 ** context is allocated on the first call.  Subsequent calls return the
988 ** same context that was returned on prior calls.
989 */
990 void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
991   assert( p && p->pFunc && p->pFunc->xFinalize );
992   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
993   testcase( nByte<0 );
994   if( (p->pMem->flags & MEM_Agg)==0 ){
995     return createAggContext(p, nByte);
996   }else{
997     return (void*)p->pMem->z;
998   }
999 }
1000 
1001 /*
1002 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
1003 ** the user-function defined by pCtx.
1004 **
1005 ** The left-most argument is 0.
1006 **
1007 ** Undocumented behavior:  If iArg is negative then access a cache of
1008 ** auxiliary data pointers that is available to all functions within a
1009 ** single prepared statement.  The iArg values must match.
1010 */
1011 void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
1012   AuxData *pAuxData;
1013 
1014   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1015 #if SQLITE_ENABLE_STAT4
1016   if( pCtx->pVdbe==0 ) return 0;
1017 #else
1018   assert( pCtx->pVdbe!=0 );
1019 #endif
1020   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1021     if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1022       return pAuxData->pAux;
1023     }
1024   }
1025   return 0;
1026 }
1027 
1028 /*
1029 ** Set the auxiliary data pointer and delete function, for the iArg'th
1030 ** argument to the user-function defined by pCtx. Any previous value is
1031 ** deleted by calling the delete function specified when it was set.
1032 **
1033 ** The left-most argument is 0.
1034 **
1035 ** Undocumented behavior:  If iArg is negative then make the data available
1036 ** to all functions within the current prepared statement using iArg as an
1037 ** access code.
1038 */
1039 void sqlite3_set_auxdata(
1040   sqlite3_context *pCtx,
1041   int iArg,
1042   void *pAux,
1043   void (*xDelete)(void*)
1044 ){
1045   AuxData *pAuxData;
1046   Vdbe *pVdbe = pCtx->pVdbe;
1047 
1048   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1049 #ifdef SQLITE_ENABLE_STAT4
1050   if( pVdbe==0 ) goto failed;
1051 #else
1052   assert( pVdbe!=0 );
1053 #endif
1054 
1055   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1056     if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1057       break;
1058     }
1059   }
1060   if( pAuxData==0 ){
1061     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
1062     if( !pAuxData ) goto failed;
1063     pAuxData->iAuxOp = pCtx->iOp;
1064     pAuxData->iAuxArg = iArg;
1065     pAuxData->pNextAux = pVdbe->pAuxData;
1066     pVdbe->pAuxData = pAuxData;
1067     if( pCtx->isError==0 ) pCtx->isError = -1;
1068   }else if( pAuxData->xDeleteAux ){
1069     pAuxData->xDeleteAux(pAuxData->pAux);
1070   }
1071 
1072   pAuxData->pAux = pAux;
1073   pAuxData->xDeleteAux = xDelete;
1074   return;
1075 
1076 failed:
1077   if( xDelete ){
1078     xDelete(pAux);
1079   }
1080 }
1081 
1082 #ifndef SQLITE_OMIT_DEPRECATED
1083 /*
1084 ** Return the number of times the Step function of an aggregate has been
1085 ** called.
1086 **
1087 ** This function is deprecated.  Do not use it for new code.  It is
1088 ** provide only to avoid breaking legacy code.  New aggregate function
1089 ** implementations should keep their own counts within their aggregate
1090 ** context.
1091 */
1092 int sqlite3_aggregate_count(sqlite3_context *p){
1093   assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
1094   return p->pMem->n;
1095 }
1096 #endif
1097 
1098 /*
1099 ** Return the number of columns in the result set for the statement pStmt.
1100 */
1101 int sqlite3_column_count(sqlite3_stmt *pStmt){
1102   Vdbe *pVm = (Vdbe *)pStmt;
1103   return pVm ? pVm->nResColumn : 0;
1104 }
1105 
1106 /*
1107 ** Return the number of values available from the current row of the
1108 ** currently executing statement pStmt.
1109 */
1110 int sqlite3_data_count(sqlite3_stmt *pStmt){
1111   Vdbe *pVm = (Vdbe *)pStmt;
1112   if( pVm==0 || pVm->pResultSet==0 ) return 0;
1113   return pVm->nResColumn;
1114 }
1115 
1116 /*
1117 ** Return a pointer to static memory containing an SQL NULL value.
1118 */
1119 static const Mem *columnNullValue(void){
1120   /* Even though the Mem structure contains an element
1121   ** of type i64, on certain architectures (x86) with certain compiler
1122   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
1123   ** instead of an 8-byte one. This all works fine, except that when
1124   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
1125   ** that a Mem structure is located on an 8-byte boundary. To prevent
1126   ** these assert()s from failing, when building with SQLITE_DEBUG defined
1127   ** using gcc, we force nullMem to be 8-byte aligned using the magical
1128   ** __attribute__((aligned(8))) macro.  */
1129   static const Mem nullMem
1130 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
1131     __attribute__((aligned(8)))
1132 #endif
1133     = {
1134         /* .u          = */ {0},
1135         /* .z          = */ (char*)0,
1136         /* .n          = */ (int)0,
1137         /* .flags      = */ (u16)MEM_Null,
1138         /* .enc        = */ (u8)0,
1139         /* .eSubtype   = */ (u8)0,
1140         /* .db         = */ (sqlite3*)0,
1141         /* .szMalloc   = */ (int)0,
1142         /* .uTemp      = */ (u32)0,
1143         /* .zMalloc    = */ (char*)0,
1144         /* .xDel       = */ (void(*)(void*))0,
1145 #ifdef SQLITE_DEBUG
1146         /* .pScopyFrom = */ (Mem*)0,
1147         /* .mScopyFlags= */ 0,
1148 #endif
1149       };
1150   return &nullMem;
1151 }
1152 
1153 /*
1154 ** Check to see if column iCol of the given statement is valid.  If
1155 ** it is, return a pointer to the Mem for the value of that column.
1156 ** If iCol is not valid, return a pointer to a Mem which has a value
1157 ** of NULL.
1158 */
1159 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
1160   Vdbe *pVm;
1161   Mem *pOut;
1162 
1163   pVm = (Vdbe *)pStmt;
1164   if( pVm==0 ) return (Mem*)columnNullValue();
1165   assert( pVm->db );
1166   sqlite3_mutex_enter(pVm->db->mutex);
1167   if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
1168     pOut = &pVm->pResultSet[i];
1169   }else{
1170     sqlite3Error(pVm->db, SQLITE_RANGE);
1171     pOut = (Mem*)columnNullValue();
1172   }
1173   return pOut;
1174 }
1175 
1176 /*
1177 ** This function is called after invoking an sqlite3_value_XXX function on a
1178 ** column value (i.e. a value returned by evaluating an SQL expression in the
1179 ** select list of a SELECT statement) that may cause a malloc() failure. If
1180 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
1181 ** code of statement pStmt set to SQLITE_NOMEM.
1182 **
1183 ** Specifically, this is called from within:
1184 **
1185 **     sqlite3_column_int()
1186 **     sqlite3_column_int64()
1187 **     sqlite3_column_text()
1188 **     sqlite3_column_text16()
1189 **     sqlite3_column_real()
1190 **     sqlite3_column_bytes()
1191 **     sqlite3_column_bytes16()
1192 **     sqiite3_column_blob()
1193 */
1194 static void columnMallocFailure(sqlite3_stmt *pStmt)
1195 {
1196   /* If malloc() failed during an encoding conversion within an
1197   ** sqlite3_column_XXX API, then set the return code of the statement to
1198   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
1199   ** and _finalize() will return NOMEM.
1200   */
1201   Vdbe *p = (Vdbe *)pStmt;
1202   if( p ){
1203     assert( p->db!=0 );
1204     assert( sqlite3_mutex_held(p->db->mutex) );
1205     p->rc = sqlite3ApiExit(p->db, p->rc);
1206     sqlite3_mutex_leave(p->db->mutex);
1207   }
1208 }
1209 
1210 /**************************** sqlite3_column_  *******************************
1211 ** The following routines are used to access elements of the current row
1212 ** in the result set.
1213 */
1214 const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
1215   const void *val;
1216   val = sqlite3_value_blob( columnMem(pStmt,i) );
1217   /* Even though there is no encoding conversion, value_blob() might
1218   ** need to call malloc() to expand the result of a zeroblob()
1219   ** expression.
1220   */
1221   columnMallocFailure(pStmt);
1222   return val;
1223 }
1224 int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
1225   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
1226   columnMallocFailure(pStmt);
1227   return val;
1228 }
1229 int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
1230   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
1231   columnMallocFailure(pStmt);
1232   return val;
1233 }
1234 double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
1235   double val = sqlite3_value_double( columnMem(pStmt,i) );
1236   columnMallocFailure(pStmt);
1237   return val;
1238 }
1239 int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
1240   int val = sqlite3_value_int( columnMem(pStmt,i) );
1241   columnMallocFailure(pStmt);
1242   return val;
1243 }
1244 sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
1245   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
1246   columnMallocFailure(pStmt);
1247   return val;
1248 }
1249 const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
1250   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
1251   columnMallocFailure(pStmt);
1252   return val;
1253 }
1254 sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
1255   Mem *pOut = columnMem(pStmt, i);
1256   if( pOut->flags&MEM_Static ){
1257     pOut->flags &= ~MEM_Static;
1258     pOut->flags |= MEM_Ephem;
1259   }
1260   columnMallocFailure(pStmt);
1261   return (sqlite3_value *)pOut;
1262 }
1263 #ifndef SQLITE_OMIT_UTF16
1264 const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
1265   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
1266   columnMallocFailure(pStmt);
1267   return val;
1268 }
1269 #endif /* SQLITE_OMIT_UTF16 */
1270 int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
1271   int iType = sqlite3_value_type( columnMem(pStmt,i) );
1272   columnMallocFailure(pStmt);
1273   return iType;
1274 }
1275 
1276 /*
1277 ** Convert the N-th element of pStmt->pColName[] into a string using
1278 ** xFunc() then return that string.  If N is out of range, return 0.
1279 **
1280 ** There are up to 5 names for each column.  useType determines which
1281 ** name is returned.  Here are the names:
1282 **
1283 **    0      The column name as it should be displayed for output
1284 **    1      The datatype name for the column
1285 **    2      The name of the database that the column derives from
1286 **    3      The name of the table that the column derives from
1287 **    4      The name of the table column that the result column derives from
1288 **
1289 ** If the result is not a simple column reference (if it is an expression
1290 ** or a constant) then useTypes 2, 3, and 4 return NULL.
1291 */
1292 static const void *columnName(
1293   sqlite3_stmt *pStmt,     /* The statement */
1294   int N,                   /* Which column to get the name for */
1295   int useUtf16,            /* True to return the name as UTF16 */
1296   int useType              /* What type of name */
1297 ){
1298   const void *ret;
1299   Vdbe *p;
1300   int n;
1301   sqlite3 *db;
1302 #ifdef SQLITE_ENABLE_API_ARMOR
1303   if( pStmt==0 ){
1304     (void)SQLITE_MISUSE_BKPT;
1305     return 0;
1306   }
1307 #endif
1308   ret = 0;
1309   p = (Vdbe *)pStmt;
1310   db = p->db;
1311   assert( db!=0 );
1312   n = sqlite3_column_count(pStmt);
1313   if( N<n && N>=0 ){
1314     N += useType*n;
1315     sqlite3_mutex_enter(db->mutex);
1316     assert( db->mallocFailed==0 );
1317 #ifndef SQLITE_OMIT_UTF16
1318     if( useUtf16 ){
1319       ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
1320     }else
1321 #endif
1322     {
1323       ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
1324     }
1325     /* A malloc may have failed inside of the _text() call. If this
1326     ** is the case, clear the mallocFailed flag and return NULL.
1327     */
1328     if( db->mallocFailed ){
1329       sqlite3OomClear(db);
1330       ret = 0;
1331     }
1332     sqlite3_mutex_leave(db->mutex);
1333   }
1334   return ret;
1335 }
1336 
1337 /*
1338 ** Return the name of the Nth column of the result set returned by SQL
1339 ** statement pStmt.
1340 */
1341 const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
1342   return columnName(pStmt, N, 0, COLNAME_NAME);
1343 }
1344 #ifndef SQLITE_OMIT_UTF16
1345 const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
1346   return columnName(pStmt, N, 1, COLNAME_NAME);
1347 }
1348 #endif
1349 
1350 /*
1351 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
1352 ** not define OMIT_DECLTYPE.
1353 */
1354 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
1355 # error "Must not define both SQLITE_OMIT_DECLTYPE \
1356          and SQLITE_ENABLE_COLUMN_METADATA"
1357 #endif
1358 
1359 #ifndef SQLITE_OMIT_DECLTYPE
1360 /*
1361 ** Return the column declaration type (if applicable) of the 'i'th column
1362 ** of the result set of SQL statement pStmt.
1363 */
1364 const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
1365   return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
1366 }
1367 #ifndef SQLITE_OMIT_UTF16
1368 const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
1369   return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
1370 }
1371 #endif /* SQLITE_OMIT_UTF16 */
1372 #endif /* SQLITE_OMIT_DECLTYPE */
1373 
1374 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1375 /*
1376 ** Return the name of the database from which a result column derives.
1377 ** NULL is returned if the result column is an expression or constant or
1378 ** anything else which is not an unambiguous reference to a database column.
1379 */
1380 const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
1381   return columnName(pStmt, N, 0, COLNAME_DATABASE);
1382 }
1383 #ifndef SQLITE_OMIT_UTF16
1384 const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
1385   return columnName(pStmt, N, 1, COLNAME_DATABASE);
1386 }
1387 #endif /* SQLITE_OMIT_UTF16 */
1388 
1389 /*
1390 ** Return the name of the table from which a result column derives.
1391 ** NULL is returned if the result column is an expression or constant or
1392 ** anything else which is not an unambiguous reference to a database column.
1393 */
1394 const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
1395   return columnName(pStmt, N, 0, COLNAME_TABLE);
1396 }
1397 #ifndef SQLITE_OMIT_UTF16
1398 const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
1399   return columnName(pStmt, N, 1, COLNAME_TABLE);
1400 }
1401 #endif /* SQLITE_OMIT_UTF16 */
1402 
1403 /*
1404 ** Return the name of the table column from which a result column derives.
1405 ** NULL is returned if the result column is an expression or constant or
1406 ** anything else which is not an unambiguous reference to a database column.
1407 */
1408 const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
1409   return columnName(pStmt, N, 0, COLNAME_COLUMN);
1410 }
1411 #ifndef SQLITE_OMIT_UTF16
1412 const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
1413   return columnName(pStmt, N, 1, COLNAME_COLUMN);
1414 }
1415 #endif /* SQLITE_OMIT_UTF16 */
1416 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
1417 
1418 
1419 /******************************* sqlite3_bind_  ***************************
1420 **
1421 ** Routines used to attach values to wildcards in a compiled SQL statement.
1422 */
1423 /*
1424 ** Unbind the value bound to variable i in virtual machine p. This is the
1425 ** the same as binding a NULL value to the column. If the "i" parameter is
1426 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
1427 **
1428 ** A successful evaluation of this routine acquires the mutex on p.
1429 ** the mutex is released if any kind of error occurs.
1430 **
1431 ** The error code stored in database p->db is overwritten with the return
1432 ** value in any case.
1433 */
1434 static int vdbeUnbind(Vdbe *p, int i){
1435   Mem *pVar;
1436   if( vdbeSafetyNotNull(p) ){
1437     return SQLITE_MISUSE_BKPT;
1438   }
1439   sqlite3_mutex_enter(p->db->mutex);
1440   if( p->eVdbeState!=VDBE_READY_STATE ){
1441     sqlite3Error(p->db, SQLITE_MISUSE);
1442     sqlite3_mutex_leave(p->db->mutex);
1443     sqlite3_log(SQLITE_MISUSE,
1444         "bind on a busy prepared statement: [%s]", p->zSql);
1445     return SQLITE_MISUSE_BKPT;
1446   }
1447   if( i<1 || i>p->nVar ){
1448     sqlite3Error(p->db, SQLITE_RANGE);
1449     sqlite3_mutex_leave(p->db->mutex);
1450     return SQLITE_RANGE;
1451   }
1452   i--;
1453   pVar = &p->aVar[i];
1454   sqlite3VdbeMemRelease(pVar);
1455   pVar->flags = MEM_Null;
1456   p->db->errCode = SQLITE_OK;
1457 
1458   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
1459   ** binding a new value to this variable invalidates the current query plan.
1460   **
1461   ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
1462   ** parameter in the WHERE clause might influence the choice of query plan
1463   ** for a statement, then the statement will be automatically recompiled,
1464   ** as if there had been a schema change, on the first sqlite3_step() call
1465   ** following any change to the bindings of that parameter.
1466   */
1467   assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
1468   if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
1469     p->expired = 1;
1470   }
1471   return SQLITE_OK;
1472 }
1473 
1474 /*
1475 ** Bind a text or BLOB value.
1476 */
1477 static int bindText(
1478   sqlite3_stmt *pStmt,   /* The statement to bind against */
1479   int i,                 /* Index of the parameter to bind */
1480   const void *zData,     /* Pointer to the data to be bound */
1481   i64 nData,             /* Number of bytes of data to be bound */
1482   void (*xDel)(void*),   /* Destructor for the data */
1483   u8 encoding            /* Encoding for the data */
1484 ){
1485   Vdbe *p = (Vdbe *)pStmt;
1486   Mem *pVar;
1487   int rc;
1488 
1489   rc = vdbeUnbind(p, i);
1490   if( rc==SQLITE_OK ){
1491     if( zData!=0 ){
1492       pVar = &p->aVar[i-1];
1493       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
1494       if( rc==SQLITE_OK && encoding!=0 ){
1495         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
1496       }
1497       if( rc ){
1498         sqlite3Error(p->db, rc);
1499         rc = sqlite3ApiExit(p->db, rc);
1500       }
1501     }
1502     sqlite3_mutex_leave(p->db->mutex);
1503   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
1504     xDel((void*)zData);
1505   }
1506   return rc;
1507 }
1508 
1509 
1510 /*
1511 ** Bind a blob value to an SQL statement variable.
1512 */
1513 int sqlite3_bind_blob(
1514   sqlite3_stmt *pStmt,
1515   int i,
1516   const void *zData,
1517   int nData,
1518   void (*xDel)(void*)
1519 ){
1520 #ifdef SQLITE_ENABLE_API_ARMOR
1521   if( nData<0 ) return SQLITE_MISUSE_BKPT;
1522 #endif
1523   return bindText(pStmt, i, zData, nData, xDel, 0);
1524 }
1525 int sqlite3_bind_blob64(
1526   sqlite3_stmt *pStmt,
1527   int i,
1528   const void *zData,
1529   sqlite3_uint64 nData,
1530   void (*xDel)(void*)
1531 ){
1532   assert( xDel!=SQLITE_DYNAMIC );
1533   return bindText(pStmt, i, zData, nData, xDel, 0);
1534 }
1535 int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
1536   int rc;
1537   Vdbe *p = (Vdbe *)pStmt;
1538   rc = vdbeUnbind(p, i);
1539   if( rc==SQLITE_OK ){
1540     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
1541     sqlite3_mutex_leave(p->db->mutex);
1542   }
1543   return rc;
1544 }
1545 int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
1546   return sqlite3_bind_int64(p, i, (i64)iValue);
1547 }
1548 int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
1549   int rc;
1550   Vdbe *p = (Vdbe *)pStmt;
1551   rc = vdbeUnbind(p, i);
1552   if( rc==SQLITE_OK ){
1553     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
1554     sqlite3_mutex_leave(p->db->mutex);
1555   }
1556   return rc;
1557 }
1558 int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
1559   int rc;
1560   Vdbe *p = (Vdbe*)pStmt;
1561   rc = vdbeUnbind(p, i);
1562   if( rc==SQLITE_OK ){
1563     sqlite3_mutex_leave(p->db->mutex);
1564   }
1565   return rc;
1566 }
1567 int sqlite3_bind_pointer(
1568   sqlite3_stmt *pStmt,
1569   int i,
1570   void *pPtr,
1571   const char *zPTtype,
1572   void (*xDestructor)(void*)
1573 ){
1574   int rc;
1575   Vdbe *p = (Vdbe*)pStmt;
1576   rc = vdbeUnbind(p, i);
1577   if( rc==SQLITE_OK ){
1578     sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
1579     sqlite3_mutex_leave(p->db->mutex);
1580   }else if( xDestructor ){
1581     xDestructor(pPtr);
1582   }
1583   return rc;
1584 }
1585 int sqlite3_bind_text(
1586   sqlite3_stmt *pStmt,
1587   int i,
1588   const char *zData,
1589   int nData,
1590   void (*xDel)(void*)
1591 ){
1592   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
1593 }
1594 int sqlite3_bind_text64(
1595   sqlite3_stmt *pStmt,
1596   int i,
1597   const char *zData,
1598   sqlite3_uint64 nData,
1599   void (*xDel)(void*),
1600   unsigned char enc
1601 ){
1602   assert( xDel!=SQLITE_DYNAMIC );
1603   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
1604   return bindText(pStmt, i, zData, nData, xDel, enc);
1605 }
1606 #ifndef SQLITE_OMIT_UTF16
1607 int sqlite3_bind_text16(
1608   sqlite3_stmt *pStmt,
1609   int i,
1610   const void *zData,
1611   int nData,
1612   void (*xDel)(void*)
1613 ){
1614   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
1615 }
1616 #endif /* SQLITE_OMIT_UTF16 */
1617 int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
1618   int rc;
1619   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
1620     case SQLITE_INTEGER: {
1621       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
1622       break;
1623     }
1624     case SQLITE_FLOAT: {
1625       assert( pValue->flags & (MEM_Real|MEM_IntReal) );
1626       rc = sqlite3_bind_double(pStmt, i,
1627           (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
1628       );
1629       break;
1630     }
1631     case SQLITE_BLOB: {
1632       if( pValue->flags & MEM_Zero ){
1633         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
1634       }else{
1635         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
1636       }
1637       break;
1638     }
1639     case SQLITE_TEXT: {
1640       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
1641                               pValue->enc);
1642       break;
1643     }
1644     default: {
1645       rc = sqlite3_bind_null(pStmt, i);
1646       break;
1647     }
1648   }
1649   return rc;
1650 }
1651 int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
1652   int rc;
1653   Vdbe *p = (Vdbe *)pStmt;
1654   rc = vdbeUnbind(p, i);
1655   if( rc==SQLITE_OK ){
1656 #ifndef SQLITE_OMIT_INCRBLOB
1657     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1658 #else
1659     rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1660 #endif
1661     sqlite3_mutex_leave(p->db->mutex);
1662   }
1663   return rc;
1664 }
1665 int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
1666   int rc;
1667   Vdbe *p = (Vdbe *)pStmt;
1668   sqlite3_mutex_enter(p->db->mutex);
1669   if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
1670     rc = SQLITE_TOOBIG;
1671   }else{
1672     assert( (n & 0x7FFFFFFF)==n );
1673     rc = sqlite3_bind_zeroblob(pStmt, i, n);
1674   }
1675   rc = sqlite3ApiExit(p->db, rc);
1676   sqlite3_mutex_leave(p->db->mutex);
1677   return rc;
1678 }
1679 
1680 /*
1681 ** Return the number of wildcards that can be potentially bound to.
1682 ** This routine is added to support DBD::SQLite.
1683 */
1684 int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
1685   Vdbe *p = (Vdbe*)pStmt;
1686   return p ? p->nVar : 0;
1687 }
1688 
1689 /*
1690 ** Return the name of a wildcard parameter.  Return NULL if the index
1691 ** is out of range or if the wildcard is unnamed.
1692 **
1693 ** The result is always UTF-8.
1694 */
1695 const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
1696   Vdbe *p = (Vdbe*)pStmt;
1697   if( p==0 ) return 0;
1698   return sqlite3VListNumToName(p->pVList, i);
1699 }
1700 
1701 /*
1702 ** Given a wildcard parameter name, return the index of the variable
1703 ** with that name.  If there is no variable with the given name,
1704 ** return 0.
1705 */
1706 int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
1707   if( p==0 || zName==0 ) return 0;
1708   return sqlite3VListNameToNum(p->pVList, zName, nName);
1709 }
1710 int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
1711   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
1712 }
1713 
1714 /*
1715 ** Transfer all bindings from the first statement over to the second.
1716 */
1717 int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1718   Vdbe *pFrom = (Vdbe*)pFromStmt;
1719   Vdbe *pTo = (Vdbe*)pToStmt;
1720   int i;
1721   assert( pTo->db==pFrom->db );
1722   assert( pTo->nVar==pFrom->nVar );
1723   sqlite3_mutex_enter(pTo->db->mutex);
1724   for(i=0; i<pFrom->nVar; i++){
1725     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
1726   }
1727   sqlite3_mutex_leave(pTo->db->mutex);
1728   return SQLITE_OK;
1729 }
1730 
1731 #ifndef SQLITE_OMIT_DEPRECATED
1732 /*
1733 ** Deprecated external interface.  Internal/core SQLite code
1734 ** should call sqlite3TransferBindings.
1735 **
1736 ** It is misuse to call this routine with statements from different
1737 ** database connections.  But as this is a deprecated interface, we
1738 ** will not bother to check for that condition.
1739 **
1740 ** If the two statements contain a different number of bindings, then
1741 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
1742 ** SQLITE_OK is returned.
1743 */
1744 int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1745   Vdbe *pFrom = (Vdbe*)pFromStmt;
1746   Vdbe *pTo = (Vdbe*)pToStmt;
1747   if( pFrom->nVar!=pTo->nVar ){
1748     return SQLITE_ERROR;
1749   }
1750   assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
1751   if( pTo->expmask ){
1752     pTo->expired = 1;
1753   }
1754   assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
1755   if( pFrom->expmask ){
1756     pFrom->expired = 1;
1757   }
1758   return sqlite3TransferBindings(pFromStmt, pToStmt);
1759 }
1760 #endif
1761 
1762 /*
1763 ** Return the sqlite3* database handle to which the prepared statement given
1764 ** in the argument belongs.  This is the same database handle that was
1765 ** the first argument to the sqlite3_prepare() that was used to create
1766 ** the statement in the first place.
1767 */
1768 sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
1769   return pStmt ? ((Vdbe*)pStmt)->db : 0;
1770 }
1771 
1772 /*
1773 ** Return true if the prepared statement is guaranteed to not modify the
1774 ** database.
1775 */
1776 int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
1777   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
1778 }
1779 
1780 /*
1781 ** Return 1 if the statement is an EXPLAIN and return 2 if the
1782 ** statement is an EXPLAIN QUERY PLAN
1783 */
1784 int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
1785   return pStmt ? ((Vdbe*)pStmt)->explain : 0;
1786 }
1787 
1788 /*
1789 ** Return true if the prepared statement is in need of being reset.
1790 */
1791 int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
1792   Vdbe *v = (Vdbe*)pStmt;
1793   return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
1794 }
1795 
1796 /*
1797 ** Return a pointer to the next prepared statement after pStmt associated
1798 ** with database connection pDb.  If pStmt is NULL, return the first
1799 ** prepared statement for the database connection.  Return NULL if there
1800 ** are no more.
1801 */
1802 sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
1803   sqlite3_stmt *pNext;
1804 #ifdef SQLITE_ENABLE_API_ARMOR
1805   if( !sqlite3SafetyCheckOk(pDb) ){
1806     (void)SQLITE_MISUSE_BKPT;
1807     return 0;
1808   }
1809 #endif
1810   sqlite3_mutex_enter(pDb->mutex);
1811   if( pStmt==0 ){
1812     pNext = (sqlite3_stmt*)pDb->pVdbe;
1813   }else{
1814     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
1815   }
1816   sqlite3_mutex_leave(pDb->mutex);
1817   return pNext;
1818 }
1819 
1820 /*
1821 ** Return the value of a status counter for a prepared statement
1822 */
1823 int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
1824   Vdbe *pVdbe = (Vdbe*)pStmt;
1825   u32 v;
1826 #ifdef SQLITE_ENABLE_API_ARMOR
1827   if( !pStmt
1828    || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
1829   ){
1830     (void)SQLITE_MISUSE_BKPT;
1831     return 0;
1832   }
1833 #endif
1834   if( op==SQLITE_STMTSTATUS_MEMUSED ){
1835     sqlite3 *db = pVdbe->db;
1836     sqlite3_mutex_enter(db->mutex);
1837     v = 0;
1838     db->pnBytesFreed = (int*)&v;
1839     sqlite3VdbeClearObject(db, pVdbe);
1840     sqlite3DbFree(db, pVdbe);
1841     db->pnBytesFreed = 0;
1842     sqlite3_mutex_leave(db->mutex);
1843   }else{
1844     v = pVdbe->aCounter[op];
1845     if( resetFlag ) pVdbe->aCounter[op] = 0;
1846   }
1847   return (int)v;
1848 }
1849 
1850 /*
1851 ** Return the SQL associated with a prepared statement
1852 */
1853 const char *sqlite3_sql(sqlite3_stmt *pStmt){
1854   Vdbe *p = (Vdbe *)pStmt;
1855   return p ? p->zSql : 0;
1856 }
1857 
1858 /*
1859 ** Return the SQL associated with a prepared statement with
1860 ** bound parameters expanded.  Space to hold the returned string is
1861 ** obtained from sqlite3_malloc().  The caller is responsible for
1862 ** freeing the returned string by passing it to sqlite3_free().
1863 **
1864 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
1865 ** expanded bound parameters.
1866 */
1867 char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
1868 #ifdef SQLITE_OMIT_TRACE
1869   return 0;
1870 #else
1871   char *z = 0;
1872   const char *zSql = sqlite3_sql(pStmt);
1873   if( zSql ){
1874     Vdbe *p = (Vdbe *)pStmt;
1875     sqlite3_mutex_enter(p->db->mutex);
1876     z = sqlite3VdbeExpandSql(p, zSql);
1877     sqlite3_mutex_leave(p->db->mutex);
1878   }
1879   return z;
1880 #endif
1881 }
1882 
1883 #ifdef SQLITE_ENABLE_NORMALIZE
1884 /*
1885 ** Return the normalized SQL associated with a prepared statement.
1886 */
1887 const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
1888   Vdbe *p = (Vdbe *)pStmt;
1889   if( p==0 ) return 0;
1890   if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
1891     sqlite3_mutex_enter(p->db->mutex);
1892     p->zNormSql = sqlite3Normalize(p, p->zSql);
1893     sqlite3_mutex_leave(p->db->mutex);
1894   }
1895   return p->zNormSql;
1896 }
1897 #endif /* SQLITE_ENABLE_NORMALIZE */
1898 
1899 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1900 /*
1901 ** Allocate and populate an UnpackedRecord structure based on the serialized
1902 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
1903 ** if successful, or a NULL pointer if an OOM error is encountered.
1904 */
1905 static UnpackedRecord *vdbeUnpackRecord(
1906   KeyInfo *pKeyInfo,
1907   int nKey,
1908   const void *pKey
1909 ){
1910   UnpackedRecord *pRet;           /* Return value */
1911 
1912   pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
1913   if( pRet ){
1914     memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
1915     sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
1916   }
1917   return pRet;
1918 }
1919 
1920 /*
1921 ** This function is called from within a pre-update callback to retrieve
1922 ** a field of the row currently being updated or deleted.
1923 */
1924 int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
1925   PreUpdate *p = db->pPreUpdate;
1926   Mem *pMem;
1927   int rc = SQLITE_OK;
1928 
1929   /* Test that this call is being made from within an SQLITE_DELETE or
1930   ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
1931   if( !p || p->op==SQLITE_INSERT ){
1932     rc = SQLITE_MISUSE_BKPT;
1933     goto preupdate_old_out;
1934   }
1935   if( p->pPk ){
1936     iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
1937   }
1938   if( iIdx>=p->pCsr->nField || iIdx<0 ){
1939     rc = SQLITE_RANGE;
1940     goto preupdate_old_out;
1941   }
1942 
1943   /* If the old.* record has not yet been loaded into memory, do so now. */
1944   if( p->pUnpacked==0 ){
1945     u32 nRec;
1946     u8 *aRec;
1947 
1948     assert( p->pCsr->eCurType==CURTYPE_BTREE );
1949     nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
1950     aRec = sqlite3DbMallocRaw(db, nRec);
1951     if( !aRec ) goto preupdate_old_out;
1952     rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
1953     if( rc==SQLITE_OK ){
1954       p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
1955       if( !p->pUnpacked ) rc = SQLITE_NOMEM;
1956     }
1957     if( rc!=SQLITE_OK ){
1958       sqlite3DbFree(db, aRec);
1959       goto preupdate_old_out;
1960     }
1961     p->aRecord = aRec;
1962   }
1963 
1964   pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
1965   if( iIdx==p->pTab->iPKey ){
1966     sqlite3VdbeMemSetInt64(pMem, p->iKey1);
1967   }else if( iIdx>=p->pUnpacked->nField ){
1968     *ppValue = (sqlite3_value *)columnNullValue();
1969   }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
1970     if( pMem->flags & (MEM_Int|MEM_IntReal) ){
1971       testcase( pMem->flags & MEM_Int );
1972       testcase( pMem->flags & MEM_IntReal );
1973       sqlite3VdbeMemRealify(pMem);
1974     }
1975   }
1976 
1977  preupdate_old_out:
1978   sqlite3Error(db, rc);
1979   return sqlite3ApiExit(db, rc);
1980 }
1981 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1982 
1983 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1984 /*
1985 ** This function is called from within a pre-update callback to retrieve
1986 ** the number of columns in the row being updated, deleted or inserted.
1987 */
1988 int sqlite3_preupdate_count(sqlite3 *db){
1989   PreUpdate *p = db->pPreUpdate;
1990   return (p ? p->keyinfo.nKeyField : 0);
1991 }
1992 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1993 
1994 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1995 /*
1996 ** This function is designed to be called from within a pre-update callback
1997 ** only. It returns zero if the change that caused the callback was made
1998 ** immediately by a user SQL statement. Or, if the change was made by a
1999 ** trigger program, it returns the number of trigger programs currently
2000 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
2001 ** top-level trigger etc.).
2002 **
2003 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
2004 ** or SET DEFAULT action is considered a trigger.
2005 */
2006 int sqlite3_preupdate_depth(sqlite3 *db){
2007   PreUpdate *p = db->pPreUpdate;
2008   return (p ? p->v->nFrame : 0);
2009 }
2010 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2011 
2012 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2013 /*
2014 ** This function is designed to be called from within a pre-update callback
2015 ** only.
2016 */
2017 int sqlite3_preupdate_blobwrite(sqlite3 *db){
2018   PreUpdate *p = db->pPreUpdate;
2019   return (p ? p->iBlobWrite : -1);
2020 }
2021 #endif
2022 
2023 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2024 /*
2025 ** This function is called from within a pre-update callback to retrieve
2026 ** a field of the row currently being updated or inserted.
2027 */
2028 int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2029   PreUpdate *p = db->pPreUpdate;
2030   int rc = SQLITE_OK;
2031   Mem *pMem;
2032 
2033   if( !p || p->op==SQLITE_DELETE ){
2034     rc = SQLITE_MISUSE_BKPT;
2035     goto preupdate_new_out;
2036   }
2037   if( p->pPk && p->op!=SQLITE_UPDATE ){
2038     iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2039   }
2040   if( iIdx>=p->pCsr->nField || iIdx<0 ){
2041     rc = SQLITE_RANGE;
2042     goto preupdate_new_out;
2043   }
2044 
2045   if( p->op==SQLITE_INSERT ){
2046     /* For an INSERT, memory cell p->iNewReg contains the serialized record
2047     ** that is being inserted. Deserialize it. */
2048     UnpackedRecord *pUnpack = p->pNewUnpacked;
2049     if( !pUnpack ){
2050       Mem *pData = &p->v->aMem[p->iNewReg];
2051       rc = ExpandBlob(pData);
2052       if( rc!=SQLITE_OK ) goto preupdate_new_out;
2053       pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
2054       if( !pUnpack ){
2055         rc = SQLITE_NOMEM;
2056         goto preupdate_new_out;
2057       }
2058       p->pNewUnpacked = pUnpack;
2059     }
2060     pMem = &pUnpack->aMem[iIdx];
2061     if( iIdx==p->pTab->iPKey ){
2062       sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2063     }else if( iIdx>=pUnpack->nField ){
2064       pMem = (sqlite3_value *)columnNullValue();
2065     }
2066   }else{
2067     /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
2068     ** value. Make a copy of the cell contents and return a pointer to it.
2069     ** It is not safe to return a pointer to the memory cell itself as the
2070     ** caller may modify the value text encoding.
2071     */
2072     assert( p->op==SQLITE_UPDATE );
2073     if( !p->aNew ){
2074       p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
2075       if( !p->aNew ){
2076         rc = SQLITE_NOMEM;
2077         goto preupdate_new_out;
2078       }
2079     }
2080     assert( iIdx>=0 && iIdx<p->pCsr->nField );
2081     pMem = &p->aNew[iIdx];
2082     if( pMem->flags==0 ){
2083       if( iIdx==p->pTab->iPKey ){
2084         sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2085       }else{
2086         rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
2087         if( rc!=SQLITE_OK ) goto preupdate_new_out;
2088       }
2089     }
2090   }
2091   *ppValue = pMem;
2092 
2093  preupdate_new_out:
2094   sqlite3Error(db, rc);
2095   return sqlite3ApiExit(db, rc);
2096 }
2097 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2098 
2099 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2100 /*
2101 ** Return status data for a single loop within query pStmt.
2102 */
2103 int sqlite3_stmt_scanstatus(
2104   sqlite3_stmt *pStmt,            /* Prepared statement being queried */
2105   int idx,                        /* Index of loop to report on */
2106   int iScanStatusOp,              /* Which metric to return */
2107   void *pOut                      /* OUT: Write the answer here */
2108 ){
2109   Vdbe *p = (Vdbe*)pStmt;
2110   ScanStatus *pScan;
2111   if( idx<0 || idx>=p->nScan ) return 1;
2112   pScan = &p->aScan[idx];
2113   switch( iScanStatusOp ){
2114     case SQLITE_SCANSTAT_NLOOP: {
2115       *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
2116       break;
2117     }
2118     case SQLITE_SCANSTAT_NVISIT: {
2119       *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
2120       break;
2121     }
2122     case SQLITE_SCANSTAT_EST: {
2123       double r = 1.0;
2124       LogEst x = pScan->nEst;
2125       while( x<100 ){
2126         x += 10;
2127         r *= 0.5;
2128       }
2129       *(double*)pOut = r*sqlite3LogEstToInt(x);
2130       break;
2131     }
2132     case SQLITE_SCANSTAT_NAME: {
2133       *(const char**)pOut = pScan->zName;
2134       break;
2135     }
2136     case SQLITE_SCANSTAT_EXPLAIN: {
2137       if( pScan->addrExplain ){
2138         *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
2139       }else{
2140         *(const char**)pOut = 0;
2141       }
2142       break;
2143     }
2144     case SQLITE_SCANSTAT_SELECTID: {
2145       if( pScan->addrExplain ){
2146         *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
2147       }else{
2148         *(int*)pOut = -1;
2149       }
2150       break;
2151     }
2152     default: {
2153       return 1;
2154     }
2155   }
2156   return 0;
2157 }
2158 
2159 /*
2160 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
2161 */
2162 void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
2163   Vdbe *p = (Vdbe*)pStmt;
2164   memset(p->anExec, 0, p->nOp * sizeof(i64));
2165 }
2166 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
2167