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