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