Merge sqlite-release(3.44.2) into prerelease-integration
[sqlcipher.git] / src / vdbeapi.c
blob3d4b9f76dcc9b1cab49a17101ff47d958c270d31
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 = ((Vdbe*)pStmt)->db->mutex;
156 #endif
157 sqlite3_mutex_enter(mutex);
158 for(i=0; i<p->nVar; i++){
159 sqlite3VdbeMemRelease(&p->aVar[i]);
160 p->aVar[i].flags = MEM_Null;
162 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
163 if( p->expmask ){
164 p->expired = 1;
166 sqlite3_mutex_leave(mutex);
167 return rc;
171 /**************************** sqlite3_value_ *******************************
172 ** The following routines extract information from a Mem or sqlite3_value
173 ** structure.
175 const void *sqlite3_value_blob(sqlite3_value *pVal){
176 Mem *p = (Mem*)pVal;
177 if( p->flags & (MEM_Blob|MEM_Str) ){
178 if( ExpandBlob(p)!=SQLITE_OK ){
179 assert( p->flags==MEM_Null && p->z==0 );
180 return 0;
182 p->flags |= MEM_Blob;
183 return p->n ? p->z : 0;
184 }else{
185 return sqlite3_value_text(pVal);
188 int sqlite3_value_bytes(sqlite3_value *pVal){
189 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
191 int sqlite3_value_bytes16(sqlite3_value *pVal){
192 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
194 double sqlite3_value_double(sqlite3_value *pVal){
195 return sqlite3VdbeRealValue((Mem*)pVal);
197 int sqlite3_value_int(sqlite3_value *pVal){
198 return (int)sqlite3VdbeIntValue((Mem*)pVal);
200 sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
201 return sqlite3VdbeIntValue((Mem*)pVal);
203 unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
204 Mem *pMem = (Mem*)pVal;
205 return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
207 void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
208 Mem *p = (Mem*)pVal;
209 if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
210 (MEM_Null|MEM_Term|MEM_Subtype)
211 && zPType!=0
212 && p->eSubtype=='p'
213 && strcmp(p->u.zPType, zPType)==0
215 return (void*)p->z;
216 }else{
217 return 0;
220 const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
221 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
223 #ifndef SQLITE_OMIT_UTF16
224 const void *sqlite3_value_text16(sqlite3_value* pVal){
225 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
227 const void *sqlite3_value_text16be(sqlite3_value *pVal){
228 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
230 const void *sqlite3_value_text16le(sqlite3_value *pVal){
231 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
233 #endif /* SQLITE_OMIT_UTF16 */
234 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
235 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
236 ** point number string BLOB NULL
238 int sqlite3_value_type(sqlite3_value* pVal){
239 static const u8 aType[] = {
240 SQLITE_BLOB, /* 0x00 (not possible) */
241 SQLITE_NULL, /* 0x01 NULL */
242 SQLITE_TEXT, /* 0x02 TEXT */
243 SQLITE_NULL, /* 0x03 (not possible) */
244 SQLITE_INTEGER, /* 0x04 INTEGER */
245 SQLITE_NULL, /* 0x05 (not possible) */
246 SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */
247 SQLITE_NULL, /* 0x07 (not possible) */
248 SQLITE_FLOAT, /* 0x08 FLOAT */
249 SQLITE_NULL, /* 0x09 (not possible) */
250 SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */
251 SQLITE_NULL, /* 0x0b (not possible) */
252 SQLITE_INTEGER, /* 0x0c (not possible) */
253 SQLITE_NULL, /* 0x0d (not possible) */
254 SQLITE_INTEGER, /* 0x0e (not possible) */
255 SQLITE_NULL, /* 0x0f (not possible) */
256 SQLITE_BLOB, /* 0x10 BLOB */
257 SQLITE_NULL, /* 0x11 (not possible) */
258 SQLITE_TEXT, /* 0x12 (not possible) */
259 SQLITE_NULL, /* 0x13 (not possible) */
260 SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */
261 SQLITE_NULL, /* 0x15 (not possible) */
262 SQLITE_INTEGER, /* 0x16 (not possible) */
263 SQLITE_NULL, /* 0x17 (not possible) */
264 SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */
265 SQLITE_NULL, /* 0x19 (not possible) */
266 SQLITE_FLOAT, /* 0x1a (not possible) */
267 SQLITE_NULL, /* 0x1b (not possible) */
268 SQLITE_INTEGER, /* 0x1c (not possible) */
269 SQLITE_NULL, /* 0x1d (not possible) */
270 SQLITE_INTEGER, /* 0x1e (not possible) */
271 SQLITE_NULL, /* 0x1f (not possible) */
272 SQLITE_FLOAT, /* 0x20 INTREAL */
273 SQLITE_NULL, /* 0x21 (not possible) */
274 SQLITE_FLOAT, /* 0x22 INTREAL + TEXT */
275 SQLITE_NULL, /* 0x23 (not possible) */
276 SQLITE_FLOAT, /* 0x24 (not possible) */
277 SQLITE_NULL, /* 0x25 (not possible) */
278 SQLITE_FLOAT, /* 0x26 (not possible) */
279 SQLITE_NULL, /* 0x27 (not possible) */
280 SQLITE_FLOAT, /* 0x28 (not possible) */
281 SQLITE_NULL, /* 0x29 (not possible) */
282 SQLITE_FLOAT, /* 0x2a (not possible) */
283 SQLITE_NULL, /* 0x2b (not possible) */
284 SQLITE_FLOAT, /* 0x2c (not possible) */
285 SQLITE_NULL, /* 0x2d (not possible) */
286 SQLITE_FLOAT, /* 0x2e (not possible) */
287 SQLITE_NULL, /* 0x2f (not possible) */
288 SQLITE_BLOB, /* 0x30 (not possible) */
289 SQLITE_NULL, /* 0x31 (not possible) */
290 SQLITE_TEXT, /* 0x32 (not possible) */
291 SQLITE_NULL, /* 0x33 (not possible) */
292 SQLITE_FLOAT, /* 0x34 (not possible) */
293 SQLITE_NULL, /* 0x35 (not possible) */
294 SQLITE_FLOAT, /* 0x36 (not possible) */
295 SQLITE_NULL, /* 0x37 (not possible) */
296 SQLITE_FLOAT, /* 0x38 (not possible) */
297 SQLITE_NULL, /* 0x39 (not possible) */
298 SQLITE_FLOAT, /* 0x3a (not possible) */
299 SQLITE_NULL, /* 0x3b (not possible) */
300 SQLITE_FLOAT, /* 0x3c (not possible) */
301 SQLITE_NULL, /* 0x3d (not possible) */
302 SQLITE_FLOAT, /* 0x3e (not possible) */
303 SQLITE_NULL, /* 0x3f (not possible) */
305 #ifdef SQLITE_DEBUG
307 int eType = SQLITE_BLOB;
308 if( pVal->flags & MEM_Null ){
309 eType = SQLITE_NULL;
310 }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
311 eType = SQLITE_FLOAT;
312 }else if( pVal->flags & MEM_Int ){
313 eType = SQLITE_INTEGER;
314 }else if( pVal->flags & MEM_Str ){
315 eType = SQLITE_TEXT;
317 assert( eType == aType[pVal->flags&MEM_AffMask] );
319 #endif
320 return aType[pVal->flags&MEM_AffMask];
322 int sqlite3_value_encoding(sqlite3_value *pVal){
323 return pVal->enc;
326 /* Return true if a parameter to xUpdate represents an unchanged column */
327 int sqlite3_value_nochange(sqlite3_value *pVal){
328 return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
331 /* Return true if a parameter value originated from an sqlite3_bind() */
332 int sqlite3_value_frombind(sqlite3_value *pVal){
333 return (pVal->flags&MEM_FromBind)!=0;
336 /* Make a copy of an sqlite3_value object
338 sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
339 sqlite3_value *pNew;
340 if( pOrig==0 ) return 0;
341 pNew = sqlite3_malloc( sizeof(*pNew) );
342 if( pNew==0 ) return 0;
343 memset(pNew, 0, sizeof(*pNew));
344 memcpy(pNew, pOrig, MEMCELLSIZE);
345 pNew->flags &= ~MEM_Dyn;
346 pNew->db = 0;
347 if( pNew->flags&(MEM_Str|MEM_Blob) ){
348 pNew->flags &= ~(MEM_Static|MEM_Dyn);
349 pNew->flags |= MEM_Ephem;
350 if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
351 sqlite3ValueFree(pNew);
352 pNew = 0;
354 }else if( pNew->flags & MEM_Null ){
355 /* Do not duplicate pointer values */
356 pNew->flags &= ~(MEM_Term|MEM_Subtype);
358 return pNew;
361 /* Destroy an sqlite3_value object previously obtained from
362 ** sqlite3_value_dup().
364 void sqlite3_value_free(sqlite3_value *pOld){
365 sqlite3ValueFree(pOld);
369 /**************************** sqlite3_result_ *******************************
370 ** The following routines are used by user-defined functions to specify
371 ** the function result.
373 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
374 ** result as a string or blob. Appropriate errors are set if the string/blob
375 ** is too big or if an OOM occurs.
377 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
378 ** on value P if P is not going to be used and need to be destroyed.
380 static void setResultStrOrError(
381 sqlite3_context *pCtx, /* Function context */
382 const char *z, /* String pointer */
383 int n, /* Bytes in string, or negative */
384 u8 enc, /* Encoding of z. 0 for BLOBs */
385 void (*xDel)(void*) /* Destructor function */
387 Mem *pOut = pCtx->pOut;
388 int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel);
389 if( rc ){
390 if( rc==SQLITE_TOOBIG ){
391 sqlite3_result_error_toobig(pCtx);
392 }else{
393 /* The only errors possible from sqlite3VdbeMemSetStr are
394 ** SQLITE_TOOBIG and SQLITE_NOMEM */
395 assert( rc==SQLITE_NOMEM );
396 sqlite3_result_error_nomem(pCtx);
398 return;
400 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
401 if( sqlite3VdbeMemTooBig(pOut) ){
402 sqlite3_result_error_toobig(pCtx);
405 static int invokeValueDestructor(
406 const void *p, /* Value to destroy */
407 void (*xDel)(void*), /* The destructor */
408 sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if not NULL */
410 assert( xDel!=SQLITE_DYNAMIC );
411 if( xDel==0 ){
412 /* noop */
413 }else if( xDel==SQLITE_TRANSIENT ){
414 /* noop */
415 }else{
416 xDel((void*)p);
418 #ifdef SQLITE_ENABLE_API_ARMOR
419 if( pCtx!=0 ){
420 sqlite3_result_error_toobig(pCtx);
422 #else
423 assert( pCtx!=0 );
424 sqlite3_result_error_toobig(pCtx);
425 #endif
426 return SQLITE_TOOBIG;
428 void sqlite3_result_blob(
429 sqlite3_context *pCtx,
430 const void *z,
431 int n,
432 void (*xDel)(void *)
434 #ifdef SQLITE_ENABLE_API_ARMOR
435 if( pCtx==0 || n<0 ){
436 invokeValueDestructor(z, xDel, pCtx);
437 return;
439 #endif
440 assert( n>=0 );
441 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
442 setResultStrOrError(pCtx, z, n, 0, xDel);
444 void sqlite3_result_blob64(
445 sqlite3_context *pCtx,
446 const void *z,
447 sqlite3_uint64 n,
448 void (*xDel)(void *)
450 assert( xDel!=SQLITE_DYNAMIC );
451 #ifdef SQLITE_ENABLE_API_ARMOR
452 if( pCtx==0 ){
453 invokeValueDestructor(z, xDel, 0);
454 return;
456 #endif
457 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
458 if( n>0x7fffffff ){
459 (void)invokeValueDestructor(z, xDel, pCtx);
460 }else{
461 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
464 void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
465 #ifdef SQLITE_ENABLE_API_ARMOR
466 if( pCtx==0 ) return;
467 #endif
468 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
469 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
471 void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
472 #ifdef SQLITE_ENABLE_API_ARMOR
473 if( pCtx==0 ) return;
474 #endif
475 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
476 pCtx->isError = SQLITE_ERROR;
477 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
479 #ifndef SQLITE_OMIT_UTF16
480 void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
481 #ifdef SQLITE_ENABLE_API_ARMOR
482 if( pCtx==0 ) return;
483 #endif
484 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
485 pCtx->isError = SQLITE_ERROR;
486 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
488 #endif
489 void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
490 #ifdef SQLITE_ENABLE_API_ARMOR
491 if( pCtx==0 ) return;
492 #endif
493 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
494 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
496 void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
497 #ifdef SQLITE_ENABLE_API_ARMOR
498 if( pCtx==0 ) return;
499 #endif
500 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
501 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
503 void sqlite3_result_null(sqlite3_context *pCtx){
504 #ifdef SQLITE_ENABLE_API_ARMOR
505 if( pCtx==0 ) return;
506 #endif
507 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
508 sqlite3VdbeMemSetNull(pCtx->pOut);
510 void sqlite3_result_pointer(
511 sqlite3_context *pCtx,
512 void *pPtr,
513 const char *zPType,
514 void (*xDestructor)(void*)
516 Mem *pOut;
517 #ifdef SQLITE_ENABLE_API_ARMOR
518 if( pCtx==0 ){
519 invokeValueDestructor(pPtr, xDestructor, 0);
520 return;
522 #endif
523 pOut = pCtx->pOut;
524 assert( sqlite3_mutex_held(pOut->db->mutex) );
525 sqlite3VdbeMemRelease(pOut);
526 pOut->flags = MEM_Null;
527 sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
529 void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
530 Mem *pOut;
531 #ifdef SQLITE_ENABLE_API_ARMOR
532 if( pCtx==0 ) return;
533 #endif
534 #if defined(SQLITE_STRICT_SUBTYPE) && SQLITE_STRICT_SUBTYPE+0!=0
535 if( pCtx->pFunc!=0
536 && (pCtx->pFunc->funcFlags & SQLITE_RESULT_SUBTYPE)==0
538 char zErr[200];
539 sqlite3_snprintf(sizeof(zErr), zErr,
540 "misuse of sqlite3_result_subtype() by %s()",
541 pCtx->pFunc->zName);
542 sqlite3_result_error(pCtx, zErr, -1);
543 return;
545 #endif /* SQLITE_STRICT_SUBTYPE */
546 pOut = pCtx->pOut;
547 assert( sqlite3_mutex_held(pOut->db->mutex) );
548 pOut->eSubtype = eSubtype & 0xff;
549 pOut->flags |= MEM_Subtype;
551 void sqlite3_result_text(
552 sqlite3_context *pCtx,
553 const char *z,
554 int n,
555 void (*xDel)(void *)
557 #ifdef SQLITE_ENABLE_API_ARMOR
558 if( pCtx==0 ){
559 invokeValueDestructor(z, xDel, 0);
560 return;
562 #endif
563 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
564 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
566 void sqlite3_result_text64(
567 sqlite3_context *pCtx,
568 const char *z,
569 sqlite3_uint64 n,
570 void (*xDel)(void *),
571 unsigned char enc
573 #ifdef SQLITE_ENABLE_API_ARMOR
574 if( pCtx==0 ){
575 invokeValueDestructor(z, xDel, 0);
576 return;
578 #endif
579 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
580 assert( xDel!=SQLITE_DYNAMIC );
581 if( enc!=SQLITE_UTF8 ){
582 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
583 n &= ~(u64)1;
585 if( n>0x7fffffff ){
586 (void)invokeValueDestructor(z, xDel, pCtx);
587 }else{
588 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
589 sqlite3VdbeMemZeroTerminateIfAble(pCtx->pOut);
592 #ifndef SQLITE_OMIT_UTF16
593 void sqlite3_result_text16(
594 sqlite3_context *pCtx,
595 const void *z,
596 int n,
597 void (*xDel)(void *)
599 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
600 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16NATIVE, xDel);
602 void sqlite3_result_text16be(
603 sqlite3_context *pCtx,
604 const void *z,
605 int n,
606 void (*xDel)(void *)
608 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
609 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16BE, xDel);
611 void sqlite3_result_text16le(
612 sqlite3_context *pCtx,
613 const void *z,
614 int n,
615 void (*xDel)(void *)
617 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
618 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16LE, xDel);
620 #endif /* SQLITE_OMIT_UTF16 */
621 void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
622 Mem *pOut;
624 #ifdef SQLITE_ENABLE_API_ARMOR
625 if( pCtx==0 ) return;
626 if( pValue==0 ){
627 sqlite3_result_null(pCtx);
628 return;
630 #endif
631 pOut = pCtx->pOut;
632 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
633 sqlite3VdbeMemCopy(pOut, pValue);
634 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
635 if( sqlite3VdbeMemTooBig(pOut) ){
636 sqlite3_result_error_toobig(pCtx);
639 void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
640 sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
642 int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
643 Mem *pOut;
645 #ifdef SQLITE_ENABLE_API_ARMOR
646 if( pCtx==0 ) return SQLITE_MISUSE_BKPT;
647 #endif
648 pOut = pCtx->pOut;
649 assert( sqlite3_mutex_held(pOut->db->mutex) );
650 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
651 sqlite3_result_error_toobig(pCtx);
652 return SQLITE_TOOBIG;
654 #ifndef SQLITE_OMIT_INCRBLOB
655 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
656 return SQLITE_OK;
657 #else
658 return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
659 #endif
661 void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
662 #ifdef SQLITE_ENABLE_API_ARMOR
663 if( pCtx==0 ) return;
664 #endif
665 pCtx->isError = errCode ? errCode : -1;
666 #ifdef SQLITE_DEBUG
667 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
668 #endif
669 if( pCtx->pOut->flags & MEM_Null ){
670 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
671 SQLITE_STATIC);
675 /* Force an SQLITE_TOOBIG error. */
676 void sqlite3_result_error_toobig(sqlite3_context *pCtx){
677 #ifdef SQLITE_ENABLE_API_ARMOR
678 if( pCtx==0 ) return;
679 #endif
680 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
681 pCtx->isError = SQLITE_TOOBIG;
682 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
683 SQLITE_UTF8, SQLITE_STATIC);
686 /* An SQLITE_NOMEM error. */
687 void sqlite3_result_error_nomem(sqlite3_context *pCtx){
688 #ifdef SQLITE_ENABLE_API_ARMOR
689 if( pCtx==0 ) return;
690 #endif
691 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
692 sqlite3VdbeMemSetNull(pCtx->pOut);
693 pCtx->isError = SQLITE_NOMEM_BKPT;
694 sqlite3OomFault(pCtx->pOut->db);
697 #ifndef SQLITE_UNTESTABLE
698 /* Force the INT64 value currently stored as the result to be
699 ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
700 ** test-control.
702 void sqlite3ResultIntReal(sqlite3_context *pCtx){
703 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
704 if( pCtx->pOut->flags & MEM_Int ){
705 pCtx->pOut->flags &= ~MEM_Int;
706 pCtx->pOut->flags |= MEM_IntReal;
709 #endif
713 ** This function is called after a transaction has been committed. It
714 ** invokes callbacks registered with sqlite3_wal_hook() as required.
716 static int doWalCallbacks(sqlite3 *db){
717 int rc = SQLITE_OK;
718 #ifndef SQLITE_OMIT_WAL
719 int i;
720 for(i=0; i<db->nDb; i++){
721 Btree *pBt = db->aDb[i].pBt;
722 if( pBt ){
723 int nEntry;
724 sqlite3BtreeEnter(pBt);
725 nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
726 sqlite3BtreeLeave(pBt);
727 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
728 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
732 #endif
733 return rc;
738 ** Execute the statement pStmt, either until a row of data is ready, the
739 ** statement is completely executed or an error occurs.
741 ** This routine implements the bulk of the logic behind the sqlite_step()
742 ** API. The only thing omitted is the automatic recompile if a
743 ** schema change has occurred. That detail is handled by the
744 ** outer sqlite3_step() wrapper procedure.
746 static int sqlite3Step(Vdbe *p){
747 sqlite3 *db;
748 int rc;
750 assert(p);
751 db = p->db;
752 if( p->eVdbeState!=VDBE_RUN_STATE ){
753 restart_step:
754 if( p->eVdbeState==VDBE_READY_STATE ){
755 if( p->expired ){
756 p->rc = SQLITE_SCHEMA;
757 rc = SQLITE_ERROR;
758 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
759 /* If this statement was prepared using saved SQL and an
760 ** error has occurred, then return the error code in p->rc to the
761 ** caller. Set the error code in the database handle to the same
762 ** value.
764 rc = sqlite3VdbeTransferError(p);
766 goto end_of_step;
769 /* If there are no other statements currently running, then
770 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
771 ** from interrupting a statement that has not yet started.
773 if( db->nVdbeActive==0 ){
774 AtomicStore(&db->u1.isInterrupted, 0);
777 assert( db->nVdbeWrite>0 || db->autoCommit==0
778 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
781 #ifndef SQLITE_OMIT_TRACE
782 if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
783 && !db->init.busy && p->zSql ){
784 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
785 }else{
786 assert( p->startTime==0 );
788 #endif
790 db->nVdbeActive++;
791 if( p->readOnly==0 ) db->nVdbeWrite++;
792 if( p->bIsReader ) db->nVdbeRead++;
793 p->pc = 0;
794 p->eVdbeState = VDBE_RUN_STATE;
795 }else
797 if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
798 /* We used to require that sqlite3_reset() be called before retrying
799 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
800 ** with version 3.7.0, we changed this so that sqlite3_reset() would
801 ** be called automatically instead of throwing the SQLITE_MISUSE error.
802 ** This "automatic-reset" change is not technically an incompatibility,
803 ** since any application that receives an SQLITE_MISUSE is broken by
804 ** definition.
806 ** Nevertheless, some published applications that were originally written
807 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
808 ** returns, and those were broken by the automatic-reset change. As a
809 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
810 ** legacy behavior of returning SQLITE_MISUSE for cases where the
811 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
812 ** or SQLITE_BUSY error.
814 #ifdef SQLITE_OMIT_AUTORESET
815 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
816 sqlite3_reset((sqlite3_stmt*)p);
817 }else{
818 return SQLITE_MISUSE_BKPT;
820 #else
821 sqlite3_reset((sqlite3_stmt*)p);
822 #endif
823 assert( p->eVdbeState==VDBE_READY_STATE );
824 goto restart_step;
828 #ifdef SQLITE_DEBUG
829 p->rcApp = SQLITE_OK;
830 #endif
831 #ifndef SQLITE_OMIT_EXPLAIN
832 if( p->explain ){
833 rc = sqlite3VdbeList(p);
834 }else
835 #endif /* SQLITE_OMIT_EXPLAIN */
837 db->nVdbeExec++;
838 rc = sqlite3VdbeExec(p);
839 db->nVdbeExec--;
842 if( rc==SQLITE_ROW ){
843 assert( p->rc==SQLITE_OK );
844 assert( db->mallocFailed==0 );
845 db->errCode = SQLITE_ROW;
846 return SQLITE_ROW;
847 }else{
848 #ifndef SQLITE_OMIT_TRACE
849 /* If the statement completed successfully, invoke the profile callback */
850 checkProfileCallback(db, p);
851 #endif
852 p->pResultRow = 0;
853 if( rc==SQLITE_DONE && db->autoCommit ){
854 assert( p->rc==SQLITE_OK );
855 p->rc = doWalCallbacks(db);
856 if( p->rc!=SQLITE_OK ){
857 rc = SQLITE_ERROR;
859 }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
860 /* If this statement was prepared using saved SQL and an
861 ** error has occurred, then return the error code in p->rc to the
862 ** caller. Set the error code in the database handle to the same value.
864 rc = sqlite3VdbeTransferError(p);
868 db->errCode = rc;
869 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
870 p->rc = SQLITE_NOMEM_BKPT;
871 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
873 end_of_step:
874 /* There are only a limited number of result codes allowed from the
875 ** statements prepared using the legacy sqlite3_prepare() interface */
876 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
877 || rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
878 || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
880 return (rc&db->errMask);
884 ** This is the top-level implementation of sqlite3_step(). Call
885 ** sqlite3Step() to do most of the work. If a schema error occurs,
886 ** call sqlite3Reprepare() and try again.
888 int sqlite3_step(sqlite3_stmt *pStmt){
889 int rc = SQLITE_OK; /* Result from sqlite3Step() */
890 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
891 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
892 sqlite3 *db; /* The database connection */
894 if( vdbeSafetyNotNull(v) ){
895 return SQLITE_MISUSE_BKPT;
897 db = v->db;
898 sqlite3_mutex_enter(db->mutex);
899 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
900 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
901 int savedPc = v->pc;
902 rc = sqlite3Reprepare(v);
903 if( rc!=SQLITE_OK ){
904 /* This case occurs after failing to recompile an sql statement.
905 ** The error message from the SQL compiler has already been loaded
906 ** into the database handle. This block copies the error message
907 ** from the database handle into the statement and sets the statement
908 ** program counter to 0 to ensure that when the statement is
909 ** finalized or reset the parser error message is available via
910 ** sqlite3_errmsg() and sqlite3_errcode().
912 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
913 sqlite3DbFree(db, v->zErrMsg);
914 if( !db->mallocFailed ){
915 v->zErrMsg = sqlite3DbStrDup(db, zErr);
916 v->rc = rc = sqlite3ApiExit(db, rc);
917 } else {
918 v->zErrMsg = 0;
919 v->rc = rc = SQLITE_NOMEM_BKPT;
921 break;
923 sqlite3_reset(pStmt);
924 if( savedPc>=0 ){
925 /* Setting minWriteFileFormat to 254 is a signal to the OP_Init and
926 ** OP_Trace opcodes to *not* perform SQLITE_TRACE_STMT because it has
927 ** already been done once on a prior invocation that failed due to
928 ** SQLITE_SCHEMA. tag-20220401a */
929 v->minWriteFileFormat = 254;
931 assert( v->expired==0 );
933 sqlite3_mutex_leave(db->mutex);
934 return rc;
939 ** Extract the user data from a sqlite3_context structure and return a
940 ** pointer to it.
942 void *sqlite3_user_data(sqlite3_context *p){
943 #ifdef SQLITE_ENABLE_API_ARMOR
944 if( p==0 ) return 0;
945 #else
946 assert( p && p->pFunc );
947 #endif
948 return p->pFunc->pUserData;
952 ** Extract the user data from a sqlite3_context structure and return a
953 ** pointer to it.
955 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
956 ** returns a copy of the pointer to the database connection (the 1st
957 ** parameter) of the sqlite3_create_function() and
958 ** sqlite3_create_function16() routines that originally registered the
959 ** application defined function.
961 sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
962 #ifdef SQLITE_ENABLE_API_ARMOR
963 if( p==0 ) return 0;
964 #else
965 assert( p && p->pOut );
966 #endif
967 return p->pOut->db;
971 ** If this routine is invoked from within an xColumn method of a virtual
972 ** table, then it returns true if and only if the the call is during an
973 ** UPDATE operation and the value of the column will not be modified
974 ** by the UPDATE.
976 ** If this routine is called from any context other than within the
977 ** xColumn method of a virtual table, then the return value is meaningless
978 ** and arbitrary.
980 ** Virtual table implements might use this routine to optimize their
981 ** performance by substituting a NULL result, or some other light-weight
982 ** value, as a signal to the xUpdate routine that the column is unchanged.
984 int sqlite3_vtab_nochange(sqlite3_context *p){
985 #ifdef SQLITE_ENABLE_API_ARMOR
986 if( p==0 ) return 0;
987 #else
988 assert( p );
989 #endif
990 return sqlite3_value_nochange(p->pOut);
994 ** The destructor function for a ValueList object. This needs to be
995 ** a separate function, unknowable to the application, to ensure that
996 ** calls to sqlite3_vtab_in_first()/sqlite3_vtab_in_next() that are not
997 ** preceded by activation of IN processing via sqlite3_vtab_int() do not
998 ** try to access a fake ValueList object inserted by a hostile extension.
1000 void sqlite3VdbeValueListFree(void *pToDelete){
1001 sqlite3_free(pToDelete);
1005 ** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
1006 ** sqlite3_vtab_in_next() (if bNext!=0).
1008 static int valueFromValueList(
1009 sqlite3_value *pVal, /* Pointer to the ValueList object */
1010 sqlite3_value **ppOut, /* Store the next value from the list here */
1011 int bNext /* 1 for _next(). 0 for _first() */
1013 int rc;
1014 ValueList *pRhs;
1016 *ppOut = 0;
1017 if( pVal==0 ) return SQLITE_MISUSE_BKPT;
1018 if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
1019 return SQLITE_ERROR;
1020 }else{
1021 assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
1022 (MEM_Null|MEM_Term|MEM_Subtype) );
1023 assert( pVal->eSubtype=='p' );
1024 assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
1025 pRhs = (ValueList*)pVal->z;
1027 if( bNext ){
1028 rc = sqlite3BtreeNext(pRhs->pCsr, 0);
1029 }else{
1030 int dummy = 0;
1031 rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
1032 assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
1033 if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
1035 if( rc==SQLITE_OK ){
1036 u32 sz; /* Size of current row in bytes */
1037 Mem sMem; /* Raw content of current row */
1038 memset(&sMem, 0, sizeof(sMem));
1039 sz = sqlite3BtreePayloadSize(pRhs->pCsr);
1040 rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
1041 if( rc==SQLITE_OK ){
1042 u8 *zBuf = (u8*)sMem.z;
1043 u32 iSerial;
1044 sqlite3_value *pOut = pRhs->pOut;
1045 int iOff = 1 + getVarint32(&zBuf[1], iSerial);
1046 sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
1047 pOut->enc = ENC(pOut->db);
1048 if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
1049 rc = SQLITE_NOMEM;
1050 }else{
1051 *ppOut = pOut;
1054 sqlite3VdbeMemRelease(&sMem);
1056 return rc;
1060 ** Set the iterator value pVal to point to the first value in the set.
1061 ** Set (*ppOut) to point to this value before returning.
1063 int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
1064 return valueFromValueList(pVal, ppOut, 0);
1068 ** Set the iterator value pVal to point to the next value in the set.
1069 ** Set (*ppOut) to point to this value before returning.
1071 int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
1072 return valueFromValueList(pVal, ppOut, 1);
1076 ** Return the current time for a statement. If the current time
1077 ** is requested more than once within the same run of a single prepared
1078 ** statement, the exact same time is returned for each invocation regardless
1079 ** of the amount of time that elapses between invocations. In other words,
1080 ** the time returned is always the time of the first call.
1082 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
1083 int rc;
1084 #ifndef SQLITE_ENABLE_STAT4
1085 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
1086 assert( p->pVdbe!=0 );
1087 #else
1088 sqlite3_int64 iTime = 0;
1089 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
1090 #endif
1091 if( *piTime==0 ){
1092 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
1093 if( rc ) *piTime = 0;
1095 return *piTime;
1099 ** Create a new aggregate context for p and return a pointer to
1100 ** its pMem->z element.
1102 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
1103 Mem *pMem = p->pMem;
1104 assert( (pMem->flags & MEM_Agg)==0 );
1105 if( nByte<=0 ){
1106 sqlite3VdbeMemSetNull(pMem);
1107 pMem->z = 0;
1108 }else{
1109 sqlite3VdbeMemClearAndResize(pMem, nByte);
1110 pMem->flags = MEM_Agg;
1111 pMem->u.pDef = p->pFunc;
1112 if( pMem->z ){
1113 memset(pMem->z, 0, nByte);
1116 return (void*)pMem->z;
1120 ** Allocate or return the aggregate context for a user function. A new
1121 ** context is allocated on the first call. Subsequent calls return the
1122 ** same context that was returned on prior calls.
1124 void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
1125 assert( p && p->pFunc && p->pFunc->xFinalize );
1126 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
1127 testcase( nByte<0 );
1128 if( (p->pMem->flags & MEM_Agg)==0 ){
1129 return createAggContext(p, nByte);
1130 }else{
1131 return (void*)p->pMem->z;
1136 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
1137 ** the user-function defined by pCtx.
1139 ** The left-most argument is 0.
1141 ** Undocumented behavior: If iArg is negative then access a cache of
1142 ** auxiliary data pointers that is available to all functions within a
1143 ** single prepared statement. The iArg values must match.
1145 void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
1146 AuxData *pAuxData;
1148 #ifdef SQLITE_ENABLE_API_ARMOR
1149 if( pCtx==0 ) return 0;
1150 #endif
1151 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1152 #if SQLITE_ENABLE_STAT4
1153 if( pCtx->pVdbe==0 ) return 0;
1154 #else
1155 assert( pCtx->pVdbe!=0 );
1156 #endif
1157 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1158 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1159 return pAuxData->pAux;
1162 return 0;
1166 ** Set the auxiliary data pointer and delete function, for the iArg'th
1167 ** argument to the user-function defined by pCtx. Any previous value is
1168 ** deleted by calling the delete function specified when it was set.
1170 ** The left-most argument is 0.
1172 ** Undocumented behavior: If iArg is negative then make the data available
1173 ** to all functions within the current prepared statement using iArg as an
1174 ** access code.
1176 void sqlite3_set_auxdata(
1177 sqlite3_context *pCtx,
1178 int iArg,
1179 void *pAux,
1180 void (*xDelete)(void*)
1182 AuxData *pAuxData;
1183 Vdbe *pVdbe;
1185 #ifdef SQLITE_ENABLE_API_ARMOR
1186 if( pCtx==0 ) return;
1187 #endif
1188 pVdbe= pCtx->pVdbe;
1189 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1190 #ifdef SQLITE_ENABLE_STAT4
1191 if( pVdbe==0 ) goto failed;
1192 #else
1193 assert( pVdbe!=0 );
1194 #endif
1196 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1197 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1198 break;
1201 if( pAuxData==0 ){
1202 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
1203 if( !pAuxData ) goto failed;
1204 pAuxData->iAuxOp = pCtx->iOp;
1205 pAuxData->iAuxArg = iArg;
1206 pAuxData->pNextAux = pVdbe->pAuxData;
1207 pVdbe->pAuxData = pAuxData;
1208 if( pCtx->isError==0 ) pCtx->isError = -1;
1209 }else if( pAuxData->xDeleteAux ){
1210 pAuxData->xDeleteAux(pAuxData->pAux);
1213 pAuxData->pAux = pAux;
1214 pAuxData->xDeleteAux = xDelete;
1215 return;
1217 failed:
1218 if( xDelete ){
1219 xDelete(pAux);
1223 #ifndef SQLITE_OMIT_DEPRECATED
1225 ** Return the number of times the Step function of an aggregate has been
1226 ** called.
1228 ** This function is deprecated. Do not use it for new code. It is
1229 ** provide only to avoid breaking legacy code. New aggregate function
1230 ** implementations should keep their own counts within their aggregate
1231 ** context.
1233 int sqlite3_aggregate_count(sqlite3_context *p){
1234 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
1235 return p->pMem->n;
1237 #endif
1240 ** Return the number of columns in the result set for the statement pStmt.
1242 int sqlite3_column_count(sqlite3_stmt *pStmt){
1243 Vdbe *pVm = (Vdbe *)pStmt;
1244 if( pVm==0 ) return 0;
1245 return pVm->nResColumn;
1249 ** Return the number of values available from the current row of the
1250 ** currently executing statement pStmt.
1252 int sqlite3_data_count(sqlite3_stmt *pStmt){
1253 Vdbe *pVm = (Vdbe *)pStmt;
1254 if( pVm==0 || pVm->pResultRow==0 ) return 0;
1255 return pVm->nResColumn;
1259 ** Return a pointer to static memory containing an SQL NULL value.
1261 static const Mem *columnNullValue(void){
1262 /* Even though the Mem structure contains an element
1263 ** of type i64, on certain architectures (x86) with certain compiler
1264 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
1265 ** instead of an 8-byte one. This all works fine, except that when
1266 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
1267 ** that a Mem structure is located on an 8-byte boundary. To prevent
1268 ** these assert()s from failing, when building with SQLITE_DEBUG defined
1269 ** using gcc, we force nullMem to be 8-byte aligned using the magical
1270 ** __attribute__((aligned(8))) macro. */
1271 static const Mem nullMem
1272 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
1273 __attribute__((aligned(8)))
1274 #endif
1276 /* .u = */ {0},
1277 /* .z = */ (char*)0,
1278 /* .n = */ (int)0,
1279 /* .flags = */ (u16)MEM_Null,
1280 /* .enc = */ (u8)0,
1281 /* .eSubtype = */ (u8)0,
1282 /* .db = */ (sqlite3*)0,
1283 /* .szMalloc = */ (int)0,
1284 /* .uTemp = */ (u32)0,
1285 /* .zMalloc = */ (char*)0,
1286 /* .xDel = */ (void(*)(void*))0,
1287 #ifdef SQLITE_DEBUG
1288 /* .pScopyFrom = */ (Mem*)0,
1289 /* .mScopyFlags= */ 0,
1290 #endif
1292 return &nullMem;
1296 ** Check to see if column iCol of the given statement is valid. If
1297 ** it is, return a pointer to the Mem for the value of that column.
1298 ** If iCol is not valid, return a pointer to a Mem which has a value
1299 ** of NULL.
1301 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
1302 Vdbe *pVm;
1303 Mem *pOut;
1305 pVm = (Vdbe *)pStmt;
1306 if( pVm==0 ) return (Mem*)columnNullValue();
1307 assert( pVm->db );
1308 sqlite3_mutex_enter(pVm->db->mutex);
1309 if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
1310 pOut = &pVm->pResultRow[i];
1311 }else{
1312 sqlite3Error(pVm->db, SQLITE_RANGE);
1313 pOut = (Mem*)columnNullValue();
1315 return pOut;
1319 ** This function is called after invoking an sqlite3_value_XXX function on a
1320 ** column value (i.e. a value returned by evaluating an SQL expression in the
1321 ** select list of a SELECT statement) that may cause a malloc() failure. If
1322 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
1323 ** code of statement pStmt set to SQLITE_NOMEM.
1325 ** Specifically, this is called from within:
1327 ** sqlite3_column_int()
1328 ** sqlite3_column_int64()
1329 ** sqlite3_column_text()
1330 ** sqlite3_column_text16()
1331 ** sqlite3_column_real()
1332 ** sqlite3_column_bytes()
1333 ** sqlite3_column_bytes16()
1334 ** sqlite3_column_blob()
1336 static void columnMallocFailure(sqlite3_stmt *pStmt)
1338 /* If malloc() failed during an encoding conversion within an
1339 ** sqlite3_column_XXX API, then set the return code of the statement to
1340 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
1341 ** and _finalize() will return NOMEM.
1343 Vdbe *p = (Vdbe *)pStmt;
1344 if( p ){
1345 assert( p->db!=0 );
1346 assert( sqlite3_mutex_held(p->db->mutex) );
1347 p->rc = sqlite3ApiExit(p->db, p->rc);
1348 sqlite3_mutex_leave(p->db->mutex);
1352 /**************************** sqlite3_column_ *******************************
1353 ** The following routines are used to access elements of the current row
1354 ** in the result set.
1356 const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
1357 const void *val;
1358 val = sqlite3_value_blob( columnMem(pStmt,i) );
1359 /* Even though there is no encoding conversion, value_blob() might
1360 ** need to call malloc() to expand the result of a zeroblob()
1361 ** expression.
1363 columnMallocFailure(pStmt);
1364 return val;
1366 int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
1367 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
1368 columnMallocFailure(pStmt);
1369 return val;
1371 int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
1372 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
1373 columnMallocFailure(pStmt);
1374 return val;
1376 double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
1377 double val = sqlite3_value_double( columnMem(pStmt,i) );
1378 columnMallocFailure(pStmt);
1379 return val;
1381 int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
1382 int val = sqlite3_value_int( columnMem(pStmt,i) );
1383 columnMallocFailure(pStmt);
1384 return val;
1386 sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
1387 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
1388 columnMallocFailure(pStmt);
1389 return val;
1391 const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
1392 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
1393 columnMallocFailure(pStmt);
1394 return val;
1396 sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
1397 Mem *pOut = columnMem(pStmt, i);
1398 if( pOut->flags&MEM_Static ){
1399 pOut->flags &= ~MEM_Static;
1400 pOut->flags |= MEM_Ephem;
1402 columnMallocFailure(pStmt);
1403 return (sqlite3_value *)pOut;
1405 #ifndef SQLITE_OMIT_UTF16
1406 const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
1407 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
1408 columnMallocFailure(pStmt);
1409 return val;
1411 #endif /* SQLITE_OMIT_UTF16 */
1412 int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
1413 int iType = sqlite3_value_type( columnMem(pStmt,i) );
1414 columnMallocFailure(pStmt);
1415 return iType;
1419 ** Column names appropriate for EXPLAIN or EXPLAIN QUERY PLAN.
1421 static const char * const azExplainColNames8[] = {
1422 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", /* EXPLAIN */
1423 "id", "parent", "notused", "detail" /* EQP */
1425 static const u16 azExplainColNames16data[] = {
1426 /* 0 */ 'a', 'd', 'd', 'r', 0,
1427 /* 5 */ 'o', 'p', 'c', 'o', 'd', 'e', 0,
1428 /* 12 */ 'p', '1', 0,
1429 /* 15 */ 'p', '2', 0,
1430 /* 18 */ 'p', '3', 0,
1431 /* 21 */ 'p', '4', 0,
1432 /* 24 */ 'p', '5', 0,
1433 /* 27 */ 'c', 'o', 'm', 'm', 'e', 'n', 't', 0,
1434 /* 35 */ 'i', 'd', 0,
1435 /* 38 */ 'p', 'a', 'r', 'e', 'n', 't', 0,
1436 /* 45 */ 'n', 'o', 't', 'u', 's', 'e', 'd', 0,
1437 /* 53 */ 'd', 'e', 't', 'a', 'i', 'l', 0
1439 static const u8 iExplainColNames16[] = {
1440 0, 5, 12, 15, 18, 21, 24, 27,
1441 35, 38, 45, 53
1445 ** Convert the N-th element of pStmt->pColName[] into a string using
1446 ** xFunc() then return that string. If N is out of range, return 0.
1448 ** There are up to 5 names for each column. useType determines which
1449 ** name is returned. Here are the names:
1451 ** 0 The column name as it should be displayed for output
1452 ** 1 The datatype name for the column
1453 ** 2 The name of the database that the column derives from
1454 ** 3 The name of the table that the column derives from
1455 ** 4 The name of the table column that the result column derives from
1457 ** If the result is not a simple column reference (if it is an expression
1458 ** or a constant) then useTypes 2, 3, and 4 return NULL.
1460 static const void *columnName(
1461 sqlite3_stmt *pStmt, /* The statement */
1462 int N, /* Which column to get the name for */
1463 int useUtf16, /* True to return the name as UTF16 */
1464 int useType /* What type of name */
1466 const void *ret;
1467 Vdbe *p;
1468 int n;
1469 sqlite3 *db;
1470 #ifdef SQLITE_ENABLE_API_ARMOR
1471 if( pStmt==0 ){
1472 (void)SQLITE_MISUSE_BKPT;
1473 return 0;
1475 #endif
1476 if( N<0 ) return 0;
1477 ret = 0;
1478 p = (Vdbe *)pStmt;
1479 db = p->db;
1480 assert( db!=0 );
1481 sqlite3_mutex_enter(db->mutex);
1483 if( p->explain ){
1484 if( useType>0 ) goto columnName_end;
1485 n = p->explain==1 ? 8 : 4;
1486 if( N>=n ) goto columnName_end;
1487 if( useUtf16 ){
1488 int i = iExplainColNames16[N + 8*p->explain - 8];
1489 ret = (void*)&azExplainColNames16data[i];
1490 }else{
1491 ret = (void*)azExplainColNames8[N + 8*p->explain - 8];
1493 goto columnName_end;
1495 n = p->nResColumn;
1496 if( N<n ){
1497 u8 prior_mallocFailed = db->mallocFailed;
1498 N += useType*n;
1499 #ifndef SQLITE_OMIT_UTF16
1500 if( useUtf16 ){
1501 ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
1502 }else
1503 #endif
1505 ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
1507 /* A malloc may have failed inside of the _text() call. If this
1508 ** is the case, clear the mallocFailed flag and return NULL.
1510 assert( db->mallocFailed==0 || db->mallocFailed==1 );
1511 if( db->mallocFailed > prior_mallocFailed ){
1512 sqlite3OomClear(db);
1513 ret = 0;
1516 columnName_end:
1517 sqlite3_mutex_leave(db->mutex);
1518 return ret;
1522 ** Return the name of the Nth column of the result set returned by SQL
1523 ** statement pStmt.
1525 const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
1526 return columnName(pStmt, N, 0, COLNAME_NAME);
1528 #ifndef SQLITE_OMIT_UTF16
1529 const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
1530 return columnName(pStmt, N, 1, COLNAME_NAME);
1532 #endif
1535 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
1536 ** not define OMIT_DECLTYPE.
1538 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
1539 # error "Must not define both SQLITE_OMIT_DECLTYPE \
1540 and SQLITE_ENABLE_COLUMN_METADATA"
1541 #endif
1543 #ifndef SQLITE_OMIT_DECLTYPE
1545 ** Return the column declaration type (if applicable) of the 'i'th column
1546 ** of the result set of SQL statement pStmt.
1548 const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
1549 return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
1551 #ifndef SQLITE_OMIT_UTF16
1552 const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
1553 return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
1555 #endif /* SQLITE_OMIT_UTF16 */
1556 #endif /* SQLITE_OMIT_DECLTYPE */
1558 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1560 ** Return the name of the database from which a result column derives.
1561 ** NULL is returned if the result column is an expression or constant or
1562 ** anything else which is not an unambiguous reference to a database column.
1564 const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
1565 return columnName(pStmt, N, 0, COLNAME_DATABASE);
1567 #ifndef SQLITE_OMIT_UTF16
1568 const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
1569 return columnName(pStmt, N, 1, COLNAME_DATABASE);
1571 #endif /* SQLITE_OMIT_UTF16 */
1574 ** Return the name of the table from which a result column derives.
1575 ** NULL is returned if the result column is an expression or constant or
1576 ** anything else which is not an unambiguous reference to a database column.
1578 const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
1579 return columnName(pStmt, N, 0, COLNAME_TABLE);
1581 #ifndef SQLITE_OMIT_UTF16
1582 const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
1583 return columnName(pStmt, N, 1, COLNAME_TABLE);
1585 #endif /* SQLITE_OMIT_UTF16 */
1588 ** Return the name of the table column from which a result column derives.
1589 ** NULL is returned if the result column is an expression or constant or
1590 ** anything else which is not an unambiguous reference to a database column.
1592 const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
1593 return columnName(pStmt, N, 0, COLNAME_COLUMN);
1595 #ifndef SQLITE_OMIT_UTF16
1596 const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
1597 return columnName(pStmt, N, 1, COLNAME_COLUMN);
1599 #endif /* SQLITE_OMIT_UTF16 */
1600 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
1603 /******************************* sqlite3_bind_ ***************************
1605 ** Routines used to attach values to wildcards in a compiled SQL statement.
1608 ** Unbind the value bound to variable i in virtual machine p. This is the
1609 ** the same as binding a NULL value to the column. If the "i" parameter is
1610 ** out of range, then SQLITE_RANGE is returned. Otherwise SQLITE_OK.
1612 ** A successful evaluation of this routine acquires the mutex on p.
1613 ** the mutex is released if any kind of error occurs.
1615 ** The error code stored in database p->db is overwritten with the return
1616 ** value in any case.
1618 static int vdbeUnbind(Vdbe *p, unsigned int i){
1619 Mem *pVar;
1620 if( vdbeSafetyNotNull(p) ){
1621 return SQLITE_MISUSE_BKPT;
1623 sqlite3_mutex_enter(p->db->mutex);
1624 if( p->eVdbeState!=VDBE_READY_STATE ){
1625 sqlite3Error(p->db, SQLITE_MISUSE_BKPT);
1626 sqlite3_mutex_leave(p->db->mutex);
1627 sqlite3_log(SQLITE_MISUSE,
1628 "bind on a busy prepared statement: [%s]", p->zSql);
1629 return SQLITE_MISUSE_BKPT;
1631 if( i>=(unsigned int)p->nVar ){
1632 sqlite3Error(p->db, SQLITE_RANGE);
1633 sqlite3_mutex_leave(p->db->mutex);
1634 return SQLITE_RANGE;
1636 pVar = &p->aVar[i];
1637 sqlite3VdbeMemRelease(pVar);
1638 pVar->flags = MEM_Null;
1639 p->db->errCode = SQLITE_OK;
1641 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
1642 ** binding a new value to this variable invalidates the current query plan.
1644 ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
1645 ** parameter in the WHERE clause might influence the choice of query plan
1646 ** for a statement, then the statement will be automatically recompiled,
1647 ** as if there had been a schema change, on the first sqlite3_step() call
1648 ** following any change to the bindings of that parameter.
1650 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
1651 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
1652 p->expired = 1;
1654 return SQLITE_OK;
1658 ** Bind a text or BLOB value.
1660 static int bindText(
1661 sqlite3_stmt *pStmt, /* The statement to bind against */
1662 int i, /* Index of the parameter to bind */
1663 const void *zData, /* Pointer to the data to be bound */
1664 i64 nData, /* Number of bytes of data to be bound */
1665 void (*xDel)(void*), /* Destructor for the data */
1666 u8 encoding /* Encoding for the data */
1668 Vdbe *p = (Vdbe *)pStmt;
1669 Mem *pVar;
1670 int rc;
1672 rc = vdbeUnbind(p, (u32)(i-1));
1673 if( rc==SQLITE_OK ){
1674 if( zData!=0 ){
1675 pVar = &p->aVar[i-1];
1676 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
1677 if( rc==SQLITE_OK && encoding!=0 ){
1678 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
1680 if( rc ){
1681 sqlite3Error(p->db, rc);
1682 rc = sqlite3ApiExit(p->db, rc);
1685 sqlite3_mutex_leave(p->db->mutex);
1686 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
1687 xDel((void*)zData);
1689 return rc;
1694 ** Bind a blob value to an SQL statement variable.
1696 int sqlite3_bind_blob(
1697 sqlite3_stmt *pStmt,
1698 int i,
1699 const void *zData,
1700 int nData,
1701 void (*xDel)(void*)
1703 #ifdef SQLITE_ENABLE_API_ARMOR
1704 if( nData<0 ) return SQLITE_MISUSE_BKPT;
1705 #endif
1706 return bindText(pStmt, i, zData, nData, xDel, 0);
1708 int sqlite3_bind_blob64(
1709 sqlite3_stmt *pStmt,
1710 int i,
1711 const void *zData,
1712 sqlite3_uint64 nData,
1713 void (*xDel)(void*)
1715 assert( xDel!=SQLITE_DYNAMIC );
1716 return bindText(pStmt, i, zData, nData, xDel, 0);
1718 int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
1719 int rc;
1720 Vdbe *p = (Vdbe *)pStmt;
1721 rc = vdbeUnbind(p, (u32)(i-1));
1722 if( rc==SQLITE_OK ){
1723 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
1724 sqlite3_mutex_leave(p->db->mutex);
1726 return rc;
1728 int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
1729 return sqlite3_bind_int64(p, i, (i64)iValue);
1731 int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
1732 int rc;
1733 Vdbe *p = (Vdbe *)pStmt;
1734 rc = vdbeUnbind(p, (u32)(i-1));
1735 if( rc==SQLITE_OK ){
1736 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
1737 sqlite3_mutex_leave(p->db->mutex);
1739 return rc;
1741 int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
1742 int rc;
1743 Vdbe *p = (Vdbe*)pStmt;
1744 rc = vdbeUnbind(p, (u32)(i-1));
1745 if( rc==SQLITE_OK ){
1746 sqlite3_mutex_leave(p->db->mutex);
1748 return rc;
1750 int sqlite3_bind_pointer(
1751 sqlite3_stmt *pStmt,
1752 int i,
1753 void *pPtr,
1754 const char *zPTtype,
1755 void (*xDestructor)(void*)
1757 int rc;
1758 Vdbe *p = (Vdbe*)pStmt;
1759 rc = vdbeUnbind(p, (u32)(i-1));
1760 if( rc==SQLITE_OK ){
1761 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
1762 sqlite3_mutex_leave(p->db->mutex);
1763 }else if( xDestructor ){
1764 xDestructor(pPtr);
1766 return rc;
1768 int sqlite3_bind_text(
1769 sqlite3_stmt *pStmt,
1770 int i,
1771 const char *zData,
1772 int nData,
1773 void (*xDel)(void*)
1775 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
1777 int sqlite3_bind_text64(
1778 sqlite3_stmt *pStmt,
1779 int i,
1780 const char *zData,
1781 sqlite3_uint64 nData,
1782 void (*xDel)(void*),
1783 unsigned char enc
1785 assert( xDel!=SQLITE_DYNAMIC );
1786 if( enc!=SQLITE_UTF8 ){
1787 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
1788 nData &= ~(u16)1;
1790 return bindText(pStmt, i, zData, nData, xDel, enc);
1792 #ifndef SQLITE_OMIT_UTF16
1793 int sqlite3_bind_text16(
1794 sqlite3_stmt *pStmt,
1795 int i,
1796 const void *zData,
1797 int n,
1798 void (*xDel)(void*)
1800 return bindText(pStmt, i, zData, n & ~(u64)1, xDel, SQLITE_UTF16NATIVE);
1802 #endif /* SQLITE_OMIT_UTF16 */
1803 int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
1804 int rc;
1805 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
1806 case SQLITE_INTEGER: {
1807 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
1808 break;
1810 case SQLITE_FLOAT: {
1811 assert( pValue->flags & (MEM_Real|MEM_IntReal) );
1812 rc = sqlite3_bind_double(pStmt, i,
1813 (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
1815 break;
1817 case SQLITE_BLOB: {
1818 if( pValue->flags & MEM_Zero ){
1819 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
1820 }else{
1821 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
1823 break;
1825 case SQLITE_TEXT: {
1826 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
1827 pValue->enc);
1828 break;
1830 default: {
1831 rc = sqlite3_bind_null(pStmt, i);
1832 break;
1835 return rc;
1837 int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
1838 int rc;
1839 Vdbe *p = (Vdbe *)pStmt;
1840 rc = vdbeUnbind(p, (u32)(i-1));
1841 if( rc==SQLITE_OK ){
1842 #ifndef SQLITE_OMIT_INCRBLOB
1843 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1844 #else
1845 rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1846 #endif
1847 sqlite3_mutex_leave(p->db->mutex);
1849 return rc;
1851 int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
1852 int rc;
1853 Vdbe *p = (Vdbe *)pStmt;
1854 #ifdef SQLITE_ENABLE_API_ARMOR
1855 if( p==0 ) return SQLITE_MISUSE_BKPT;
1856 #endif
1857 sqlite3_mutex_enter(p->db->mutex);
1858 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
1859 rc = SQLITE_TOOBIG;
1860 }else{
1861 assert( (n & 0x7FFFFFFF)==n );
1862 rc = sqlite3_bind_zeroblob(pStmt, i, n);
1864 rc = sqlite3ApiExit(p->db, rc);
1865 sqlite3_mutex_leave(p->db->mutex);
1866 return rc;
1870 ** Return the number of wildcards that can be potentially bound to.
1871 ** This routine is added to support DBD::SQLite.
1873 int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
1874 Vdbe *p = (Vdbe*)pStmt;
1875 return p ? p->nVar : 0;
1879 ** Return the name of a wildcard parameter. Return NULL if the index
1880 ** is out of range or if the wildcard is unnamed.
1882 ** The result is always UTF-8.
1884 const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
1885 Vdbe *p = (Vdbe*)pStmt;
1886 if( p==0 ) return 0;
1887 return sqlite3VListNumToName(p->pVList, i);
1891 ** Given a wildcard parameter name, return the index of the variable
1892 ** with that name. If there is no variable with the given name,
1893 ** return 0.
1895 int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
1896 if( p==0 || zName==0 ) return 0;
1897 return sqlite3VListNameToNum(p->pVList, zName, nName);
1899 int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
1900 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
1904 ** Transfer all bindings from the first statement over to the second.
1906 int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1907 Vdbe *pFrom = (Vdbe*)pFromStmt;
1908 Vdbe *pTo = (Vdbe*)pToStmt;
1909 int i;
1910 assert( pTo->db==pFrom->db );
1911 assert( pTo->nVar==pFrom->nVar );
1912 sqlite3_mutex_enter(pTo->db->mutex);
1913 for(i=0; i<pFrom->nVar; i++){
1914 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
1916 sqlite3_mutex_leave(pTo->db->mutex);
1917 return SQLITE_OK;
1920 #ifndef SQLITE_OMIT_DEPRECATED
1922 ** Deprecated external interface. Internal/core SQLite code
1923 ** should call sqlite3TransferBindings.
1925 ** It is misuse to call this routine with statements from different
1926 ** database connections. But as this is a deprecated interface, we
1927 ** will not bother to check for that condition.
1929 ** If the two statements contain a different number of bindings, then
1930 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
1931 ** SQLITE_OK is returned.
1933 int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1934 Vdbe *pFrom = (Vdbe*)pFromStmt;
1935 Vdbe *pTo = (Vdbe*)pToStmt;
1936 if( pFrom->nVar!=pTo->nVar ){
1937 return SQLITE_ERROR;
1939 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
1940 if( pTo->expmask ){
1941 pTo->expired = 1;
1943 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
1944 if( pFrom->expmask ){
1945 pFrom->expired = 1;
1947 return sqlite3TransferBindings(pFromStmt, pToStmt);
1949 #endif
1952 ** Return the sqlite3* database handle to which the prepared statement given
1953 ** in the argument belongs. This is the same database handle that was
1954 ** the first argument to the sqlite3_prepare() that was used to create
1955 ** the statement in the first place.
1957 sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
1958 return pStmt ? ((Vdbe*)pStmt)->db : 0;
1962 ** Return true if the prepared statement is guaranteed to not modify the
1963 ** database.
1965 int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
1966 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
1970 ** Return 1 if the statement is an EXPLAIN and return 2 if the
1971 ** statement is an EXPLAIN QUERY PLAN
1973 int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
1974 return pStmt ? ((Vdbe*)pStmt)->explain : 0;
1978 ** Set the explain mode for a statement.
1980 int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode){
1981 Vdbe *v = (Vdbe*)pStmt;
1982 int rc;
1983 #ifdef SQLITE_ENABLE_API_ARMOR
1984 if( pStmt==0 ) return SQLITE_MISUSE_BKPT;
1985 #endif
1986 sqlite3_mutex_enter(v->db->mutex);
1987 if( ((int)v->explain)==eMode ){
1988 rc = SQLITE_OK;
1989 }else if( eMode<0 || eMode>2 ){
1990 rc = SQLITE_ERROR;
1991 }else if( (v->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
1992 rc = SQLITE_ERROR;
1993 }else if( v->eVdbeState!=VDBE_READY_STATE ){
1994 rc = SQLITE_BUSY;
1995 }else if( v->nMem>=10 && (eMode!=2 || v->haveEqpOps) ){
1996 /* No reprepare necessary */
1997 v->explain = eMode;
1998 rc = SQLITE_OK;
1999 }else{
2000 v->explain = eMode;
2001 rc = sqlite3Reprepare(v);
2002 v->haveEqpOps = eMode==2;
2004 if( v->explain ){
2005 v->nResColumn = 12 - 4*v->explain;
2006 }else{
2007 v->nResColumn = v->nResAlloc;
2009 sqlite3_mutex_leave(v->db->mutex);
2010 return rc;
2014 ** Return true if the prepared statement is in need of being reset.
2016 int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
2017 Vdbe *v = (Vdbe*)pStmt;
2018 return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
2022 ** Return a pointer to the next prepared statement after pStmt associated
2023 ** with database connection pDb. If pStmt is NULL, return the first
2024 ** prepared statement for the database connection. Return NULL if there
2025 ** are no more.
2027 sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
2028 sqlite3_stmt *pNext;
2029 #ifdef SQLITE_ENABLE_API_ARMOR
2030 if( !sqlite3SafetyCheckOk(pDb) ){
2031 (void)SQLITE_MISUSE_BKPT;
2032 return 0;
2034 #endif
2035 sqlite3_mutex_enter(pDb->mutex);
2036 if( pStmt==0 ){
2037 pNext = (sqlite3_stmt*)pDb->pVdbe;
2038 }else{
2039 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
2041 sqlite3_mutex_leave(pDb->mutex);
2042 return pNext;
2046 ** Return the value of a status counter for a prepared statement
2048 int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
2049 Vdbe *pVdbe = (Vdbe*)pStmt;
2050 u32 v;
2051 #ifdef SQLITE_ENABLE_API_ARMOR
2052 if( !pStmt
2053 || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
2055 (void)SQLITE_MISUSE_BKPT;
2056 return 0;
2058 #endif
2059 if( op==SQLITE_STMTSTATUS_MEMUSED ){
2060 sqlite3 *db = pVdbe->db;
2061 sqlite3_mutex_enter(db->mutex);
2062 v = 0;
2063 db->pnBytesFreed = (int*)&v;
2064 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
2065 db->lookaside.pEnd = db->lookaside.pStart;
2066 sqlite3VdbeDelete(pVdbe);
2067 db->pnBytesFreed = 0;
2068 db->lookaside.pEnd = db->lookaside.pTrueEnd;
2069 sqlite3_mutex_leave(db->mutex);
2070 }else{
2071 v = pVdbe->aCounter[op];
2072 if( resetFlag ) pVdbe->aCounter[op] = 0;
2074 return (int)v;
2078 ** Return the SQL associated with a prepared statement
2080 const char *sqlite3_sql(sqlite3_stmt *pStmt){
2081 Vdbe *p = (Vdbe *)pStmt;
2082 return p ? p->zSql : 0;
2086 ** Return the SQL associated with a prepared statement with
2087 ** bound parameters expanded. Space to hold the returned string is
2088 ** obtained from sqlite3_malloc(). The caller is responsible for
2089 ** freeing the returned string by passing it to sqlite3_free().
2091 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
2092 ** expanded bound parameters.
2094 char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
2095 #ifdef SQLITE_OMIT_TRACE
2096 return 0;
2097 #else
2098 char *z = 0;
2099 const char *zSql = sqlite3_sql(pStmt);
2100 if( zSql ){
2101 Vdbe *p = (Vdbe *)pStmt;
2102 sqlite3_mutex_enter(p->db->mutex);
2103 z = sqlite3VdbeExpandSql(p, zSql);
2104 sqlite3_mutex_leave(p->db->mutex);
2106 return z;
2107 #endif
2110 #ifdef SQLITE_ENABLE_NORMALIZE
2112 ** Return the normalized SQL associated with a prepared statement.
2114 const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
2115 Vdbe *p = (Vdbe *)pStmt;
2116 if( p==0 ) return 0;
2117 if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
2118 sqlite3_mutex_enter(p->db->mutex);
2119 p->zNormSql = sqlite3Normalize(p, p->zSql);
2120 sqlite3_mutex_leave(p->db->mutex);
2122 return p->zNormSql;
2124 #endif /* SQLITE_ENABLE_NORMALIZE */
2126 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2128 ** Allocate and populate an UnpackedRecord structure based on the serialized
2129 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
2130 ** if successful, or a NULL pointer if an OOM error is encountered.
2132 static UnpackedRecord *vdbeUnpackRecord(
2133 KeyInfo *pKeyInfo,
2134 int nKey,
2135 const void *pKey
2137 UnpackedRecord *pRet; /* Return value */
2139 pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
2140 if( pRet ){
2141 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
2142 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
2144 return pRet;
2148 ** This function is called from within a pre-update callback to retrieve
2149 ** a field of the row currently being updated or deleted.
2151 int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2152 PreUpdate *p;
2153 Mem *pMem;
2154 int rc = SQLITE_OK;
2156 #ifdef SQLITE_ENABLE_API_ARMOR
2157 if( db==0 || ppValue==0 ){
2158 return SQLITE_MISUSE_BKPT;
2160 #endif
2161 p = db->pPreUpdate;
2162 /* Test that this call is being made from within an SQLITE_DELETE or
2163 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
2164 if( !p || p->op==SQLITE_INSERT ){
2165 rc = SQLITE_MISUSE_BKPT;
2166 goto preupdate_old_out;
2168 if( p->pPk ){
2169 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2171 if( iIdx>=p->pCsr->nField || iIdx<0 ){
2172 rc = SQLITE_RANGE;
2173 goto preupdate_old_out;
2176 /* If the old.* record has not yet been loaded into memory, do so now. */
2177 if( p->pUnpacked==0 ){
2178 u32 nRec;
2179 u8 *aRec;
2181 assert( p->pCsr->eCurType==CURTYPE_BTREE );
2182 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
2183 aRec = sqlite3DbMallocRaw(db, nRec);
2184 if( !aRec ) goto preupdate_old_out;
2185 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
2186 if( rc==SQLITE_OK ){
2187 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
2188 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
2190 if( rc!=SQLITE_OK ){
2191 sqlite3DbFree(db, aRec);
2192 goto preupdate_old_out;
2194 p->aRecord = aRec;
2197 pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
2198 if( iIdx==p->pTab->iPKey ){
2199 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
2200 }else if( iIdx>=p->pUnpacked->nField ){
2201 *ppValue = (sqlite3_value *)columnNullValue();
2202 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
2203 if( pMem->flags & (MEM_Int|MEM_IntReal) ){
2204 testcase( pMem->flags & MEM_Int );
2205 testcase( pMem->flags & MEM_IntReal );
2206 sqlite3VdbeMemRealify(pMem);
2210 preupdate_old_out:
2211 sqlite3Error(db, rc);
2212 return sqlite3ApiExit(db, rc);
2214 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2216 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2218 ** This function is called from within a pre-update callback to retrieve
2219 ** the number of columns in the row being updated, deleted or inserted.
2221 int sqlite3_preupdate_count(sqlite3 *db){
2222 PreUpdate *p;
2223 #ifdef SQLITE_ENABLE_API_ARMOR
2224 p = db!=0 ? db->pPreUpdate : 0;
2225 #else
2226 p = db->pPreUpdate;
2227 #endif
2228 return (p ? p->keyinfo.nKeyField : 0);
2230 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2232 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2234 ** This function is designed to be called from within a pre-update callback
2235 ** only. It returns zero if the change that caused the callback was made
2236 ** immediately by a user SQL statement. Or, if the change was made by a
2237 ** trigger program, it returns the number of trigger programs currently
2238 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
2239 ** top-level trigger etc.).
2241 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
2242 ** or SET DEFAULT action is considered a trigger.
2244 int sqlite3_preupdate_depth(sqlite3 *db){
2245 PreUpdate *p;
2246 #ifdef SQLITE_ENABLE_API_ARMOR
2247 p = db!=0 ? db->pPreUpdate : 0;
2248 #else
2249 p = db->pPreUpdate;
2250 #endif
2251 return (p ? p->v->nFrame : 0);
2253 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2255 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2257 ** This function is designed to be called from within a pre-update callback
2258 ** only.
2260 int sqlite3_preupdate_blobwrite(sqlite3 *db){
2261 PreUpdate *p;
2262 #ifdef SQLITE_ENABLE_API_ARMOR
2263 p = db!=0 ? db->pPreUpdate : 0;
2264 #else
2265 p = db->pPreUpdate;
2266 #endif
2267 return (p ? p->iBlobWrite : -1);
2269 #endif
2271 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2273 ** This function is called from within a pre-update callback to retrieve
2274 ** a field of the row currently being updated or inserted.
2276 int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2277 PreUpdate *p;
2278 int rc = SQLITE_OK;
2279 Mem *pMem;
2281 #ifdef SQLITE_ENABLE_API_ARMOR
2282 if( db==0 || ppValue==0 ){
2283 return SQLITE_MISUSE_BKPT;
2285 #endif
2286 p = db->pPreUpdate;
2287 if( !p || p->op==SQLITE_DELETE ){
2288 rc = SQLITE_MISUSE_BKPT;
2289 goto preupdate_new_out;
2291 if( p->pPk && p->op!=SQLITE_UPDATE ){
2292 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2294 if( iIdx>=p->pCsr->nField || iIdx<0 ){
2295 rc = SQLITE_RANGE;
2296 goto preupdate_new_out;
2299 if( p->op==SQLITE_INSERT ){
2300 /* For an INSERT, memory cell p->iNewReg contains the serialized record
2301 ** that is being inserted. Deserialize it. */
2302 UnpackedRecord *pUnpack = p->pNewUnpacked;
2303 if( !pUnpack ){
2304 Mem *pData = &p->v->aMem[p->iNewReg];
2305 rc = ExpandBlob(pData);
2306 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2307 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
2308 if( !pUnpack ){
2309 rc = SQLITE_NOMEM;
2310 goto preupdate_new_out;
2312 p->pNewUnpacked = pUnpack;
2314 pMem = &pUnpack->aMem[iIdx];
2315 if( iIdx==p->pTab->iPKey ){
2316 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2317 }else if( iIdx>=pUnpack->nField ){
2318 pMem = (sqlite3_value *)columnNullValue();
2320 }else{
2321 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
2322 ** value. Make a copy of the cell contents and return a pointer to it.
2323 ** It is not safe to return a pointer to the memory cell itself as the
2324 ** caller may modify the value text encoding.
2326 assert( p->op==SQLITE_UPDATE );
2327 if( !p->aNew ){
2328 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
2329 if( !p->aNew ){
2330 rc = SQLITE_NOMEM;
2331 goto preupdate_new_out;
2334 assert( iIdx>=0 && iIdx<p->pCsr->nField );
2335 pMem = &p->aNew[iIdx];
2336 if( pMem->flags==0 ){
2337 if( iIdx==p->pTab->iPKey ){
2338 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2339 }else{
2340 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
2341 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2345 *ppValue = pMem;
2347 preupdate_new_out:
2348 sqlite3Error(db, rc);
2349 return sqlite3ApiExit(db, rc);
2351 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2353 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2355 ** Return status data for a single loop within query pStmt.
2357 int sqlite3_stmt_scanstatus_v2(
2358 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2359 int iScan, /* Index of loop to report on */
2360 int iScanStatusOp, /* Which metric to return */
2361 int flags,
2362 void *pOut /* OUT: Write the answer here */
2364 Vdbe *p = (Vdbe*)pStmt;
2365 VdbeOp *aOp;
2366 int nOp;
2367 ScanStatus *pScan = 0;
2368 int idx;
2370 #ifdef SQLITE_ENABLE_API_ARMOR
2371 if( p==0 || pOut==0
2372 || iScanStatusOp<SQLITE_SCANSTAT_NLOOP
2373 || iScanStatusOp>SQLITE_SCANSTAT_NCYCLE ){
2374 return 1;
2376 #endif
2377 aOp = p->aOp;
2378 nOp = p->nOp;
2379 if( p->pFrame ){
2380 VdbeFrame *pFrame;
2381 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2382 aOp = pFrame->aOp;
2383 nOp = pFrame->nOp;
2386 if( iScan<0 ){
2387 int ii;
2388 if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
2389 i64 res = 0;
2390 for(ii=0; ii<nOp; ii++){
2391 res += aOp[ii].nCycle;
2393 *(i64*)pOut = res;
2394 return 0;
2396 return 1;
2398 if( flags & SQLITE_SCANSTAT_COMPLEX ){
2399 idx = iScan;
2400 pScan = &p->aScan[idx];
2401 }else{
2402 /* If the COMPLEX flag is clear, then this function must ignore any
2403 ** ScanStatus structures with ScanStatus.addrLoop set to 0. */
2404 for(idx=0; idx<p->nScan; idx++){
2405 pScan = &p->aScan[idx];
2406 if( pScan->zName ){
2407 iScan--;
2408 if( iScan<0 ) break;
2412 if( idx>=p->nScan ) return 1;
2414 switch( iScanStatusOp ){
2415 case SQLITE_SCANSTAT_NLOOP: {
2416 if( pScan->addrLoop>0 ){
2417 *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
2418 }else{
2419 *(sqlite3_int64*)pOut = -1;
2421 break;
2423 case SQLITE_SCANSTAT_NVISIT: {
2424 if( pScan->addrVisit>0 ){
2425 *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
2426 }else{
2427 *(sqlite3_int64*)pOut = -1;
2429 break;
2431 case SQLITE_SCANSTAT_EST: {
2432 double r = 1.0;
2433 LogEst x = pScan->nEst;
2434 while( x<100 ){
2435 x += 10;
2436 r *= 0.5;
2438 *(double*)pOut = r*sqlite3LogEstToInt(x);
2439 break;
2441 case SQLITE_SCANSTAT_NAME: {
2442 *(const char**)pOut = pScan->zName;
2443 break;
2445 case SQLITE_SCANSTAT_EXPLAIN: {
2446 if( pScan->addrExplain ){
2447 *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
2448 }else{
2449 *(const char**)pOut = 0;
2451 break;
2453 case SQLITE_SCANSTAT_SELECTID: {
2454 if( pScan->addrExplain ){
2455 *(int*)pOut = aOp[ pScan->addrExplain ].p1;
2456 }else{
2457 *(int*)pOut = -1;
2459 break;
2461 case SQLITE_SCANSTAT_PARENTID: {
2462 if( pScan->addrExplain ){
2463 *(int*)pOut = aOp[ pScan->addrExplain ].p2;
2464 }else{
2465 *(int*)pOut = -1;
2467 break;
2469 case SQLITE_SCANSTAT_NCYCLE: {
2470 i64 res = 0;
2471 if( pScan->aAddrRange[0]==0 ){
2472 res = -1;
2473 }else{
2474 int ii;
2475 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
2476 int iIns = pScan->aAddrRange[ii];
2477 int iEnd = pScan->aAddrRange[ii+1];
2478 if( iIns==0 ) break;
2479 if( iIns>0 ){
2480 while( iIns<=iEnd ){
2481 res += aOp[iIns].nCycle;
2482 iIns++;
2484 }else{
2485 int iOp;
2486 for(iOp=0; iOp<nOp; iOp++){
2487 Op *pOp = &aOp[iOp];
2488 if( pOp->p1!=iEnd ) continue;
2489 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
2490 continue;
2492 res += aOp[iOp].nCycle;
2497 *(i64*)pOut = res;
2498 break;
2500 default: {
2501 return 1;
2504 return 0;
2508 ** Return status data for a single loop within query pStmt.
2510 int sqlite3_stmt_scanstatus(
2511 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2512 int iScan, /* Index of loop to report on */
2513 int iScanStatusOp, /* Which metric to return */
2514 void *pOut /* OUT: Write the answer here */
2516 return sqlite3_stmt_scanstatus_v2(pStmt, iScan, iScanStatusOp, 0, pOut);
2520 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
2522 void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
2523 Vdbe *p = (Vdbe*)pStmt;
2524 int ii;
2525 for(ii=0; p!=0 && ii<p->nOp; ii++){
2526 Op *pOp = &p->aOp[ii];
2527 pOp->nExec = 0;
2528 pOp->nCycle = 0;
2531 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */