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