Fixes default log output to console for macOS
[sqlcipher.git] / src / vdbeapi.c
blob3182e4070ffbbfe5b6f933e45cf365ea7e7dae7d
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.
11 *************************************************************************
13 ** This file contains code use to implement APIs that are part of the
14 ** VDBE.
16 #include "sqliteInt.h"
17 #include "vdbeInt.h"
18 #include "opcodes.h"
20 #ifndef SQLITE_OMIT_DEPRECATED
22 ** Return TRUE (non-zero) of the statement supplied as an argument needs
23 ** to be recompiled. A statement needs to be recompiled whenever the
24 ** execution environment changes in a way that would alter the program
25 ** that sqlite3_prepare() generates. For example, if new functions or
26 ** collating sequences are registered or if an authorizer function is
27 ** added or changed.
29 int sqlite3_expired(sqlite3_stmt *pStmt){
30 Vdbe *p = (Vdbe*)pStmt;
31 return p==0 || p->expired;
33 #endif
36 ** Check on a Vdbe to make sure it has not been finalized. Log
37 ** an error and return true if it has been finalized (or is otherwise
38 ** invalid). Return false if it is ok.
40 static int vdbeSafety(Vdbe *p){
41 if( p->db==0 ){
42 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
43 return 1;
44 }else{
45 return 0;
48 static int vdbeSafetyNotNull(Vdbe *p){
49 if( p==0 ){
50 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
51 return 1;
52 }else{
53 return vdbeSafety(p);
57 #ifndef SQLITE_OMIT_TRACE
59 ** Invoke the profile callback. This routine is only called if we already
60 ** know that the profile callback is defined and needs to be invoked.
62 static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
63 sqlite3_int64 iNow;
64 sqlite3_int64 iElapse;
65 assert( p->startTime>0 );
66 assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
67 assert( db->init.busy==0 );
68 assert( p->zSql!=0 );
69 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
70 iElapse = (iNow - p->startTime)*1000000;
71 #ifndef SQLITE_OMIT_DEPRECATED
72 if( db->xProfile ){
73 db->xProfile(db->pProfileArg, p->zSql, iElapse);
75 #endif
76 if( db->mTrace & SQLITE_TRACE_PROFILE ){
77 db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
79 p->startTime = 0;
82 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
83 ** is needed, and it invokes the callback if it is needed.
85 # define checkProfileCallback(DB,P) \
86 if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
87 #else
88 # define checkProfileCallback(DB,P) /*no-op*/
89 #endif
92 ** The following routine destroys a virtual machine that is created by
93 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
94 ** success/failure code that describes the result of executing the virtual
95 ** machine.
97 ** This routine sets the error code and string returned by
98 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
100 int sqlite3_finalize(sqlite3_stmt *pStmt){
101 int rc;
102 if( pStmt==0 ){
103 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
104 ** pointer is a harmless no-op. */
105 rc = SQLITE_OK;
106 }else{
107 Vdbe *v = (Vdbe*)pStmt;
108 sqlite3 *db = v->db;
109 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
110 sqlite3_mutex_enter(db->mutex);
111 checkProfileCallback(db, v);
112 assert( v->eVdbeState>=VDBE_READY_STATE );
113 rc = sqlite3VdbeReset(v);
114 sqlite3VdbeDelete(v);
115 rc = sqlite3ApiExit(db, rc);
116 sqlite3LeaveMutexAndCloseZombie(db);
118 return rc;
122 ** Terminate the current execution of an SQL statement and reset it
123 ** back to its starting state so that it can be reused. A success code from
124 ** the prior execution is returned.
126 ** This routine sets the error code and string returned by
127 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
129 int sqlite3_reset(sqlite3_stmt *pStmt){
130 int rc;
131 if( pStmt==0 ){
132 rc = SQLITE_OK;
133 }else{
134 Vdbe *v = (Vdbe*)pStmt;
135 sqlite3 *db = v->db;
136 sqlite3_mutex_enter(db->mutex);
137 checkProfileCallback(db, v);
138 rc = sqlite3VdbeReset(v);
139 sqlite3VdbeRewind(v);
140 assert( (rc & (db->errMask))==rc );
141 rc = sqlite3ApiExit(db, rc);
142 sqlite3_mutex_leave(db->mutex);
144 return rc;
148 ** Set all the parameters in the compiled SQL statement to NULL.
150 int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
151 int i;
152 int rc = SQLITE_OK;
153 Vdbe *p = (Vdbe*)pStmt;
154 #if SQLITE_THREADSAFE
155 sqlite3_mutex *mutex;
156 #endif
157 #ifdef SQLITE_ENABLE_API_ARMOR
158 if( pStmt==0 ){
159 return SQLITE_MISUSE_BKPT;
161 #endif
162 #if SQLITE_THREADSAFE
163 mutex = p->db->mutex;
164 #endif
165 sqlite3_mutex_enter(mutex);
166 for(i=0; i<p->nVar; i++){
167 sqlite3VdbeMemRelease(&p->aVar[i]);
168 p->aVar[i].flags = MEM_Null;
170 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
171 if( p->expmask ){
172 p->expired = 1;
174 sqlite3_mutex_leave(mutex);
175 return rc;
179 /**************************** sqlite3_value_ *******************************
180 ** The following routines extract information from a Mem or sqlite3_value
181 ** structure.
183 const void *sqlite3_value_blob(sqlite3_value *pVal){
184 Mem *p = (Mem*)pVal;
185 if( p->flags & (MEM_Blob|MEM_Str) ){
186 if( ExpandBlob(p)!=SQLITE_OK ){
187 assert( p->flags==MEM_Null && p->z==0 );
188 return 0;
190 p->flags |= MEM_Blob;
191 return p->n ? p->z : 0;
192 }else{
193 return sqlite3_value_text(pVal);
196 int sqlite3_value_bytes(sqlite3_value *pVal){
197 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
199 int sqlite3_value_bytes16(sqlite3_value *pVal){
200 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
202 double sqlite3_value_double(sqlite3_value *pVal){
203 return sqlite3VdbeRealValue((Mem*)pVal);
205 int sqlite3_value_int(sqlite3_value *pVal){
206 return (int)sqlite3VdbeIntValue((Mem*)pVal);
208 sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
209 return sqlite3VdbeIntValue((Mem*)pVal);
211 unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
212 Mem *pMem = (Mem*)pVal;
213 return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
215 void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
216 Mem *p = (Mem*)pVal;
217 if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
218 (MEM_Null|MEM_Term|MEM_Subtype)
219 && zPType!=0
220 && p->eSubtype=='p'
221 && strcmp(p->u.zPType, zPType)==0
223 return (void*)p->z;
224 }else{
225 return 0;
228 const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
229 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
231 #ifndef SQLITE_OMIT_UTF16
232 const void *sqlite3_value_text16(sqlite3_value* pVal){
233 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
235 const void *sqlite3_value_text16be(sqlite3_value *pVal){
236 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
238 const void *sqlite3_value_text16le(sqlite3_value *pVal){
239 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
241 #endif /* SQLITE_OMIT_UTF16 */
242 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
243 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
244 ** point number string BLOB NULL
246 int sqlite3_value_type(sqlite3_value* pVal){
247 static const u8 aType[] = {
248 SQLITE_BLOB, /* 0x00 (not possible) */
249 SQLITE_NULL, /* 0x01 NULL */
250 SQLITE_TEXT, /* 0x02 TEXT */
251 SQLITE_NULL, /* 0x03 (not possible) */
252 SQLITE_INTEGER, /* 0x04 INTEGER */
253 SQLITE_NULL, /* 0x05 (not possible) */
254 SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */
255 SQLITE_NULL, /* 0x07 (not possible) */
256 SQLITE_FLOAT, /* 0x08 FLOAT */
257 SQLITE_NULL, /* 0x09 (not possible) */
258 SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */
259 SQLITE_NULL, /* 0x0b (not possible) */
260 SQLITE_INTEGER, /* 0x0c (not possible) */
261 SQLITE_NULL, /* 0x0d (not possible) */
262 SQLITE_INTEGER, /* 0x0e (not possible) */
263 SQLITE_NULL, /* 0x0f (not possible) */
264 SQLITE_BLOB, /* 0x10 BLOB */
265 SQLITE_NULL, /* 0x11 (not possible) */
266 SQLITE_TEXT, /* 0x12 (not possible) */
267 SQLITE_NULL, /* 0x13 (not possible) */
268 SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */
269 SQLITE_NULL, /* 0x15 (not possible) */
270 SQLITE_INTEGER, /* 0x16 (not possible) */
271 SQLITE_NULL, /* 0x17 (not possible) */
272 SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */
273 SQLITE_NULL, /* 0x19 (not possible) */
274 SQLITE_FLOAT, /* 0x1a (not possible) */
275 SQLITE_NULL, /* 0x1b (not possible) */
276 SQLITE_INTEGER, /* 0x1c (not possible) */
277 SQLITE_NULL, /* 0x1d (not possible) */
278 SQLITE_INTEGER, /* 0x1e (not possible) */
279 SQLITE_NULL, /* 0x1f (not possible) */
280 SQLITE_FLOAT, /* 0x20 INTREAL */
281 SQLITE_NULL, /* 0x21 (not possible) */
282 SQLITE_FLOAT, /* 0x22 INTREAL + TEXT */
283 SQLITE_NULL, /* 0x23 (not possible) */
284 SQLITE_FLOAT, /* 0x24 (not possible) */
285 SQLITE_NULL, /* 0x25 (not possible) */
286 SQLITE_FLOAT, /* 0x26 (not possible) */
287 SQLITE_NULL, /* 0x27 (not possible) */
288 SQLITE_FLOAT, /* 0x28 (not possible) */
289 SQLITE_NULL, /* 0x29 (not possible) */
290 SQLITE_FLOAT, /* 0x2a (not possible) */
291 SQLITE_NULL, /* 0x2b (not possible) */
292 SQLITE_FLOAT, /* 0x2c (not possible) */
293 SQLITE_NULL, /* 0x2d (not possible) */
294 SQLITE_FLOAT, /* 0x2e (not possible) */
295 SQLITE_NULL, /* 0x2f (not possible) */
296 SQLITE_BLOB, /* 0x30 (not possible) */
297 SQLITE_NULL, /* 0x31 (not possible) */
298 SQLITE_TEXT, /* 0x32 (not possible) */
299 SQLITE_NULL, /* 0x33 (not possible) */
300 SQLITE_FLOAT, /* 0x34 (not possible) */
301 SQLITE_NULL, /* 0x35 (not possible) */
302 SQLITE_FLOAT, /* 0x36 (not possible) */
303 SQLITE_NULL, /* 0x37 (not possible) */
304 SQLITE_FLOAT, /* 0x38 (not possible) */
305 SQLITE_NULL, /* 0x39 (not possible) */
306 SQLITE_FLOAT, /* 0x3a (not possible) */
307 SQLITE_NULL, /* 0x3b (not possible) */
308 SQLITE_FLOAT, /* 0x3c (not possible) */
309 SQLITE_NULL, /* 0x3d (not possible) */
310 SQLITE_FLOAT, /* 0x3e (not possible) */
311 SQLITE_NULL, /* 0x3f (not possible) */
313 #ifdef SQLITE_DEBUG
315 int eType = SQLITE_BLOB;
316 if( pVal->flags & MEM_Null ){
317 eType = SQLITE_NULL;
318 }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
319 eType = SQLITE_FLOAT;
320 }else if( pVal->flags & MEM_Int ){
321 eType = SQLITE_INTEGER;
322 }else if( pVal->flags & MEM_Str ){
323 eType = SQLITE_TEXT;
325 assert( eType == aType[pVal->flags&MEM_AffMask] );
327 #endif
328 return aType[pVal->flags&MEM_AffMask];
330 int sqlite3_value_encoding(sqlite3_value *pVal){
331 return pVal->enc;
334 /* Return true if a parameter to xUpdate represents an unchanged column */
335 int sqlite3_value_nochange(sqlite3_value *pVal){
336 return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
339 /* Return true if a parameter value originated from an sqlite3_bind() */
340 int sqlite3_value_frombind(sqlite3_value *pVal){
341 return (pVal->flags&MEM_FromBind)!=0;
344 /* Make a copy of an sqlite3_value object
346 sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
347 sqlite3_value *pNew;
348 if( pOrig==0 ) return 0;
349 pNew = sqlite3_malloc( sizeof(*pNew) );
350 if( pNew==0 ) return 0;
351 memset(pNew, 0, sizeof(*pNew));
352 memcpy(pNew, pOrig, MEMCELLSIZE);
353 pNew->flags &= ~MEM_Dyn;
354 pNew->db = 0;
355 if( pNew->flags&(MEM_Str|MEM_Blob) ){
356 pNew->flags &= ~(MEM_Static|MEM_Dyn);
357 pNew->flags |= MEM_Ephem;
358 if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
359 sqlite3ValueFree(pNew);
360 pNew = 0;
362 }else if( pNew->flags & MEM_Null ){
363 /* Do not duplicate pointer values */
364 pNew->flags &= ~(MEM_Term|MEM_Subtype);
366 return pNew;
369 /* Destroy an sqlite3_value object previously obtained from
370 ** sqlite3_value_dup().
372 void sqlite3_value_free(sqlite3_value *pOld){
373 sqlite3ValueFree(pOld);
377 /**************************** sqlite3_result_ *******************************
378 ** The following routines are used by user-defined functions to specify
379 ** the function result.
381 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
382 ** result as a string or blob. Appropriate errors are set if the string/blob
383 ** is too big or if an OOM occurs.
385 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
386 ** on value P if P is not going to be used and need to be destroyed.
388 static void setResultStrOrError(
389 sqlite3_context *pCtx, /* Function context */
390 const char *z, /* String pointer */
391 int n, /* Bytes in string, or negative */
392 u8 enc, /* Encoding of z. 0 for BLOBs */
393 void (*xDel)(void*) /* Destructor function */
395 Mem *pOut = pCtx->pOut;
396 int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
397 if( rc ){
398 if( rc==SQLITE_TOOBIG ){
399 sqlite3_result_error_toobig(pCtx);
400 }else{
401 /* The only errors possible from sqlite3VdbeMemSetStr are
402 ** SQLITE_TOOBIG and SQLITE_NOMEM */
403 assert( rc==SQLITE_NOMEM );
404 sqlite3_result_error_nomem(pCtx);
406 return;
408 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
409 if( sqlite3VdbeMemTooBig(pOut) ){
410 sqlite3_result_error_toobig(pCtx);
413 static int invokeValueDestructor(
414 const void *p, /* Value to destroy */
415 void (*xDel)(void*), /* The destructor */
416 sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if not NULL */
418 assert( xDel!=SQLITE_DYNAMIC );
419 if( xDel==0 ){
420 /* noop */
421 }else if( xDel==SQLITE_TRANSIENT ){
422 /* noop */
423 }else{
424 xDel((void*)p);
426 #ifdef SQLITE_ENABLE_API_ARMOR
427 if( pCtx!=0 ){
428 sqlite3_result_error_toobig(pCtx);
430 #else
431 assert( pCtx!=0 );
432 sqlite3_result_error_toobig(pCtx);
433 #endif
434 return SQLITE_TOOBIG;
436 void sqlite3_result_blob(
437 sqlite3_context *pCtx,
438 const void *z,
439 int n,
440 void (*xDel)(void *)
442 #ifdef SQLITE_ENABLE_API_ARMOR
443 if( pCtx==0 || n<0 ){
444 invokeValueDestructor(z, xDel, pCtx);
445 return;
447 #endif
448 assert( n>=0 );
449 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
450 setResultStrOrError(pCtx, z, n, 0, xDel);
452 void sqlite3_result_blob64(
453 sqlite3_context *pCtx,
454 const void *z,
455 sqlite3_uint64 n,
456 void (*xDel)(void *)
458 assert( xDel!=SQLITE_DYNAMIC );
459 #ifdef SQLITE_ENABLE_API_ARMOR
460 if( pCtx==0 ){
461 invokeValueDestructor(z, xDel, 0);
462 return;
464 #endif
465 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
466 if( n>0x7fffffff ){
467 (void)invokeValueDestructor(z, xDel, pCtx);
468 }else{
469 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
472 void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
473 #ifdef SQLITE_ENABLE_API_ARMOR
474 if( pCtx==0 ) return;
475 #endif
476 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
477 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
479 void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
480 #ifdef SQLITE_ENABLE_API_ARMOR
481 if( pCtx==0 ) return;
482 #endif
483 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
484 pCtx->isError = SQLITE_ERROR;
485 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
487 #ifndef SQLITE_OMIT_UTF16
488 void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
489 #ifdef SQLITE_ENABLE_API_ARMOR
490 if( pCtx==0 ) return;
491 #endif
492 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
493 pCtx->isError = SQLITE_ERROR;
494 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
496 #endif
497 void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
498 #ifdef SQLITE_ENABLE_API_ARMOR
499 if( pCtx==0 ) return;
500 #endif
501 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
502 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
504 void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
505 #ifdef SQLITE_ENABLE_API_ARMOR
506 if( pCtx==0 ) return;
507 #endif
508 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
509 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
511 void sqlite3_result_null(sqlite3_context *pCtx){
512 #ifdef SQLITE_ENABLE_API_ARMOR
513 if( pCtx==0 ) return;
514 #endif
515 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
516 sqlite3VdbeMemSetNull(pCtx->pOut);
518 void sqlite3_result_pointer(
519 sqlite3_context *pCtx,
520 void *pPtr,
521 const char *zPType,
522 void (*xDestructor)(void*)
524 Mem *pOut;
525 #ifdef SQLITE_ENABLE_API_ARMOR
526 if( pCtx==0 ){
527 invokeValueDestructor(pPtr, xDestructor, 0);
528 return;
530 #endif
531 pOut = pCtx->pOut;
532 assert( sqlite3_mutex_held(pOut->db->mutex) );
533 sqlite3VdbeMemRelease(pOut);
534 pOut->flags = MEM_Null;
535 sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
537 void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
538 Mem *pOut;
539 #ifdef SQLITE_ENABLE_API_ARMOR
540 if( pCtx==0 ) return;
541 #endif
542 #if defined(SQLITE_STRICT_SUBTYPE) && SQLITE_STRICT_SUBTYPE+0!=0
543 if( pCtx->pFunc!=0
544 && (pCtx->pFunc->funcFlags & SQLITE_RESULT_SUBTYPE)==0
546 char zErr[200];
547 sqlite3_snprintf(sizeof(zErr), zErr,
548 "misuse of sqlite3_result_subtype() by %s()",
549 pCtx->pFunc->zName);
550 sqlite3_result_error(pCtx, zErr, -1);
551 return;
553 #endif /* SQLITE_STRICT_SUBTYPE */
554 pOut = pCtx->pOut;
555 assert( sqlite3_mutex_held(pOut->db->mutex) );
556 pOut->eSubtype = eSubtype & 0xff;
557 pOut->flags |= MEM_Subtype;
559 void sqlite3_result_text(
560 sqlite3_context *pCtx,
561 const char *z,
562 int n,
563 void (*xDel)(void *)
565 #ifdef SQLITE_ENABLE_API_ARMOR
566 if( pCtx==0 ){
567 invokeValueDestructor(z, xDel, 0);
568 return;
570 #endif
571 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
572 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
574 void sqlite3_result_text64(
575 sqlite3_context *pCtx,
576 const char *z,
577 sqlite3_uint64 n,
578 void (*xDel)(void *),
579 unsigned char enc
581 #ifdef SQLITE_ENABLE_API_ARMOR
582 if( pCtx==0 ){
583 invokeValueDestructor(z, xDel, 0);
584 return;
586 #endif
587 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
588 assert( xDel!=SQLITE_DYNAMIC );
589 if( enc!=SQLITE_UTF8 ){
590 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
591 n &= ~(u64)1;
593 if( n>0x7fffffff ){
594 (void)invokeValueDestructor(z, xDel, pCtx);
595 }else{
596 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
597 sqlite3VdbeMemZeroTerminateIfAble(pCtx->pOut);
600 #ifndef SQLITE_OMIT_UTF16
601 void sqlite3_result_text16(
602 sqlite3_context *pCtx,
603 const void *z,
604 int n,
605 void (*xDel)(void *)
607 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
608 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16NATIVE, xDel);
610 void sqlite3_result_text16be(
611 sqlite3_context *pCtx,
612 const void *z,
613 int n,
614 void (*xDel)(void *)
616 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
617 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16BE, xDel);
619 void sqlite3_result_text16le(
620 sqlite3_context *pCtx,
621 const void *z,
622 int n,
623 void (*xDel)(void *)
625 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
626 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16LE, xDel);
628 #endif /* SQLITE_OMIT_UTF16 */
629 void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
630 Mem *pOut;
632 #ifdef SQLITE_ENABLE_API_ARMOR
633 if( pCtx==0 ) return;
634 if( pValue==0 ){
635 sqlite3_result_null(pCtx);
636 return;
638 #endif
639 pOut = pCtx->pOut;
640 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
641 sqlite3VdbeMemCopy(pOut, pValue);
642 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
643 if( sqlite3VdbeMemTooBig(pOut) ){
644 sqlite3_result_error_toobig(pCtx);
647 void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
648 sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
650 int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
651 Mem *pOut;
653 #ifdef SQLITE_ENABLE_API_ARMOR
654 if( pCtx==0 ) return SQLITE_MISUSE_BKPT;
655 #endif
656 pOut = pCtx->pOut;
657 assert( sqlite3_mutex_held(pOut->db->mutex) );
658 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
659 sqlite3_result_error_toobig(pCtx);
660 return SQLITE_TOOBIG;
662 #ifndef SQLITE_OMIT_INCRBLOB
663 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
664 return SQLITE_OK;
665 #else
666 return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
667 #endif
669 void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
670 #ifdef SQLITE_ENABLE_API_ARMOR
671 if( pCtx==0 ) return;
672 #endif
673 pCtx->isError = errCode ? errCode : -1;
674 #ifdef SQLITE_DEBUG
675 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
676 #endif
677 if( pCtx->pOut->flags & MEM_Null ){
678 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
679 SQLITE_STATIC);
683 /* Force an SQLITE_TOOBIG error. */
684 void sqlite3_result_error_toobig(sqlite3_context *pCtx){
685 #ifdef SQLITE_ENABLE_API_ARMOR
686 if( pCtx==0 ) return;
687 #endif
688 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
689 pCtx->isError = SQLITE_TOOBIG;
690 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
691 SQLITE_UTF8, SQLITE_STATIC);
694 /* An SQLITE_NOMEM error. */
695 void sqlite3_result_error_nomem(sqlite3_context *pCtx){
696 #ifdef SQLITE_ENABLE_API_ARMOR
697 if( pCtx==0 ) return;
698 #endif
699 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
700 sqlite3VdbeMemSetNull(pCtx->pOut);
701 pCtx->isError = SQLITE_NOMEM_BKPT;
702 sqlite3OomFault(pCtx->pOut->db);
705 #ifndef SQLITE_UNTESTABLE
706 /* Force the INT64 value currently stored as the result to be
707 ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
708 ** test-control.
710 void sqlite3ResultIntReal(sqlite3_context *pCtx){
711 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
712 if( pCtx->pOut->flags & MEM_Int ){
713 pCtx->pOut->flags &= ~MEM_Int;
714 pCtx->pOut->flags |= MEM_IntReal;
717 #endif
721 ** This function is called after a transaction has been committed. It
722 ** invokes callbacks registered with sqlite3_wal_hook() as required.
724 static int doWalCallbacks(sqlite3 *db){
725 int rc = SQLITE_OK;
726 #ifndef SQLITE_OMIT_WAL
727 int i;
728 for(i=0; i<db->nDb; i++){
729 Btree *pBt = db->aDb[i].pBt;
730 if( pBt ){
731 int nEntry;
732 sqlite3BtreeEnter(pBt);
733 nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
734 sqlite3BtreeLeave(pBt);
735 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
736 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
740 #endif
741 return rc;
746 ** Execute the statement pStmt, either until a row of data is ready, the
747 ** statement is completely executed or an error occurs.
749 ** This routine implements the bulk of the logic behind the sqlite_step()
750 ** API. The only thing omitted is the automatic recompile if a
751 ** schema change has occurred. That detail is handled by the
752 ** outer sqlite3_step() wrapper procedure.
754 static int sqlite3Step(Vdbe *p){
755 sqlite3 *db;
756 int rc;
758 assert(p);
759 db = p->db;
760 if( p->eVdbeState!=VDBE_RUN_STATE ){
761 restart_step:
762 if( p->eVdbeState==VDBE_READY_STATE ){
763 if( p->expired ){
764 p->rc = SQLITE_SCHEMA;
765 rc = SQLITE_ERROR;
766 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
767 /* If this statement was prepared using saved SQL and an
768 ** error has occurred, then return the error code in p->rc to the
769 ** caller. Set the error code in the database handle to the same
770 ** value.
772 rc = sqlite3VdbeTransferError(p);
774 goto end_of_step;
777 /* If there are no other statements currently running, then
778 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
779 ** from interrupting a statement that has not yet started.
781 if( db->nVdbeActive==0 ){
782 AtomicStore(&db->u1.isInterrupted, 0);
785 assert( db->nVdbeWrite>0 || db->autoCommit==0
786 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
789 #ifndef SQLITE_OMIT_TRACE
790 if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
791 && !db->init.busy && p->zSql ){
792 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
793 }else{
794 assert( p->startTime==0 );
796 #endif
798 db->nVdbeActive++;
799 if( p->readOnly==0 ) db->nVdbeWrite++;
800 if( p->bIsReader ) db->nVdbeRead++;
801 p->pc = 0;
802 p->eVdbeState = VDBE_RUN_STATE;
803 }else
805 if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
806 /* We used to require that sqlite3_reset() be called before retrying
807 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
808 ** with version 3.7.0, we changed this so that sqlite3_reset() would
809 ** be called automatically instead of throwing the SQLITE_MISUSE error.
810 ** This "automatic-reset" change is not technically an incompatibility,
811 ** since any application that receives an SQLITE_MISUSE is broken by
812 ** definition.
814 ** Nevertheless, some published applications that were originally written
815 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
816 ** returns, and those were broken by the automatic-reset change. As a
817 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
818 ** legacy behavior of returning SQLITE_MISUSE for cases where the
819 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
820 ** or SQLITE_BUSY error.
822 #ifdef SQLITE_OMIT_AUTORESET
823 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
824 sqlite3_reset((sqlite3_stmt*)p);
825 }else{
826 return SQLITE_MISUSE_BKPT;
828 #else
829 sqlite3_reset((sqlite3_stmt*)p);
830 #endif
831 assert( p->eVdbeState==VDBE_READY_STATE );
832 goto restart_step;
836 #ifdef SQLITE_DEBUG
837 p->rcApp = SQLITE_OK;
838 #endif
839 #ifndef SQLITE_OMIT_EXPLAIN
840 if( p->explain ){
841 rc = sqlite3VdbeList(p);
842 }else
843 #endif /* SQLITE_OMIT_EXPLAIN */
845 db->nVdbeExec++;
846 rc = sqlite3VdbeExec(p);
847 db->nVdbeExec--;
850 if( rc==SQLITE_ROW ){
851 assert( p->rc==SQLITE_OK );
852 assert( db->mallocFailed==0 );
853 db->errCode = SQLITE_ROW;
854 return SQLITE_ROW;
855 }else{
856 #ifndef SQLITE_OMIT_TRACE
857 /* If the statement completed successfully, invoke the profile callback */
858 checkProfileCallback(db, p);
859 #endif
860 p->pResultRow = 0;
861 if( rc==SQLITE_DONE && db->autoCommit ){
862 assert( p->rc==SQLITE_OK );
863 p->rc = doWalCallbacks(db);
864 if( p->rc!=SQLITE_OK ){
865 rc = SQLITE_ERROR;
867 }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
868 /* If this statement was prepared using saved SQL and an
869 ** error has occurred, then return the error code in p->rc to the
870 ** caller. Set the error code in the database handle to the same value.
872 rc = sqlite3VdbeTransferError(p);
876 db->errCode = rc;
877 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
878 p->rc = SQLITE_NOMEM_BKPT;
879 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
881 end_of_step:
882 /* There are only a limited number of result codes allowed from the
883 ** statements prepared using the legacy sqlite3_prepare() interface */
884 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
885 || rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
886 || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
888 return (rc&db->errMask);
892 ** This is the top-level implementation of sqlite3_step(). Call
893 ** sqlite3Step() to do most of the work. If a schema error occurs,
894 ** call sqlite3Reprepare() and try again.
896 int sqlite3_step(sqlite3_stmt *pStmt){
897 int rc = SQLITE_OK; /* Result from sqlite3Step() */
898 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
899 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
900 sqlite3 *db; /* The database connection */
902 if( vdbeSafetyNotNull(v) ){
903 return SQLITE_MISUSE_BKPT;
905 db = v->db;
906 sqlite3_mutex_enter(db->mutex);
907 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
908 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
909 int savedPc = v->pc;
910 rc = sqlite3Reprepare(v);
911 if( rc!=SQLITE_OK ){
912 /* This case occurs after failing to recompile an sql statement.
913 ** The error message from the SQL compiler has already been loaded
914 ** into the database handle. This block copies the error message
915 ** from the database handle into the statement and sets the statement
916 ** program counter to 0 to ensure that when the statement is
917 ** finalized or reset the parser error message is available via
918 ** sqlite3_errmsg() and sqlite3_errcode().
920 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
921 sqlite3DbFree(db, v->zErrMsg);
922 if( !db->mallocFailed ){
923 v->zErrMsg = sqlite3DbStrDup(db, zErr);
924 v->rc = rc = sqlite3ApiExit(db, rc);
925 } else {
926 v->zErrMsg = 0;
927 v->rc = rc = SQLITE_NOMEM_BKPT;
929 break;
931 sqlite3_reset(pStmt);
932 if( savedPc>=0 ){
933 /* Setting minWriteFileFormat to 254 is a signal to the OP_Init and
934 ** OP_Trace opcodes to *not* perform SQLITE_TRACE_STMT because it has
935 ** already been done once on a prior invocation that failed due to
936 ** SQLITE_SCHEMA. tag-20220401a */
937 v->minWriteFileFormat = 254;
939 assert( v->expired==0 );
941 sqlite3_mutex_leave(db->mutex);
942 return rc;
947 ** Extract the user data from a sqlite3_context structure and return a
948 ** pointer to it.
950 void *sqlite3_user_data(sqlite3_context *p){
951 #ifdef SQLITE_ENABLE_API_ARMOR
952 if( p==0 ) return 0;
953 #endif
954 assert( p && p->pFunc );
955 return p->pFunc->pUserData;
959 ** Extract the user data from a sqlite3_context structure and return a
960 ** pointer to it.
962 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
963 ** returns a copy of the pointer to the database connection (the 1st
964 ** parameter) of the sqlite3_create_function() and
965 ** sqlite3_create_function16() routines that originally registered the
966 ** application defined function.
968 sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
969 #ifdef SQLITE_ENABLE_API_ARMOR
970 if( p==0 ) return 0;
971 #else
972 assert( p && p->pOut );
973 #endif
974 return p->pOut->db;
978 ** If this routine is invoked from within an xColumn method of a virtual
979 ** table, then it returns true if and only if the the call is during an
980 ** UPDATE operation and the value of the column will not be modified
981 ** by the UPDATE.
983 ** If this routine is called from any context other than within the
984 ** xColumn method of a virtual table, then the return value is meaningless
985 ** and arbitrary.
987 ** Virtual table implements might use this routine to optimize their
988 ** performance by substituting a NULL result, or some other light-weight
989 ** value, as a signal to the xUpdate routine that the column is unchanged.
991 int sqlite3_vtab_nochange(sqlite3_context *p){
992 #ifdef SQLITE_ENABLE_API_ARMOR
993 if( p==0 ) return 0;
994 #else
995 assert( p );
996 #endif
997 return sqlite3_value_nochange(p->pOut);
1001 ** The destructor function for a ValueList object. This needs to be
1002 ** a separate function, unknowable to the application, to ensure that
1003 ** calls to sqlite3_vtab_in_first()/sqlite3_vtab_in_next() that are not
1004 ** preceded by activation of IN processing via sqlite3_vtab_int() do not
1005 ** try to access a fake ValueList object inserted by a hostile extension.
1007 void sqlite3VdbeValueListFree(void *pToDelete){
1008 sqlite3_free(pToDelete);
1012 ** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
1013 ** sqlite3_vtab_in_next() (if bNext!=0).
1015 static int valueFromValueList(
1016 sqlite3_value *pVal, /* Pointer to the ValueList object */
1017 sqlite3_value **ppOut, /* Store the next value from the list here */
1018 int bNext /* 1 for _next(). 0 for _first() */
1020 int rc;
1021 ValueList *pRhs;
1023 *ppOut = 0;
1024 if( pVal==0 ) return SQLITE_MISUSE_BKPT;
1025 if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
1026 return SQLITE_ERROR;
1027 }else{
1028 assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
1029 (MEM_Null|MEM_Term|MEM_Subtype) );
1030 assert( pVal->eSubtype=='p' );
1031 assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
1032 pRhs = (ValueList*)pVal->z;
1034 if( bNext ){
1035 rc = sqlite3BtreeNext(pRhs->pCsr, 0);
1036 }else{
1037 int dummy = 0;
1038 rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
1039 assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
1040 if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
1042 if( rc==SQLITE_OK ){
1043 u32 sz; /* Size of current row in bytes */
1044 Mem sMem; /* Raw content of current row */
1045 memset(&sMem, 0, sizeof(sMem));
1046 sz = sqlite3BtreePayloadSize(pRhs->pCsr);
1047 rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
1048 if( rc==SQLITE_OK ){
1049 u8 *zBuf = (u8*)sMem.z;
1050 u32 iSerial;
1051 sqlite3_value *pOut = pRhs->pOut;
1052 int iOff = 1 + getVarint32(&zBuf[1], iSerial);
1053 sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
1054 pOut->enc = ENC(pOut->db);
1055 if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
1056 rc = SQLITE_NOMEM;
1057 }else{
1058 *ppOut = pOut;
1061 sqlite3VdbeMemRelease(&sMem);
1063 return rc;
1067 ** Set the iterator value pVal to point to the first value in the set.
1068 ** Set (*ppOut) to point to this value before returning.
1070 int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
1071 return valueFromValueList(pVal, ppOut, 0);
1075 ** Set the iterator value pVal to point to the next value in the set.
1076 ** Set (*ppOut) to point to this value before returning.
1078 int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
1079 return valueFromValueList(pVal, ppOut, 1);
1083 ** Return the current time for a statement. If the current time
1084 ** is requested more than once within the same run of a single prepared
1085 ** statement, the exact same time is returned for each invocation regardless
1086 ** of the amount of time that elapses between invocations. In other words,
1087 ** the time returned is always the time of the first call.
1089 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
1090 int rc;
1091 #ifndef SQLITE_ENABLE_STAT4
1092 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
1093 assert( p->pVdbe!=0 );
1094 #else
1095 sqlite3_int64 iTime = 0;
1096 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
1097 #endif
1098 if( *piTime==0 ){
1099 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
1100 if( rc ) *piTime = 0;
1102 return *piTime;
1106 ** Create a new aggregate context for p and return a pointer to
1107 ** its pMem->z element.
1109 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
1110 Mem *pMem = p->pMem;
1111 assert( (pMem->flags & MEM_Agg)==0 );
1112 if( nByte<=0 ){
1113 sqlite3VdbeMemSetNull(pMem);
1114 pMem->z = 0;
1115 }else{
1116 sqlite3VdbeMemClearAndResize(pMem, nByte);
1117 pMem->flags = MEM_Agg;
1118 pMem->u.pDef = p->pFunc;
1119 if( pMem->z ){
1120 memset(pMem->z, 0, nByte);
1123 return (void*)pMem->z;
1127 ** Allocate or return the aggregate context for a user function. A new
1128 ** context is allocated on the first call. Subsequent calls return the
1129 ** same context that was returned on prior calls.
1131 void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
1132 assert( p && p->pFunc && p->pFunc->xFinalize );
1133 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
1134 testcase( nByte<0 );
1135 if( (p->pMem->flags & MEM_Agg)==0 ){
1136 return createAggContext(p, nByte);
1137 }else{
1138 return (void*)p->pMem->z;
1143 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
1144 ** the user-function defined by pCtx.
1146 ** The left-most argument is 0.
1148 ** Undocumented behavior: If iArg is negative then access a cache of
1149 ** auxiliary data pointers that is available to all functions within a
1150 ** single prepared statement. The iArg values must match.
1152 void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
1153 AuxData *pAuxData;
1155 #ifdef SQLITE_ENABLE_API_ARMOR
1156 if( pCtx==0 ) return 0;
1157 #endif
1158 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1159 #if SQLITE_ENABLE_STAT4
1160 if( pCtx->pVdbe==0 ) return 0;
1161 #else
1162 assert( pCtx->pVdbe!=0 );
1163 #endif
1164 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1165 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1166 return pAuxData->pAux;
1169 return 0;
1173 ** Set the auxiliary data pointer and delete function, for the iArg'th
1174 ** argument to the user-function defined by pCtx. Any previous value is
1175 ** deleted by calling the delete function specified when it was set.
1177 ** The left-most argument is 0.
1179 ** Undocumented behavior: If iArg is negative then make the data available
1180 ** to all functions within the current prepared statement using iArg as an
1181 ** access code.
1183 void sqlite3_set_auxdata(
1184 sqlite3_context *pCtx,
1185 int iArg,
1186 void *pAux,
1187 void (*xDelete)(void*)
1189 AuxData *pAuxData;
1190 Vdbe *pVdbe;
1192 #ifdef SQLITE_ENABLE_API_ARMOR
1193 if( pCtx==0 ) return;
1194 #endif
1195 pVdbe= pCtx->pVdbe;
1196 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1197 #ifdef SQLITE_ENABLE_STAT4
1198 if( pVdbe==0 ) goto failed;
1199 #else
1200 assert( pVdbe!=0 );
1201 #endif
1203 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1204 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1205 break;
1208 if( pAuxData==0 ){
1209 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
1210 if( !pAuxData ) goto failed;
1211 pAuxData->iAuxOp = pCtx->iOp;
1212 pAuxData->iAuxArg = iArg;
1213 pAuxData->pNextAux = pVdbe->pAuxData;
1214 pVdbe->pAuxData = pAuxData;
1215 if( pCtx->isError==0 ) pCtx->isError = -1;
1216 }else if( pAuxData->xDeleteAux ){
1217 pAuxData->xDeleteAux(pAuxData->pAux);
1220 pAuxData->pAux = pAux;
1221 pAuxData->xDeleteAux = xDelete;
1222 return;
1224 failed:
1225 if( xDelete ){
1226 xDelete(pAux);
1230 #ifndef SQLITE_OMIT_DEPRECATED
1232 ** Return the number of times the Step function of an aggregate has been
1233 ** called.
1235 ** This function is deprecated. Do not use it for new code. It is
1236 ** provide only to avoid breaking legacy code. New aggregate function
1237 ** implementations should keep their own counts within their aggregate
1238 ** context.
1240 int sqlite3_aggregate_count(sqlite3_context *p){
1241 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
1242 return p->pMem->n;
1244 #endif
1247 ** Return the number of columns in the result set for the statement pStmt.
1249 int sqlite3_column_count(sqlite3_stmt *pStmt){
1250 Vdbe *pVm = (Vdbe *)pStmt;
1251 if( pVm==0 ) return 0;
1252 return pVm->nResColumn;
1256 ** Return the number of values available from the current row of the
1257 ** currently executing statement pStmt.
1259 int sqlite3_data_count(sqlite3_stmt *pStmt){
1260 Vdbe *pVm = (Vdbe *)pStmt;
1261 if( pVm==0 || pVm->pResultRow==0 ) return 0;
1262 return pVm->nResColumn;
1266 ** Return a pointer to static memory containing an SQL NULL value.
1268 static const Mem *columnNullValue(void){
1269 /* Even though the Mem structure contains an element
1270 ** of type i64, on certain architectures (x86) with certain compiler
1271 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
1272 ** instead of an 8-byte one. This all works fine, except that when
1273 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
1274 ** that a Mem structure is located on an 8-byte boundary. To prevent
1275 ** these assert()s from failing, when building with SQLITE_DEBUG defined
1276 ** using gcc, we force nullMem to be 8-byte aligned using the magical
1277 ** __attribute__((aligned(8))) macro. */
1278 static const Mem nullMem
1279 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
1280 __attribute__((aligned(8)))
1281 #endif
1283 /* .u = */ {0},
1284 /* .z = */ (char*)0,
1285 /* .n = */ (int)0,
1286 /* .flags = */ (u16)MEM_Null,
1287 /* .enc = */ (u8)0,
1288 /* .eSubtype = */ (u8)0,
1289 /* .db = */ (sqlite3*)0,
1290 /* .szMalloc = */ (int)0,
1291 /* .uTemp = */ (u32)0,
1292 /* .zMalloc = */ (char*)0,
1293 /* .xDel = */ (void(*)(void*))0,
1294 #ifdef SQLITE_DEBUG
1295 /* .pScopyFrom = */ (Mem*)0,
1296 /* .mScopyFlags= */ 0,
1297 #endif
1299 return &nullMem;
1303 ** Check to see if column iCol of the given statement is valid. If
1304 ** it is, return a pointer to the Mem for the value of that column.
1305 ** If iCol is not valid, return a pointer to a Mem which has a value
1306 ** of NULL.
1308 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
1309 Vdbe *pVm;
1310 Mem *pOut;
1312 pVm = (Vdbe *)pStmt;
1313 if( pVm==0 ) return (Mem*)columnNullValue();
1314 assert( pVm->db );
1315 sqlite3_mutex_enter(pVm->db->mutex);
1316 if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
1317 pOut = &pVm->pResultRow[i];
1318 }else{
1319 sqlite3Error(pVm->db, SQLITE_RANGE);
1320 pOut = (Mem*)columnNullValue();
1322 return pOut;
1326 ** This function is called after invoking an sqlite3_value_XXX function on a
1327 ** column value (i.e. a value returned by evaluating an SQL expression in the
1328 ** select list of a SELECT statement) that may cause a malloc() failure. If
1329 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
1330 ** code of statement pStmt set to SQLITE_NOMEM.
1332 ** Specifically, this is called from within:
1334 ** sqlite3_column_int()
1335 ** sqlite3_column_int64()
1336 ** sqlite3_column_text()
1337 ** sqlite3_column_text16()
1338 ** sqlite3_column_real()
1339 ** sqlite3_column_bytes()
1340 ** sqlite3_column_bytes16()
1341 ** sqlite3_column_blob()
1343 static void columnMallocFailure(sqlite3_stmt *pStmt)
1345 /* If malloc() failed during an encoding conversion within an
1346 ** sqlite3_column_XXX API, then set the return code of the statement to
1347 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
1348 ** and _finalize() will return NOMEM.
1350 Vdbe *p = (Vdbe *)pStmt;
1351 if( p ){
1352 assert( p->db!=0 );
1353 assert( sqlite3_mutex_held(p->db->mutex) );
1354 p->rc = sqlite3ApiExit(p->db, p->rc);
1355 sqlite3_mutex_leave(p->db->mutex);
1359 /**************************** sqlite3_column_ *******************************
1360 ** The following routines are used to access elements of the current row
1361 ** in the result set.
1363 const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
1364 const void *val;
1365 val = sqlite3_value_blob( columnMem(pStmt,i) );
1366 /* Even though there is no encoding conversion, value_blob() might
1367 ** need to call malloc() to expand the result of a zeroblob()
1368 ** expression.
1370 columnMallocFailure(pStmt);
1371 return val;
1373 int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
1374 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
1375 columnMallocFailure(pStmt);
1376 return val;
1378 int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
1379 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
1380 columnMallocFailure(pStmt);
1381 return val;
1383 double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
1384 double val = sqlite3_value_double( columnMem(pStmt,i) );
1385 columnMallocFailure(pStmt);
1386 return val;
1388 int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
1389 int val = sqlite3_value_int( columnMem(pStmt,i) );
1390 columnMallocFailure(pStmt);
1391 return val;
1393 sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
1394 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
1395 columnMallocFailure(pStmt);
1396 return val;
1398 const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
1399 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
1400 columnMallocFailure(pStmt);
1401 return val;
1403 sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
1404 Mem *pOut = columnMem(pStmt, i);
1405 if( pOut->flags&MEM_Static ){
1406 pOut->flags &= ~MEM_Static;
1407 pOut->flags |= MEM_Ephem;
1409 columnMallocFailure(pStmt);
1410 return (sqlite3_value *)pOut;
1412 #ifndef SQLITE_OMIT_UTF16
1413 const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
1414 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
1415 columnMallocFailure(pStmt);
1416 return val;
1418 #endif /* SQLITE_OMIT_UTF16 */
1419 int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
1420 int iType = sqlite3_value_type( columnMem(pStmt,i) );
1421 columnMallocFailure(pStmt);
1422 return iType;
1426 ** Column names appropriate for EXPLAIN or EXPLAIN QUERY PLAN.
1428 static const char * const azExplainColNames8[] = {
1429 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", /* EXPLAIN */
1430 "id", "parent", "notused", "detail" /* EQP */
1432 static const u16 azExplainColNames16data[] = {
1433 /* 0 */ 'a', 'd', 'd', 'r', 0,
1434 /* 5 */ 'o', 'p', 'c', 'o', 'd', 'e', 0,
1435 /* 12 */ 'p', '1', 0,
1436 /* 15 */ 'p', '2', 0,
1437 /* 18 */ 'p', '3', 0,
1438 /* 21 */ 'p', '4', 0,
1439 /* 24 */ 'p', '5', 0,
1440 /* 27 */ 'c', 'o', 'm', 'm', 'e', 'n', 't', 0,
1441 /* 35 */ 'i', 'd', 0,
1442 /* 38 */ 'p', 'a', 'r', 'e', 'n', 't', 0,
1443 /* 45 */ 'n', 'o', 't', 'u', 's', 'e', 'd', 0,
1444 /* 53 */ 'd', 'e', 't', 'a', 'i', 'l', 0
1446 static const u8 iExplainColNames16[] = {
1447 0, 5, 12, 15, 18, 21, 24, 27,
1448 35, 38, 45, 53
1452 ** Convert the N-th element of pStmt->pColName[] into a string using
1453 ** xFunc() then return that string. If N is out of range, return 0.
1455 ** There are up to 5 names for each column. useType determines which
1456 ** name is returned. Here are the names:
1458 ** 0 The column name as it should be displayed for output
1459 ** 1 The datatype name for the column
1460 ** 2 The name of the database that the column derives from
1461 ** 3 The name of the table that the column derives from
1462 ** 4 The name of the table column that the result column derives from
1464 ** If the result is not a simple column reference (if it is an expression
1465 ** or a constant) then useTypes 2, 3, and 4 return NULL.
1467 static const void *columnName(
1468 sqlite3_stmt *pStmt, /* The statement */
1469 int N, /* Which column to get the name for */
1470 int useUtf16, /* True to return the name as UTF16 */
1471 int useType /* What type of name */
1473 const void *ret;
1474 Vdbe *p;
1475 int n;
1476 sqlite3 *db;
1477 #ifdef SQLITE_ENABLE_API_ARMOR
1478 if( pStmt==0 ){
1479 (void)SQLITE_MISUSE_BKPT;
1480 return 0;
1482 #endif
1483 if( N<0 ) return 0;
1484 ret = 0;
1485 p = (Vdbe *)pStmt;
1486 db = p->db;
1487 assert( db!=0 );
1488 sqlite3_mutex_enter(db->mutex);
1490 if( p->explain ){
1491 if( useType>0 ) goto columnName_end;
1492 n = p->explain==1 ? 8 : 4;
1493 if( N>=n ) goto columnName_end;
1494 if( useUtf16 ){
1495 int i = iExplainColNames16[N + 8*p->explain - 8];
1496 ret = (void*)&azExplainColNames16data[i];
1497 }else{
1498 ret = (void*)azExplainColNames8[N + 8*p->explain - 8];
1500 goto columnName_end;
1502 n = p->nResColumn;
1503 if( N<n ){
1504 u8 prior_mallocFailed = db->mallocFailed;
1505 N += useType*n;
1506 #ifndef SQLITE_OMIT_UTF16
1507 if( useUtf16 ){
1508 ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
1509 }else
1510 #endif
1512 ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
1514 /* A malloc may have failed inside of the _text() call. If this
1515 ** is the case, clear the mallocFailed flag and return NULL.
1517 assert( db->mallocFailed==0 || db->mallocFailed==1 );
1518 if( db->mallocFailed > prior_mallocFailed ){
1519 sqlite3OomClear(db);
1520 ret = 0;
1523 columnName_end:
1524 sqlite3_mutex_leave(db->mutex);
1525 return ret;
1529 ** Return the name of the Nth column of the result set returned by SQL
1530 ** statement pStmt.
1532 const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
1533 return columnName(pStmt, N, 0, COLNAME_NAME);
1535 #ifndef SQLITE_OMIT_UTF16
1536 const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
1537 return columnName(pStmt, N, 1, COLNAME_NAME);
1539 #endif
1542 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
1543 ** not define OMIT_DECLTYPE.
1545 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
1546 # error "Must not define both SQLITE_OMIT_DECLTYPE \
1547 and SQLITE_ENABLE_COLUMN_METADATA"
1548 #endif
1550 #ifndef SQLITE_OMIT_DECLTYPE
1552 ** Return the column declaration type (if applicable) of the 'i'th column
1553 ** of the result set of SQL statement pStmt.
1555 const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
1556 return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
1558 #ifndef SQLITE_OMIT_UTF16
1559 const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
1560 return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
1562 #endif /* SQLITE_OMIT_UTF16 */
1563 #endif /* SQLITE_OMIT_DECLTYPE */
1565 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1567 ** Return the name of the database from which a result column derives.
1568 ** NULL is returned if the result column is an expression or constant or
1569 ** anything else which is not an unambiguous reference to a database column.
1571 const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
1572 return columnName(pStmt, N, 0, COLNAME_DATABASE);
1574 #ifndef SQLITE_OMIT_UTF16
1575 const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
1576 return columnName(pStmt, N, 1, COLNAME_DATABASE);
1578 #endif /* SQLITE_OMIT_UTF16 */
1581 ** Return the name of the table from which a result column derives.
1582 ** NULL is returned if the result column is an expression or constant or
1583 ** anything else which is not an unambiguous reference to a database column.
1585 const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
1586 return columnName(pStmt, N, 0, COLNAME_TABLE);
1588 #ifndef SQLITE_OMIT_UTF16
1589 const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
1590 return columnName(pStmt, N, 1, COLNAME_TABLE);
1592 #endif /* SQLITE_OMIT_UTF16 */
1595 ** Return the name of the table column from which a result column derives.
1596 ** NULL is returned if the result column is an expression or constant or
1597 ** anything else which is not an unambiguous reference to a database column.
1599 const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
1600 return columnName(pStmt, N, 0, COLNAME_COLUMN);
1602 #ifndef SQLITE_OMIT_UTF16
1603 const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
1604 return columnName(pStmt, N, 1, COLNAME_COLUMN);
1606 #endif /* SQLITE_OMIT_UTF16 */
1607 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
1610 /******************************* sqlite3_bind_ ***************************
1612 ** Routines used to attach values to wildcards in a compiled SQL statement.
1615 ** Unbind the value bound to variable i in virtual machine p. This is the
1616 ** the same as binding a NULL value to the column. If the "i" parameter is
1617 ** out of range, then SQLITE_RANGE is returned. Otherwise SQLITE_OK.
1619 ** A successful evaluation of this routine acquires the mutex on p.
1620 ** the mutex is released if any kind of error occurs.
1622 ** The error code stored in database p->db is overwritten with the return
1623 ** value in any case.
1625 static int vdbeUnbind(Vdbe *p, unsigned int i){
1626 Mem *pVar;
1627 if( vdbeSafetyNotNull(p) ){
1628 return SQLITE_MISUSE_BKPT;
1630 sqlite3_mutex_enter(p->db->mutex);
1631 if( p->eVdbeState!=VDBE_READY_STATE ){
1632 sqlite3Error(p->db, SQLITE_MISUSE_BKPT);
1633 sqlite3_mutex_leave(p->db->mutex);
1634 sqlite3_log(SQLITE_MISUSE,
1635 "bind on a busy prepared statement: [%s]", p->zSql);
1636 return SQLITE_MISUSE_BKPT;
1638 if( i>=(unsigned int)p->nVar ){
1639 sqlite3Error(p->db, SQLITE_RANGE);
1640 sqlite3_mutex_leave(p->db->mutex);
1641 return SQLITE_RANGE;
1643 pVar = &p->aVar[i];
1644 sqlite3VdbeMemRelease(pVar);
1645 pVar->flags = MEM_Null;
1646 p->db->errCode = SQLITE_OK;
1648 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
1649 ** binding a new value to this variable invalidates the current query plan.
1651 ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
1652 ** parameter in the WHERE clause might influence the choice of query plan
1653 ** for a statement, then the statement will be automatically recompiled,
1654 ** as if there had been a schema change, on the first sqlite3_step() call
1655 ** following any change to the bindings of that parameter.
1657 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
1658 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
1659 p->expired = 1;
1661 return SQLITE_OK;
1665 ** Bind a text or BLOB value.
1667 static int bindText(
1668 sqlite3_stmt *pStmt, /* The statement to bind against */
1669 int i, /* Index of the parameter to bind */
1670 const void *zData, /* Pointer to the data to be bound */
1671 i64 nData, /* Number of bytes of data to be bound */
1672 void (*xDel)(void*), /* Destructor for the data */
1673 u8 encoding /* Encoding for the data */
1675 Vdbe *p = (Vdbe *)pStmt;
1676 Mem *pVar;
1677 int rc;
1679 rc = vdbeUnbind(p, (u32)(i-1));
1680 if( rc==SQLITE_OK ){
1681 if( zData!=0 ){
1682 pVar = &p->aVar[i-1];
1683 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
1684 if( rc==SQLITE_OK && encoding!=0 ){
1685 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
1687 if( rc ){
1688 sqlite3Error(p->db, rc);
1689 rc = sqlite3ApiExit(p->db, rc);
1692 sqlite3_mutex_leave(p->db->mutex);
1693 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
1694 xDel((void*)zData);
1696 return rc;
1701 ** Bind a blob value to an SQL statement variable.
1703 int sqlite3_bind_blob(
1704 sqlite3_stmt *pStmt,
1705 int i,
1706 const void *zData,
1707 int nData,
1708 void (*xDel)(void*)
1710 #ifdef SQLITE_ENABLE_API_ARMOR
1711 if( nData<0 ) return SQLITE_MISUSE_BKPT;
1712 #endif
1713 return bindText(pStmt, i, zData, nData, xDel, 0);
1715 int sqlite3_bind_blob64(
1716 sqlite3_stmt *pStmt,
1717 int i,
1718 const void *zData,
1719 sqlite3_uint64 nData,
1720 void (*xDel)(void*)
1722 assert( xDel!=SQLITE_DYNAMIC );
1723 return bindText(pStmt, i, zData, nData, xDel, 0);
1725 int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
1726 int rc;
1727 Vdbe *p = (Vdbe *)pStmt;
1728 rc = vdbeUnbind(p, (u32)(i-1));
1729 if( rc==SQLITE_OK ){
1730 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
1731 sqlite3_mutex_leave(p->db->mutex);
1733 return rc;
1735 int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
1736 return sqlite3_bind_int64(p, i, (i64)iValue);
1738 int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
1739 int rc;
1740 Vdbe *p = (Vdbe *)pStmt;
1741 rc = vdbeUnbind(p, (u32)(i-1));
1742 if( rc==SQLITE_OK ){
1743 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
1744 sqlite3_mutex_leave(p->db->mutex);
1746 return rc;
1748 int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
1749 int rc;
1750 Vdbe *p = (Vdbe*)pStmt;
1751 rc = vdbeUnbind(p, (u32)(i-1));
1752 if( rc==SQLITE_OK ){
1753 sqlite3_mutex_leave(p->db->mutex);
1755 return rc;
1757 int sqlite3_bind_pointer(
1758 sqlite3_stmt *pStmt,
1759 int i,
1760 void *pPtr,
1761 const char *zPTtype,
1762 void (*xDestructor)(void*)
1764 int rc;
1765 Vdbe *p = (Vdbe*)pStmt;
1766 rc = vdbeUnbind(p, (u32)(i-1));
1767 if( rc==SQLITE_OK ){
1768 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
1769 sqlite3_mutex_leave(p->db->mutex);
1770 }else if( xDestructor ){
1771 xDestructor(pPtr);
1773 return rc;
1775 int sqlite3_bind_text(
1776 sqlite3_stmt *pStmt,
1777 int i,
1778 const char *zData,
1779 int nData,
1780 void (*xDel)(void*)
1782 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
1784 int sqlite3_bind_text64(
1785 sqlite3_stmt *pStmt,
1786 int i,
1787 const char *zData,
1788 sqlite3_uint64 nData,
1789 void (*xDel)(void*),
1790 unsigned char enc
1792 assert( xDel!=SQLITE_DYNAMIC );
1793 if( enc!=SQLITE_UTF8 ){
1794 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
1795 nData &= ~(u16)1;
1797 return bindText(pStmt, i, zData, nData, xDel, enc);
1799 #ifndef SQLITE_OMIT_UTF16
1800 int sqlite3_bind_text16(
1801 sqlite3_stmt *pStmt,
1802 int i,
1803 const void *zData,
1804 int n,
1805 void (*xDel)(void*)
1807 return bindText(pStmt, i, zData, n & ~(u64)1, xDel, SQLITE_UTF16NATIVE);
1809 #endif /* SQLITE_OMIT_UTF16 */
1810 int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
1811 int rc;
1812 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
1813 case SQLITE_INTEGER: {
1814 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
1815 break;
1817 case SQLITE_FLOAT: {
1818 assert( pValue->flags & (MEM_Real|MEM_IntReal) );
1819 rc = sqlite3_bind_double(pStmt, i,
1820 (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
1822 break;
1824 case SQLITE_BLOB: {
1825 if( pValue->flags & MEM_Zero ){
1826 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
1827 }else{
1828 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
1830 break;
1832 case SQLITE_TEXT: {
1833 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
1834 pValue->enc);
1835 break;
1837 default: {
1838 rc = sqlite3_bind_null(pStmt, i);
1839 break;
1842 return rc;
1844 int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
1845 int rc;
1846 Vdbe *p = (Vdbe *)pStmt;
1847 rc = vdbeUnbind(p, (u32)(i-1));
1848 if( rc==SQLITE_OK ){
1849 #ifndef SQLITE_OMIT_INCRBLOB
1850 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1851 #else
1852 rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1853 #endif
1854 sqlite3_mutex_leave(p->db->mutex);
1856 return rc;
1858 int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
1859 int rc;
1860 Vdbe *p = (Vdbe *)pStmt;
1861 #ifdef SQLITE_ENABLE_API_ARMOR
1862 if( p==0 ) return SQLITE_MISUSE_BKPT;
1863 #endif
1864 sqlite3_mutex_enter(p->db->mutex);
1865 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
1866 rc = SQLITE_TOOBIG;
1867 }else{
1868 assert( (n & 0x7FFFFFFF)==n );
1869 rc = sqlite3_bind_zeroblob(pStmt, i, n);
1871 rc = sqlite3ApiExit(p->db, rc);
1872 sqlite3_mutex_leave(p->db->mutex);
1873 return rc;
1877 ** Return the number of wildcards that can be potentially bound to.
1878 ** This routine is added to support DBD::SQLite.
1880 int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
1881 Vdbe *p = (Vdbe*)pStmt;
1882 return p ? p->nVar : 0;
1886 ** Return the name of a wildcard parameter. Return NULL if the index
1887 ** is out of range or if the wildcard is unnamed.
1889 ** The result is always UTF-8.
1891 const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
1892 Vdbe *p = (Vdbe*)pStmt;
1893 if( p==0 ) return 0;
1894 return sqlite3VListNumToName(p->pVList, i);
1898 ** Given a wildcard parameter name, return the index of the variable
1899 ** with that name. If there is no variable with the given name,
1900 ** return 0.
1902 int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
1903 if( p==0 || zName==0 ) return 0;
1904 return sqlite3VListNameToNum(p->pVList, zName, nName);
1906 int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
1907 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
1911 ** Transfer all bindings from the first statement over to the second.
1913 int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1914 Vdbe *pFrom = (Vdbe*)pFromStmt;
1915 Vdbe *pTo = (Vdbe*)pToStmt;
1916 int i;
1917 assert( pTo->db==pFrom->db );
1918 assert( pTo->nVar==pFrom->nVar );
1919 sqlite3_mutex_enter(pTo->db->mutex);
1920 for(i=0; i<pFrom->nVar; i++){
1921 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
1923 sqlite3_mutex_leave(pTo->db->mutex);
1924 return SQLITE_OK;
1927 #ifndef SQLITE_OMIT_DEPRECATED
1929 ** Deprecated external interface. Internal/core SQLite code
1930 ** should call sqlite3TransferBindings.
1932 ** It is misuse to call this routine with statements from different
1933 ** database connections. But as this is a deprecated interface, we
1934 ** will not bother to check for that condition.
1936 ** If the two statements contain a different number of bindings, then
1937 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
1938 ** SQLITE_OK is returned.
1940 int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1941 Vdbe *pFrom = (Vdbe*)pFromStmt;
1942 Vdbe *pTo = (Vdbe*)pToStmt;
1943 if( pFrom->nVar!=pTo->nVar ){
1944 return SQLITE_ERROR;
1946 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
1947 if( pTo->expmask ){
1948 pTo->expired = 1;
1950 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
1951 if( pFrom->expmask ){
1952 pFrom->expired = 1;
1954 return sqlite3TransferBindings(pFromStmt, pToStmt);
1956 #endif
1959 ** Return the sqlite3* database handle to which the prepared statement given
1960 ** in the argument belongs. This is the same database handle that was
1961 ** the first argument to the sqlite3_prepare() that was used to create
1962 ** the statement in the first place.
1964 sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
1965 return pStmt ? ((Vdbe*)pStmt)->db : 0;
1969 ** Return true if the prepared statement is guaranteed to not modify the
1970 ** database.
1972 int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
1973 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
1977 ** Return 1 if the statement is an EXPLAIN and return 2 if the
1978 ** statement is an EXPLAIN QUERY PLAN
1980 int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
1981 return pStmt ? ((Vdbe*)pStmt)->explain : 0;
1985 ** Set the explain mode for a statement.
1987 int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode){
1988 Vdbe *v = (Vdbe*)pStmt;
1989 int rc;
1990 #ifdef SQLITE_ENABLE_API_ARMOR
1991 if( pStmt==0 ) return SQLITE_MISUSE_BKPT;
1992 #endif
1993 sqlite3_mutex_enter(v->db->mutex);
1994 if( ((int)v->explain)==eMode ){
1995 rc = SQLITE_OK;
1996 }else if( eMode<0 || eMode>2 ){
1997 rc = SQLITE_ERROR;
1998 }else if( (v->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
1999 rc = SQLITE_ERROR;
2000 }else if( v->eVdbeState!=VDBE_READY_STATE ){
2001 rc = SQLITE_BUSY;
2002 }else if( v->nMem>=10 && (eMode!=2 || v->haveEqpOps) ){
2003 /* No reprepare necessary */
2004 v->explain = eMode;
2005 rc = SQLITE_OK;
2006 }else{
2007 v->explain = eMode;
2008 rc = sqlite3Reprepare(v);
2009 v->haveEqpOps = eMode==2;
2011 if( v->explain ){
2012 v->nResColumn = 12 - 4*v->explain;
2013 }else{
2014 v->nResColumn = v->nResAlloc;
2016 sqlite3_mutex_leave(v->db->mutex);
2017 return rc;
2021 ** Return true if the prepared statement is in need of being reset.
2023 int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
2024 Vdbe *v = (Vdbe*)pStmt;
2025 return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
2029 ** Return a pointer to the next prepared statement after pStmt associated
2030 ** with database connection pDb. If pStmt is NULL, return the first
2031 ** prepared statement for the database connection. Return NULL if there
2032 ** are no more.
2034 sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
2035 sqlite3_stmt *pNext;
2036 #ifdef SQLITE_ENABLE_API_ARMOR
2037 if( !sqlite3SafetyCheckOk(pDb) ){
2038 (void)SQLITE_MISUSE_BKPT;
2039 return 0;
2041 #endif
2042 sqlite3_mutex_enter(pDb->mutex);
2043 if( pStmt==0 ){
2044 pNext = (sqlite3_stmt*)pDb->pVdbe;
2045 }else{
2046 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
2048 sqlite3_mutex_leave(pDb->mutex);
2049 return pNext;
2053 ** Return the value of a status counter for a prepared statement
2055 int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
2056 Vdbe *pVdbe = (Vdbe*)pStmt;
2057 u32 v;
2058 #ifdef SQLITE_ENABLE_API_ARMOR
2059 if( !pStmt
2060 || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
2062 (void)SQLITE_MISUSE_BKPT;
2063 return 0;
2065 #endif
2066 if( op==SQLITE_STMTSTATUS_MEMUSED ){
2067 sqlite3 *db = pVdbe->db;
2068 sqlite3_mutex_enter(db->mutex);
2069 v = 0;
2070 db->pnBytesFreed = (int*)&v;
2071 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
2072 db->lookaside.pEnd = db->lookaside.pStart;
2073 sqlite3VdbeDelete(pVdbe);
2074 db->pnBytesFreed = 0;
2075 db->lookaside.pEnd = db->lookaside.pTrueEnd;
2076 sqlite3_mutex_leave(db->mutex);
2077 }else{
2078 v = pVdbe->aCounter[op];
2079 if( resetFlag ) pVdbe->aCounter[op] = 0;
2081 return (int)v;
2085 ** Return the SQL associated with a prepared statement
2087 const char *sqlite3_sql(sqlite3_stmt *pStmt){
2088 Vdbe *p = (Vdbe *)pStmt;
2089 return p ? p->zSql : 0;
2093 ** Return the SQL associated with a prepared statement with
2094 ** bound parameters expanded. Space to hold the returned string is
2095 ** obtained from sqlite3_malloc(). The caller is responsible for
2096 ** freeing the returned string by passing it to sqlite3_free().
2098 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
2099 ** expanded bound parameters.
2101 char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
2102 #ifdef SQLITE_OMIT_TRACE
2103 return 0;
2104 #else
2105 char *z = 0;
2106 const char *zSql = sqlite3_sql(pStmt);
2107 if( zSql ){
2108 Vdbe *p = (Vdbe *)pStmt;
2109 sqlite3_mutex_enter(p->db->mutex);
2110 z = sqlite3VdbeExpandSql(p, zSql);
2111 sqlite3_mutex_leave(p->db->mutex);
2113 return z;
2114 #endif
2117 #ifdef SQLITE_ENABLE_NORMALIZE
2119 ** Return the normalized SQL associated with a prepared statement.
2121 const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
2122 Vdbe *p = (Vdbe *)pStmt;
2123 if( p==0 ) return 0;
2124 if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
2125 sqlite3_mutex_enter(p->db->mutex);
2126 p->zNormSql = sqlite3Normalize(p, p->zSql);
2127 sqlite3_mutex_leave(p->db->mutex);
2129 return p->zNormSql;
2131 #endif /* SQLITE_ENABLE_NORMALIZE */
2133 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2135 ** Allocate and populate an UnpackedRecord structure based on the serialized
2136 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
2137 ** if successful, or a NULL pointer if an OOM error is encountered.
2139 static UnpackedRecord *vdbeUnpackRecord(
2140 KeyInfo *pKeyInfo,
2141 int nKey,
2142 const void *pKey
2144 UnpackedRecord *pRet; /* Return value */
2146 pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
2147 if( pRet ){
2148 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
2149 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
2151 return pRet;
2155 ** This function is called from within a pre-update callback to retrieve
2156 ** a field of the row currently being updated or deleted.
2158 int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2159 PreUpdate *p;
2160 Mem *pMem;
2161 int rc = SQLITE_OK;
2163 #ifdef SQLITE_ENABLE_API_ARMOR
2164 if( db==0 || ppValue==0 ){
2165 return SQLITE_MISUSE_BKPT;
2167 #endif
2168 p = db->pPreUpdate;
2169 /* Test that this call is being made from within an SQLITE_DELETE or
2170 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
2171 if( !p || p->op==SQLITE_INSERT ){
2172 rc = SQLITE_MISUSE_BKPT;
2173 goto preupdate_old_out;
2175 if( p->pPk ){
2176 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2178 if( iIdx>=p->pCsr->nField || iIdx<0 ){
2179 rc = SQLITE_RANGE;
2180 goto preupdate_old_out;
2183 /* If the old.* record has not yet been loaded into memory, do so now. */
2184 if( p->pUnpacked==0 ){
2185 u32 nRec;
2186 u8 *aRec;
2188 assert( p->pCsr->eCurType==CURTYPE_BTREE );
2189 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
2190 aRec = sqlite3DbMallocRaw(db, nRec);
2191 if( !aRec ) goto preupdate_old_out;
2192 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
2193 if( rc==SQLITE_OK ){
2194 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
2195 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
2197 if( rc!=SQLITE_OK ){
2198 sqlite3DbFree(db, aRec);
2199 goto preupdate_old_out;
2201 p->aRecord = aRec;
2204 pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
2205 if( iIdx==p->pTab->iPKey ){
2206 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
2207 }else if( iIdx>=p->pUnpacked->nField ){
2208 *ppValue = (sqlite3_value *)columnNullValue();
2209 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
2210 if( pMem->flags & (MEM_Int|MEM_IntReal) ){
2211 testcase( pMem->flags & MEM_Int );
2212 testcase( pMem->flags & MEM_IntReal );
2213 sqlite3VdbeMemRealify(pMem);
2217 preupdate_old_out:
2218 sqlite3Error(db, rc);
2219 return sqlite3ApiExit(db, rc);
2221 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2223 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2225 ** This function is called from within a pre-update callback to retrieve
2226 ** the number of columns in the row being updated, deleted or inserted.
2228 int sqlite3_preupdate_count(sqlite3 *db){
2229 PreUpdate *p;
2230 #ifdef SQLITE_ENABLE_API_ARMOR
2231 p = db!=0 ? db->pPreUpdate : 0;
2232 #else
2233 p = db->pPreUpdate;
2234 #endif
2235 return (p ? p->keyinfo.nKeyField : 0);
2237 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2239 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2241 ** This function is designed to be called from within a pre-update callback
2242 ** only. It returns zero if the change that caused the callback was made
2243 ** immediately by a user SQL statement. Or, if the change was made by a
2244 ** trigger program, it returns the number of trigger programs currently
2245 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
2246 ** top-level trigger etc.).
2248 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
2249 ** or SET DEFAULT action is considered a trigger.
2251 int sqlite3_preupdate_depth(sqlite3 *db){
2252 PreUpdate *p;
2253 #ifdef SQLITE_ENABLE_API_ARMOR
2254 p = db!=0 ? db->pPreUpdate : 0;
2255 #else
2256 p = db->pPreUpdate;
2257 #endif
2258 return (p ? p->v->nFrame : 0);
2260 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2262 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2264 ** This function is designed to be called from within a pre-update callback
2265 ** only.
2267 int sqlite3_preupdate_blobwrite(sqlite3 *db){
2268 PreUpdate *p;
2269 #ifdef SQLITE_ENABLE_API_ARMOR
2270 p = db!=0 ? db->pPreUpdate : 0;
2271 #else
2272 p = db->pPreUpdate;
2273 #endif
2274 return (p ? p->iBlobWrite : -1);
2276 #endif
2278 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2280 ** This function is called from within a pre-update callback to retrieve
2281 ** a field of the row currently being updated or inserted.
2283 int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2284 PreUpdate *p;
2285 int rc = SQLITE_OK;
2286 Mem *pMem;
2288 #ifdef SQLITE_ENABLE_API_ARMOR
2289 if( db==0 || ppValue==0 ){
2290 return SQLITE_MISUSE_BKPT;
2292 #endif
2293 p = db->pPreUpdate;
2294 if( !p || p->op==SQLITE_DELETE ){
2295 rc = SQLITE_MISUSE_BKPT;
2296 goto preupdate_new_out;
2298 if( p->pPk && p->op!=SQLITE_UPDATE ){
2299 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2301 if( iIdx>=p->pCsr->nField || iIdx<0 ){
2302 rc = SQLITE_RANGE;
2303 goto preupdate_new_out;
2306 if( p->op==SQLITE_INSERT ){
2307 /* For an INSERT, memory cell p->iNewReg contains the serialized record
2308 ** that is being inserted. Deserialize it. */
2309 UnpackedRecord *pUnpack = p->pNewUnpacked;
2310 if( !pUnpack ){
2311 Mem *pData = &p->v->aMem[p->iNewReg];
2312 rc = ExpandBlob(pData);
2313 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2314 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
2315 if( !pUnpack ){
2316 rc = SQLITE_NOMEM;
2317 goto preupdate_new_out;
2319 p->pNewUnpacked = pUnpack;
2321 pMem = &pUnpack->aMem[iIdx];
2322 if( iIdx==p->pTab->iPKey ){
2323 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2324 }else if( iIdx>=pUnpack->nField ){
2325 pMem = (sqlite3_value *)columnNullValue();
2327 }else{
2328 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
2329 ** value. Make a copy of the cell contents and return a pointer to it.
2330 ** It is not safe to return a pointer to the memory cell itself as the
2331 ** caller may modify the value text encoding.
2333 assert( p->op==SQLITE_UPDATE );
2334 if( !p->aNew ){
2335 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
2336 if( !p->aNew ){
2337 rc = SQLITE_NOMEM;
2338 goto preupdate_new_out;
2341 assert( iIdx>=0 && iIdx<p->pCsr->nField );
2342 pMem = &p->aNew[iIdx];
2343 if( pMem->flags==0 ){
2344 if( iIdx==p->pTab->iPKey ){
2345 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2346 }else{
2347 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
2348 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2352 *ppValue = pMem;
2354 preupdate_new_out:
2355 sqlite3Error(db, rc);
2356 return sqlite3ApiExit(db, rc);
2358 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2360 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2362 ** Return status data for a single loop within query pStmt.
2364 int sqlite3_stmt_scanstatus_v2(
2365 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2366 int iScan, /* Index of loop to report on */
2367 int iScanStatusOp, /* Which metric to return */
2368 int flags,
2369 void *pOut /* OUT: Write the answer here */
2371 Vdbe *p = (Vdbe*)pStmt;
2372 VdbeOp *aOp;
2373 int nOp;
2374 ScanStatus *pScan = 0;
2375 int idx;
2377 #ifdef SQLITE_ENABLE_API_ARMOR
2378 if( p==0 || pOut==0
2379 || iScanStatusOp<SQLITE_SCANSTAT_NLOOP
2380 || iScanStatusOp>SQLITE_SCANSTAT_NCYCLE ){
2381 return 1;
2383 #endif
2384 aOp = p->aOp;
2385 nOp = p->nOp;
2386 if( p->pFrame ){
2387 VdbeFrame *pFrame;
2388 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2389 aOp = pFrame->aOp;
2390 nOp = pFrame->nOp;
2393 if( iScan<0 ){
2394 int ii;
2395 if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
2396 i64 res = 0;
2397 for(ii=0; ii<nOp; ii++){
2398 res += aOp[ii].nCycle;
2400 *(i64*)pOut = res;
2401 return 0;
2403 return 1;
2405 if( flags & SQLITE_SCANSTAT_COMPLEX ){
2406 idx = iScan;
2407 }else{
2408 /* If the COMPLEX flag is clear, then this function must ignore any
2409 ** ScanStatus structures with ScanStatus.addrLoop set to 0. */
2410 for(idx=0; idx<p->nScan; idx++){
2411 pScan = &p->aScan[idx];
2412 if( pScan->zName ){
2413 iScan--;
2414 if( iScan<0 ) break;
2418 if( idx>=p->nScan ) return 1;
2419 assert( pScan==0 || pScan==&p->aScan[idx] );
2420 pScan = &p->aScan[idx];
2422 switch( iScanStatusOp ){
2423 case SQLITE_SCANSTAT_NLOOP: {
2424 if( pScan->addrLoop>0 ){
2425 *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
2426 }else{
2427 *(sqlite3_int64*)pOut = -1;
2429 break;
2431 case SQLITE_SCANSTAT_NVISIT: {
2432 if( pScan->addrVisit>0 ){
2433 *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
2434 }else{
2435 *(sqlite3_int64*)pOut = -1;
2437 break;
2439 case SQLITE_SCANSTAT_EST: {
2440 double r = 1.0;
2441 LogEst x = pScan->nEst;
2442 while( x<100 ){
2443 x += 10;
2444 r *= 0.5;
2446 *(double*)pOut = r*sqlite3LogEstToInt(x);
2447 break;
2449 case SQLITE_SCANSTAT_NAME: {
2450 *(const char**)pOut = pScan->zName;
2451 break;
2453 case SQLITE_SCANSTAT_EXPLAIN: {
2454 if( pScan->addrExplain ){
2455 *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
2456 }else{
2457 *(const char**)pOut = 0;
2459 break;
2461 case SQLITE_SCANSTAT_SELECTID: {
2462 if( pScan->addrExplain ){
2463 *(int*)pOut = aOp[ pScan->addrExplain ].p1;
2464 }else{
2465 *(int*)pOut = -1;
2467 break;
2469 case SQLITE_SCANSTAT_PARENTID: {
2470 if( pScan->addrExplain ){
2471 *(int*)pOut = aOp[ pScan->addrExplain ].p2;
2472 }else{
2473 *(int*)pOut = -1;
2475 break;
2477 case SQLITE_SCANSTAT_NCYCLE: {
2478 i64 res = 0;
2479 if( pScan->aAddrRange[0]==0 ){
2480 res = -1;
2481 }else{
2482 int ii;
2483 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
2484 int iIns = pScan->aAddrRange[ii];
2485 int iEnd = pScan->aAddrRange[ii+1];
2486 if( iIns==0 ) break;
2487 if( iIns>0 ){
2488 while( iIns<=iEnd ){
2489 res += aOp[iIns].nCycle;
2490 iIns++;
2492 }else{
2493 int iOp;
2494 for(iOp=0; iOp<nOp; iOp++){
2495 Op *pOp = &aOp[iOp];
2496 if( pOp->p1!=iEnd ) continue;
2497 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
2498 continue;
2500 res += aOp[iOp].nCycle;
2505 *(i64*)pOut = res;
2506 break;
2508 default: {
2509 return 1;
2512 return 0;
2516 ** Return status data for a single loop within query pStmt.
2518 int sqlite3_stmt_scanstatus(
2519 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2520 int iScan, /* Index of loop to report on */
2521 int iScanStatusOp, /* Which metric to return */
2522 void *pOut /* OUT: Write the answer here */
2524 return sqlite3_stmt_scanstatus_v2(pStmt, iScan, iScanStatusOp, 0, pOut);
2528 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
2530 void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
2531 Vdbe *p = (Vdbe*)pStmt;
2532 int ii;
2533 for(ii=0; p!=0 && ii<p->nOp; ii++){
2534 Op *pOp = &p->aOp[ii];
2535 pOp->nExec = 0;
2536 pOp->nCycle = 0;
2539 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */