Snapshot of upstream SQLite 3.38.3
[sqlcipher.git] / src / vdbemem.c
blob184f811da9af0e7bb7ea15dfe3d0d58ff4f12e55
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 manipulate "Mem" structure. A "Mem"
14 ** stores a single value in the VDBE. Mem is an opaque structure visible
15 ** only within the VDBE. Interface routines refer to a Mem using the
16 ** name sqlite_value
18 #include "sqliteInt.h"
19 #include "vdbeInt.h"
21 /* True if X is a power of two. 0 is considered a power of two here.
22 ** In other words, return true if X has at most one bit set.
24 #define ISPOWEROF2(X) (((X)&((X)-1))==0)
26 #ifdef SQLITE_DEBUG
28 ** Check invariants on a Mem object.
30 ** This routine is intended for use inside of assert() statements, like
31 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
33 int sqlite3VdbeCheckMemInvariants(Mem *p){
34 /* If MEM_Dyn is set then Mem.xDel!=0.
35 ** Mem.xDel might not be initialized if MEM_Dyn is clear.
37 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
39 /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
40 ** ensure that if Mem.szMalloc>0 then it is safe to do
41 ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
42 ** That saves a few cycles in inner loops. */
43 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
45 /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
46 assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
48 if( p->flags & MEM_Null ){
49 /* Cannot be both MEM_Null and some other type */
50 assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
52 /* If MEM_Null is set, then either the value is a pure NULL (the usual
53 ** case) or it is a pointer set using sqlite3_bind_pointer() or
54 ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
55 ** set.
57 if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
58 /* This is a pointer type. There may be a flag to indicate what to
59 ** do with the pointer. */
60 assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
62 ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
64 /* No other bits set */
65 assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
66 |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
67 }else{
68 /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
69 ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
71 }else{
72 /* The MEM_Cleared bit is only allowed on NULLs */
73 assert( (p->flags & MEM_Cleared)==0 );
76 /* The szMalloc field holds the correct memory allocation size */
77 assert( p->szMalloc==0
78 || (p->flags==MEM_Undefined
79 && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
80 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
82 /* If p holds a string or blob, the Mem.z must point to exactly
83 ** one of the following:
85 ** (1) Memory in Mem.zMalloc and managed by the Mem object
86 ** (2) Memory to be freed using Mem.xDel
87 ** (3) An ephemeral string or blob
88 ** (4) A static string or blob
90 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
91 assert(
92 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
93 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
94 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
95 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
98 return 1;
100 #endif
103 ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
104 ** into a buffer.
106 static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
107 StrAccum acc;
108 assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
109 assert( sz>22 );
110 if( p->flags & MEM_Int ){
111 #if GCC_VERSION>=7000000
112 /* Work-around for GCC bug
113 ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
114 i64 x;
115 assert( (p->flags&MEM_Int)*2==sizeof(x) );
116 memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
117 sqlite3Int64ToText(x, zBuf);
118 #else
119 sqlite3Int64ToText(p->u.i, zBuf);
120 #endif
121 }else{
122 sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
123 sqlite3_str_appendf(&acc, "%!.15g",
124 (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
125 assert( acc.zText==zBuf && acc.mxAlloc<=0 );
126 zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
130 #ifdef SQLITE_DEBUG
132 ** Validity checks on pMem. pMem holds a string.
134 ** (1) Check that string value of pMem agrees with its integer or real value.
135 ** (2) Check that the string is correctly zero terminated
137 ** A single int or real value always converts to the same strings. But
138 ** many different strings can be converted into the same int or real.
139 ** If a table contains a numeric value and an index is based on the
140 ** corresponding string value, then it is important that the string be
141 ** derived from the numeric value, not the other way around, to ensure
142 ** that the index and table are consistent. See ticket
143 ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
144 ** an example.
146 ** This routine looks at pMem to verify that if it has both a numeric
147 ** representation and a string representation then the string rep has
148 ** been derived from the numeric and not the other way around. It returns
149 ** true if everything is ok and false if there is a problem.
151 ** This routine is for use inside of assert() statements only.
153 int sqlite3VdbeMemValidStrRep(Mem *p){
154 char zBuf[100];
155 char *z;
156 int i, j, incr;
157 if( (p->flags & MEM_Str)==0 ) return 1;
158 if( p->flags & MEM_Term ){
159 /* Insure that the string is properly zero-terminated. Pay particular
160 ** attention to the case where p->n is odd */
161 if( p->szMalloc>0 && p->z==p->zMalloc ){
162 assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
163 assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
165 assert( p->z[p->n]==0 );
166 assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
167 assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
169 if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
170 vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
171 z = p->z;
172 i = j = 0;
173 incr = 1;
174 if( p->enc!=SQLITE_UTF8 ){
175 incr = 2;
176 if( p->enc==SQLITE_UTF16BE ) z++;
178 while( zBuf[j] ){
179 if( zBuf[j++]!=z[i] ) return 0;
180 i += incr;
182 return 1;
184 #endif /* SQLITE_DEBUG */
187 ** If pMem is an object with a valid string representation, this routine
188 ** ensures the internal encoding for the string representation is
189 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
191 ** If pMem is not a string object, or the encoding of the string
192 ** representation is already stored using the requested encoding, then this
193 ** routine is a no-op.
195 ** SQLITE_OK is returned if the conversion is successful (or not required).
196 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
197 ** between formats.
199 int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
200 #ifndef SQLITE_OMIT_UTF16
201 int rc;
202 #endif
203 assert( pMem!=0 );
204 assert( !sqlite3VdbeMemIsRowSet(pMem) );
205 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
206 || desiredEnc==SQLITE_UTF16BE );
207 if( !(pMem->flags&MEM_Str) ){
208 pMem->enc = desiredEnc;
209 return SQLITE_OK;
211 if( pMem->enc==desiredEnc ){
212 return SQLITE_OK;
214 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
215 #ifdef SQLITE_OMIT_UTF16
216 return SQLITE_ERROR;
217 #else
219 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
220 ** then the encoding of the value may not have changed.
222 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
223 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
224 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
225 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
226 return rc;
227 #endif
231 ** Make sure pMem->z points to a writable allocation of at least n bytes.
233 ** If the bPreserve argument is true, then copy of the content of
234 ** pMem->z into the new allocation. pMem must be either a string or
235 ** blob if bPreserve is true. If bPreserve is false, any prior content
236 ** in pMem->z is discarded.
238 SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
239 assert( sqlite3VdbeCheckMemInvariants(pMem) );
240 assert( !sqlite3VdbeMemIsRowSet(pMem) );
241 testcase( pMem->db==0 );
243 /* If the bPreserve flag is set to true, then the memory cell must already
244 ** contain a valid string or blob value. */
245 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
246 testcase( bPreserve && pMem->z==0 );
248 assert( pMem->szMalloc==0
249 || (pMem->flags==MEM_Undefined
250 && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
251 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
252 if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
253 if( pMem->db ){
254 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
255 }else{
256 pMem->zMalloc = sqlite3Realloc(pMem->z, n);
257 if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
258 pMem->z = pMem->zMalloc;
260 bPreserve = 0;
261 }else{
262 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
263 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
265 if( pMem->zMalloc==0 ){
266 sqlite3VdbeMemSetNull(pMem);
267 pMem->z = 0;
268 pMem->szMalloc = 0;
269 return SQLITE_NOMEM_BKPT;
270 }else{
271 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
274 if( bPreserve && pMem->z ){
275 assert( pMem->z!=pMem->zMalloc );
276 memcpy(pMem->zMalloc, pMem->z, pMem->n);
278 if( (pMem->flags&MEM_Dyn)!=0 ){
279 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
280 pMem->xDel((void *)(pMem->z));
283 pMem->z = pMem->zMalloc;
284 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
285 return SQLITE_OK;
289 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
290 ** If pMem->zMalloc already meets or exceeds the requested size, this
291 ** routine is a no-op.
293 ** Any prior string or blob content in the pMem object may be discarded.
294 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
295 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
296 ** and MEM_Null values are preserved.
298 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
299 ** if unable to complete the resizing.
301 int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
302 assert( CORRUPT_DB || szNew>0 );
303 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
304 if( pMem->szMalloc<szNew ){
305 return sqlite3VdbeMemGrow(pMem, szNew, 0);
307 assert( (pMem->flags & MEM_Dyn)==0 );
308 pMem->z = pMem->zMalloc;
309 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
310 return SQLITE_OK;
314 ** It is already known that pMem contains an unterminated string.
315 ** Add the zero terminator.
317 ** Three bytes of zero are added. In this way, there is guaranteed
318 ** to be a double-zero byte at an even byte boundary in order to
319 ** terminate a UTF16 string, even if the initial size of the buffer
320 ** is an odd number of bytes.
322 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
323 if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
324 return SQLITE_NOMEM_BKPT;
326 pMem->z[pMem->n] = 0;
327 pMem->z[pMem->n+1] = 0;
328 pMem->z[pMem->n+2] = 0;
329 pMem->flags |= MEM_Term;
330 return SQLITE_OK;
334 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
335 ** MEM.zMalloc, where it can be safely written.
337 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
339 int sqlite3VdbeMemMakeWriteable(Mem *pMem){
340 assert( pMem!=0 );
341 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
342 assert( !sqlite3VdbeMemIsRowSet(pMem) );
343 if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
344 if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
345 if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
346 int rc = vdbeMemAddTerminator(pMem);
347 if( rc ) return rc;
350 pMem->flags &= ~MEM_Ephem;
351 #ifdef SQLITE_DEBUG
352 pMem->pScopyFrom = 0;
353 #endif
355 return SQLITE_OK;
359 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
360 ** blob stored in dynamically allocated space.
362 #ifndef SQLITE_OMIT_INCRBLOB
363 int sqlite3VdbeMemExpandBlob(Mem *pMem){
364 int nByte;
365 assert( pMem!=0 );
366 assert( pMem->flags & MEM_Zero );
367 assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
368 testcase( sqlite3_value_nochange(pMem) );
369 assert( !sqlite3VdbeMemIsRowSet(pMem) );
370 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
372 /* Set nByte to the number of bytes required to store the expanded blob. */
373 nByte = pMem->n + pMem->u.nZero;
374 if( nByte<=0 ){
375 if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
376 nByte = 1;
378 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
379 return SQLITE_NOMEM_BKPT;
381 assert( pMem->z!=0 );
382 assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
384 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
385 pMem->n += pMem->u.nZero;
386 pMem->flags &= ~(MEM_Zero|MEM_Term);
387 return SQLITE_OK;
389 #endif
392 ** Make sure the given Mem is \u0000 terminated.
394 int sqlite3VdbeMemNulTerminate(Mem *pMem){
395 assert( pMem!=0 );
396 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
397 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
398 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
399 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
400 return SQLITE_OK; /* Nothing to do */
401 }else{
402 return vdbeMemAddTerminator(pMem);
407 ** Add MEM_Str to the set of representations for the given Mem. This
408 ** routine is only called if pMem is a number of some kind, not a NULL
409 ** or a BLOB.
411 ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
412 ** if bForce is true but are retained if bForce is false.
414 ** A MEM_Null value will never be passed to this function. This function is
415 ** used for converting values to text for returning to the user (i.e. via
416 ** sqlite3_value_text()), or for ensuring that values to be used as btree
417 ** keys are strings. In the former case a NULL pointer is returned the
418 ** user and the latter is an internal programming error.
420 int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
421 const int nByte = 32;
423 assert( pMem!=0 );
424 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
425 assert( !(pMem->flags&MEM_Zero) );
426 assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
427 assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
428 assert( !sqlite3VdbeMemIsRowSet(pMem) );
429 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
432 if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
433 pMem->enc = 0;
434 return SQLITE_NOMEM_BKPT;
437 vdbeMemRenderNum(nByte, pMem->z, pMem);
438 assert( pMem->z!=0 );
439 pMem->n = sqlite3Strlen30NN(pMem->z);
440 pMem->enc = SQLITE_UTF8;
441 pMem->flags |= MEM_Str|MEM_Term;
442 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
443 sqlite3VdbeChangeEncoding(pMem, enc);
444 return SQLITE_OK;
448 ** Memory cell pMem contains the context of an aggregate function.
449 ** This routine calls the finalize method for that function. The
450 ** result of the aggregate is stored back into pMem.
452 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
453 ** otherwise.
455 int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
456 sqlite3_context ctx;
457 Mem t;
458 assert( pFunc!=0 );
459 assert( pMem!=0 );
460 assert( pFunc->xFinalize!=0 );
461 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
462 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
463 memset(&ctx, 0, sizeof(ctx));
464 memset(&t, 0, sizeof(t));
465 t.flags = MEM_Null;
466 t.db = pMem->db;
467 ctx.pOut = &t;
468 ctx.pMem = pMem;
469 ctx.pFunc = pFunc;
470 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
471 assert( (pMem->flags & MEM_Dyn)==0 );
472 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
473 memcpy(pMem, &t, sizeof(t));
474 return ctx.isError;
478 ** Memory cell pAccum contains the context of an aggregate function.
479 ** This routine calls the xValue method for that function and stores
480 ** the results in memory cell pMem.
482 ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
483 ** otherwise.
485 #ifndef SQLITE_OMIT_WINDOWFUNC
486 int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
487 sqlite3_context ctx;
488 assert( pFunc!=0 );
489 assert( pFunc->xValue!=0 );
490 assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
491 assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
492 memset(&ctx, 0, sizeof(ctx));
493 sqlite3VdbeMemSetNull(pOut);
494 ctx.pOut = pOut;
495 ctx.pMem = pAccum;
496 ctx.pFunc = pFunc;
497 pFunc->xValue(&ctx);
498 return ctx.isError;
500 #endif /* SQLITE_OMIT_WINDOWFUNC */
503 ** If the memory cell contains a value that must be freed by
504 ** invoking the external callback in Mem.xDel, then this routine
505 ** will free that value. It also sets Mem.flags to MEM_Null.
507 ** This is a helper routine for sqlite3VdbeMemSetNull() and
508 ** for sqlite3VdbeMemRelease(). Use those other routines as the
509 ** entry point for releasing Mem resources.
511 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
512 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
513 assert( VdbeMemDynamic(p) );
514 if( p->flags&MEM_Agg ){
515 sqlite3VdbeMemFinalize(p, p->u.pDef);
516 assert( (p->flags & MEM_Agg)==0 );
517 testcase( p->flags & MEM_Dyn );
519 if( p->flags&MEM_Dyn ){
520 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
521 p->xDel((void *)p->z);
523 p->flags = MEM_Null;
527 ** Release memory held by the Mem p, both external memory cleared
528 ** by p->xDel and memory in p->zMalloc.
530 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
531 ** the unusual case where there really is memory in p that needs
532 ** to be freed.
534 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
535 if( VdbeMemDynamic(p) ){
536 vdbeMemClearExternAndSetNull(p);
538 if( p->szMalloc ){
539 sqlite3DbFreeNN(p->db, p->zMalloc);
540 p->szMalloc = 0;
542 p->z = 0;
546 ** Release any memory resources held by the Mem. Both the memory that is
547 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
549 ** Use this routine prior to clean up prior to abandoning a Mem, or to
550 ** reset a Mem back to its minimum memory utilization.
552 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
553 ** prior to inserting new content into the Mem.
555 void sqlite3VdbeMemRelease(Mem *p){
556 assert( sqlite3VdbeCheckMemInvariants(p) );
557 if( VdbeMemDynamic(p) || p->szMalloc ){
558 vdbeMemClear(p);
563 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
564 ** If the double is out of range of a 64-bit signed integer then
565 ** return the closest available 64-bit signed integer.
567 static SQLITE_NOINLINE i64 doubleToInt64(double r){
568 #ifdef SQLITE_OMIT_FLOATING_POINT
569 /* When floating-point is omitted, double and int64 are the same thing */
570 return r;
571 #else
573 ** Many compilers we encounter do not define constants for the
574 ** minimum and maximum 64-bit integers, or they define them
575 ** inconsistently. And many do not understand the "LL" notation.
576 ** So we define our own static constants here using nothing
577 ** larger than a 32-bit integer constant.
579 static const i64 maxInt = LARGEST_INT64;
580 static const i64 minInt = SMALLEST_INT64;
582 if( r<=(double)minInt ){
583 return minInt;
584 }else if( r>=(double)maxInt ){
585 return maxInt;
586 }else{
587 return (i64)r;
589 #endif
593 ** Return some kind of integer value which is the best we can do
594 ** at representing the value that *pMem describes as an integer.
595 ** If pMem is an integer, then the value is exact. If pMem is
596 ** a floating-point then the value returned is the integer part.
597 ** If pMem is a string or blob, then we make an attempt to convert
598 ** it into an integer and return that. If pMem represents an
599 ** an SQL-NULL value, return 0.
601 ** If pMem represents a string value, its encoding might be changed.
603 static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
604 i64 value = 0;
605 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
606 return value;
608 i64 sqlite3VdbeIntValue(const Mem *pMem){
609 int flags;
610 assert( pMem!=0 );
611 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
612 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
613 flags = pMem->flags;
614 if( flags & (MEM_Int|MEM_IntReal) ){
615 testcase( flags & MEM_IntReal );
616 return pMem->u.i;
617 }else if( flags & MEM_Real ){
618 return doubleToInt64(pMem->u.r);
619 }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
620 return memIntValue(pMem);
621 }else{
622 return 0;
627 ** Return the best representation of pMem that we can get into a
628 ** double. If pMem is already a double or an integer, return its
629 ** value. If it is a string or blob, try to convert it to a double.
630 ** If it is a NULL, return 0.0.
632 static SQLITE_NOINLINE double memRealValue(Mem *pMem){
633 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
634 double val = (double)0;
635 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
636 return val;
638 double sqlite3VdbeRealValue(Mem *pMem){
639 assert( pMem!=0 );
640 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
641 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
642 if( pMem->flags & MEM_Real ){
643 return pMem->u.r;
644 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
645 testcase( pMem->flags & MEM_IntReal );
646 return (double)pMem->u.i;
647 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
648 return memRealValue(pMem);
649 }else{
650 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
651 return (double)0;
656 ** Return 1 if pMem represents true, and return 0 if pMem represents false.
657 ** Return the value ifNull if pMem is NULL.
659 int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
660 testcase( pMem->flags & MEM_IntReal );
661 if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
662 if( pMem->flags & MEM_Null ) return ifNull;
663 return sqlite3VdbeRealValue(pMem)!=0.0;
667 ** The MEM structure is already a MEM_Real. Try to also make it a
668 ** MEM_Int if we can.
670 void sqlite3VdbeIntegerAffinity(Mem *pMem){
671 i64 ix;
672 assert( pMem!=0 );
673 assert( pMem->flags & MEM_Real );
674 assert( !sqlite3VdbeMemIsRowSet(pMem) );
675 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
676 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
678 ix = doubleToInt64(pMem->u.r);
680 /* Only mark the value as an integer if
682 ** (1) the round-trip conversion real->int->real is a no-op, and
683 ** (2) The integer is neither the largest nor the smallest
684 ** possible integer (ticket #3922)
686 ** The second and third terms in the following conditional enforces
687 ** the second condition under the assumption that addition overflow causes
688 ** values to wrap around.
690 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
691 pMem->u.i = ix;
692 MemSetTypeFlag(pMem, MEM_Int);
697 ** Convert pMem to type integer. Invalidate any prior representations.
699 int sqlite3VdbeMemIntegerify(Mem *pMem){
700 assert( pMem!=0 );
701 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
702 assert( !sqlite3VdbeMemIsRowSet(pMem) );
703 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
705 pMem->u.i = sqlite3VdbeIntValue(pMem);
706 MemSetTypeFlag(pMem, MEM_Int);
707 return SQLITE_OK;
711 ** Convert pMem so that it is of type MEM_Real.
712 ** Invalidate any prior representations.
714 int sqlite3VdbeMemRealify(Mem *pMem){
715 assert( pMem!=0 );
716 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
717 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
719 pMem->u.r = sqlite3VdbeRealValue(pMem);
720 MemSetTypeFlag(pMem, MEM_Real);
721 return SQLITE_OK;
724 /* Compare a floating point value to an integer. Return true if the two
725 ** values are the same within the precision of the floating point value.
727 ** This function assumes that i was obtained by assignment from r1.
729 ** For some versions of GCC on 32-bit machines, if you do the more obvious
730 ** comparison of "r1==(double)i" you sometimes get an answer of false even
731 ** though the r1 and (double)i values are bit-for-bit the same.
733 int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
734 double r2 = (double)i;
735 return r1==0.0
736 || (memcmp(&r1, &r2, sizeof(r1))==0
737 && i >= -2251799813685248LL && i < 2251799813685248LL);
741 ** Convert pMem so that it has type MEM_Real or MEM_Int.
742 ** Invalidate any prior representations.
744 ** Every effort is made to force the conversion, even if the input
745 ** is a string that does not look completely like a number. Convert
746 ** as much of the string as we can and ignore the rest.
748 int sqlite3VdbeMemNumerify(Mem *pMem){
749 assert( pMem!=0 );
750 testcase( pMem->flags & MEM_Int );
751 testcase( pMem->flags & MEM_Real );
752 testcase( pMem->flags & MEM_IntReal );
753 testcase( pMem->flags & MEM_Null );
754 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
755 int rc;
756 sqlite3_int64 ix;
757 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
758 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
759 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
760 if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
761 || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))
763 pMem->u.i = ix;
764 MemSetTypeFlag(pMem, MEM_Int);
765 }else{
766 MemSetTypeFlag(pMem, MEM_Real);
769 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
770 pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
771 return SQLITE_OK;
775 ** Cast the datatype of the value in pMem according to the affinity
776 ** "aff". Casting is different from applying affinity in that a cast
777 ** is forced. In other words, the value is converted into the desired
778 ** affinity even if that results in loss of data. This routine is
779 ** used (for example) to implement the SQL "cast()" operator.
781 int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
782 if( pMem->flags & MEM_Null ) return SQLITE_OK;
783 switch( aff ){
784 case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
785 if( (pMem->flags & MEM_Blob)==0 ){
786 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
787 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
788 if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
789 }else{
790 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
792 break;
794 case SQLITE_AFF_NUMERIC: {
795 sqlite3VdbeMemNumerify(pMem);
796 break;
798 case SQLITE_AFF_INTEGER: {
799 sqlite3VdbeMemIntegerify(pMem);
800 break;
802 case SQLITE_AFF_REAL: {
803 sqlite3VdbeMemRealify(pMem);
804 break;
806 default: {
807 assert( aff==SQLITE_AFF_TEXT );
808 assert( MEM_Str==(MEM_Blob>>3) );
809 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
810 sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
811 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
812 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
813 return sqlite3VdbeChangeEncoding(pMem, encoding);
816 return SQLITE_OK;
820 ** Initialize bulk memory to be a consistent Mem object.
822 ** The minimum amount of initialization feasible is performed.
824 void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
825 assert( (flags & ~MEM_TypeMask)==0 );
826 pMem->flags = flags;
827 pMem->db = db;
828 pMem->szMalloc = 0;
833 ** Delete any previous value and set the value stored in *pMem to NULL.
835 ** This routine calls the Mem.xDel destructor to dispose of values that
836 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
837 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
838 ** routine to invoke the destructor and deallocates Mem.zMalloc.
840 ** Use this routine to reset the Mem prior to insert a new value.
842 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
844 void sqlite3VdbeMemSetNull(Mem *pMem){
845 if( VdbeMemDynamic(pMem) ){
846 vdbeMemClearExternAndSetNull(pMem);
847 }else{
848 pMem->flags = MEM_Null;
851 void sqlite3ValueSetNull(sqlite3_value *p){
852 sqlite3VdbeMemSetNull((Mem*)p);
856 ** Delete any previous value and set the value to be a BLOB of length
857 ** n containing all zeros.
859 #ifndef SQLITE_OMIT_INCRBLOB
860 void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
861 sqlite3VdbeMemRelease(pMem);
862 pMem->flags = MEM_Blob|MEM_Zero;
863 pMem->n = 0;
864 if( n<0 ) n = 0;
865 pMem->u.nZero = n;
866 pMem->enc = SQLITE_UTF8;
867 pMem->z = 0;
869 #else
870 int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
871 int nByte = n>0?n:1;
872 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
873 return SQLITE_NOMEM_BKPT;
875 assert( pMem->z!=0 );
876 assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
877 memset(pMem->z, 0, nByte);
878 pMem->n = n>0?n:0;
879 pMem->flags = MEM_Blob;
880 pMem->enc = SQLITE_UTF8;
881 return SQLITE_OK;
883 #endif
886 ** The pMem is known to contain content that needs to be destroyed prior
887 ** to a value change. So invoke the destructor, then set the value to
888 ** a 64-bit integer.
890 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
891 sqlite3VdbeMemSetNull(pMem);
892 pMem->u.i = val;
893 pMem->flags = MEM_Int;
897 ** Delete any previous value and set the value stored in *pMem to val,
898 ** manifest type INTEGER.
900 void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
901 if( VdbeMemDynamic(pMem) ){
902 vdbeReleaseAndSetInt64(pMem, val);
903 }else{
904 pMem->u.i = val;
905 pMem->flags = MEM_Int;
909 /* A no-op destructor */
910 void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
913 ** Set the value stored in *pMem should already be a NULL.
914 ** Also store a pointer to go with it.
916 void sqlite3VdbeMemSetPointer(
917 Mem *pMem,
918 void *pPtr,
919 const char *zPType,
920 void (*xDestructor)(void*)
922 assert( pMem->flags==MEM_Null );
923 vdbeMemClear(pMem);
924 pMem->u.zPType = zPType ? zPType : "";
925 pMem->z = pPtr;
926 pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
927 pMem->eSubtype = 'p';
928 pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
931 #ifndef SQLITE_OMIT_FLOATING_POINT
933 ** Delete any previous value and set the value stored in *pMem to val,
934 ** manifest type REAL.
936 void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
937 sqlite3VdbeMemSetNull(pMem);
938 if( !sqlite3IsNaN(val) ){
939 pMem->u.r = val;
940 pMem->flags = MEM_Real;
943 #endif
945 #ifdef SQLITE_DEBUG
947 ** Return true if the Mem holds a RowSet object. This routine is intended
948 ** for use inside of assert() statements.
950 int sqlite3VdbeMemIsRowSet(const Mem *pMem){
951 return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
952 && pMem->xDel==sqlite3RowSetDelete;
954 #endif
957 ** Delete any previous value and set the value of pMem to be an
958 ** empty boolean index.
960 ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
961 ** error occurs.
963 int sqlite3VdbeMemSetRowSet(Mem *pMem){
964 sqlite3 *db = pMem->db;
965 RowSet *p;
966 assert( db!=0 );
967 assert( !sqlite3VdbeMemIsRowSet(pMem) );
968 sqlite3VdbeMemRelease(pMem);
969 p = sqlite3RowSetInit(db);
970 if( p==0 ) return SQLITE_NOMEM;
971 pMem->z = (char*)p;
972 pMem->flags = MEM_Blob|MEM_Dyn;
973 pMem->xDel = sqlite3RowSetDelete;
974 return SQLITE_OK;
978 ** Return true if the Mem object contains a TEXT or BLOB that is
979 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
981 int sqlite3VdbeMemTooBig(Mem *p){
982 assert( p->db!=0 );
983 if( p->flags & (MEM_Str|MEM_Blob) ){
984 int n = p->n;
985 if( p->flags & MEM_Zero ){
986 n += p->u.nZero;
988 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
990 return 0;
993 #ifdef SQLITE_DEBUG
995 ** This routine prepares a memory cell for modification by breaking
996 ** its link to a shallow copy and by marking any current shallow
997 ** copies of this cell as invalid.
999 ** This is used for testing and debugging only - to help ensure that shallow
1000 ** copies (created by OP_SCopy) are not misused.
1002 void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
1003 int i;
1004 Mem *pX;
1005 for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
1006 if( pX->pScopyFrom==pMem ){
1007 u16 mFlags;
1008 if( pVdbe->db->flags & SQLITE_VdbeTrace ){
1009 sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
1010 (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
1012 /* If pX is marked as a shallow copy of pMem, then try to verify that
1013 ** no significant changes have been made to pX since the OP_SCopy.
1014 ** A significant change would indicated a missed call to this
1015 ** function for pX. Minor changes, such as adding or removing a
1016 ** dual type, are allowed, as long as the underlying value is the
1017 ** same. */
1018 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
1019 assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
1021 /* pMem is the register that is changing. But also mark pX as
1022 ** undefined so that we can quickly detect the shallow-copy error */
1023 pX->flags = MEM_Undefined;
1024 pX->pScopyFrom = 0;
1027 pMem->pScopyFrom = 0;
1029 #endif /* SQLITE_DEBUG */
1032 ** Make an shallow copy of pFrom into pTo. Prior contents of
1033 ** pTo are freed. The pFrom->z field is not duplicated. If
1034 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
1035 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
1037 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
1038 vdbeMemClearExternAndSetNull(pTo);
1039 assert( !VdbeMemDynamic(pTo) );
1040 sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
1042 void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
1043 assert( !sqlite3VdbeMemIsRowSet(pFrom) );
1044 assert( pTo->db==pFrom->db );
1045 if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
1046 memcpy(pTo, pFrom, MEMCELLSIZE);
1047 if( (pFrom->flags&MEM_Static)==0 ){
1048 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
1049 assert( srcType==MEM_Ephem || srcType==MEM_Static );
1050 pTo->flags |= srcType;
1055 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
1056 ** freed before the copy is made.
1058 int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
1059 int rc = SQLITE_OK;
1061 assert( !sqlite3VdbeMemIsRowSet(pFrom) );
1062 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
1063 memcpy(pTo, pFrom, MEMCELLSIZE);
1064 pTo->flags &= ~MEM_Dyn;
1065 if( pTo->flags&(MEM_Str|MEM_Blob) ){
1066 if( 0==(pFrom->flags&MEM_Static) ){
1067 pTo->flags |= MEM_Ephem;
1068 rc = sqlite3VdbeMemMakeWriteable(pTo);
1072 return rc;
1076 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
1077 ** freed. If pFrom contains ephemeral data, a copy is made.
1079 ** pFrom contains an SQL NULL when this routine returns.
1081 void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
1082 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
1083 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
1084 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
1086 sqlite3VdbeMemRelease(pTo);
1087 memcpy(pTo, pFrom, sizeof(Mem));
1088 pFrom->flags = MEM_Null;
1089 pFrom->szMalloc = 0;
1093 ** Change the value of a Mem to be a string or a BLOB.
1095 ** The memory management strategy depends on the value of the xDel
1096 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
1097 ** string is copied into a (possibly existing) buffer managed by the
1098 ** Mem structure. Otherwise, any existing buffer is freed and the
1099 ** pointer copied.
1101 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
1102 ** size limit) then no memory allocation occurs. If the string can be
1103 ** stored without allocating memory, then it is. If a memory allocation
1104 ** is required to store the string, then value of pMem is unchanged. In
1105 ** either case, SQLITE_TOOBIG is returned.
1107 int sqlite3VdbeMemSetStr(
1108 Mem *pMem, /* Memory cell to set to string value */
1109 const char *z, /* String pointer */
1110 i64 n, /* Bytes in string, or negative */
1111 u8 enc, /* Encoding of z. 0 for BLOBs */
1112 void (*xDel)(void*) /* Destructor function */
1114 i64 nByte = n; /* New value for pMem->n */
1115 int iLimit; /* Maximum allowed string or blob size */
1116 u16 flags = 0; /* New value for pMem->flags */
1118 assert( pMem!=0 );
1119 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
1120 assert( !sqlite3VdbeMemIsRowSet(pMem) );
1122 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
1123 if( !z ){
1124 sqlite3VdbeMemSetNull(pMem);
1125 return SQLITE_OK;
1128 if( pMem->db ){
1129 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
1130 }else{
1131 iLimit = SQLITE_MAX_LENGTH;
1133 flags = (enc==0?MEM_Blob:MEM_Str);
1134 if( nByte<0 ){
1135 assert( enc!=0 );
1136 if( enc==SQLITE_UTF8 ){
1137 nByte = strlen(z);
1138 }else{
1139 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
1141 flags |= MEM_Term;
1144 /* The following block sets the new values of Mem.z and Mem.xDel. It
1145 ** also sets a flag in local variable "flags" to indicate the memory
1146 ** management (one of MEM_Dyn or MEM_Static).
1148 if( xDel==SQLITE_TRANSIENT ){
1149 i64 nAlloc = nByte;
1150 if( flags&MEM_Term ){
1151 nAlloc += (enc==SQLITE_UTF8?1:2);
1153 if( nByte>iLimit ){
1154 return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
1156 testcase( nAlloc==0 );
1157 testcase( nAlloc==31 );
1158 testcase( nAlloc==32 );
1159 if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
1160 return SQLITE_NOMEM_BKPT;
1162 memcpy(pMem->z, z, nAlloc);
1163 }else{
1164 sqlite3VdbeMemRelease(pMem);
1165 pMem->z = (char *)z;
1166 if( xDel==SQLITE_DYNAMIC ){
1167 pMem->zMalloc = pMem->z;
1168 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
1169 }else{
1170 pMem->xDel = xDel;
1171 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
1175 pMem->n = (int)(nByte & 0x7fffffff);
1176 pMem->flags = flags;
1177 if( enc ){
1178 pMem->enc = enc;
1179 #ifdef SQLITE_ENABLE_SESSION
1180 }else if( pMem->db==0 ){
1181 pMem->enc = SQLITE_UTF8;
1182 #endif
1183 }else{
1184 assert( pMem->db!=0 );
1185 pMem->enc = ENC(pMem->db);
1188 #ifndef SQLITE_OMIT_UTF16
1189 if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
1190 return SQLITE_NOMEM_BKPT;
1192 #endif
1194 if( nByte>iLimit ){
1195 return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
1198 return SQLITE_OK;
1202 ** Move data out of a btree key or data field and into a Mem structure.
1203 ** The data is payload from the entry that pCur is currently pointing
1204 ** to. offset and amt determine what portion of the data or key to retrieve.
1205 ** The result is written into the pMem element.
1207 ** The pMem object must have been initialized. This routine will use
1208 ** pMem->zMalloc to hold the content from the btree, if possible. New
1209 ** pMem->zMalloc space will be allocated if necessary. The calling routine
1210 ** is responsible for making sure that the pMem object is eventually
1211 ** destroyed.
1213 ** If this routine fails for any reason (malloc returns NULL or unable
1214 ** to read from the disk) then the pMem is left in an inconsistent state.
1216 int sqlite3VdbeMemFromBtree(
1217 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
1218 u32 offset, /* Offset from the start of data to return bytes from. */
1219 u32 amt, /* Number of bytes to return. */
1220 Mem *pMem /* OUT: Return data in this Mem structure. */
1222 int rc;
1223 pMem->flags = MEM_Null;
1224 if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
1225 return SQLITE_CORRUPT_BKPT;
1227 if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
1228 rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
1229 if( rc==SQLITE_OK ){
1230 pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
1231 pMem->flags = MEM_Blob;
1232 pMem->n = (int)amt;
1233 }else{
1234 sqlite3VdbeMemRelease(pMem);
1237 return rc;
1239 int sqlite3VdbeMemFromBtreeZeroOffset(
1240 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
1241 u32 amt, /* Number of bytes to return. */
1242 Mem *pMem /* OUT: Return data in this Mem structure. */
1244 u32 available = 0; /* Number of bytes available on the local btree page */
1245 int rc = SQLITE_OK; /* Return code */
1247 assert( sqlite3BtreeCursorIsValid(pCur) );
1248 assert( !VdbeMemDynamic(pMem) );
1250 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
1251 ** that both the BtShared and database handle mutexes are held. */
1252 assert( !sqlite3VdbeMemIsRowSet(pMem) );
1253 pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
1254 assert( pMem->z!=0 );
1256 if( amt<=available ){
1257 pMem->flags = MEM_Blob|MEM_Ephem;
1258 pMem->n = (int)amt;
1259 }else{
1260 rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
1263 return rc;
1267 ** The pVal argument is known to be a value other than NULL.
1268 ** Convert it into a string with encoding enc and return a pointer
1269 ** to a zero-terminated version of that string.
1271 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
1272 assert( pVal!=0 );
1273 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
1274 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
1275 assert( !sqlite3VdbeMemIsRowSet(pVal) );
1276 assert( (pVal->flags & (MEM_Null))==0 );
1277 if( pVal->flags & (MEM_Blob|MEM_Str) ){
1278 if( ExpandBlob(pVal) ) return 0;
1279 pVal->flags |= MEM_Str;
1280 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
1281 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
1283 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
1284 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
1285 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
1286 return 0;
1289 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
1290 }else{
1291 sqlite3VdbeMemStringify(pVal, enc, 0);
1292 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
1294 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
1295 || pVal->db->mallocFailed );
1296 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
1297 assert( sqlite3VdbeMemValidStrRep(pVal) );
1298 return pVal->z;
1299 }else{
1300 return 0;
1304 /* This function is only available internally, it is not part of the
1305 ** external API. It works in a similar way to sqlite3_value_text(),
1306 ** except the data returned is in the encoding specified by the second
1307 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
1308 ** SQLITE_UTF8.
1310 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
1311 ** If that is the case, then the result must be aligned on an even byte
1312 ** boundary.
1314 const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
1315 if( !pVal ) return 0;
1316 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
1317 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
1318 assert( !sqlite3VdbeMemIsRowSet(pVal) );
1319 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
1320 assert( sqlite3VdbeMemValidStrRep(pVal) );
1321 return pVal->z;
1323 if( pVal->flags&MEM_Null ){
1324 return 0;
1326 return valueToText(pVal, enc);
1330 ** Create a new sqlite3_value object.
1332 sqlite3_value *sqlite3ValueNew(sqlite3 *db){
1333 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
1334 if( p ){
1335 p->flags = MEM_Null;
1336 p->db = db;
1338 return p;
1342 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
1343 ** valueNew(). See comments above valueNew() for details.
1345 struct ValueNewStat4Ctx {
1346 Parse *pParse;
1347 Index *pIdx;
1348 UnpackedRecord **ppRec;
1349 int iVal;
1353 ** Allocate and return a pointer to a new sqlite3_value object. If
1354 ** the second argument to this function is NULL, the object is allocated
1355 ** by calling sqlite3ValueNew().
1357 ** Otherwise, if the second argument is non-zero, then this function is
1358 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
1359 ** already been allocated, allocate the UnpackedRecord structure that
1360 ** that function will return to its caller here. Then return a pointer to
1361 ** an sqlite3_value within the UnpackedRecord.a[] array.
1363 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
1364 #ifdef SQLITE_ENABLE_STAT4
1365 if( p ){
1366 UnpackedRecord *pRec = p->ppRec[0];
1368 if( pRec==0 ){
1369 Index *pIdx = p->pIdx; /* Index being probed */
1370 int nByte; /* Bytes of space to allocate */
1371 int i; /* Counter variable */
1372 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
1374 nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
1375 pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
1376 if( pRec ){
1377 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
1378 if( pRec->pKeyInfo ){
1379 assert( pRec->pKeyInfo->nAllField==nCol );
1380 assert( pRec->pKeyInfo->enc==ENC(db) );
1381 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
1382 for(i=0; i<nCol; i++){
1383 pRec->aMem[i].flags = MEM_Null;
1384 pRec->aMem[i].db = db;
1386 }else{
1387 sqlite3DbFreeNN(db, pRec);
1388 pRec = 0;
1391 if( pRec==0 ) return 0;
1392 p->ppRec[0] = pRec;
1395 pRec->nField = p->iVal+1;
1396 return &pRec->aMem[p->iVal];
1398 #else
1399 UNUSED_PARAMETER(p);
1400 #endif /* defined(SQLITE_ENABLE_STAT4) */
1401 return sqlite3ValueNew(db);
1405 ** The expression object indicated by the second argument is guaranteed
1406 ** to be a scalar SQL function. If
1408 ** * all function arguments are SQL literals,
1409 ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
1410 ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
1412 ** then this routine attempts to invoke the SQL function. Assuming no
1413 ** error occurs, output parameter (*ppVal) is set to point to a value
1414 ** object containing the result before returning SQLITE_OK.
1416 ** Affinity aff is applied to the result of the function before returning.
1417 ** If the result is a text value, the sqlite3_value object uses encoding
1418 ** enc.
1420 ** If the conditions above are not met, this function returns SQLITE_OK
1421 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
1422 ** NULL and an SQLite error code returned.
1424 #ifdef SQLITE_ENABLE_STAT4
1425 static int valueFromFunction(
1426 sqlite3 *db, /* The database connection */
1427 const Expr *p, /* The expression to evaluate */
1428 u8 enc, /* Encoding to use */
1429 u8 aff, /* Affinity to use */
1430 sqlite3_value **ppVal, /* Write the new value here */
1431 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
1433 sqlite3_context ctx; /* Context object for function invocation */
1434 sqlite3_value **apVal = 0; /* Function arguments */
1435 int nVal = 0; /* Size of apVal[] array */
1436 FuncDef *pFunc = 0; /* Function definition */
1437 sqlite3_value *pVal = 0; /* New value */
1438 int rc = SQLITE_OK; /* Return code */
1439 ExprList *pList = 0; /* Function arguments */
1440 int i; /* Iterator variable */
1442 assert( pCtx!=0 );
1443 assert( (p->flags & EP_TokenOnly)==0 );
1444 assert( ExprUseXList(p) );
1445 pList = p->x.pList;
1446 if( pList ) nVal = pList->nExpr;
1447 assert( !ExprHasProperty(p, EP_IntValue) );
1448 pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
1449 assert( pFunc );
1450 if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
1451 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
1453 return SQLITE_OK;
1456 if( pList ){
1457 apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
1458 if( apVal==0 ){
1459 rc = SQLITE_NOMEM_BKPT;
1460 goto value_from_function_out;
1462 for(i=0; i<nVal; i++){
1463 rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
1464 if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
1468 pVal = valueNew(db, pCtx);
1469 if( pVal==0 ){
1470 rc = SQLITE_NOMEM_BKPT;
1471 goto value_from_function_out;
1474 assert( pCtx->pParse->rc==SQLITE_OK );
1475 memset(&ctx, 0, sizeof(ctx));
1476 ctx.pOut = pVal;
1477 ctx.pFunc = pFunc;
1478 pFunc->xSFunc(&ctx, nVal, apVal);
1479 if( ctx.isError ){
1480 rc = ctx.isError;
1481 sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
1482 }else{
1483 sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
1484 assert( rc==SQLITE_OK );
1485 rc = sqlite3VdbeChangeEncoding(pVal, enc);
1486 if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
1487 rc = SQLITE_TOOBIG;
1488 pCtx->pParse->nErr++;
1491 pCtx->pParse->rc = rc;
1493 value_from_function_out:
1494 if( rc!=SQLITE_OK ){
1495 pVal = 0;
1497 if( apVal ){
1498 for(i=0; i<nVal; i++){
1499 sqlite3ValueFree(apVal[i]);
1501 sqlite3DbFreeNN(db, apVal);
1504 *ppVal = pVal;
1505 return rc;
1507 #else
1508 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
1509 #endif /* defined(SQLITE_ENABLE_STAT4) */
1512 ** Extract a value from the supplied expression in the manner described
1513 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
1514 ** using valueNew().
1516 ** If pCtx is NULL and an error occurs after the sqlite3_value object
1517 ** has been allocated, it is freed before returning. Or, if pCtx is not
1518 ** NULL, it is assumed that the caller will free any allocated object
1519 ** in all cases.
1521 static int valueFromExpr(
1522 sqlite3 *db, /* The database connection */
1523 const Expr *pExpr, /* The expression to evaluate */
1524 u8 enc, /* Encoding to use */
1525 u8 affinity, /* Affinity to use */
1526 sqlite3_value **ppVal, /* Write the new value here */
1527 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
1529 int op;
1530 char *zVal = 0;
1531 sqlite3_value *pVal = 0;
1532 int negInt = 1;
1533 const char *zNeg = "";
1534 int rc = SQLITE_OK;
1536 assert( pExpr!=0 );
1537 while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
1538 if( op==TK_REGISTER ) op = pExpr->op2;
1540 /* Compressed expressions only appear when parsing the DEFAULT clause
1541 ** on a table column definition, and hence only when pCtx==0. This
1542 ** check ensures that an EP_TokenOnly expression is never passed down
1543 ** into valueFromFunction(). */
1544 assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
1546 if( op==TK_CAST ){
1547 u8 aff;
1548 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1549 aff = sqlite3AffinityType(pExpr->u.zToken,0);
1550 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
1551 testcase( rc!=SQLITE_OK );
1552 if( *ppVal ){
1553 sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
1554 sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
1556 return rc;
1559 /* Handle negative integers in a single step. This is needed in the
1560 ** case when the value is -9223372036854775808.
1562 if( op==TK_UMINUS
1563 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
1564 pExpr = pExpr->pLeft;
1565 op = pExpr->op;
1566 negInt = -1;
1567 zNeg = "-";
1570 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
1571 pVal = valueNew(db, pCtx);
1572 if( pVal==0 ) goto no_mem;
1573 if( ExprHasProperty(pExpr, EP_IntValue) ){
1574 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
1575 }else{
1576 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
1577 if( zVal==0 ) goto no_mem;
1578 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
1580 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
1581 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
1582 }else{
1583 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
1585 assert( (pVal->flags & MEM_IntReal)==0 );
1586 if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
1587 testcase( pVal->flags & MEM_Int );
1588 testcase( pVal->flags & MEM_Real );
1589 pVal->flags &= ~MEM_Str;
1591 if( enc!=SQLITE_UTF8 ){
1592 rc = sqlite3VdbeChangeEncoding(pVal, enc);
1594 }else if( op==TK_UMINUS ) {
1595 /* This branch happens for multiple negative signs. Ex: -(-5) */
1596 if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
1597 && pVal!=0
1599 sqlite3VdbeMemNumerify(pVal);
1600 if( pVal->flags & MEM_Real ){
1601 pVal->u.r = -pVal->u.r;
1602 }else if( pVal->u.i==SMALLEST_INT64 ){
1603 #ifndef SQLITE_OMIT_FLOATING_POINT
1604 pVal->u.r = -(double)SMALLEST_INT64;
1605 #else
1606 pVal->u.r = LARGEST_INT64;
1607 #endif
1608 MemSetTypeFlag(pVal, MEM_Real);
1609 }else{
1610 pVal->u.i = -pVal->u.i;
1612 sqlite3ValueApplyAffinity(pVal, affinity, enc);
1614 }else if( op==TK_NULL ){
1615 pVal = valueNew(db, pCtx);
1616 if( pVal==0 ) goto no_mem;
1617 sqlite3VdbeMemSetNull(pVal);
1619 #ifndef SQLITE_OMIT_BLOB_LITERAL
1620 else if( op==TK_BLOB ){
1621 int nVal;
1622 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1623 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
1624 assert( pExpr->u.zToken[1]=='\'' );
1625 pVal = valueNew(db, pCtx);
1626 if( !pVal ) goto no_mem;
1627 zVal = &pExpr->u.zToken[2];
1628 nVal = sqlite3Strlen30(zVal)-1;
1629 assert( zVal[nVal]=='\'' );
1630 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
1631 0, SQLITE_DYNAMIC);
1633 #endif
1634 #ifdef SQLITE_ENABLE_STAT4
1635 else if( op==TK_FUNCTION && pCtx!=0 ){
1636 rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
1638 #endif
1639 else if( op==TK_TRUEFALSE ){
1640 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1641 pVal = valueNew(db, pCtx);
1642 if( pVal ){
1643 pVal->flags = MEM_Int;
1644 pVal->u.i = pExpr->u.zToken[4]==0;
1648 *ppVal = pVal;
1649 return rc;
1651 no_mem:
1652 #ifdef SQLITE_ENABLE_STAT4
1653 if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
1654 #endif
1655 sqlite3OomFault(db);
1656 sqlite3DbFree(db, zVal);
1657 assert( *ppVal==0 );
1658 #ifdef SQLITE_ENABLE_STAT4
1659 if( pCtx==0 ) sqlite3ValueFree(pVal);
1660 #else
1661 assert( pCtx==0 ); sqlite3ValueFree(pVal);
1662 #endif
1663 return SQLITE_NOMEM_BKPT;
1667 ** Create a new sqlite3_value object, containing the value of pExpr.
1669 ** This only works for very simple expressions that consist of one constant
1670 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
1671 ** be converted directly into a value, then the value is allocated and
1672 ** a pointer written to *ppVal. The caller is responsible for deallocating
1673 ** the value by passing it to sqlite3ValueFree() later on. If the expression
1674 ** cannot be converted to a value, then *ppVal is set to NULL.
1676 int sqlite3ValueFromExpr(
1677 sqlite3 *db, /* The database connection */
1678 const Expr *pExpr, /* The expression to evaluate */
1679 u8 enc, /* Encoding to use */
1680 u8 affinity, /* Affinity to use */
1681 sqlite3_value **ppVal /* Write the new value here */
1683 return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
1686 #ifdef SQLITE_ENABLE_STAT4
1688 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
1690 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
1691 ** pAlloc if one does not exist and the new value is added to the
1692 ** UnpackedRecord object.
1694 ** A value is extracted in the following cases:
1696 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
1698 ** * The expression is a bound variable, and this is a reprepare, or
1700 ** * The expression is a literal value.
1702 ** On success, *ppVal is made to point to the extracted value. The caller
1703 ** is responsible for ensuring that the value is eventually freed.
1705 static int stat4ValueFromExpr(
1706 Parse *pParse, /* Parse context */
1707 Expr *pExpr, /* The expression to extract a value from */
1708 u8 affinity, /* Affinity to use */
1709 struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
1710 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
1712 int rc = SQLITE_OK;
1713 sqlite3_value *pVal = 0;
1714 sqlite3 *db = pParse->db;
1716 /* Skip over any TK_COLLATE nodes */
1717 pExpr = sqlite3ExprSkipCollate(pExpr);
1719 assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
1720 if( !pExpr ){
1721 pVal = valueNew(db, pAlloc);
1722 if( pVal ){
1723 sqlite3VdbeMemSetNull((Mem*)pVal);
1725 }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
1726 Vdbe *v;
1727 int iBindVar = pExpr->iColumn;
1728 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
1729 if( (v = pParse->pReprepare)!=0 ){
1730 pVal = valueNew(db, pAlloc);
1731 if( pVal ){
1732 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
1733 sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
1734 pVal->db = pParse->db;
1737 }else{
1738 rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
1741 assert( pVal==0 || pVal->db==db );
1742 *ppVal = pVal;
1743 return rc;
1747 ** This function is used to allocate and populate UnpackedRecord
1748 ** structures intended to be compared against sample index keys stored
1749 ** in the sqlite_stat4 table.
1751 ** A single call to this function populates zero or more fields of the
1752 ** record starting with field iVal (fields are numbered from left to
1753 ** right starting with 0). A single field is populated if:
1755 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
1757 ** * The expression is a bound variable, and this is a reprepare, or
1759 ** * The sqlite3ValueFromExpr() function is able to extract a value
1760 ** from the expression (i.e. the expression is a literal value).
1762 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
1763 ** vector components that match either of the two latter criteria listed
1764 ** above.
1766 ** Before any value is appended to the record, the affinity of the
1767 ** corresponding column within index pIdx is applied to it. Before
1768 ** this function returns, output parameter *pnExtract is set to the
1769 ** number of values appended to the record.
1771 ** When this function is called, *ppRec must either point to an object
1772 ** allocated by an earlier call to this function, or must be NULL. If it
1773 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
1774 ** is allocated (and *ppRec set to point to it) before returning.
1776 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
1777 ** error if a value cannot be extracted from pExpr. If an error does
1778 ** occur, an SQLite error code is returned.
1780 int sqlite3Stat4ProbeSetValue(
1781 Parse *pParse, /* Parse context */
1782 Index *pIdx, /* Index being probed */
1783 UnpackedRecord **ppRec, /* IN/OUT: Probe record */
1784 Expr *pExpr, /* The expression to extract a value from */
1785 int nElem, /* Maximum number of values to append */
1786 int iVal, /* Array element to populate */
1787 int *pnExtract /* OUT: Values appended to the record */
1789 int rc = SQLITE_OK;
1790 int nExtract = 0;
1792 if( pExpr==0 || pExpr->op!=TK_SELECT ){
1793 int i;
1794 struct ValueNewStat4Ctx alloc;
1796 alloc.pParse = pParse;
1797 alloc.pIdx = pIdx;
1798 alloc.ppRec = ppRec;
1800 for(i=0; i<nElem; i++){
1801 sqlite3_value *pVal = 0;
1802 Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
1803 u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
1804 alloc.iVal = iVal+i;
1805 rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
1806 if( !pVal ) break;
1807 nExtract++;
1811 *pnExtract = nExtract;
1812 return rc;
1816 ** Attempt to extract a value from expression pExpr using the methods
1817 ** as described for sqlite3Stat4ProbeSetValue() above.
1819 ** If successful, set *ppVal to point to a new value object and return
1820 ** SQLITE_OK. If no value can be extracted, but no other error occurs
1821 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
1822 ** does occur, return an SQLite error code. The final value of *ppVal
1823 ** is undefined in this case.
1825 int sqlite3Stat4ValueFromExpr(
1826 Parse *pParse, /* Parse context */
1827 Expr *pExpr, /* The expression to extract a value from */
1828 u8 affinity, /* Affinity to use */
1829 sqlite3_value **ppVal /* OUT: New value object (or NULL) */
1831 return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
1835 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
1836 ** the column value into *ppVal. If *ppVal is initially NULL then a new
1837 ** sqlite3_value object is allocated.
1839 ** If *ppVal is initially NULL then the caller is responsible for
1840 ** ensuring that the value written into *ppVal is eventually freed.
1842 int sqlite3Stat4Column(
1843 sqlite3 *db, /* Database handle */
1844 const void *pRec, /* Pointer to buffer containing record */
1845 int nRec, /* Size of buffer pRec in bytes */
1846 int iCol, /* Column to extract */
1847 sqlite3_value **ppVal /* OUT: Extracted value */
1849 u32 t = 0; /* a column type code */
1850 int nHdr; /* Size of the header in the record */
1851 int iHdr; /* Next unread header byte */
1852 int iField; /* Next unread data byte */
1853 int szField = 0; /* Size of the current data field */
1854 int i; /* Column index */
1855 u8 *a = (u8*)pRec; /* Typecast byte array */
1856 Mem *pMem = *ppVal; /* Write result into this Mem object */
1858 assert( iCol>0 );
1859 iHdr = getVarint32(a, nHdr);
1860 if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
1861 iField = nHdr;
1862 for(i=0; i<=iCol; i++){
1863 iHdr += getVarint32(&a[iHdr], t);
1864 testcase( iHdr==nHdr );
1865 testcase( iHdr==nHdr+1 );
1866 if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
1867 szField = sqlite3VdbeSerialTypeLen(t);
1868 iField += szField;
1870 testcase( iField==nRec );
1871 testcase( iField==nRec+1 );
1872 if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
1873 if( pMem==0 ){
1874 pMem = *ppVal = sqlite3ValueNew(db);
1875 if( pMem==0 ) return SQLITE_NOMEM_BKPT;
1877 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
1878 pMem->enc = ENC(db);
1879 return SQLITE_OK;
1883 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
1884 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
1885 ** the object.
1887 void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
1888 if( pRec ){
1889 int i;
1890 int nCol = pRec->pKeyInfo->nAllField;
1891 Mem *aMem = pRec->aMem;
1892 sqlite3 *db = aMem[0].db;
1893 for(i=0; i<nCol; i++){
1894 sqlite3VdbeMemRelease(&aMem[i]);
1896 sqlite3KeyInfoUnref(pRec->pKeyInfo);
1897 sqlite3DbFreeNN(db, pRec);
1900 #endif /* ifdef SQLITE_ENABLE_STAT4 */
1903 ** Change the string value of an sqlite3_value object
1905 void sqlite3ValueSetStr(
1906 sqlite3_value *v, /* Value to be set */
1907 int n, /* Length of string z */
1908 const void *z, /* Text of the new string */
1909 u8 enc, /* Encoding to use */
1910 void (*xDel)(void*) /* Destructor for the string */
1912 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
1916 ** Free an sqlite3_value object
1918 void sqlite3ValueFree(sqlite3_value *v){
1919 if( !v ) return;
1920 sqlite3VdbeMemRelease((Mem *)v);
1921 sqlite3DbFreeNN(((Mem*)v)->db, v);
1925 ** The sqlite3ValueBytes() routine returns the number of bytes in the
1926 ** sqlite3_value object assuming that it uses the encoding "enc".
1927 ** The valueBytes() routine is a helper function.
1929 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
1930 return valueToText(pVal, enc)!=0 ? pVal->n : 0;
1932 int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
1933 Mem *p = (Mem*)pVal;
1934 assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
1935 if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
1936 return p->n;
1938 if( (p->flags & MEM_Blob)!=0 ){
1939 if( p->flags & MEM_Zero ){
1940 return p->n + p->u.nZero;
1941 }else{
1942 return p->n;
1945 if( p->flags & MEM_Null ) return 0;
1946 return valueBytes(pVal, enc);