adjustments for constant time function volatile variables
[sqlcipher.git] / src / vdbeapi.c
blobd8fcda96dfb263f329aed21e3f9d1cade04842f3
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 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 no 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 sqlite3_result_error_toobig(pCtx);
419 return SQLITE_TOOBIG;
421 void sqlite3_result_blob(
422 sqlite3_context *pCtx,
423 const void *z,
424 int n,
425 void (*xDel)(void *)
427 assert( n>=0 );
428 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
429 setResultStrOrError(pCtx, z, n, 0, xDel);
431 void sqlite3_result_blob64(
432 sqlite3_context *pCtx,
433 const void *z,
434 sqlite3_uint64 n,
435 void (*xDel)(void *)
437 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
438 assert( xDel!=SQLITE_DYNAMIC );
439 if( n>0x7fffffff ){
440 (void)invokeValueDestructor(z, xDel, pCtx);
441 }else{
442 setResultStrOrError(pCtx, z, (int)n, 0, xDel);
445 void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
446 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
447 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
449 void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
450 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
451 pCtx->isError = SQLITE_ERROR;
452 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
454 #ifndef SQLITE_OMIT_UTF16
455 void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
456 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
457 pCtx->isError = SQLITE_ERROR;
458 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
460 #endif
461 void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
462 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
463 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
465 void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
466 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
467 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
469 void sqlite3_result_null(sqlite3_context *pCtx){
470 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
471 sqlite3VdbeMemSetNull(pCtx->pOut);
473 void sqlite3_result_pointer(
474 sqlite3_context *pCtx,
475 void *pPtr,
476 const char *zPType,
477 void (*xDestructor)(void*)
479 Mem *pOut = pCtx->pOut;
480 assert( sqlite3_mutex_held(pOut->db->mutex) );
481 sqlite3VdbeMemRelease(pOut);
482 pOut->flags = MEM_Null;
483 sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
485 void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
486 Mem *pOut = pCtx->pOut;
487 assert( sqlite3_mutex_held(pOut->db->mutex) );
488 pOut->eSubtype = eSubtype & 0xff;
489 pOut->flags |= MEM_Subtype;
491 void sqlite3_result_text(
492 sqlite3_context *pCtx,
493 const char *z,
494 int n,
495 void (*xDel)(void *)
497 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
498 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
500 void sqlite3_result_text64(
501 sqlite3_context *pCtx,
502 const char *z,
503 sqlite3_uint64 n,
504 void (*xDel)(void *),
505 unsigned char enc
507 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
508 assert( xDel!=SQLITE_DYNAMIC );
509 if( enc!=SQLITE_UTF8 ){
510 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
511 n &= ~(u64)1;
513 if( n>0x7fffffff ){
514 (void)invokeValueDestructor(z, xDel, pCtx);
515 }else{
516 setResultStrOrError(pCtx, z, (int)n, enc, xDel);
519 #ifndef SQLITE_OMIT_UTF16
520 void sqlite3_result_text16(
521 sqlite3_context *pCtx,
522 const void *z,
523 int n,
524 void (*xDel)(void *)
526 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
527 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16NATIVE, xDel);
529 void sqlite3_result_text16be(
530 sqlite3_context *pCtx,
531 const void *z,
532 int n,
533 void (*xDel)(void *)
535 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
536 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16BE, xDel);
538 void sqlite3_result_text16le(
539 sqlite3_context *pCtx,
540 const void *z,
541 int n,
542 void (*xDel)(void *)
544 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
545 setResultStrOrError(pCtx, z, n & ~(u64)1, SQLITE_UTF16LE, xDel);
547 #endif /* SQLITE_OMIT_UTF16 */
548 void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
549 Mem *pOut = pCtx->pOut;
550 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
551 sqlite3VdbeMemCopy(pOut, pValue);
552 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
553 if( sqlite3VdbeMemTooBig(pOut) ){
554 sqlite3_result_error_toobig(pCtx);
557 void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
558 sqlite3_result_zeroblob64(pCtx, n>0 ? n : 0);
560 int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
561 Mem *pOut = pCtx->pOut;
562 assert( sqlite3_mutex_held(pOut->db->mutex) );
563 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
564 sqlite3_result_error_toobig(pCtx);
565 return SQLITE_TOOBIG;
567 #ifndef SQLITE_OMIT_INCRBLOB
568 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
569 return SQLITE_OK;
570 #else
571 return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
572 #endif
574 void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
575 pCtx->isError = errCode ? errCode : -1;
576 #ifdef SQLITE_DEBUG
577 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
578 #endif
579 if( pCtx->pOut->flags & MEM_Null ){
580 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
581 SQLITE_STATIC);
585 /* Force an SQLITE_TOOBIG error. */
586 void sqlite3_result_error_toobig(sqlite3_context *pCtx){
587 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
588 pCtx->isError = SQLITE_TOOBIG;
589 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
590 SQLITE_UTF8, SQLITE_STATIC);
593 /* An SQLITE_NOMEM error. */
594 void sqlite3_result_error_nomem(sqlite3_context *pCtx){
595 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
596 sqlite3VdbeMemSetNull(pCtx->pOut);
597 pCtx->isError = SQLITE_NOMEM_BKPT;
598 sqlite3OomFault(pCtx->pOut->db);
601 #ifndef SQLITE_UNTESTABLE
602 /* Force the INT64 value currently stored as the result to be
603 ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
604 ** test-control.
606 void sqlite3ResultIntReal(sqlite3_context *pCtx){
607 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
608 if( pCtx->pOut->flags & MEM_Int ){
609 pCtx->pOut->flags &= ~MEM_Int;
610 pCtx->pOut->flags |= MEM_IntReal;
613 #endif
617 ** This function is called after a transaction has been committed. It
618 ** invokes callbacks registered with sqlite3_wal_hook() as required.
620 static int doWalCallbacks(sqlite3 *db){
621 int rc = SQLITE_OK;
622 #ifndef SQLITE_OMIT_WAL
623 int i;
624 for(i=0; i<db->nDb; i++){
625 Btree *pBt = db->aDb[i].pBt;
626 if( pBt ){
627 int nEntry;
628 sqlite3BtreeEnter(pBt);
629 nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
630 sqlite3BtreeLeave(pBt);
631 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
632 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
636 #endif
637 return rc;
642 ** Execute the statement pStmt, either until a row of data is ready, the
643 ** statement is completely executed or an error occurs.
645 ** This routine implements the bulk of the logic behind the sqlite_step()
646 ** API. The only thing omitted is the automatic recompile if a
647 ** schema change has occurred. That detail is handled by the
648 ** outer sqlite3_step() wrapper procedure.
650 static int sqlite3Step(Vdbe *p){
651 sqlite3 *db;
652 int rc;
654 assert(p);
655 db = p->db;
656 if( p->eVdbeState!=VDBE_RUN_STATE ){
657 restart_step:
658 if( p->eVdbeState==VDBE_READY_STATE ){
659 if( p->expired ){
660 p->rc = SQLITE_SCHEMA;
661 rc = SQLITE_ERROR;
662 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
663 /* If this statement was prepared using saved SQL and an
664 ** error has occurred, then return the error code in p->rc to the
665 ** caller. Set the error code in the database handle to the same
666 ** value.
668 rc = sqlite3VdbeTransferError(p);
670 goto end_of_step;
673 /* If there are no other statements currently running, then
674 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
675 ** from interrupting a statement that has not yet started.
677 if( db->nVdbeActive==0 ){
678 AtomicStore(&db->u1.isInterrupted, 0);
681 assert( db->nVdbeWrite>0 || db->autoCommit==0
682 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
685 #ifndef SQLITE_OMIT_TRACE
686 if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
687 && !db->init.busy && p->zSql ){
688 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
689 }else{
690 assert( p->startTime==0 );
692 #endif
694 db->nVdbeActive++;
695 if( p->readOnly==0 ) db->nVdbeWrite++;
696 if( p->bIsReader ) db->nVdbeRead++;
697 p->pc = 0;
698 p->eVdbeState = VDBE_RUN_STATE;
699 }else
701 if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
702 /* We used to require that sqlite3_reset() be called before retrying
703 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
704 ** with version 3.7.0, we changed this so that sqlite3_reset() would
705 ** be called automatically instead of throwing the SQLITE_MISUSE error.
706 ** This "automatic-reset" change is not technically an incompatibility,
707 ** since any application that receives an SQLITE_MISUSE is broken by
708 ** definition.
710 ** Nevertheless, some published applications that were originally written
711 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
712 ** returns, and those were broken by the automatic-reset change. As a
713 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
714 ** legacy behavior of returning SQLITE_MISUSE for cases where the
715 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
716 ** or SQLITE_BUSY error.
718 #ifdef SQLITE_OMIT_AUTORESET
719 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
720 sqlite3_reset((sqlite3_stmt*)p);
721 }else{
722 return SQLITE_MISUSE_BKPT;
724 #else
725 sqlite3_reset((sqlite3_stmt*)p);
726 #endif
727 assert( p->eVdbeState==VDBE_READY_STATE );
728 goto restart_step;
732 #ifdef SQLITE_DEBUG
733 p->rcApp = SQLITE_OK;
734 #endif
735 #ifndef SQLITE_OMIT_EXPLAIN
736 if( p->explain ){
737 rc = sqlite3VdbeList(p);
738 }else
739 #endif /* SQLITE_OMIT_EXPLAIN */
741 db->nVdbeExec++;
742 rc = sqlite3VdbeExec(p);
743 db->nVdbeExec--;
746 if( rc==SQLITE_ROW ){
747 assert( p->rc==SQLITE_OK );
748 assert( db->mallocFailed==0 );
749 db->errCode = SQLITE_ROW;
750 return SQLITE_ROW;
751 }else{
752 #ifndef SQLITE_OMIT_TRACE
753 /* If the statement completed successfully, invoke the profile callback */
754 checkProfileCallback(db, p);
755 #endif
756 p->pResultRow = 0;
757 if( rc==SQLITE_DONE && db->autoCommit ){
758 assert( p->rc==SQLITE_OK );
759 p->rc = doWalCallbacks(db);
760 if( p->rc!=SQLITE_OK ){
761 rc = SQLITE_ERROR;
763 }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
764 /* If this statement was prepared using saved SQL and an
765 ** error has occurred, then return the error code in p->rc to the
766 ** caller. Set the error code in the database handle to the same value.
768 rc = sqlite3VdbeTransferError(p);
772 db->errCode = rc;
773 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
774 p->rc = SQLITE_NOMEM_BKPT;
775 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
777 end_of_step:
778 /* There are only a limited number of result codes allowed from the
779 ** statements prepared using the legacy sqlite3_prepare() interface */
780 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
781 || rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
782 || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
784 return (rc&db->errMask);
788 ** This is the top-level implementation of sqlite3_step(). Call
789 ** sqlite3Step() to do most of the work. If a schema error occurs,
790 ** call sqlite3Reprepare() and try again.
792 int sqlite3_step(sqlite3_stmt *pStmt){
793 int rc = SQLITE_OK; /* Result from sqlite3Step() */
794 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
795 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
796 sqlite3 *db; /* The database connection */
798 if( vdbeSafetyNotNull(v) ){
799 return SQLITE_MISUSE_BKPT;
801 db = v->db;
802 sqlite3_mutex_enter(db->mutex);
803 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
804 && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
805 int savedPc = v->pc;
806 rc = sqlite3Reprepare(v);
807 if( rc!=SQLITE_OK ){
808 /* This case occurs after failing to recompile an sql statement.
809 ** The error message from the SQL compiler has already been loaded
810 ** into the database handle. This block copies the error message
811 ** from the database handle into the statement and sets the statement
812 ** program counter to 0 to ensure that when the statement is
813 ** finalized or reset the parser error message is available via
814 ** sqlite3_errmsg() and sqlite3_errcode().
816 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
817 sqlite3DbFree(db, v->zErrMsg);
818 if( !db->mallocFailed ){
819 v->zErrMsg = sqlite3DbStrDup(db, zErr);
820 v->rc = rc = sqlite3ApiExit(db, rc);
821 } else {
822 v->zErrMsg = 0;
823 v->rc = rc = SQLITE_NOMEM_BKPT;
825 break;
827 sqlite3_reset(pStmt);
828 if( savedPc>=0 ){
829 /* Setting minWriteFileFormat to 254 is a signal to the OP_Init and
830 ** OP_Trace opcodes to *not* perform SQLITE_TRACE_STMT because it has
831 ** already been done once on a prior invocation that failed due to
832 ** SQLITE_SCHEMA. tag-20220401a */
833 v->minWriteFileFormat = 254;
835 assert( v->expired==0 );
837 sqlite3_mutex_leave(db->mutex);
838 return rc;
843 ** Extract the user data from a sqlite3_context structure and return a
844 ** pointer to it.
846 void *sqlite3_user_data(sqlite3_context *p){
847 assert( p && p->pFunc );
848 return p->pFunc->pUserData;
852 ** Extract the user data from a sqlite3_context structure and return a
853 ** pointer to it.
855 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
856 ** returns a copy of the pointer to the database connection (the 1st
857 ** parameter) of the sqlite3_create_function() and
858 ** sqlite3_create_function16() routines that originally registered the
859 ** application defined function.
861 sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
862 assert( p && p->pOut );
863 return p->pOut->db;
867 ** If this routine is invoked from within an xColumn method of a virtual
868 ** table, then it returns true if and only if the the call is during an
869 ** UPDATE operation and the value of the column will not be modified
870 ** by the UPDATE.
872 ** If this routine is called from any context other than within the
873 ** xColumn method of a virtual table, then the return value is meaningless
874 ** and arbitrary.
876 ** Virtual table implements might use this routine to optimize their
877 ** performance by substituting a NULL result, or some other light-weight
878 ** value, as a signal to the xUpdate routine that the column is unchanged.
880 int sqlite3_vtab_nochange(sqlite3_context *p){
881 assert( p );
882 return sqlite3_value_nochange(p->pOut);
886 ** The destructor function for a ValueList object. This needs to be
887 ** a separate function, unknowable to the application, to ensure that
888 ** calls to sqlite3_vtab_in_first()/sqlite3_vtab_in_next() that are not
889 ** preceeded by activation of IN processing via sqlite3_vtab_int() do not
890 ** try to access a fake ValueList object inserted by a hostile extension.
892 void sqlite3VdbeValueListFree(void *pToDelete){
893 sqlite3_free(pToDelete);
897 ** Implementation of sqlite3_vtab_in_first() (if bNext==0) and
898 ** sqlite3_vtab_in_next() (if bNext!=0).
900 static int valueFromValueList(
901 sqlite3_value *pVal, /* Pointer to the ValueList object */
902 sqlite3_value **ppOut, /* Store the next value from the list here */
903 int bNext /* 1 for _next(). 0 for _first() */
905 int rc;
906 ValueList *pRhs;
908 *ppOut = 0;
909 if( pVal==0 ) return SQLITE_MISUSE;
910 if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
911 return SQLITE_ERROR;
912 }else{
913 assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
914 (MEM_Null|MEM_Term|MEM_Subtype) );
915 assert( pVal->eSubtype=='p' );
916 assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
917 pRhs = (ValueList*)pVal->z;
919 if( bNext ){
920 rc = sqlite3BtreeNext(pRhs->pCsr, 0);
921 }else{
922 int dummy = 0;
923 rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
924 assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
925 if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
927 if( rc==SQLITE_OK ){
928 u32 sz; /* Size of current row in bytes */
929 Mem sMem; /* Raw content of current row */
930 memset(&sMem, 0, sizeof(sMem));
931 sz = sqlite3BtreePayloadSize(pRhs->pCsr);
932 rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
933 if( rc==SQLITE_OK ){
934 u8 *zBuf = (u8*)sMem.z;
935 u32 iSerial;
936 sqlite3_value *pOut = pRhs->pOut;
937 int iOff = 1 + getVarint32(&zBuf[1], iSerial);
938 sqlite3VdbeSerialGet(&zBuf[iOff], iSerial, pOut);
939 pOut->enc = ENC(pOut->db);
940 if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
941 rc = SQLITE_NOMEM;
942 }else{
943 *ppOut = pOut;
946 sqlite3VdbeMemRelease(&sMem);
948 return rc;
952 ** Set the iterator value pVal to point to the first value in the set.
953 ** Set (*ppOut) to point to this value before returning.
955 int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut){
956 return valueFromValueList(pVal, ppOut, 0);
960 ** Set the iterator value pVal to point to the next value in the set.
961 ** Set (*ppOut) to point to this value before returning.
963 int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut){
964 return valueFromValueList(pVal, ppOut, 1);
968 ** Return the current time for a statement. If the current time
969 ** is requested more than once within the same run of a single prepared
970 ** statement, the exact same time is returned for each invocation regardless
971 ** of the amount of time that elapses between invocations. In other words,
972 ** the time returned is always the time of the first call.
974 sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
975 int rc;
976 #ifndef SQLITE_ENABLE_STAT4
977 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
978 assert( p->pVdbe!=0 );
979 #else
980 sqlite3_int64 iTime = 0;
981 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
982 #endif
983 if( *piTime==0 ){
984 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
985 if( rc ) *piTime = 0;
987 return *piTime;
991 ** Create a new aggregate context for p and return a pointer to
992 ** its pMem->z element.
994 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
995 Mem *pMem = p->pMem;
996 assert( (pMem->flags & MEM_Agg)==0 );
997 if( nByte<=0 ){
998 sqlite3VdbeMemSetNull(pMem);
999 pMem->z = 0;
1000 }else{
1001 sqlite3VdbeMemClearAndResize(pMem, nByte);
1002 pMem->flags = MEM_Agg;
1003 pMem->u.pDef = p->pFunc;
1004 if( pMem->z ){
1005 memset(pMem->z, 0, nByte);
1008 return (void*)pMem->z;
1012 ** Allocate or return the aggregate context for a user function. A new
1013 ** context is allocated on the first call. Subsequent calls return the
1014 ** same context that was returned on prior calls.
1016 void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
1017 assert( p && p->pFunc && p->pFunc->xFinalize );
1018 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
1019 testcase( nByte<0 );
1020 if( (p->pMem->flags & MEM_Agg)==0 ){
1021 return createAggContext(p, nByte);
1022 }else{
1023 return (void*)p->pMem->z;
1028 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
1029 ** the user-function defined by pCtx.
1031 ** The left-most argument is 0.
1033 ** Undocumented behavior: If iArg is negative then access a cache of
1034 ** auxiliary data pointers that is available to all functions within a
1035 ** single prepared statement. The iArg values must match.
1037 void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
1038 AuxData *pAuxData;
1040 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1041 #if SQLITE_ENABLE_STAT4
1042 if( pCtx->pVdbe==0 ) return 0;
1043 #else
1044 assert( pCtx->pVdbe!=0 );
1045 #endif
1046 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1047 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1048 return pAuxData->pAux;
1051 return 0;
1055 ** Set the auxiliary data pointer and delete function, for the iArg'th
1056 ** argument to the user-function defined by pCtx. Any previous value is
1057 ** deleted by calling the delete function specified when it was set.
1059 ** The left-most argument is 0.
1061 ** Undocumented behavior: If iArg is negative then make the data available
1062 ** to all functions within the current prepared statement using iArg as an
1063 ** access code.
1065 void sqlite3_set_auxdata(
1066 sqlite3_context *pCtx,
1067 int iArg,
1068 void *pAux,
1069 void (*xDelete)(void*)
1071 AuxData *pAuxData;
1072 Vdbe *pVdbe = pCtx->pVdbe;
1074 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
1075 #ifdef SQLITE_ENABLE_STAT4
1076 if( pVdbe==0 ) goto failed;
1077 #else
1078 assert( pVdbe!=0 );
1079 #endif
1081 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
1082 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
1083 break;
1086 if( pAuxData==0 ){
1087 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
1088 if( !pAuxData ) goto failed;
1089 pAuxData->iAuxOp = pCtx->iOp;
1090 pAuxData->iAuxArg = iArg;
1091 pAuxData->pNextAux = pVdbe->pAuxData;
1092 pVdbe->pAuxData = pAuxData;
1093 if( pCtx->isError==0 ) pCtx->isError = -1;
1094 }else if( pAuxData->xDeleteAux ){
1095 pAuxData->xDeleteAux(pAuxData->pAux);
1098 pAuxData->pAux = pAux;
1099 pAuxData->xDeleteAux = xDelete;
1100 return;
1102 failed:
1103 if( xDelete ){
1104 xDelete(pAux);
1108 #ifndef SQLITE_OMIT_DEPRECATED
1110 ** Return the number of times the Step function of an aggregate has been
1111 ** called.
1113 ** This function is deprecated. Do not use it for new code. It is
1114 ** provide only to avoid breaking legacy code. New aggregate function
1115 ** implementations should keep their own counts within their aggregate
1116 ** context.
1118 int sqlite3_aggregate_count(sqlite3_context *p){
1119 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
1120 return p->pMem->n;
1122 #endif
1125 ** Return the number of columns in the result set for the statement pStmt.
1127 int sqlite3_column_count(sqlite3_stmt *pStmt){
1128 Vdbe *pVm = (Vdbe *)pStmt;
1129 return pVm ? pVm->nResColumn : 0;
1133 ** Return the number of values available from the current row of the
1134 ** currently executing statement pStmt.
1136 int sqlite3_data_count(sqlite3_stmt *pStmt){
1137 Vdbe *pVm = (Vdbe *)pStmt;
1138 if( pVm==0 || pVm->pResultRow==0 ) return 0;
1139 return pVm->nResColumn;
1143 ** Return a pointer to static memory containing an SQL NULL value.
1145 static const Mem *columnNullValue(void){
1146 /* Even though the Mem structure contains an element
1147 ** of type i64, on certain architectures (x86) with certain compiler
1148 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
1149 ** instead of an 8-byte one. This all works fine, except that when
1150 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
1151 ** that a Mem structure is located on an 8-byte boundary. To prevent
1152 ** these assert()s from failing, when building with SQLITE_DEBUG defined
1153 ** using gcc, we force nullMem to be 8-byte aligned using the magical
1154 ** __attribute__((aligned(8))) macro. */
1155 static const Mem nullMem
1156 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
1157 __attribute__((aligned(8)))
1158 #endif
1160 /* .u = */ {0},
1161 /* .z = */ (char*)0,
1162 /* .n = */ (int)0,
1163 /* .flags = */ (u16)MEM_Null,
1164 /* .enc = */ (u8)0,
1165 /* .eSubtype = */ (u8)0,
1166 /* .db = */ (sqlite3*)0,
1167 /* .szMalloc = */ (int)0,
1168 /* .uTemp = */ (u32)0,
1169 /* .zMalloc = */ (char*)0,
1170 /* .xDel = */ (void(*)(void*))0,
1171 #ifdef SQLITE_DEBUG
1172 /* .pScopyFrom = */ (Mem*)0,
1173 /* .mScopyFlags= */ 0,
1174 #endif
1176 return &nullMem;
1180 ** Check to see if column iCol of the given statement is valid. If
1181 ** it is, return a pointer to the Mem for the value of that column.
1182 ** If iCol is not valid, return a pointer to a Mem which has a value
1183 ** of NULL.
1185 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
1186 Vdbe *pVm;
1187 Mem *pOut;
1189 pVm = (Vdbe *)pStmt;
1190 if( pVm==0 ) return (Mem*)columnNullValue();
1191 assert( pVm->db );
1192 sqlite3_mutex_enter(pVm->db->mutex);
1193 if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
1194 pOut = &pVm->pResultRow[i];
1195 }else{
1196 sqlite3Error(pVm->db, SQLITE_RANGE);
1197 pOut = (Mem*)columnNullValue();
1199 return pOut;
1203 ** This function is called after invoking an sqlite3_value_XXX function on a
1204 ** column value (i.e. a value returned by evaluating an SQL expression in the
1205 ** select list of a SELECT statement) that may cause a malloc() failure. If
1206 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
1207 ** code of statement pStmt set to SQLITE_NOMEM.
1209 ** Specifically, this is called from within:
1211 ** sqlite3_column_int()
1212 ** sqlite3_column_int64()
1213 ** sqlite3_column_text()
1214 ** sqlite3_column_text16()
1215 ** sqlite3_column_real()
1216 ** sqlite3_column_bytes()
1217 ** sqlite3_column_bytes16()
1218 ** sqiite3_column_blob()
1220 static void columnMallocFailure(sqlite3_stmt *pStmt)
1222 /* If malloc() failed during an encoding conversion within an
1223 ** sqlite3_column_XXX API, then set the return code of the statement to
1224 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
1225 ** and _finalize() will return NOMEM.
1227 Vdbe *p = (Vdbe *)pStmt;
1228 if( p ){
1229 assert( p->db!=0 );
1230 assert( sqlite3_mutex_held(p->db->mutex) );
1231 p->rc = sqlite3ApiExit(p->db, p->rc);
1232 sqlite3_mutex_leave(p->db->mutex);
1236 /**************************** sqlite3_column_ *******************************
1237 ** The following routines are used to access elements of the current row
1238 ** in the result set.
1240 const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
1241 const void *val;
1242 val = sqlite3_value_blob( columnMem(pStmt,i) );
1243 /* Even though there is no encoding conversion, value_blob() might
1244 ** need to call malloc() to expand the result of a zeroblob()
1245 ** expression.
1247 columnMallocFailure(pStmt);
1248 return val;
1250 int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
1251 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
1252 columnMallocFailure(pStmt);
1253 return val;
1255 int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
1256 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
1257 columnMallocFailure(pStmt);
1258 return val;
1260 double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
1261 double val = sqlite3_value_double( columnMem(pStmt,i) );
1262 columnMallocFailure(pStmt);
1263 return val;
1265 int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
1266 int val = sqlite3_value_int( columnMem(pStmt,i) );
1267 columnMallocFailure(pStmt);
1268 return val;
1270 sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
1271 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
1272 columnMallocFailure(pStmt);
1273 return val;
1275 const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
1276 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
1277 columnMallocFailure(pStmt);
1278 return val;
1280 sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
1281 Mem *pOut = columnMem(pStmt, i);
1282 if( pOut->flags&MEM_Static ){
1283 pOut->flags &= ~MEM_Static;
1284 pOut->flags |= MEM_Ephem;
1286 columnMallocFailure(pStmt);
1287 return (sqlite3_value *)pOut;
1289 #ifndef SQLITE_OMIT_UTF16
1290 const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
1291 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
1292 columnMallocFailure(pStmt);
1293 return val;
1295 #endif /* SQLITE_OMIT_UTF16 */
1296 int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
1297 int iType = sqlite3_value_type( columnMem(pStmt,i) );
1298 columnMallocFailure(pStmt);
1299 return iType;
1303 ** Convert the N-th element of pStmt->pColName[] into a string using
1304 ** xFunc() then return that string. If N is out of range, return 0.
1306 ** There are up to 5 names for each column. useType determines which
1307 ** name is returned. Here are the names:
1309 ** 0 The column name as it should be displayed for output
1310 ** 1 The datatype name for the column
1311 ** 2 The name of the database that the column derives from
1312 ** 3 The name of the table that the column derives from
1313 ** 4 The name of the table column that the result column derives from
1315 ** If the result is not a simple column reference (if it is an expression
1316 ** or a constant) then useTypes 2, 3, and 4 return NULL.
1318 static const void *columnName(
1319 sqlite3_stmt *pStmt, /* The statement */
1320 int N, /* Which column to get the name for */
1321 int useUtf16, /* True to return the name as UTF16 */
1322 int useType /* What type of name */
1324 const void *ret;
1325 Vdbe *p;
1326 int n;
1327 sqlite3 *db;
1328 #ifdef SQLITE_ENABLE_API_ARMOR
1329 if( pStmt==0 ){
1330 (void)SQLITE_MISUSE_BKPT;
1331 return 0;
1333 #endif
1334 ret = 0;
1335 p = (Vdbe *)pStmt;
1336 db = p->db;
1337 assert( db!=0 );
1338 n = sqlite3_column_count(pStmt);
1339 if( N<n && N>=0 ){
1340 u8 prior_mallocFailed = db->mallocFailed;
1341 N += useType*n;
1342 sqlite3_mutex_enter(db->mutex);
1343 #ifndef SQLITE_OMIT_UTF16
1344 if( useUtf16 ){
1345 ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
1346 }else
1347 #endif
1349 ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
1351 /* A malloc may have failed inside of the _text() call. If this
1352 ** is the case, clear the mallocFailed flag and return NULL.
1354 assert( db->mallocFailed==0 || db->mallocFailed==1 );
1355 if( db->mallocFailed > prior_mallocFailed ){
1356 sqlite3OomClear(db);
1357 ret = 0;
1359 sqlite3_mutex_leave(db->mutex);
1361 return ret;
1365 ** Return the name of the Nth column of the result set returned by SQL
1366 ** statement pStmt.
1368 const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
1369 return columnName(pStmt, N, 0, COLNAME_NAME);
1371 #ifndef SQLITE_OMIT_UTF16
1372 const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
1373 return columnName(pStmt, N, 1, COLNAME_NAME);
1375 #endif
1378 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
1379 ** not define OMIT_DECLTYPE.
1381 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
1382 # error "Must not define both SQLITE_OMIT_DECLTYPE \
1383 and SQLITE_ENABLE_COLUMN_METADATA"
1384 #endif
1386 #ifndef SQLITE_OMIT_DECLTYPE
1388 ** Return the column declaration type (if applicable) of the 'i'th column
1389 ** of the result set of SQL statement pStmt.
1391 const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
1392 return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
1394 #ifndef SQLITE_OMIT_UTF16
1395 const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
1396 return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
1398 #endif /* SQLITE_OMIT_UTF16 */
1399 #endif /* SQLITE_OMIT_DECLTYPE */
1401 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1403 ** Return the name of the database from which a result column derives.
1404 ** NULL is returned if the result column is an expression or constant or
1405 ** anything else which is not an unambiguous reference to a database column.
1407 const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
1408 return columnName(pStmt, N, 0, COLNAME_DATABASE);
1410 #ifndef SQLITE_OMIT_UTF16
1411 const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
1412 return columnName(pStmt, N, 1, COLNAME_DATABASE);
1414 #endif /* SQLITE_OMIT_UTF16 */
1417 ** Return the name of the table from which a result column derives.
1418 ** NULL is returned if the result column is an expression or constant or
1419 ** anything else which is not an unambiguous reference to a database column.
1421 const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
1422 return columnName(pStmt, N, 0, COLNAME_TABLE);
1424 #ifndef SQLITE_OMIT_UTF16
1425 const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
1426 return columnName(pStmt, N, 1, COLNAME_TABLE);
1428 #endif /* SQLITE_OMIT_UTF16 */
1431 ** Return the name of the table column from which a result column derives.
1432 ** NULL is returned if the result column is an expression or constant or
1433 ** anything else which is not an unambiguous reference to a database column.
1435 const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
1436 return columnName(pStmt, N, 0, COLNAME_COLUMN);
1438 #ifndef SQLITE_OMIT_UTF16
1439 const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
1440 return columnName(pStmt, N, 1, COLNAME_COLUMN);
1442 #endif /* SQLITE_OMIT_UTF16 */
1443 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
1446 /******************************* sqlite3_bind_ ***************************
1448 ** Routines used to attach values to wildcards in a compiled SQL statement.
1451 ** Unbind the value bound to variable i in virtual machine p. This is the
1452 ** the same as binding a NULL value to the column. If the "i" parameter is
1453 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
1455 ** A successful evaluation of this routine acquires the mutex on p.
1456 ** the mutex is released if any kind of error occurs.
1458 ** The error code stored in database p->db is overwritten with the return
1459 ** value in any case.
1461 static int vdbeUnbind(Vdbe *p, unsigned int i){
1462 Mem *pVar;
1463 if( vdbeSafetyNotNull(p) ){
1464 return SQLITE_MISUSE_BKPT;
1466 sqlite3_mutex_enter(p->db->mutex);
1467 if( p->eVdbeState!=VDBE_READY_STATE ){
1468 sqlite3Error(p->db, SQLITE_MISUSE);
1469 sqlite3_mutex_leave(p->db->mutex);
1470 sqlite3_log(SQLITE_MISUSE,
1471 "bind on a busy prepared statement: [%s]", p->zSql);
1472 return SQLITE_MISUSE_BKPT;
1474 if( i>=(unsigned int)p->nVar ){
1475 sqlite3Error(p->db, SQLITE_RANGE);
1476 sqlite3_mutex_leave(p->db->mutex);
1477 return SQLITE_RANGE;
1479 pVar = &p->aVar[i];
1480 sqlite3VdbeMemRelease(pVar);
1481 pVar->flags = MEM_Null;
1482 p->db->errCode = SQLITE_OK;
1484 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
1485 ** binding a new value to this variable invalidates the current query plan.
1487 ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
1488 ** parameter in the WHERE clause might influence the choice of query plan
1489 ** for a statement, then the statement will be automatically recompiled,
1490 ** as if there had been a schema change, on the first sqlite3_step() call
1491 ** following any change to the bindings of that parameter.
1493 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
1494 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
1495 p->expired = 1;
1497 return SQLITE_OK;
1501 ** Bind a text or BLOB value.
1503 static int bindText(
1504 sqlite3_stmt *pStmt, /* The statement to bind against */
1505 int i, /* Index of the parameter to bind */
1506 const void *zData, /* Pointer to the data to be bound */
1507 i64 nData, /* Number of bytes of data to be bound */
1508 void (*xDel)(void*), /* Destructor for the data */
1509 u8 encoding /* Encoding for the data */
1511 Vdbe *p = (Vdbe *)pStmt;
1512 Mem *pVar;
1513 int rc;
1515 rc = vdbeUnbind(p, (u32)(i-1));
1516 if( rc==SQLITE_OK ){
1517 if( zData!=0 ){
1518 pVar = &p->aVar[i-1];
1519 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
1520 if( rc==SQLITE_OK && encoding!=0 ){
1521 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
1523 if( rc ){
1524 sqlite3Error(p->db, rc);
1525 rc = sqlite3ApiExit(p->db, rc);
1528 sqlite3_mutex_leave(p->db->mutex);
1529 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
1530 xDel((void*)zData);
1532 return rc;
1537 ** Bind a blob value to an SQL statement variable.
1539 int sqlite3_bind_blob(
1540 sqlite3_stmt *pStmt,
1541 int i,
1542 const void *zData,
1543 int nData,
1544 void (*xDel)(void*)
1546 #ifdef SQLITE_ENABLE_API_ARMOR
1547 if( nData<0 ) return SQLITE_MISUSE_BKPT;
1548 #endif
1549 return bindText(pStmt, i, zData, nData, xDel, 0);
1551 int sqlite3_bind_blob64(
1552 sqlite3_stmt *pStmt,
1553 int i,
1554 const void *zData,
1555 sqlite3_uint64 nData,
1556 void (*xDel)(void*)
1558 assert( xDel!=SQLITE_DYNAMIC );
1559 return bindText(pStmt, i, zData, nData, xDel, 0);
1561 int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
1562 int rc;
1563 Vdbe *p = (Vdbe *)pStmt;
1564 rc = vdbeUnbind(p, (u32)(i-1));
1565 if( rc==SQLITE_OK ){
1566 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
1567 sqlite3_mutex_leave(p->db->mutex);
1569 return rc;
1571 int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
1572 return sqlite3_bind_int64(p, i, (i64)iValue);
1574 int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
1575 int rc;
1576 Vdbe *p = (Vdbe *)pStmt;
1577 rc = vdbeUnbind(p, (u32)(i-1));
1578 if( rc==SQLITE_OK ){
1579 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
1580 sqlite3_mutex_leave(p->db->mutex);
1582 return rc;
1584 int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
1585 int rc;
1586 Vdbe *p = (Vdbe*)pStmt;
1587 rc = vdbeUnbind(p, (u32)(i-1));
1588 if( rc==SQLITE_OK ){
1589 sqlite3_mutex_leave(p->db->mutex);
1591 return rc;
1593 int sqlite3_bind_pointer(
1594 sqlite3_stmt *pStmt,
1595 int i,
1596 void *pPtr,
1597 const char *zPTtype,
1598 void (*xDestructor)(void*)
1600 int rc;
1601 Vdbe *p = (Vdbe*)pStmt;
1602 rc = vdbeUnbind(p, (u32)(i-1));
1603 if( rc==SQLITE_OK ){
1604 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
1605 sqlite3_mutex_leave(p->db->mutex);
1606 }else if( xDestructor ){
1607 xDestructor(pPtr);
1609 return rc;
1611 int sqlite3_bind_text(
1612 sqlite3_stmt *pStmt,
1613 int i,
1614 const char *zData,
1615 int nData,
1616 void (*xDel)(void*)
1618 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
1620 int sqlite3_bind_text64(
1621 sqlite3_stmt *pStmt,
1622 int i,
1623 const char *zData,
1624 sqlite3_uint64 nData,
1625 void (*xDel)(void*),
1626 unsigned char enc
1628 assert( xDel!=SQLITE_DYNAMIC );
1629 if( enc!=SQLITE_UTF8 ){
1630 if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
1631 nData &= ~(u16)1;
1633 return bindText(pStmt, i, zData, nData, xDel, enc);
1635 #ifndef SQLITE_OMIT_UTF16
1636 int sqlite3_bind_text16(
1637 sqlite3_stmt *pStmt,
1638 int i,
1639 const void *zData,
1640 int n,
1641 void (*xDel)(void*)
1643 return bindText(pStmt, i, zData, n & ~(u64)1, xDel, SQLITE_UTF16NATIVE);
1645 #endif /* SQLITE_OMIT_UTF16 */
1646 int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
1647 int rc;
1648 switch( sqlite3_value_type((sqlite3_value*)pValue) ){
1649 case SQLITE_INTEGER: {
1650 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
1651 break;
1653 case SQLITE_FLOAT: {
1654 assert( pValue->flags & (MEM_Real|MEM_IntReal) );
1655 rc = sqlite3_bind_double(pStmt, i,
1656 (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
1658 break;
1660 case SQLITE_BLOB: {
1661 if( pValue->flags & MEM_Zero ){
1662 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
1663 }else{
1664 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
1666 break;
1668 case SQLITE_TEXT: {
1669 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
1670 pValue->enc);
1671 break;
1673 default: {
1674 rc = sqlite3_bind_null(pStmt, i);
1675 break;
1678 return rc;
1680 int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
1681 int rc;
1682 Vdbe *p = (Vdbe *)pStmt;
1683 rc = vdbeUnbind(p, (u32)(i-1));
1684 if( rc==SQLITE_OK ){
1685 #ifndef SQLITE_OMIT_INCRBLOB
1686 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1687 #else
1688 rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
1689 #endif
1690 sqlite3_mutex_leave(p->db->mutex);
1692 return rc;
1694 int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
1695 int rc;
1696 Vdbe *p = (Vdbe *)pStmt;
1697 sqlite3_mutex_enter(p->db->mutex);
1698 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
1699 rc = SQLITE_TOOBIG;
1700 }else{
1701 assert( (n & 0x7FFFFFFF)==n );
1702 rc = sqlite3_bind_zeroblob(pStmt, i, n);
1704 rc = sqlite3ApiExit(p->db, rc);
1705 sqlite3_mutex_leave(p->db->mutex);
1706 return rc;
1710 ** Return the number of wildcards that can be potentially bound to.
1711 ** This routine is added to support DBD::SQLite.
1713 int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
1714 Vdbe *p = (Vdbe*)pStmt;
1715 return p ? p->nVar : 0;
1719 ** Return the name of a wildcard parameter. Return NULL if the index
1720 ** is out of range or if the wildcard is unnamed.
1722 ** The result is always UTF-8.
1724 const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
1725 Vdbe *p = (Vdbe*)pStmt;
1726 if( p==0 ) return 0;
1727 return sqlite3VListNumToName(p->pVList, i);
1731 ** Given a wildcard parameter name, return the index of the variable
1732 ** with that name. If there is no variable with the given name,
1733 ** return 0.
1735 int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
1736 if( p==0 || zName==0 ) return 0;
1737 return sqlite3VListNameToNum(p->pVList, zName, nName);
1739 int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
1740 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
1744 ** Transfer all bindings from the first statement over to the second.
1746 int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1747 Vdbe *pFrom = (Vdbe*)pFromStmt;
1748 Vdbe *pTo = (Vdbe*)pToStmt;
1749 int i;
1750 assert( pTo->db==pFrom->db );
1751 assert( pTo->nVar==pFrom->nVar );
1752 sqlite3_mutex_enter(pTo->db->mutex);
1753 for(i=0; i<pFrom->nVar; i++){
1754 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
1756 sqlite3_mutex_leave(pTo->db->mutex);
1757 return SQLITE_OK;
1760 #ifndef SQLITE_OMIT_DEPRECATED
1762 ** Deprecated external interface. Internal/core SQLite code
1763 ** should call sqlite3TransferBindings.
1765 ** It is misuse to call this routine with statements from different
1766 ** database connections. But as this is a deprecated interface, we
1767 ** will not bother to check for that condition.
1769 ** If the two statements contain a different number of bindings, then
1770 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
1771 ** SQLITE_OK is returned.
1773 int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
1774 Vdbe *pFrom = (Vdbe*)pFromStmt;
1775 Vdbe *pTo = (Vdbe*)pToStmt;
1776 if( pFrom->nVar!=pTo->nVar ){
1777 return SQLITE_ERROR;
1779 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
1780 if( pTo->expmask ){
1781 pTo->expired = 1;
1783 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
1784 if( pFrom->expmask ){
1785 pFrom->expired = 1;
1787 return sqlite3TransferBindings(pFromStmt, pToStmt);
1789 #endif
1792 ** Return the sqlite3* database handle to which the prepared statement given
1793 ** in the argument belongs. This is the same database handle that was
1794 ** the first argument to the sqlite3_prepare() that was used to create
1795 ** the statement in the first place.
1797 sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
1798 return pStmt ? ((Vdbe*)pStmt)->db : 0;
1802 ** Return true if the prepared statement is guaranteed to not modify the
1803 ** database.
1805 int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
1806 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
1810 ** Return 1 if the statement is an EXPLAIN and return 2 if the
1811 ** statement is an EXPLAIN QUERY PLAN
1813 int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
1814 return pStmt ? ((Vdbe*)pStmt)->explain : 0;
1818 ** Return true if the prepared statement is in need of being reset.
1820 int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
1821 Vdbe *v = (Vdbe*)pStmt;
1822 return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
1826 ** Return a pointer to the next prepared statement after pStmt associated
1827 ** with database connection pDb. If pStmt is NULL, return the first
1828 ** prepared statement for the database connection. Return NULL if there
1829 ** are no more.
1831 sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
1832 sqlite3_stmt *pNext;
1833 #ifdef SQLITE_ENABLE_API_ARMOR
1834 if( !sqlite3SafetyCheckOk(pDb) ){
1835 (void)SQLITE_MISUSE_BKPT;
1836 return 0;
1838 #endif
1839 sqlite3_mutex_enter(pDb->mutex);
1840 if( pStmt==0 ){
1841 pNext = (sqlite3_stmt*)pDb->pVdbe;
1842 }else{
1843 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
1845 sqlite3_mutex_leave(pDb->mutex);
1846 return pNext;
1850 ** Return the value of a status counter for a prepared statement
1852 int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
1853 Vdbe *pVdbe = (Vdbe*)pStmt;
1854 u32 v;
1855 #ifdef SQLITE_ENABLE_API_ARMOR
1856 if( !pStmt
1857 || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
1859 (void)SQLITE_MISUSE_BKPT;
1860 return 0;
1862 #endif
1863 if( op==SQLITE_STMTSTATUS_MEMUSED ){
1864 sqlite3 *db = pVdbe->db;
1865 sqlite3_mutex_enter(db->mutex);
1866 v = 0;
1867 db->pnBytesFreed = (int*)&v;
1868 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
1869 db->lookaside.pEnd = db->lookaside.pStart;
1870 sqlite3VdbeDelete(pVdbe);
1871 db->pnBytesFreed = 0;
1872 db->lookaside.pEnd = db->lookaside.pTrueEnd;
1873 sqlite3_mutex_leave(db->mutex);
1874 }else{
1875 v = pVdbe->aCounter[op];
1876 if( resetFlag ) pVdbe->aCounter[op] = 0;
1878 return (int)v;
1882 ** Return the SQL associated with a prepared statement
1884 const char *sqlite3_sql(sqlite3_stmt *pStmt){
1885 Vdbe *p = (Vdbe *)pStmt;
1886 return p ? p->zSql : 0;
1890 ** Return the SQL associated with a prepared statement with
1891 ** bound parameters expanded. Space to hold the returned string is
1892 ** obtained from sqlite3_malloc(). The caller is responsible for
1893 ** freeing the returned string by passing it to sqlite3_free().
1895 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
1896 ** expanded bound parameters.
1898 char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
1899 #ifdef SQLITE_OMIT_TRACE
1900 return 0;
1901 #else
1902 char *z = 0;
1903 const char *zSql = sqlite3_sql(pStmt);
1904 if( zSql ){
1905 Vdbe *p = (Vdbe *)pStmt;
1906 sqlite3_mutex_enter(p->db->mutex);
1907 z = sqlite3VdbeExpandSql(p, zSql);
1908 sqlite3_mutex_leave(p->db->mutex);
1910 return z;
1911 #endif
1914 #ifdef SQLITE_ENABLE_NORMALIZE
1916 ** Return the normalized SQL associated with a prepared statement.
1918 const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
1919 Vdbe *p = (Vdbe *)pStmt;
1920 if( p==0 ) return 0;
1921 if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
1922 sqlite3_mutex_enter(p->db->mutex);
1923 p->zNormSql = sqlite3Normalize(p, p->zSql);
1924 sqlite3_mutex_leave(p->db->mutex);
1926 return p->zNormSql;
1928 #endif /* SQLITE_ENABLE_NORMALIZE */
1930 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1932 ** Allocate and populate an UnpackedRecord structure based on the serialized
1933 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
1934 ** if successful, or a NULL pointer if an OOM error is encountered.
1936 static UnpackedRecord *vdbeUnpackRecord(
1937 KeyInfo *pKeyInfo,
1938 int nKey,
1939 const void *pKey
1941 UnpackedRecord *pRet; /* Return value */
1943 pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
1944 if( pRet ){
1945 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
1946 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
1948 return pRet;
1952 ** This function is called from within a pre-update callback to retrieve
1953 ** a field of the row currently being updated or deleted.
1955 int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
1956 PreUpdate *p = db->pPreUpdate;
1957 Mem *pMem;
1958 int rc = SQLITE_OK;
1960 /* Test that this call is being made from within an SQLITE_DELETE or
1961 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
1962 if( !p || p->op==SQLITE_INSERT ){
1963 rc = SQLITE_MISUSE_BKPT;
1964 goto preupdate_old_out;
1966 if( p->pPk ){
1967 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
1969 if( iIdx>=p->pCsr->nField || iIdx<0 ){
1970 rc = SQLITE_RANGE;
1971 goto preupdate_old_out;
1974 /* If the old.* record has not yet been loaded into memory, do so now. */
1975 if( p->pUnpacked==0 ){
1976 u32 nRec;
1977 u8 *aRec;
1979 assert( p->pCsr->eCurType==CURTYPE_BTREE );
1980 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
1981 aRec = sqlite3DbMallocRaw(db, nRec);
1982 if( !aRec ) goto preupdate_old_out;
1983 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
1984 if( rc==SQLITE_OK ){
1985 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
1986 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
1988 if( rc!=SQLITE_OK ){
1989 sqlite3DbFree(db, aRec);
1990 goto preupdate_old_out;
1992 p->aRecord = aRec;
1995 pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
1996 if( iIdx==p->pTab->iPKey ){
1997 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
1998 }else if( iIdx>=p->pUnpacked->nField ){
1999 *ppValue = (sqlite3_value *)columnNullValue();
2000 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
2001 if( pMem->flags & (MEM_Int|MEM_IntReal) ){
2002 testcase( pMem->flags & MEM_Int );
2003 testcase( pMem->flags & MEM_IntReal );
2004 sqlite3VdbeMemRealify(pMem);
2008 preupdate_old_out:
2009 sqlite3Error(db, rc);
2010 return sqlite3ApiExit(db, rc);
2012 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2014 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2016 ** This function is called from within a pre-update callback to retrieve
2017 ** the number of columns in the row being updated, deleted or inserted.
2019 int sqlite3_preupdate_count(sqlite3 *db){
2020 PreUpdate *p = db->pPreUpdate;
2021 return (p ? p->keyinfo.nKeyField : 0);
2023 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2025 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2027 ** This function is designed to be called from within a pre-update callback
2028 ** only. It returns zero if the change that caused the callback was made
2029 ** immediately by a user SQL statement. Or, if the change was made by a
2030 ** trigger program, it returns the number of trigger programs currently
2031 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
2032 ** top-level trigger etc.).
2034 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
2035 ** or SET DEFAULT action is considered a trigger.
2037 int sqlite3_preupdate_depth(sqlite3 *db){
2038 PreUpdate *p = db->pPreUpdate;
2039 return (p ? p->v->nFrame : 0);
2041 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2043 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2045 ** This function is designed to be called from within a pre-update callback
2046 ** only.
2048 int sqlite3_preupdate_blobwrite(sqlite3 *db){
2049 PreUpdate *p = db->pPreUpdate;
2050 return (p ? p->iBlobWrite : -1);
2052 #endif
2054 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2056 ** This function is called from within a pre-update callback to retrieve
2057 ** a field of the row currently being updated or inserted.
2059 int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
2060 PreUpdate *p = db->pPreUpdate;
2061 int rc = SQLITE_OK;
2062 Mem *pMem;
2064 if( !p || p->op==SQLITE_DELETE ){
2065 rc = SQLITE_MISUSE_BKPT;
2066 goto preupdate_new_out;
2068 if( p->pPk && p->op!=SQLITE_UPDATE ){
2069 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
2071 if( iIdx>=p->pCsr->nField || iIdx<0 ){
2072 rc = SQLITE_RANGE;
2073 goto preupdate_new_out;
2076 if( p->op==SQLITE_INSERT ){
2077 /* For an INSERT, memory cell p->iNewReg contains the serialized record
2078 ** that is being inserted. Deserialize it. */
2079 UnpackedRecord *pUnpack = p->pNewUnpacked;
2080 if( !pUnpack ){
2081 Mem *pData = &p->v->aMem[p->iNewReg];
2082 rc = ExpandBlob(pData);
2083 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2084 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
2085 if( !pUnpack ){
2086 rc = SQLITE_NOMEM;
2087 goto preupdate_new_out;
2089 p->pNewUnpacked = pUnpack;
2091 pMem = &pUnpack->aMem[iIdx];
2092 if( iIdx==p->pTab->iPKey ){
2093 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2094 }else if( iIdx>=pUnpack->nField ){
2095 pMem = (sqlite3_value *)columnNullValue();
2097 }else{
2098 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
2099 ** value. Make a copy of the cell contents and return a pointer to it.
2100 ** It is not safe to return a pointer to the memory cell itself as the
2101 ** caller may modify the value text encoding.
2103 assert( p->op==SQLITE_UPDATE );
2104 if( !p->aNew ){
2105 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
2106 if( !p->aNew ){
2107 rc = SQLITE_NOMEM;
2108 goto preupdate_new_out;
2111 assert( iIdx>=0 && iIdx<p->pCsr->nField );
2112 pMem = &p->aNew[iIdx];
2113 if( pMem->flags==0 ){
2114 if( iIdx==p->pTab->iPKey ){
2115 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
2116 }else{
2117 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
2118 if( rc!=SQLITE_OK ) goto preupdate_new_out;
2122 *ppValue = pMem;
2124 preupdate_new_out:
2125 sqlite3Error(db, rc);
2126 return sqlite3ApiExit(db, rc);
2128 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
2130 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2132 ** Return status data for a single loop within query pStmt.
2134 int sqlite3_stmt_scanstatus_v2(
2135 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2136 int iScan, /* Index of loop to report on */
2137 int iScanStatusOp, /* Which metric to return */
2138 int flags,
2139 void *pOut /* OUT: Write the answer here */
2141 Vdbe *p = (Vdbe*)pStmt;
2142 VdbeOp *aOp = p->aOp;
2143 int nOp = p->nOp;
2144 ScanStatus *pScan = 0;
2145 int idx;
2147 if( p->pFrame ){
2148 VdbeFrame *pFrame;
2149 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
2150 aOp = pFrame->aOp;
2151 nOp = pFrame->nOp;
2154 if( iScan<0 ){
2155 int ii;
2156 if( iScanStatusOp==SQLITE_SCANSTAT_NCYCLE ){
2157 i64 res = 0;
2158 for(ii=0; ii<nOp; ii++){
2159 res += aOp[ii].nCycle;
2161 *(i64*)pOut = res;
2162 return 0;
2164 return 1;
2166 if( flags & SQLITE_SCANSTAT_COMPLEX ){
2167 idx = iScan;
2168 pScan = &p->aScan[idx];
2169 }else{
2170 /* If the COMPLEX flag is clear, then this function must ignore any
2171 ** ScanStatus structures with ScanStatus.addrLoop set to 0. */
2172 for(idx=0; idx<p->nScan; idx++){
2173 pScan = &p->aScan[idx];
2174 if( pScan->zName ){
2175 iScan--;
2176 if( iScan<0 ) break;
2180 if( idx>=p->nScan ) return 1;
2182 switch( iScanStatusOp ){
2183 case SQLITE_SCANSTAT_NLOOP: {
2184 if( pScan->addrLoop>0 ){
2185 *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
2186 }else{
2187 *(sqlite3_int64*)pOut = -1;
2189 break;
2191 case SQLITE_SCANSTAT_NVISIT: {
2192 if( pScan->addrVisit>0 ){
2193 *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
2194 }else{
2195 *(sqlite3_int64*)pOut = -1;
2197 break;
2199 case SQLITE_SCANSTAT_EST: {
2200 double r = 1.0;
2201 LogEst x = pScan->nEst;
2202 while( x<100 ){
2203 x += 10;
2204 r *= 0.5;
2206 *(double*)pOut = r*sqlite3LogEstToInt(x);
2207 break;
2209 case SQLITE_SCANSTAT_NAME: {
2210 *(const char**)pOut = pScan->zName;
2211 break;
2213 case SQLITE_SCANSTAT_EXPLAIN: {
2214 if( pScan->addrExplain ){
2215 *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
2216 }else{
2217 *(const char**)pOut = 0;
2219 break;
2221 case SQLITE_SCANSTAT_SELECTID: {
2222 if( pScan->addrExplain ){
2223 *(int*)pOut = aOp[ pScan->addrExplain ].p1;
2224 }else{
2225 *(int*)pOut = -1;
2227 break;
2229 case SQLITE_SCANSTAT_PARENTID: {
2230 if( pScan->addrExplain ){
2231 *(int*)pOut = aOp[ pScan->addrExplain ].p2;
2232 }else{
2233 *(int*)pOut = -1;
2235 break;
2237 case SQLITE_SCANSTAT_NCYCLE: {
2238 i64 res = 0;
2239 if( pScan->aAddrRange[0]==0 ){
2240 res = -1;
2241 }else{
2242 int ii;
2243 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
2244 int iIns = pScan->aAddrRange[ii];
2245 int iEnd = pScan->aAddrRange[ii+1];
2246 if( iIns==0 ) break;
2247 if( iIns>0 ){
2248 while( iIns<=iEnd ){
2249 res += aOp[iIns].nCycle;
2250 iIns++;
2252 }else{
2253 int iOp;
2254 for(iOp=0; iOp<nOp; iOp++){
2255 Op *pOp = &aOp[iOp];
2256 if( pOp->p1!=iEnd ) continue;
2257 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
2258 continue;
2260 res += aOp[iOp].nCycle;
2265 *(i64*)pOut = res;
2266 break;
2268 default: {
2269 return 1;
2272 return 0;
2276 ** Return status data for a single loop within query pStmt.
2278 int sqlite3_stmt_scanstatus(
2279 sqlite3_stmt *pStmt, /* Prepared statement being queried */
2280 int iScan, /* Index of loop to report on */
2281 int iScanStatusOp, /* Which metric to return */
2282 void *pOut /* OUT: Write the answer here */
2284 return sqlite3_stmt_scanstatus_v2(pStmt, iScan, iScanStatusOp, 0, pOut);
2288 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
2290 void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
2291 Vdbe *p = (Vdbe*)pStmt;
2292 int ii;
2293 for(ii=0; ii<p->nOp; ii++){
2294 Op *pOp = &p->aOp[ii];
2295 pOp->nExec = 0;
2296 pOp->nCycle = 0;
2299 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */