xref: /sqlite-3.40.0/src/vdbemem.c (revision 47996ea7)
14f26d6c4Sdrh /*
24f26d6c4Sdrh ** 2004 May 26
34f26d6c4Sdrh **
44f26d6c4Sdrh ** The author disclaims copyright to this source code.  In place of
54f26d6c4Sdrh ** a legal notice, here is a blessing:
64f26d6c4Sdrh **
74f26d6c4Sdrh **    May you do good and not evil.
84f26d6c4Sdrh **    May you find forgiveness for yourself and forgive others.
94f26d6c4Sdrh **    May you share freely, never taking more than you give.
104f26d6c4Sdrh **
114f26d6c4Sdrh *************************************************************************
124f26d6c4Sdrh **
134f26d6c4Sdrh ** This file contains code use to manipulate "Mem" structure.  A "Mem"
144f26d6c4Sdrh ** stores a single value in the VDBE.  Mem is an opaque structure visible
154f26d6c4Sdrh ** only within the VDBE.  Interface routines refer to a Mem using the
164f26d6c4Sdrh ** name sqlite_value
174f26d6c4Sdrh */
184f26d6c4Sdrh #include "sqliteInt.h"
194f26d6c4Sdrh #include "vdbeInt.h"
204f26d6c4Sdrh 
21169f077eSdrh /* True if X is a power of two.  0 is considered a power of two here.
22169f077eSdrh ** In other words, return true if X has at most one bit set.
23169f077eSdrh */
24169f077eSdrh #define ISPOWEROF2(X)  (((X)&((X)-1))==0)
25169f077eSdrh 
2675fd0542Sdrh #ifdef SQLITE_DEBUG
2775fd0542Sdrh /*
2875fd0542Sdrh ** Check invariants on a Mem object.
2975fd0542Sdrh **
3075fd0542Sdrh ** This routine is intended for use inside of assert() statements, like
3175fd0542Sdrh ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
3275fd0542Sdrh */
sqlite3VdbeCheckMemInvariants(Mem * p)3375fd0542Sdrh int sqlite3VdbeCheckMemInvariants(Mem *p){
34d3b74200Sdrh   /* If MEM_Dyn is set then Mem.xDel!=0.
35a0024e6cSdrh   ** Mem.xDel might not be initialized if MEM_Dyn is clear.
36c91b2fd3Sdrh   */
37c91b2fd3Sdrh   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
38c91b2fd3Sdrh 
39722246e8Sdrh   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
40722246e8Sdrh   ** ensure that if Mem.szMalloc>0 then it is safe to do
41722246e8Sdrh   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
42722246e8Sdrh   ** That saves a few cycles in inner loops. */
431eda9f7dSdrh   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
441eda9f7dSdrh 
45169f077eSdrh   /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
46169f077eSdrh   assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
4774eaba4dSdrh 
48a0024e6cSdrh   if( p->flags & MEM_Null ){
49e2bc6552Sdrh     /* Cannot be both MEM_Null and some other type */
509d67afc4Sdrh     assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
51a0024e6cSdrh 
52a0024e6cSdrh     /* If MEM_Null is set, then either the value is a pure NULL (the usual
53a0024e6cSdrh     ** case) or it is a pointer set using sqlite3_bind_pointer() or
54a0024e6cSdrh     ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
55a0024e6cSdrh     ** set.
56a0024e6cSdrh     */
57a0024e6cSdrh     if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
58a0024e6cSdrh       /* This is a pointer type.  There may be a flag to indicate what to
59a0024e6cSdrh       ** do with the pointer. */
60a0024e6cSdrh       assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61a0024e6cSdrh               ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
62a0024e6cSdrh               ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
63a0024e6cSdrh 
64a0024e6cSdrh       /* No other bits set */
65e0f20b46Sdrh       assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
66a0024e6cSdrh                            |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
67a0024e6cSdrh     }else{
68a0024e6cSdrh       /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
69a0024e6cSdrh       ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
70a0024e6cSdrh     }
71a0024e6cSdrh   }else{
72a0024e6cSdrh     /* The MEM_Cleared bit is only allowed on NULLs */
73a0024e6cSdrh     assert( (p->flags & MEM_Cleared)==0 );
74a0024e6cSdrh   }
75e2bc6552Sdrh 
7617bcb102Sdrh   /* The szMalloc field holds the correct memory allocation size */
7717bcb102Sdrh   assert( p->szMalloc==0
782454e4a9Sdrh        || (p->flags==MEM_Undefined
792454e4a9Sdrh            && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
8017bcb102Sdrh        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
81c91b2fd3Sdrh 
82c91b2fd3Sdrh   /* If p holds a string or blob, the Mem.z must point to exactly
83c91b2fd3Sdrh   ** one of the following:
84c91b2fd3Sdrh   **
85c91b2fd3Sdrh   **   (1) Memory in Mem.zMalloc and managed by the Mem object
86c91b2fd3Sdrh   **   (2) Memory to be freed using Mem.xDel
8760ec914cSpeter.d.reid   **   (3) An ephemeral string or blob
88c91b2fd3Sdrh   **   (4) A static string or blob
89c91b2fd3Sdrh   */
9017bcb102Sdrh   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
9175fd0542Sdrh     assert(
9217bcb102Sdrh       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
93c91b2fd3Sdrh       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
94c91b2fd3Sdrh       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
95c91b2fd3Sdrh       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
96c91b2fd3Sdrh     );
97c91b2fd3Sdrh   }
9875fd0542Sdrh   return 1;
9975fd0542Sdrh }
10075fd0542Sdrh #endif
10175fd0542Sdrh 
10283a1dafbSdrh /*
103169f077eSdrh ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
104169f077eSdrh ** into a buffer.
10583a1dafbSdrh */
vdbeMemRenderNum(int sz,char * zBuf,Mem * p)10683a1dafbSdrh static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
10783a1dafbSdrh   StrAccum acc;
108169f077eSdrh   assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
10982b0f106Sdrh   assert( sz>22 );
110169f077eSdrh   if( p->flags & MEM_Int ){
1112f04583fSdrh #if GCC_VERSION>=7000000
1122f04583fSdrh     /* Work-around for GCC bug
1132f04583fSdrh     ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
1142f04583fSdrh     i64 x;
1152f04583fSdrh     assert( (p->flags&MEM_Int)*2==sizeof(x) );
1162f04583fSdrh     memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
1172f04583fSdrh     sqlite3Int64ToText(x, zBuf);
1182f04583fSdrh #else
11982b0f106Sdrh     sqlite3Int64ToText(p->u.i, zBuf);
1202f04583fSdrh #endif
12183a1dafbSdrh   }else{
12282b0f106Sdrh     sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
12382b0f106Sdrh     sqlite3_str_appendf(&acc, "%!.15g",
12482b0f106Sdrh          (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
12583a1dafbSdrh     assert( acc.zText==zBuf && acc.mxAlloc<=0 );
12683a1dafbSdrh     zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
12783a1dafbSdrh   }
12882b0f106Sdrh }
12983a1dafbSdrh 
130563ddbe5Sdrh #ifdef SQLITE_DEBUG
131563ddbe5Sdrh /*
132df82afc0Sdrh ** Validity checks on pMem.  pMem holds a string.
133df82afc0Sdrh **
134df82afc0Sdrh ** (1) Check that string value of pMem agrees with its integer or real value.
135df82afc0Sdrh ** (2) Check that the string is correctly zero terminated
136563ddbe5Sdrh **
137563ddbe5Sdrh ** A single int or real value always converts to the same strings.  But
138563ddbe5Sdrh ** many different strings can be converted into the same int or real.
139563ddbe5Sdrh ** If a table contains a numeric value and an index is based on the
140563ddbe5Sdrh ** corresponding string value, then it is important that the string be
141563ddbe5Sdrh ** derived from the numeric value, not the other way around, to ensure
142563ddbe5Sdrh ** that the index and table are consistent.  See ticket
143563ddbe5Sdrh ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
144563ddbe5Sdrh ** an example.
145563ddbe5Sdrh **
146563ddbe5Sdrh ** This routine looks at pMem to verify that if it has both a numeric
147563ddbe5Sdrh ** representation and a string representation then the string rep has
148563ddbe5Sdrh ** been derived from the numeric and not the other way around.  It returns
149563ddbe5Sdrh ** true if everything is ok and false if there is a problem.
150563ddbe5Sdrh **
151563ddbe5Sdrh ** This routine is for use inside of assert() statements only.
152563ddbe5Sdrh */
sqlite3VdbeMemValidStrRep(Mem * p)153df82afc0Sdrh int sqlite3VdbeMemValidStrRep(Mem *p){
154563ddbe5Sdrh   char zBuf[100];
155563ddbe5Sdrh   char *z;
156563ddbe5Sdrh   int i, j, incr;
157563ddbe5Sdrh   if( (p->flags & MEM_Str)==0 ) return 1;
158df82afc0Sdrh   if( p->flags & MEM_Term ){
159df82afc0Sdrh     /* Insure that the string is properly zero-terminated.  Pay particular
160df82afc0Sdrh     ** attention to the case where p->n is odd */
161e72d1a86Sdrh     if( p->szMalloc>0 && p->z==p->zMalloc ){
162df82afc0Sdrh       assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
163df82afc0Sdrh       assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
164df82afc0Sdrh     }
165df82afc0Sdrh     assert( p->z[p->n]==0 );
166df82afc0Sdrh     assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
167df82afc0Sdrh     assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
168df82afc0Sdrh   }
169169f077eSdrh   if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
17083a1dafbSdrh   vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
171563ddbe5Sdrh   z = p->z;
172563ddbe5Sdrh   i = j = 0;
173563ddbe5Sdrh   incr = 1;
174563ddbe5Sdrh   if( p->enc!=SQLITE_UTF8 ){
175563ddbe5Sdrh     incr = 2;
176563ddbe5Sdrh     if( p->enc==SQLITE_UTF16BE ) z++;
177563ddbe5Sdrh   }
178563ddbe5Sdrh   while( zBuf[j] ){
179563ddbe5Sdrh     if( zBuf[j++]!=z[i] ) return 0;
180563ddbe5Sdrh     i += incr;
181563ddbe5Sdrh   }
182563ddbe5Sdrh   return 1;
183563ddbe5Sdrh }
184563ddbe5Sdrh #endif /* SQLITE_DEBUG */
18575fd0542Sdrh 
1864f26d6c4Sdrh /*
187bfd6cce5Sdanielk1977 ** If pMem is an object with a valid string representation, this routine
188bfd6cce5Sdanielk1977 ** ensures the internal encoding for the string representation is
189bfd6cce5Sdanielk1977 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
1904f26d6c4Sdrh **
191bfd6cce5Sdanielk1977 ** If pMem is not a string object, or the encoding of the string
192bfd6cce5Sdanielk1977 ** representation is already stored using the requested encoding, then this
193bfd6cce5Sdanielk1977 ** routine is a no-op.
1944f26d6c4Sdrh **
1954f26d6c4Sdrh ** SQLITE_OK is returned if the conversion is successful (or not required).
1964f26d6c4Sdrh ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
1974f26d6c4Sdrh ** between formats.
1984f26d6c4Sdrh */
sqlite3VdbeChangeEncoding(Mem * pMem,int desiredEnc)199b21c8cd4Sdrh int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
200ef593f29Smistachkin #ifndef SQLITE_OMIT_UTF16
2012c336549Sdanielk1977   int rc;
202ef593f29Smistachkin #endif
2037d4c94bcSdrh   assert( pMem!=0 );
2049d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
205b27b7f5dSdrh   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
206b27b7f5dSdrh            || desiredEnc==SQLITE_UTF16BE );
207fb92e071Sdrh   if( !(pMem->flags&MEM_Str) ){
208fb92e071Sdrh     pMem->enc = desiredEnc;
2094f26d6c4Sdrh     return SQLITE_OK;
2104f26d6c4Sdrh   }
211555db979Sdrh   if( pMem->enc==desiredEnc ){
212555db979Sdrh     return SQLITE_OK;
213555db979Sdrh   }
214b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
2156c62608fSdrh #ifdef SQLITE_OMIT_UTF16
2166c62608fSdrh   return SQLITE_ERROR;
2176c62608fSdrh #else
21800fd957bSdanielk1977 
21900fd957bSdanielk1977   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
22000fd957bSdanielk1977   ** then the encoding of the value may not have changed.
22100fd957bSdanielk1977   */
222b27b7f5dSdrh   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
22300fd957bSdanielk1977   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
22400fd957bSdanielk1977   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
22500fd957bSdanielk1977   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
2262c336549Sdanielk1977   return rc;
2276c62608fSdrh #endif
2284f26d6c4Sdrh }
2294f26d6c4Sdrh 
230eb2e176aSdrh /*
2316ff74277Sdrh ** Make sure pMem->z points to a writable allocation of at least n bytes.
232a7a8e14bSdanielk1977 **
233b0e7704eSdrh ** If the bPreserve argument is true, then copy of the content of
234b0e7704eSdrh ** pMem->z into the new allocation.  pMem must be either a string or
235b0e7704eSdrh ** blob if bPreserve is true.  If bPreserve is false, any prior content
236b0e7704eSdrh ** in pMem->z is discarded.
237a7a8e14bSdanielk1977 */
sqlite3VdbeMemGrow(Mem * pMem,int n,int bPreserve)238322f2852Sdrh SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
23975fd0542Sdrh   assert( sqlite3VdbeCheckMemInvariants(pMem) );
2409d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
241575fad65Sdrh   testcase( pMem->db==0 );
242a7a8e14bSdanielk1977 
243b0e7704eSdrh   /* If the bPreserve flag is set to true, then the memory cell must already
2442b9ee77fSdan   ** contain a valid string or blob value.  */
2450364f229Sdrh   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
246b0e7704eSdrh   testcase( bPreserve && pMem->z==0 );
2472b9ee77fSdan 
24817bcb102Sdrh   assert( pMem->szMalloc==0
2492454e4a9Sdrh        || (pMem->flags==MEM_Undefined
2502454e4a9Sdrh            && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
25117bcb102Sdrh        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
252762dffa5Sdrh   if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
25397b02505Sdrh     if( pMem->db ){
2545f096135Sdanielk1977       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
25597b02505Sdrh     }else{
25697b02505Sdrh       pMem->zMalloc = sqlite3Realloc(pMem->z, n);
25797b02505Sdrh       if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
25897b02505Sdrh       pMem->z = pMem->zMalloc;
25997b02505Sdrh     }
260b0e7704eSdrh     bPreserve = 0;
261a7a8e14bSdanielk1977   }else{
262dbd6a7dcSdrh     if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
2635f096135Sdanielk1977     pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
264a7a8e14bSdanielk1977   }
265b0e7704eSdrh   if( pMem->zMalloc==0 ){
2660725cabeSdrh     sqlite3VdbeMemSetNull(pMem);
267d1053a43Sdrh     pMem->z = 0;
26817bcb102Sdrh     pMem->szMalloc = 0;
269fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
27017bcb102Sdrh   }else{
27117bcb102Sdrh     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
272b0e7704eSdrh   }
273a7a8e14bSdanielk1977 
274762dffa5Sdrh   if( bPreserve && pMem->z ){
275762dffa5Sdrh     assert( pMem->z!=pMem->zMalloc );
2765f096135Sdanielk1977     memcpy(pMem->zMalloc, pMem->z, pMem->n);
2775f096135Sdanielk1977   }
278c91b2fd3Sdrh   if( (pMem->flags&MEM_Dyn)!=0 ){
279c91b2fd3Sdrh     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
2805f096135Sdanielk1977     pMem->xDel((void *)(pMem->z));
281a7a8e14bSdanielk1977   }
282a7a8e14bSdanielk1977 
2835f096135Sdanielk1977   pMem->z = pMem->zMalloc;
284c91b2fd3Sdrh   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
285b0e7704eSdrh   return SQLITE_OK;
286a7a8e14bSdanielk1977 }
287a7a8e14bSdanielk1977 
288a7a8e14bSdanielk1977 /*
289322f2852Sdrh ** Change the pMem->zMalloc allocation to be at least szNew bytes.
290322f2852Sdrh ** If pMem->zMalloc already meets or exceeds the requested size, this
291322f2852Sdrh ** routine is a no-op.
292322f2852Sdrh **
293322f2852Sdrh ** Any prior string or blob content in the pMem object may be discarded.
294a5476e92Sdrh ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
295169f077eSdrh ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
296169f077eSdrh ** and MEM_Null values are preserved.
297322f2852Sdrh **
298322f2852Sdrh ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
299322f2852Sdrh ** if unable to complete the resizing.
300322f2852Sdrh */
sqlite3VdbeMemClearAndResize(Mem * pMem,int szNew)301322f2852Sdrh int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
302b4738ddbSdan   assert( CORRUPT_DB || szNew>0 );
303722246e8Sdrh   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
3041eda9f7dSdrh   if( pMem->szMalloc<szNew ){
305322f2852Sdrh     return sqlite3VdbeMemGrow(pMem, szNew, 0);
306322f2852Sdrh   }
3071eda9f7dSdrh   assert( (pMem->flags & MEM_Dyn)==0 );
308322f2852Sdrh   pMem->z = pMem->zMalloc;
30983a1dafbSdrh   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
310322f2852Sdrh   return SQLITE_OK;
311322f2852Sdrh }
312322f2852Sdrh 
313322f2852Sdrh /*
31497397a70Sdrh ** It is already known that pMem contains an unterminated string.
31597397a70Sdrh ** Add the zero terminator.
31630d3b0ceSdrh **
31730d3b0ceSdrh ** Three bytes of zero are added.  In this way, there is guaranteed
31830d3b0ceSdrh ** to be a double-zero byte at an even byte boundary in order to
31930d3b0ceSdrh ** terminate a UTF16 string, even if the initial size of the buffer
32030d3b0ceSdrh ** is an odd number of bytes.
32197397a70Sdrh */
vdbeMemAddTerminator(Mem * pMem)32297397a70Sdrh static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
32330d3b0ceSdrh   if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
32497397a70Sdrh     return SQLITE_NOMEM_BKPT;
32597397a70Sdrh   }
32697397a70Sdrh   pMem->z[pMem->n] = 0;
32797397a70Sdrh   pMem->z[pMem->n+1] = 0;
32830d3b0ceSdrh   pMem->z[pMem->n+2] = 0;
32997397a70Sdrh   pMem->flags |= MEM_Term;
33097397a70Sdrh   return SQLITE_OK;
33197397a70Sdrh }
33297397a70Sdrh 
33397397a70Sdrh /*
3341eda9f7dSdrh ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
3351eda9f7dSdrh ** MEM.zMalloc, where it can be safely written.
336eb2e176aSdrh **
337eb2e176aSdrh ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
338eb2e176aSdrh */
sqlite3VdbeMemMakeWriteable(Mem * pMem)339dab898f8Sdrh int sqlite3VdbeMemMakeWriteable(Mem *pMem){
3407d4c94bcSdrh   assert( pMem!=0 );
341b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
3429d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
3438aaf7bccSdrh   if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
3448aaf7bccSdrh     if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
3458aaf7bccSdrh     if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
34697397a70Sdrh       int rc = vdbeMemAddTerminator(pMem);
34797397a70Sdrh       if( rc ) return rc;
348bd6789e7Sdrh     }
3498aaf7bccSdrh   }
350bd6789e7Sdrh   pMem->flags &= ~MEM_Ephem;
351ebc16717Sdrh #ifdef SQLITE_DEBUG
352ebc16717Sdrh   pMem->pScopyFrom = 0;
353ebc16717Sdrh #endif
354a7a8e14bSdanielk1977 
355f4479501Sdrh   return SQLITE_OK;
356eb2e176aSdrh }
357eb2e176aSdrh 
358eb2e176aSdrh /*
359fdf972a9Sdrh ** If the given Mem* has a zero-filled tail, turn it into an ordinary
360b026e05eSdrh ** blob stored in dynamically allocated space.
361b026e05eSdrh */
362246ad31dSdanielk1977 #ifndef SQLITE_OMIT_INCRBLOB
sqlite3VdbeMemExpandBlob(Mem * pMem)363b21c8cd4Sdrh int sqlite3VdbeMemExpandBlob(Mem *pMem){
36498640a3fSdrh   int nByte;
3657d4c94bcSdrh   assert( pMem!=0 );
366ff535a24Sdrh   assert( pMem->flags & MEM_Zero );
3677d683394Sdrh   assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
368427db2d2Sdrh   testcase( sqlite3_value_nochange(pMem) );
3699d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
370b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
371a7a8e14bSdanielk1977 
372a7a8e14bSdanielk1977   /* Set nByte to the number of bytes required to store the expanded blob. */
3738df32841Sdrh   nByte = pMem->n + pMem->u.nZero;
374a7a8e14bSdanielk1977   if( nByte<=0 ){
3750364f229Sdrh     if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
376a7a8e14bSdanielk1977     nByte = 1;
377a7a8e14bSdanielk1977   }
378a7a8e14bSdanielk1977   if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
379fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
380b026e05eSdrh   }
3819b2adcc3Sdrh   assert( pMem->z!=0 );
3829b2adcc3Sdrh   assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
383a7a8e14bSdanielk1977 
3848df32841Sdrh   memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
3858df32841Sdrh   pMem->n += pMem->u.nZero;
386a7a8e14bSdanielk1977   pMem->flags &= ~(MEM_Zero|MEM_Term);
387b026e05eSdrh   return SQLITE_OK;
388b026e05eSdrh }
389246ad31dSdanielk1977 #endif
390b026e05eSdrh 
391b026e05eSdrh /*
392b63388b6Sdrh ** Make sure the given Mem is \u0000 terminated.
393b63388b6Sdrh */
sqlite3VdbeMemNulTerminate(Mem * pMem)394b63388b6Sdrh int sqlite3VdbeMemNulTerminate(Mem *pMem){
3957d4c94bcSdrh   assert( pMem!=0 );
396b63388b6Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
397b63388b6Sdrh   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
398b63388b6Sdrh   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
399b63388b6Sdrh   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
400b63388b6Sdrh     return SQLITE_OK;   /* Nothing to do */
401b63388b6Sdrh   }else{
402b63388b6Sdrh     return vdbeMemAddTerminator(pMem);
403b63388b6Sdrh   }
404b63388b6Sdrh }
405b63388b6Sdrh 
406b63388b6Sdrh /*
40730d3b0ceSdrh ** Add MEM_Str to the set of representations for the given Mem.  This
40830d3b0ceSdrh ** routine is only called if pMem is a number of some kind, not a NULL
40930d3b0ceSdrh ** or a BLOB.
410eb2e176aSdrh **
411169f077eSdrh ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
412169f077eSdrh ** if bForce is true but are retained if bForce is false.
41313073931Sdanielk1977 **
41413073931Sdanielk1977 ** A MEM_Null value will never be passed to this function. This function is
41513073931Sdanielk1977 ** used for converting values to text for returning to the user (i.e. via
41613073931Sdanielk1977 ** sqlite3_value_text()), or for ensuring that values to be used as btree
41713073931Sdanielk1977 ** keys are strings. In the former case a NULL pointer is returned the
41860ec914cSpeter.d.reid ** user and the latter is an internal programming error.
419eb2e176aSdrh */
sqlite3VdbeMemStringify(Mem * pMem,u8 enc,u8 bForce)420bd9507c8Sdrh int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
421a7a8e14bSdanielk1977   const int nByte = 32;
422eb2e176aSdrh 
4237d4c94bcSdrh   assert( pMem!=0 );
424b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
42583a1dafbSdrh   assert( !(pMem->flags&MEM_Zero) );
42683a1dafbSdrh   assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
427169f077eSdrh   assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
4289d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
429ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
4303d4501e5Sdrh 
431eb2e176aSdrh 
432322f2852Sdrh   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
4332a1df937Sdrh     pMem->enc = 0;
434fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
435a7a8e14bSdanielk1977   }
436a7a8e14bSdanielk1977 
43783a1dafbSdrh   vdbeMemRenderNum(nByte, pMem->z, pMem);
4387301e774Sdrh   assert( pMem->z!=0 );
4397301e774Sdrh   pMem->n = sqlite3Strlen30NN(pMem->z);
440dc8453fdSdanielk1977   pMem->enc = SQLITE_UTF8;
441a7a8e14bSdanielk1977   pMem->flags |= MEM_Str|MEM_Term;
44283a1dafbSdrh   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
443b21c8cd4Sdrh   sqlite3VdbeChangeEncoding(pMem, enc);
444bd9507c8Sdrh   return SQLITE_OK;
445eb2e176aSdrh }
446eb2e176aSdrh 
447eb2e176aSdrh /*
448abfcea25Sdrh ** Memory cell pMem contains the context of an aggregate function.
449abfcea25Sdrh ** This routine calls the finalize method for that function.  The
450abfcea25Sdrh ** result of the aggregate is stored back into pMem.
45190669c1dSdrh **
45290669c1dSdrh ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
45390669c1dSdrh ** otherwise.
454abfcea25Sdrh */
sqlite3VdbeMemFinalize(Mem * pMem,FuncDef * pFunc)45590669c1dSdrh int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
456abfcea25Sdrh   sqlite3_context ctx;
4579bd038f1Sdrh   Mem t;
4589d9c41e2Sdrh   assert( pFunc!=0 );
4597d4c94bcSdrh   assert( pMem!=0 );
460c381056eSdrh   assert( pMem->db!=0 );
4619d9c41e2Sdrh   assert( pFunc->xFinalize!=0 );
4623c024d69Sdrh   assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
463c381056eSdrh   assert( sqlite3_mutex_held(pMem->db->mutex) );
464709b8cb4Sdrh   memset(&ctx, 0, sizeof(ctx));
4659bd038f1Sdrh   memset(&t, 0, sizeof(t));
4669bd038f1Sdrh   t.flags = MEM_Null;
4679bd038f1Sdrh   t.db = pMem->db;
4689bd038f1Sdrh   ctx.pOut = &t;
469abfcea25Sdrh   ctx.pMem = pMem;
470abfcea25Sdrh   ctx.pFunc = pFunc;
471659fdb4dSdrh   ctx.enc = ENC(t.db);
472ee9ff672Sdrh   pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
473d3b74200Sdrh   assert( (pMem->flags & MEM_Dyn)==0 );
474dbd6a7dcSdrh   if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
4759bd038f1Sdrh   memcpy(pMem, &t, sizeof(t));
4769d9c41e2Sdrh   return ctx.isError;
47790669c1dSdrh }
478abfcea25Sdrh 
4799a94722dSdan /*
4809a94722dSdan ** Memory cell pAccum contains the context of an aggregate function.
4819a94722dSdan ** This routine calls the xValue method for that function and stores
4829a94722dSdan ** the results in memory cell pMem.
4839a94722dSdan **
4849a94722dSdan ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
4859a94722dSdan ** otherwise.
4869a94722dSdan */
48767a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
sqlite3VdbeMemAggValue(Mem * pAccum,Mem * pOut,FuncDef * pFunc)48886fb6e17Sdan int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
48986fb6e17Sdan   sqlite3_context ctx;
49086fb6e17Sdan   assert( pFunc!=0 );
49186fb6e17Sdan   assert( pFunc->xValue!=0 );
49286fb6e17Sdan   assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
493c381056eSdrh   assert( pAccum->db!=0 );
494c381056eSdrh   assert( sqlite3_mutex_held(pAccum->db->mutex) );
49586fb6e17Sdan   memset(&ctx, 0, sizeof(ctx));
4968f26da6cSdrh   sqlite3VdbeMemSetNull(pOut);
49786fb6e17Sdan   ctx.pOut = pOut;
49886fb6e17Sdan   ctx.pMem = pAccum;
49986fb6e17Sdan   ctx.pFunc = pFunc;
500659fdb4dSdrh   ctx.enc = ENC(pAccum->db);
50186fb6e17Sdan   pFunc->xValue(&ctx);
50286fb6e17Sdan   return ctx.isError;
50386fb6e17Sdan }
50467a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
5059a94722dSdan 
506abfcea25Sdrh /*
5078740a600Sdrh ** If the memory cell contains a value that must be freed by
5080725cabeSdrh ** invoking the external callback in Mem.xDel, then this routine
5090725cabeSdrh ** will free that value.  It also sets Mem.flags to MEM_Null.
51012b7c7d8Sdrh **
5110725cabeSdrh ** This is a helper routine for sqlite3VdbeMemSetNull() and
5120725cabeSdrh ** for sqlite3VdbeMemRelease().  Use those other routines as the
5130725cabeSdrh ** entry point for releasing Mem resources.
5145f096135Sdanielk1977 */
vdbeMemClearExternAndSetNull(Mem * p)5150725cabeSdrh static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
5165f096135Sdanielk1977   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
5170725cabeSdrh   assert( VdbeMemDynamic(p) );
5185f096135Sdanielk1977   if( p->flags&MEM_Agg ){
5195f096135Sdanielk1977     sqlite3VdbeMemFinalize(p, p->u.pDef);
5205f096135Sdanielk1977     assert( (p->flags & MEM_Agg)==0 );
5210725cabeSdrh     testcase( p->flags & MEM_Dyn );
5220725cabeSdrh   }
5230725cabeSdrh   if( p->flags&MEM_Dyn ){
524c91b2fd3Sdrh     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
5255f096135Sdanielk1977     p->xDel((void *)p->z);
5261d46146bSdanielk1977   }
5276b478bcdSdrh   p->flags = MEM_Null;
5285f096135Sdanielk1977 }
5295f096135Sdanielk1977 
5305f096135Sdanielk1977 /*
53112b7c7d8Sdrh ** Release memory held by the Mem p, both external memory cleared
53212b7c7d8Sdrh ** by p->xDel and memory in p->zMalloc.
53312b7c7d8Sdrh **
53412b7c7d8Sdrh ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
5350725cabeSdrh ** the unusual case where there really is memory in p that needs
5360725cabeSdrh ** to be freed.
53712b7c7d8Sdrh */
vdbeMemClear(Mem * p)5380725cabeSdrh static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
53912b7c7d8Sdrh   if( VdbeMemDynamic(p) ){
5400725cabeSdrh     vdbeMemClearExternAndSetNull(p);
54112b7c7d8Sdrh   }
54217bcb102Sdrh   if( p->szMalloc ){
543dbd6a7dcSdrh     sqlite3DbFreeNN(p->db, p->zMalloc);
54417bcb102Sdrh     p->szMalloc = 0;
54512b7c7d8Sdrh   }
54612b7c7d8Sdrh   p->z = 0;
54712b7c7d8Sdrh }
54812b7c7d8Sdrh 
54912b7c7d8Sdrh /*
5500725cabeSdrh ** Release any memory resources held by the Mem.  Both the memory that is
5510725cabeSdrh ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
5528740a600Sdrh **
5530725cabeSdrh ** Use this routine prior to clean up prior to abandoning a Mem, or to
5540725cabeSdrh ** reset a Mem back to its minimum memory utilization.
5550725cabeSdrh **
5560725cabeSdrh ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
5570725cabeSdrh ** prior to inserting new content into the Mem.
558f4479501Sdrh */
sqlite3VdbeMemRelease(Mem * p)559d8123366Sdanielk1977 void sqlite3VdbeMemRelease(Mem *p){
56075fd0542Sdrh   assert( sqlite3VdbeCheckMemInvariants(p) );
56117bcb102Sdrh   if( VdbeMemDynamic(p) || p->szMalloc ){
5620725cabeSdrh     vdbeMemClear(p);
56312b7c7d8Sdrh   }
564f4479501Sdrh }
565f4479501Sdrh 
566fc854505Sdrh /* Like sqlite3VdbeMemRelease() but faster for cases where we
567fc854505Sdrh ** know in advance that the Mem is not MEM_Dyn or MEM_Agg.
568fc854505Sdrh */
sqlite3VdbeMemReleaseMalloc(Mem * p)569fc854505Sdrh void sqlite3VdbeMemReleaseMalloc(Mem *p){
570fc854505Sdrh   assert( !VdbeMemDynamic(p) );
571fc854505Sdrh   if( p->szMalloc ) vdbeMemClear(p);
572fc854505Sdrh }
573fc854505Sdrh 
574f4479501Sdrh /*
575d8c303feSdrh ** Convert a 64-bit IEEE double into a 64-bit signed integer.
576de1a8b8cSdrh ** If the double is out of range of a 64-bit signed integer then
577de1a8b8cSdrh ** return the closest available 64-bit signed integer.
578d8c303feSdrh */
doubleToInt64(double r)579b808d777Sdrh static SQLITE_NOINLINE i64 doubleToInt64(double r){
58052d14521Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
58152d14521Sdrh   /* When floating-point is omitted, double and int64 are the same thing */
58252d14521Sdrh   return r;
58352d14521Sdrh #else
584d8c303feSdrh   /*
585d8c303feSdrh   ** Many compilers we encounter do not define constants for the
586d8c303feSdrh   ** minimum and maximum 64-bit integers, or they define them
587d8c303feSdrh   ** inconsistently.  And many do not understand the "LL" notation.
588d8c303feSdrh   ** So we define our own static constants here using nothing
589d8c303feSdrh   ** larger than a 32-bit integer constant.
590d8c303feSdrh   */
5910f050353Sdrh   static const i64 maxInt = LARGEST_INT64;
5920f050353Sdrh   static const i64 minInt = SMALLEST_INT64;
593d8c303feSdrh 
594de1a8b8cSdrh   if( r<=(double)minInt ){
595d8c303feSdrh     return minInt;
596de1a8b8cSdrh   }else if( r>=(double)maxInt ){
597de1a8b8cSdrh     return maxInt;
598d8c303feSdrh   }else{
599d8c303feSdrh     return (i64)r;
600d8c303feSdrh   }
60152d14521Sdrh #endif
602d8c303feSdrh }
603d8c303feSdrh 
604d8c303feSdrh /*
6056a6124e2Sdrh ** Return some kind of integer value which is the best we can do
6066a6124e2Sdrh ** at representing the value that *pMem describes as an integer.
6076a6124e2Sdrh ** If pMem is an integer, then the value is exact.  If pMem is
6086a6124e2Sdrh ** a floating-point then the value returned is the integer part.
6096a6124e2Sdrh ** If pMem is a string or blob, then we make an attempt to convert
61060ec914cSpeter.d.reid ** it into an integer and return that.  If pMem represents an
611347a7cb3Sdrh ** an SQL-NULL value, return 0.
6126a6124e2Sdrh **
613347a7cb3Sdrh ** If pMem represents a string value, its encoding might be changed.
614eb2e176aSdrh */
memIntValue(const Mem * pMem)6152db144c3Sdrh static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
616b808d777Sdrh   i64 value = 0;
617b808d777Sdrh   sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
618b808d777Sdrh   return value;
619b808d777Sdrh }
sqlite3VdbeIntValue(const Mem * pMem)6202db144c3Sdrh i64 sqlite3VdbeIntValue(const Mem *pMem){
621b21c8cd4Sdrh   int flags;
6227d4c94bcSdrh   assert( pMem!=0 );
623b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
624ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
625b21c8cd4Sdrh   flags = pMem->flags;
626169f077eSdrh   if( flags & (MEM_Int|MEM_IntReal) ){
6273242c69cSdrh     testcase( flags & MEM_IntReal );
6283c024d69Sdrh     return pMem->u.i;
6296fec0762Sdrh   }else if( flags & MEM_Real ){
63074eaba4dSdrh     return doubleToInt64(pMem->u.r);
63122e6f67cSdrh   }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
632b808d777Sdrh     return memIntValue(pMem);
633eb2e176aSdrh   }else{
6346a6124e2Sdrh     return 0;
635eb2e176aSdrh   }
6366a6124e2Sdrh }
6376a6124e2Sdrh 
6386a6124e2Sdrh /*
6396a6124e2Sdrh ** Return the best representation of pMem that we can get into a
6406a6124e2Sdrh ** double.  If pMem is already a double or an integer, return its
6416a6124e2Sdrh ** value.  If it is a string or blob, try to convert it to a double.
6426a6124e2Sdrh ** If it is a NULL, return 0.0.
643eb2e176aSdrh */
memRealValue(Mem * pMem)644b808d777Sdrh static SQLITE_NOINLINE double memRealValue(Mem *pMem){
645b808d777Sdrh   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
646b808d777Sdrh   double val = (double)0;
647b808d777Sdrh   sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
648b808d777Sdrh   return val;
649b808d777Sdrh }
sqlite3VdbeRealValue(Mem * pMem)6506a6124e2Sdrh double sqlite3VdbeRealValue(Mem *pMem){
6517d4c94bcSdrh   assert( pMem!=0 );
652b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
653ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
654f93bbbeaSdanielk1977   if( pMem->flags & MEM_Real ){
65574eaba4dSdrh     return pMem->u.r;
656169f077eSdrh   }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
6573242c69cSdrh     testcase( pMem->flags & MEM_IntReal );
6583c024d69Sdrh     return (double)pMem->u.i;
659eb2e176aSdrh   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
660b808d777Sdrh     return memRealValue(pMem);
661eb2e176aSdrh   }else{
662fbd60f82Sshane     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
663fbd60f82Sshane     return (double)0;
664eb2e176aSdrh   }
6656a6124e2Sdrh }
6666a6124e2Sdrh 
6676a6124e2Sdrh /*
6681fcfa724Sdrh ** Return 1 if pMem represents true, and return 0 if pMem represents false.
6691fcfa724Sdrh ** Return the value ifNull if pMem is NULL.
6701fcfa724Sdrh */
sqlite3VdbeBooleanValue(Mem * pMem,int ifNull)6711fcfa724Sdrh int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
6723242c69cSdrh   testcase( pMem->flags & MEM_IntReal );
673169f077eSdrh   if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
6741fcfa724Sdrh   if( pMem->flags & MEM_Null ) return ifNull;
6751fcfa724Sdrh   return sqlite3VdbeRealValue(pMem)!=0.0;
6761fcfa724Sdrh }
6771fcfa724Sdrh 
6781fcfa724Sdrh /*
6798df447f0Sdrh ** The MEM structure is already a MEM_Real.  Try to also make it a
6808df447f0Sdrh ** MEM_Int if we can.
6818df447f0Sdrh */
sqlite3VdbeIntegerAffinity(Mem * pMem)6828df447f0Sdrh void sqlite3VdbeIntegerAffinity(Mem *pMem){
68374eaba4dSdrh   i64 ix;
6847d4c94bcSdrh   assert( pMem!=0 );
6858df447f0Sdrh   assert( pMem->flags & MEM_Real );
6869d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
687b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
688ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
689efe3d656Sdrh 
69074eaba4dSdrh   ix = doubleToInt64(pMem->u.r);
69194c3a2b1Sdrh 
69294c3a2b1Sdrh   /* Only mark the value as an integer if
69394c3a2b1Sdrh   **
69494c3a2b1Sdrh   **    (1) the round-trip conversion real->int->real is a no-op, and
69594c3a2b1Sdrh   **    (2) The integer is neither the largest nor the smallest
69694c3a2b1Sdrh   **        possible integer (ticket #3922)
69794c3a2b1Sdrh   **
698e74871acSdrh   ** The second and third terms in the following conditional enforces
699e74871acSdrh   ** the second condition under the assumption that addition overflow causes
700de1a8b8cSdrh   ** values to wrap around.
70194c3a2b1Sdrh   */
70274eaba4dSdrh   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
70374eaba4dSdrh     pMem->u.i = ix;
70474eaba4dSdrh     MemSetTypeFlag(pMem, MEM_Int);
7058df447f0Sdrh   }
7068df447f0Sdrh }
7078df447f0Sdrh 
7088a51256cSdrh /*
7098a51256cSdrh ** Convert pMem to type integer.  Invalidate any prior representations.
7108a51256cSdrh */
sqlite3VdbeMemIntegerify(Mem * pMem)7118a51256cSdrh int sqlite3VdbeMemIntegerify(Mem *pMem){
7127d4c94bcSdrh   assert( pMem!=0 );
713b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
7149d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
715ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
716ea598cbdSdrh 
7173c024d69Sdrh   pMem->u.i = sqlite3VdbeIntValue(pMem);
7183d4501e5Sdrh   MemSetTypeFlag(pMem, MEM_Int);
7198a51256cSdrh   return SQLITE_OK;
7208a51256cSdrh }
7218df447f0Sdrh 
7228df447f0Sdrh /*
7238a51256cSdrh ** Convert pMem so that it is of type MEM_Real.
7248a51256cSdrh ** Invalidate any prior representations.
7256a6124e2Sdrh */
sqlite3VdbeMemRealify(Mem * pMem)7266a6124e2Sdrh int sqlite3VdbeMemRealify(Mem *pMem){
7277d4c94bcSdrh   assert( pMem!=0 );
728b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
729ea598cbdSdrh   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
730ea598cbdSdrh 
73174eaba4dSdrh   pMem->u.r = sqlite3VdbeRealValue(pMem);
7323d4501e5Sdrh   MemSetTypeFlag(pMem, MEM_Real);
7338a51256cSdrh   return SQLITE_OK;
7348a51256cSdrh }
7358a51256cSdrh 
736d15046acSdrh /* Compare a floating point value to an integer.  Return true if the two
737d15046acSdrh ** values are the same within the precision of the floating point value.
738d15046acSdrh **
73913d04020Sdrh ** This function assumes that i was obtained by assignment from r1.
74013d04020Sdrh **
741d15046acSdrh ** For some versions of GCC on 32-bit machines, if you do the more obvious
742d15046acSdrh ** comparison of "r1==(double)i" you sometimes get an answer of false even
743d15046acSdrh ** though the r1 and (double)i values are bit-for-bit the same.
744d15046acSdrh */
sqlite3RealSameAsInt(double r1,sqlite3_int64 i)7458a3884efSdrh int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
746d15046acSdrh   double r2 = (double)i;
74713d04020Sdrh   return r1==0.0
74813d04020Sdrh       || (memcmp(&r1, &r2, sizeof(r1))==0
749ea9b564dSdrh           && i >= -2251799813685248LL && i < 2251799813685248LL);
750d15046acSdrh }
751d15046acSdrh 
75226e817f6Sdrh /* Convert a floating point value to its closest integer.  Do so in
75326e817f6Sdrh ** a way that avoids 'outside the range of representable values' warnings
75426e817f6Sdrh ** from UBSAN.
75526e817f6Sdrh */
sqlite3RealToI64(double r)75626e817f6Sdrh i64 sqlite3RealToI64(double r){
75726e817f6Sdrh   if( r<=(double)SMALLEST_INT64 ) return SMALLEST_INT64;
75826e817f6Sdrh   if( r>=(double)LARGEST_INT64) return LARGEST_INT64;
75926e817f6Sdrh   return (i64)r;
76026e817f6Sdrh }
76126e817f6Sdrh 
7628a51256cSdrh /*
763169f077eSdrh ** Convert pMem so that it has type MEM_Real or MEM_Int.
7648a51256cSdrh ** Invalidate any prior representations.
7654b5db5acSdrh **
7664b5db5acSdrh ** Every effort is made to force the conversion, even if the input
7674b5db5acSdrh ** is a string that does not look completely like a number.  Convert
7684b5db5acSdrh ** as much of the string as we can and ignore the rest.
7698a51256cSdrh */
sqlite3VdbeMemNumerify(Mem * pMem)7708a51256cSdrh int sqlite3VdbeMemNumerify(Mem *pMem){
7717d4c94bcSdrh   assert( pMem!=0 );
7723242c69cSdrh   testcase( pMem->flags & MEM_Int );
7733242c69cSdrh   testcase( pMem->flags & MEM_Real );
7743242c69cSdrh   testcase( pMem->flags & MEM_IntReal );
7753242c69cSdrh   testcase( pMem->flags & MEM_Null );
776169f077eSdrh   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
77784d4f1a3Sdrh     int rc;
7789a278229Sdrh     sqlite3_int64 ix;
779cd7b46dbSdrh     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
780b21c8cd4Sdrh     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
7819a278229Sdrh     rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
782c285ded2Sdrh     if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
78326e817f6Sdrh      || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r)))
784c285ded2Sdrh     ){
7859a278229Sdrh       pMem->u.i = ix;
7869a278229Sdrh       MemSetTypeFlag(pMem, MEM_Int);
7879a278229Sdrh     }else{
7889a278229Sdrh       MemSetTypeFlag(pMem, MEM_Real);
789cd7b46dbSdrh     }
7909351862bSdrh   }
791169f077eSdrh   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
79227fe1c3fSdrh   pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
793f4479501Sdrh   return SQLITE_OK;
7944f26d6c4Sdrh }
7954f26d6c4Sdrh 
7964f26d6c4Sdrh /*
7974169e430Sdrh ** Cast the datatype of the value in pMem according to the affinity
7984169e430Sdrh ** "aff".  Casting is different from applying affinity in that a cast
7994169e430Sdrh ** is forced.  In other words, the value is converted into the desired
8004169e430Sdrh ** affinity even if that results in loss of data.  This routine is
8014169e430Sdrh ** used (for example) to implement the SQL "cast()" operator.
8024169e430Sdrh */
sqlite3VdbeMemCast(Mem * pMem,u8 aff,u8 encoding)8030af6ddd3Sdrh int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
8040af6ddd3Sdrh   if( pMem->flags & MEM_Null ) return SQLITE_OK;
8054169e430Sdrh   switch( aff ){
80605883a34Sdrh     case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
8074169e430Sdrh       if( (pMem->flags & MEM_Blob)==0 ){
8084169e430Sdrh         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
8094169e430Sdrh         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
810da5c6240Sdrh         if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
8114169e430Sdrh       }else{
8124169e430Sdrh         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
8134169e430Sdrh       }
8144169e430Sdrh       break;
8154169e430Sdrh     }
8164169e430Sdrh     case SQLITE_AFF_NUMERIC: {
8174169e430Sdrh       sqlite3VdbeMemNumerify(pMem);
8184169e430Sdrh       break;
8194169e430Sdrh     }
8204169e430Sdrh     case SQLITE_AFF_INTEGER: {
8214169e430Sdrh       sqlite3VdbeMemIntegerify(pMem);
8224169e430Sdrh       break;
8234169e430Sdrh     }
8244169e430Sdrh     case SQLITE_AFF_REAL: {
8254169e430Sdrh       sqlite3VdbeMemRealify(pMem);
8264169e430Sdrh       break;
8274169e430Sdrh     }
8284169e430Sdrh     default: {
8294169e430Sdrh       assert( aff==SQLITE_AFF_TEXT );
8304169e430Sdrh       assert( MEM_Str==(MEM_Blob>>3) );
8314169e430Sdrh       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
8324169e430Sdrh       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
8334169e430Sdrh       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
83483a1dafbSdrh       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
835211a1a72Sdrh       if( encoding!=SQLITE_UTF8 ) pMem->n &= ~1;
8360af6ddd3Sdrh       return sqlite3VdbeChangeEncoding(pMem, encoding);
8374169e430Sdrh     }
8384169e430Sdrh   }
8390af6ddd3Sdrh   return SQLITE_OK;
8404169e430Sdrh }
8414169e430Sdrh 
842d3b74200Sdrh /*
843d3b74200Sdrh ** Initialize bulk memory to be a consistent Mem object.
844d3b74200Sdrh **
845d3b74200Sdrh ** The minimum amount of initialization feasible is performed.
846d3b74200Sdrh */
sqlite3VdbeMemInit(Mem * pMem,sqlite3 * db,u16 flags)847d3b74200Sdrh void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
848d3b74200Sdrh   assert( (flags & ~MEM_TypeMask)==0 );
849d3b74200Sdrh   pMem->flags = flags;
850d3b74200Sdrh   pMem->db = db;
85117bcb102Sdrh   pMem->szMalloc = 0;
852d3b74200Sdrh }
853d3b74200Sdrh 
8544169e430Sdrh 
8554169e430Sdrh /*
8564f26d6c4Sdrh ** Delete any previous value and set the value stored in *pMem to NULL.
8570725cabeSdrh **
8580725cabeSdrh ** This routine calls the Mem.xDel destructor to dispose of values that
8590725cabeSdrh ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
8600725cabeSdrh ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
8610725cabeSdrh ** routine to invoke the destructor and deallocates Mem.zMalloc.
8620725cabeSdrh **
8630725cabeSdrh ** Use this routine to reset the Mem prior to insert a new value.
8640725cabeSdrh **
8650725cabeSdrh ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
8664f26d6c4Sdrh */
sqlite3VdbeMemSetNull(Mem * pMem)8674f26d6c4Sdrh void sqlite3VdbeMemSetNull(Mem *pMem){
8686b478bcdSdrh   if( VdbeMemDynamic(pMem) ){
8690725cabeSdrh     vdbeMemClearExternAndSetNull(pMem);
8706b478bcdSdrh   }else{
8716b478bcdSdrh     pMem->flags = MEM_Null;
872165921a7Sdan   }
8734f26d6c4Sdrh }
sqlite3ValueSetNull(sqlite3_value * p)874a3cc007dSdrh void sqlite3ValueSetNull(sqlite3_value *p){
875a3cc007dSdrh   sqlite3VdbeMemSetNull((Mem*)p);
876a3cc007dSdrh }
8774f26d6c4Sdrh 
8784f26d6c4Sdrh /*
879b026e05eSdrh ** Delete any previous value and set the value to be a BLOB of length
880b026e05eSdrh ** n containing all zeros.
881b026e05eSdrh */
882a32536b4Sdan #ifndef SQLITE_OMIT_INCRBLOB
sqlite3VdbeMemSetZeroBlob(Mem * pMem,int n)883b026e05eSdrh void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
884b026e05eSdrh   sqlite3VdbeMemRelease(pMem);
885a7a8e14bSdanielk1977   pMem->flags = MEM_Blob|MEM_Zero;
886b026e05eSdrh   pMem->n = 0;
88798640a3fSdrh   if( n<0 ) n = 0;
8888df32841Sdrh   pMem->u.nZero = n;
889def0fec8Sdanielk1977   pMem->enc = SQLITE_UTF8;
8900725cabeSdrh   pMem->z = 0;
891b026e05eSdrh }
892a32536b4Sdan #else
sqlite3VdbeMemSetZeroBlob(Mem * pMem,int n)893a32536b4Sdan int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
894a32536b4Sdan   int nByte = n>0?n:1;
895a32536b4Sdan   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
896a32536b4Sdan     return SQLITE_NOMEM_BKPT;
897a32536b4Sdan   }
898a32536b4Sdan   assert( pMem->z!=0 );
899a32536b4Sdan   assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
900a32536b4Sdan   memset(pMem->z, 0, nByte);
901a32536b4Sdan   pMem->n = n>0?n:0;
902a32536b4Sdan   pMem->flags = MEM_Blob;
903a32536b4Sdan   pMem->enc = SQLITE_UTF8;
904a32536b4Sdan   return SQLITE_OK;
905a32536b4Sdan }
906a32536b4Sdan #endif
907b026e05eSdrh 
908b026e05eSdrh /*
9099bd038f1Sdrh ** The pMem is known to contain content that needs to be destroyed prior
9109bd038f1Sdrh ** to a value change.  So invoke the destructor, then set the value to
9119bd038f1Sdrh ** a 64-bit integer.
9129bd038f1Sdrh */
vdbeReleaseAndSetInt64(Mem * pMem,i64 val)9139bd038f1Sdrh static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
9140725cabeSdrh   sqlite3VdbeMemSetNull(pMem);
9159bd038f1Sdrh   pMem->u.i = val;
9169bd038f1Sdrh   pMem->flags = MEM_Int;
9179bd038f1Sdrh }
9189bd038f1Sdrh 
9199bd038f1Sdrh /*
9204f26d6c4Sdrh ** Delete any previous value and set the value stored in *pMem to val,
9214f26d6c4Sdrh ** manifest type INTEGER.
9224f26d6c4Sdrh */
sqlite3VdbeMemSetInt64(Mem * pMem,i64 val)923eb2e176aSdrh void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
9249bd038f1Sdrh   if( VdbeMemDynamic(pMem) ){
9259bd038f1Sdrh     vdbeReleaseAndSetInt64(pMem, val);
9269bd038f1Sdrh   }else{
9273c024d69Sdrh     pMem->u.i = val;
9284f26d6c4Sdrh     pMem->flags = MEM_Int;
9294f26d6c4Sdrh   }
9309bd038f1Sdrh }
9314f26d6c4Sdrh 
932a0024e6cSdrh /* A no-op destructor */
sqlite3NoopDestructor(void * p)93392011847Sdrh void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
934a0024e6cSdrh 
9353a96a5d9Sdrh /*
9363a96a5d9Sdrh ** Set the value stored in *pMem should already be a NULL.
9373a96a5d9Sdrh ** Also store a pointer to go with it.
9383a96a5d9Sdrh */
sqlite3VdbeMemSetPointer(Mem * pMem,void * pPtr,const char * zPType,void (* xDestructor)(void *))93922930062Sdrh void sqlite3VdbeMemSetPointer(
94022930062Sdrh   Mem *pMem,
94122930062Sdrh   void *pPtr,
94222930062Sdrh   const char *zPType,
94322930062Sdrh   void (*xDestructor)(void*)
94422930062Sdrh ){
9453a96a5d9Sdrh   assert( pMem->flags==MEM_Null );
9466f9d6881Sdrh   vdbeMemClear(pMem);
947a0024e6cSdrh   pMem->u.zPType = zPType ? zPType : "";
94822930062Sdrh   pMem->z = pPtr;
949a0024e6cSdrh   pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
950a0024e6cSdrh   pMem->eSubtype = 'p';
951a0024e6cSdrh   pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
9523a96a5d9Sdrh }
9533a96a5d9Sdrh 
9547ec5ea94Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
9554f26d6c4Sdrh /*
9564f26d6c4Sdrh ** Delete any previous value and set the value stored in *pMem to val,
9574f26d6c4Sdrh ** manifest type REAL.
9584f26d6c4Sdrh */
sqlite3VdbeMemSetDouble(Mem * pMem,double val)959eb2e176aSdrh void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
96053c14021Sdrh   sqlite3VdbeMemSetNull(pMem);
9610725cabeSdrh   if( !sqlite3IsNaN(val) ){
96274eaba4dSdrh     pMem->u.r = val;
9634f26d6c4Sdrh     pMem->flags = MEM_Real;
9644f26d6c4Sdrh   }
96553c14021Sdrh }
9667ec5ea94Sdrh #endif
9674f26d6c4Sdrh 
9689d67afc4Sdrh #ifdef SQLITE_DEBUG
9699d67afc4Sdrh /*
9709d67afc4Sdrh ** Return true if the Mem holds a RowSet object.  This routine is intended
9719d67afc4Sdrh ** for use inside of assert() statements.
9729d67afc4Sdrh */
sqlite3VdbeMemIsRowSet(const Mem * pMem)9739d67afc4Sdrh int sqlite3VdbeMemIsRowSet(const Mem *pMem){
9749d67afc4Sdrh   return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
9759d67afc4Sdrh          && pMem->xDel==sqlite3RowSetDelete;
9769d67afc4Sdrh }
9779d67afc4Sdrh #endif
9789d67afc4Sdrh 
9794f26d6c4Sdrh /*
9803d4501e5Sdrh ** Delete any previous value and set the value of pMem to be an
9813d4501e5Sdrh ** empty boolean index.
9829d67afc4Sdrh **
9839d67afc4Sdrh ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
9849d67afc4Sdrh ** error occurs.
9853d4501e5Sdrh */
sqlite3VdbeMemSetRowSet(Mem * pMem)9869d67afc4Sdrh int sqlite3VdbeMemSetRowSet(Mem *pMem){
9873d4501e5Sdrh   sqlite3 *db = pMem->db;
9889d67afc4Sdrh   RowSet *p;
9893d4501e5Sdrh   assert( db!=0 );
9909d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
9913d4501e5Sdrh   sqlite3VdbeMemRelease(pMem);
9929d67afc4Sdrh   p = sqlite3RowSetInit(db);
9939d67afc4Sdrh   if( p==0 ) return SQLITE_NOMEM;
9949d67afc4Sdrh   pMem->z = (char*)p;
9959d67afc4Sdrh   pMem->flags = MEM_Blob|MEM_Dyn;
9969d67afc4Sdrh   pMem->xDel = sqlite3RowSetDelete;
9979d67afc4Sdrh   return SQLITE_OK;
9983d4501e5Sdrh }
9993d4501e5Sdrh 
10003d4501e5Sdrh /*
1001023ae03aSdrh ** Return true if the Mem object contains a TEXT or BLOB that is
1002023ae03aSdrh ** too large - whose size exceeds SQLITE_MAX_LENGTH.
1003023ae03aSdrh */
sqlite3VdbeMemTooBig(Mem * p)1004023ae03aSdrh int sqlite3VdbeMemTooBig(Mem *p){
1005fa4a4b91Sdrh   assert( p->db!=0 );
1006023ae03aSdrh   if( p->flags & (MEM_Str|MEM_Blob) ){
1007023ae03aSdrh     int n = p->n;
1008023ae03aSdrh     if( p->flags & MEM_Zero ){
10098df32841Sdrh       n += p->u.nZero;
1010023ae03aSdrh     }
1011bb4957f8Sdrh     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
1012023ae03aSdrh   }
1013023ae03aSdrh   return 0;
1014023ae03aSdrh }
1015023ae03aSdrh 
10162b4ded99Sdrh #ifdef SQLITE_DEBUG
10172b4ded99Sdrh /*
101860ec914cSpeter.d.reid ** This routine prepares a memory cell for modification by breaking
10192b4ded99Sdrh ** its link to a shallow copy and by marking any current shallow
10202b4ded99Sdrh ** copies of this cell as invalid.
10212b4ded99Sdrh **
102252f11b88Sdrh ** This is used for testing and debugging only - to help ensure that shallow
102352f11b88Sdrh ** copies (created by OP_SCopy) are not misused.
10242b4ded99Sdrh */
sqlite3VdbeMemAboutToChange(Vdbe * pVdbe,Mem * pMem)1025e4c88c0cSdrh void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
10262b4ded99Sdrh   int i;
10272b4ded99Sdrh   Mem *pX;
10284cbd847aSdrh   for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
10292b4ded99Sdrh     if( pX->pScopyFrom==pMem ){
103065cdae00Smistachkin       u16 mFlags;
103122e95fbdSdrh       if( pVdbe->db->flags & SQLITE_VdbeTrace ){
103222e95fbdSdrh         sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
103322e95fbdSdrh           (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
103422e95fbdSdrh       }
1035d346fe0aSdrh       /* If pX is marked as a shallow copy of pMem, then try to verify that
10368d7b212cSdrh       ** no significant changes have been made to pX since the OP_SCopy.
10378d7b212cSdrh       ** A significant change would indicated a missed call to this
10388d7b212cSdrh       ** function for pX.  Minor changes, such as adding or removing a
10398d7b212cSdrh       ** dual type, are allowed, as long as the underlying value is the
10408d7b212cSdrh       ** same. */
104165cdae00Smistachkin       mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
1042169f077eSdrh       assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
10438d7b212cSdrh 
10448d7b212cSdrh       /* pMem is the register that is changing.  But also mark pX as
10458d7b212cSdrh       ** undefined so that we can quickly detect the shallow-copy error */
10468d7b212cSdrh       pX->flags = MEM_Undefined;
10472b4ded99Sdrh       pX->pScopyFrom = 0;
10482b4ded99Sdrh     }
10492b4ded99Sdrh   }
10502b4ded99Sdrh   pMem->pScopyFrom = 0;
10512b4ded99Sdrh }
10522b4ded99Sdrh #endif /* SQLITE_DEBUG */
10532b4ded99Sdrh 
1054023ae03aSdrh /*
1055febe1060Sdrh ** Make an shallow copy of pFrom into pTo.  Prior contents of
1056a05a722fSdrh ** pTo are freed.  The pFrom->z field is not duplicated.  If
1057febe1060Sdrh ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
1058febe1060Sdrh ** and flags gets srcType (either MEM_Ephem or MEM_Static).
10594f26d6c4Sdrh */
vdbeClrCopy(Mem * pTo,const Mem * pFrom,int eType)106014e06745Sdrh static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
106114e06745Sdrh   vdbeMemClearExternAndSetNull(pTo);
106214e06745Sdrh   assert( !VdbeMemDynamic(pTo) );
106314e06745Sdrh   sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
106414e06745Sdrh }
sqlite3VdbeMemShallowCopy(Mem * pTo,const Mem * pFrom,int srcType)1065febe1060Sdrh void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
10669d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pFrom) );
1067035e563bSdrh   assert( pTo->db==pFrom->db );
106814e06745Sdrh   if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
10695f096135Sdanielk1977   memcpy(pTo, pFrom, MEMCELLSIZE);
10705fea9076Sdan   if( (pFrom->flags&MEM_Static)==0 ){
1071a7a8e14bSdanielk1977     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
1072febe1060Sdrh     assert( srcType==MEM_Ephem || srcType==MEM_Static );
1073febe1060Sdrh     pTo->flags |= srcType;
1074febe1060Sdrh   }
1075febe1060Sdrh }
1076febe1060Sdrh 
1077febe1060Sdrh /*
1078febe1060Sdrh ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
1079febe1060Sdrh ** freed before the copy is made.
1080febe1060Sdrh */
sqlite3VdbeMemCopy(Mem * pTo,const Mem * pFrom)1081b21c8cd4Sdrh int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
1082a7a8e14bSdanielk1977   int rc = SQLITE_OK;
1083a7a8e14bSdanielk1977 
10849d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pFrom) );
10850725cabeSdrh   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
10865f096135Sdanielk1977   memcpy(pTo, pFrom, MEMCELLSIZE);
10875f096135Sdanielk1977   pTo->flags &= ~MEM_Dyn;
1088a7a8e14bSdanielk1977   if( pTo->flags&(MEM_Str|MEM_Blob) ){
10895f096135Sdanielk1977     if( 0==(pFrom->flags&MEM_Static) ){
10905f096135Sdanielk1977       pTo->flags |= MEM_Ephem;
10915f096135Sdanielk1977       rc = sqlite3VdbeMemMakeWriteable(pTo);
1092a7a8e14bSdanielk1977     }
1093a7a8e14bSdanielk1977   }
10945f096135Sdanielk1977 
109571c697efSdrh   return rc;
10964f26d6c4Sdrh }
10974f26d6c4Sdrh 
1098eb2e176aSdrh /*
1099369f27ebSdanielk1977 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
1100febe1060Sdrh ** freed. If pFrom contains ephemeral data, a copy is made.
1101febe1060Sdrh **
1102643167ffSdrh ** pFrom contains an SQL NULL when this routine returns.
1103369f27ebSdanielk1977 */
sqlite3VdbeMemMove(Mem * pTo,Mem * pFrom)1104643167ffSdrh void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
1105b21c8cd4Sdrh   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
1106b21c8cd4Sdrh   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
1107b21c8cd4Sdrh   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
11085f096135Sdanielk1977 
1109febe1060Sdrh   sqlite3VdbeMemRelease(pTo);
1110369f27ebSdanielk1977   memcpy(pTo, pFrom, sizeof(Mem));
111113073931Sdanielk1977   pFrom->flags = MEM_Null;
111217bcb102Sdrh   pFrom->szMalloc = 0;
1113369f27ebSdanielk1977 }
1114369f27ebSdanielk1977 
1115369f27ebSdanielk1977 /*
1116eb2e176aSdrh ** Change the value of a Mem to be a string or a BLOB.
1117a7a8e14bSdanielk1977 **
1118a7a8e14bSdanielk1977 ** The memory management strategy depends on the value of the xDel
1119a7a8e14bSdanielk1977 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
1120a7a8e14bSdanielk1977 ** string is copied into a (possibly existing) buffer managed by the
1121a7a8e14bSdanielk1977 ** Mem structure. Otherwise, any existing buffer is freed and the
1122a7a8e14bSdanielk1977 ** pointer copied.
11239a65f2cdSdrh **
11249a65f2cdSdrh ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
11259a65f2cdSdrh ** size limit) then no memory allocation occurs.  If the string can be
11269a65f2cdSdrh ** stored without allocating memory, then it is.  If a memory allocation
11279a65f2cdSdrh ** is required to store the string, then value of pMem is unchanged.  In
11289a65f2cdSdrh ** either case, SQLITE_TOOBIG is returned.
1129f4dd18eaSdrh **
1130f4dd18eaSdrh ** The "enc" parameter is the text encoding for the string, or zero
1131f4dd18eaSdrh ** to store a blob.
1132f4dd18eaSdrh **
1133f4dd18eaSdrh ** If n is negative, then the string consists of all bytes up to but
1134f4dd18eaSdrh ** excluding the first zero character.  The n parameter must be
1135f4dd18eaSdrh ** non-negative for blobs.
1136eb2e176aSdrh */
sqlite3VdbeMemSetStr(Mem * pMem,const char * z,i64 n,u8 enc,void (* xDel)(void *))11374f26d6c4Sdrh int sqlite3VdbeMemSetStr(
11384f26d6c4Sdrh   Mem *pMem,          /* Memory cell to set to string value */
11394f26d6c4Sdrh   const char *z,      /* String pointer */
1140d622855eSdrh   i64 n,              /* Bytes in string, or negative */
1141eb2e176aSdrh   u8 enc,             /* Encoding of z.  0 for BLOBs */
1142d8123366Sdanielk1977   void (*xDel)(void*) /* Destructor function */
11434f26d6c4Sdrh ){
1144d622855eSdrh   i64 nByte = n;      /* New value for pMem->n */
11450a687d12Sdrh   int iLimit;         /* Maximum allowed string or blob size */
1146bcedbb27Sdrh   u16 flags;          /* New value for pMem->flags */
1147a7a8e14bSdanielk1977 
11487d4c94bcSdrh   assert( pMem!=0 );
1149b21c8cd4Sdrh   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
11509d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
1151f4dd18eaSdrh   assert( enc!=0 || n>=0 );
1152a7a8e14bSdanielk1977 
1153a7a8e14bSdanielk1977   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
11544f26d6c4Sdrh   if( !z ){
1155a7a8e14bSdanielk1977     sqlite3VdbeMemSetNull(pMem);
11564f26d6c4Sdrh     return SQLITE_OK;
11574f26d6c4Sdrh   }
1158a7a8e14bSdanielk1977 
11590a687d12Sdrh   if( pMem->db ){
11600a687d12Sdrh     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
11610a687d12Sdrh   }else{
11620a687d12Sdrh     iLimit = SQLITE_MAX_LENGTH;
11630a687d12Sdrh   }
1164a7a8e14bSdanielk1977   if( nByte<0 ){
1165a7a8e14bSdanielk1977     assert( enc!=0 );
11668fd3897cSdrh     if( enc==SQLITE_UTF8 ){
1167d622855eSdrh       nByte = strlen(z);
11688fd3897cSdrh     }else{
11690a687d12Sdrh       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
11708fd3897cSdrh     }
1171bcedbb27Sdrh     flags= MEM_Str|MEM_Term;
1172bcedbb27Sdrh   }else if( enc==0 ){
1173bcedbb27Sdrh     flags = MEM_Blob;
1174fb92e071Sdrh     enc = SQLITE_UTF8;
1175f4dd18eaSdrh   }else{
1176bcedbb27Sdrh     flags = MEM_Str;
1177bcedbb27Sdrh   }
1178bcedbb27Sdrh   if( nByte>iLimit ){
1179bcedbb27Sdrh     if( xDel && xDel!=SQLITE_TRANSIENT ){
1180bcedbb27Sdrh       if( xDel==SQLITE_DYNAMIC ){
1181bcedbb27Sdrh         sqlite3DbFree(pMem->db, (void*)z);
1182bcedbb27Sdrh       }else{
1183bcedbb27Sdrh         xDel((void*)z);
1184bcedbb27Sdrh       }
1185bcedbb27Sdrh     }
11864cb32b70Sdrh     sqlite3VdbeMemSetNull(pMem);
1187bcedbb27Sdrh     return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
11884f26d6c4Sdrh   }
1189d8123366Sdanielk1977 
1190a7a8e14bSdanielk1977   /* The following block sets the new values of Mem.z and Mem.xDel. It
1191a7a8e14bSdanielk1977   ** also sets a flag in local variable "flags" to indicate the memory
1192a7a8e14bSdanielk1977   ** management (one of MEM_Dyn or MEM_Static).
1193a7a8e14bSdanielk1977   */
1194a7a8e14bSdanielk1977   if( xDel==SQLITE_TRANSIENT ){
1195d622855eSdrh     i64 nAlloc = nByte;
1196a7a8e14bSdanielk1977     if( flags&MEM_Term ){
1197a7a8e14bSdanielk1977       nAlloc += (enc==SQLITE_UTF8?1:2);
11984f26d6c4Sdrh     }
1199722246e8Sdrh     testcase( nAlloc==0 );
1200722246e8Sdrh     testcase( nAlloc==31 );
1201722246e8Sdrh     testcase( nAlloc==32 );
120216d7e87cSdrh     if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
1203fad3039cSmistachkin       return SQLITE_NOMEM_BKPT;
1204bfd6cce5Sdanielk1977     }
1205a7a8e14bSdanielk1977     memcpy(pMem->z, z, nAlloc);
1206a7a8e14bSdanielk1977   }else{
1207a7a8e14bSdanielk1977     sqlite3VdbeMemRelease(pMem);
1208a7a8e14bSdanielk1977     pMem->z = (char *)z;
120916d7e87cSdrh     if( xDel==SQLITE_DYNAMIC ){
121016d7e87cSdrh       pMem->zMalloc = pMem->z;
121116d7e87cSdrh       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
121216d7e87cSdrh     }else{
1213a7a8e14bSdanielk1977       pMem->xDel = xDel;
1214a7a8e14bSdanielk1977       flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
12154f26d6c4Sdrh     }
121616d7e87cSdrh   }
1217a7a8e14bSdanielk1977 
1218d622855eSdrh   pMem->n = (int)(nByte & 0x7fffffff);
1219a7a8e14bSdanielk1977   pMem->flags = flags;
12209f3e6fadSdan   pMem->enc = enc;
12219f3e6fadSdan 
1222a7a8e14bSdanielk1977 #ifndef SQLITE_OMIT_UTF16
1223fb92e071Sdrh   if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
1224fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
12254f26d6c4Sdrh   }
1226a7a8e14bSdanielk1977 #endif
1227a7a8e14bSdanielk1977 
12289a65f2cdSdrh 
1229f4479501Sdrh   return SQLITE_OK;
12304f26d6c4Sdrh }
12314f26d6c4Sdrh 
12324f26d6c4Sdrh /*
1233d5788201Sdrh ** Move data out of a btree key or data field and into a Mem structure.
1234cb3cabd0Sdrh ** The data is payload from the entry that pCur is currently pointing
1235d5788201Sdrh ** to.  offset and amt determine what portion of the data or key to retrieve.
1236cb3cabd0Sdrh ** The result is written into the pMem element.
1237d5788201Sdrh **
12382a2a696cSdrh ** The pMem object must have been initialized.  This routine will use
12392a2a696cSdrh ** pMem->zMalloc to hold the content from the btree, if possible.  New
12402a2a696cSdrh ** pMem->zMalloc space will be allocated if necessary.  The calling routine
12412a2a696cSdrh ** is responsible for making sure that the pMem object is eventually
12422a2a696cSdrh ** destroyed.
1243d5788201Sdrh **
1244d5788201Sdrh ** If this routine fails for any reason (malloc returns NULL or unable
1245d5788201Sdrh ** to read from the disk) then the pMem is left in an inconsistent state.
1246d5788201Sdrh */
sqlite3VdbeMemFromBtree(BtCursor * pCur,u32 offset,u32 amt,Mem * pMem)12472a740060Sdrh int sqlite3VdbeMemFromBtree(
1248f1aabd6bSdrh   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
1249f1aabd6bSdrh   u32 offset,       /* Offset from the start of data to return bytes from. */
1250f1aabd6bSdrh   u32 amt,          /* Number of bytes to return. */
1251f1aabd6bSdrh   Mem *pMem         /* OUT: Return data in this Mem structure. */
1252f1aabd6bSdrh ){
1253f1aabd6bSdrh   int rc;
1254f1aabd6bSdrh   pMem->flags = MEM_Null;
125553d30dd3Sdrh   if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
125653d30dd3Sdrh     return SQLITE_CORRUPT_BKPT;
125753d30dd3Sdrh   }
125824ddadfaSdrh   if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
1259cb3cabd0Sdrh     rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
1260f1aabd6bSdrh     if( rc==SQLITE_OK ){
126124ddadfaSdrh       pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
126263d1632fSdrh       pMem->flags = MEM_Blob;
1263f1aabd6bSdrh       pMem->n = (int)amt;
1264f1aabd6bSdrh     }else{
1265f1aabd6bSdrh       sqlite3VdbeMemRelease(pMem);
1266f1aabd6bSdrh     }
1267f1aabd6bSdrh   }
1268f1aabd6bSdrh   return rc;
1269f1aabd6bSdrh }
sqlite3VdbeMemFromBtreeZeroOffset(BtCursor * pCur,u32 amt,Mem * pMem)12702a740060Sdrh int sqlite3VdbeMemFromBtreeZeroOffset(
1271d5788201Sdrh   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
1272501932caSdrh   u32 amt,          /* Number of bytes to return. */
1273d5788201Sdrh   Mem *pMem         /* OUT: Return data in this Mem structure. */
1274d5788201Sdrh ){
1275501932caSdrh   u32 available = 0;  /* Number of bytes available on the local btree page */
12764b0aa4cfSdanielk1977   int rc = SQLITE_OK; /* Return code */
1277d5788201Sdrh 
12785d1a872aSdrh   assert( sqlite3BtreeCursorIsValid(pCur) );
1279d3b74200Sdrh   assert( !VdbeMemDynamic(pMem) );
12805d1a872aSdrh 
12814b0aa4cfSdanielk1977   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
12824b0aa4cfSdanielk1977   ** that both the BtShared and database handle mutexes are held. */
12839d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pMem) );
12842a740060Sdrh   pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
12852a740060Sdrh   assert( pMem->z!=0 );
1286d5788201Sdrh 
12872a740060Sdrh   if( amt<=available ){
1288d5788201Sdrh     pMem->flags = MEM_Blob|MEM_Ephem;
12895f1d536bSdrh     pMem->n = (int)amt;
12908740a600Sdrh   }else{
12912a740060Sdrh     rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
12928740a600Sdrh   }
1293d5788201Sdrh 
1294a7a8e14bSdanielk1977   return rc;
1295d5788201Sdrh }
1296d5788201Sdrh 
12976c9f8e67Sdrh /*
12986c9f8e67Sdrh ** The pVal argument is known to be a value other than NULL.
12996c9f8e67Sdrh ** Convert it into a string with encoding enc and return a pointer
13006c9f8e67Sdrh ** to a zero-terminated version of that string.
13016c9f8e67Sdrh */
valueToText(sqlite3_value * pVal,u8 enc)13023b335fceSdrh static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
13036c9f8e67Sdrh   assert( pVal!=0 );
13046c9f8e67Sdrh   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
13056c9f8e67Sdrh   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
13069d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pVal) );
13076c9f8e67Sdrh   assert( (pVal->flags & (MEM_Null))==0 );
13086c9f8e67Sdrh   if( pVal->flags & (MEM_Blob|MEM_Str) ){
130934d04d64Sdrh     if( ExpandBlob(pVal) ) return 0;
13106c9f8e67Sdrh     pVal->flags |= MEM_Str;
13116c9f8e67Sdrh     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
13126c9f8e67Sdrh       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
13136c9f8e67Sdrh     }
13146c9f8e67Sdrh     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
13156c9f8e67Sdrh       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
13166c9f8e67Sdrh       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
13176c9f8e67Sdrh         return 0;
13186c9f8e67Sdrh       }
13196c9f8e67Sdrh     }
13206c9f8e67Sdrh     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
13216c9f8e67Sdrh   }else{
13226c9f8e67Sdrh     sqlite3VdbeMemStringify(pVal, enc, 0);
13236c9f8e67Sdrh     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
13246c9f8e67Sdrh   }
13256c9f8e67Sdrh   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
13266c9f8e67Sdrh               || pVal->db->mallocFailed );
13276c9f8e67Sdrh   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
1328df82afc0Sdrh     assert( sqlite3VdbeMemValidStrRep(pVal) );
13296c9f8e67Sdrh     return pVal->z;
13306c9f8e67Sdrh   }else{
13316c9f8e67Sdrh     return 0;
13326c9f8e67Sdrh   }
13336c9f8e67Sdrh }
13346c9f8e67Sdrh 
13354e6af134Sdanielk1977 /* This function is only available internally, it is not part of the
13364e6af134Sdanielk1977 ** external API. It works in a similar way to sqlite3_value_text(),
13374e6af134Sdanielk1977 ** except the data returned is in the encoding specified by the second
13384e6af134Sdanielk1977 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
13394e6af134Sdanielk1977 ** SQLITE_UTF8.
13407d9bd4e1Sdrh **
13417d9bd4e1Sdrh ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
13427d9bd4e1Sdrh ** If that is the case, then the result must be aligned on an even byte
13437d9bd4e1Sdrh ** boundary.
13444e6af134Sdanielk1977 */
sqlite3ValueText(sqlite3_value * pVal,u8 enc)1345b21c8cd4Sdrh const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
1346bfd6cce5Sdanielk1977   if( !pVal ) return 0;
1347b21c8cd4Sdrh   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
13487d9bd4e1Sdrh   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
13499d67afc4Sdrh   assert( !sqlite3VdbeMemIsRowSet(pVal) );
13506c9f8e67Sdrh   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
1351df82afc0Sdrh     assert( sqlite3VdbeMemValidStrRep(pVal) );
13526c9f8e67Sdrh     return pVal->z;
13536c9f8e67Sdrh   }
13544e6af134Sdanielk1977   if( pVal->flags&MEM_Null ){
13554e6af134Sdanielk1977     return 0;
13564e6af134Sdanielk1977   }
13576c9f8e67Sdrh   return valueToText(pVal, enc);
13584e6af134Sdanielk1977 }
13594e6af134Sdanielk1977 
13606a6124e2Sdrh /*
13616a6124e2Sdrh ** Create a new sqlite3_value object.
13626a6124e2Sdrh */
sqlite3ValueNew(sqlite3 * db)136317435752Sdrh sqlite3_value *sqlite3ValueNew(sqlite3 *db){
136426783a58Sdanielk1977   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
13654e6af134Sdanielk1977   if( p ){
13664e6af134Sdanielk1977     p->flags = MEM_Null;
1367b21c8cd4Sdrh     p->db = db;
13684e6af134Sdanielk1977   }
13694e6af134Sdanielk1977   return p;
13704e6af134Sdanielk1977 }
13714e6af134Sdanielk1977 
13726a6124e2Sdrh /*
1373af2583c8Sdan ** Context object passed by sqlite3Stat4ProbeSetValue() through to
1374af2583c8Sdan ** valueNew(). See comments above valueNew() for details.
1375aee18ef8Sdanielk1977 */
1376af2583c8Sdan struct ValueNewStat4Ctx {
1377af2583c8Sdan   Parse *pParse;
1378af2583c8Sdan   Index *pIdx;
1379af2583c8Sdan   UnpackedRecord **ppRec;
1380af2583c8Sdan   int iVal;
1381af2583c8Sdan };
1382af2583c8Sdan 
1383af2583c8Sdan /*
1384af2583c8Sdan ** Allocate and return a pointer to a new sqlite3_value object. If
1385af2583c8Sdan ** the second argument to this function is NULL, the object is allocated
1386af2583c8Sdan ** by calling sqlite3ValueNew().
1387af2583c8Sdan **
1388af2583c8Sdan ** Otherwise, if the second argument is non-zero, then this function is
1389af2583c8Sdan ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
1390af2583c8Sdan ** already been allocated, allocate the UnpackedRecord structure that
139196f4ad20Sdrh ** that function will return to its caller here. Then return a pointer to
1392af2583c8Sdan ** an sqlite3_value within the UnpackedRecord.a[] array.
1393af2583c8Sdan */
valueNew(sqlite3 * db,struct ValueNewStat4Ctx * p)1394af2583c8Sdan static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
1395175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
1396af2583c8Sdan   if( p ){
1397af2583c8Sdan     UnpackedRecord *pRec = p->ppRec[0];
1398af2583c8Sdan 
1399af2583c8Sdan     if( pRec==0 ){
1400af2583c8Sdan       Index *pIdx = p->pIdx;      /* Index being probed */
1401af2583c8Sdan       int nByte;                  /* Bytes of space to allocate */
1402af2583c8Sdan       int i;                      /* Counter variable */
1403d269461cSdrh       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
1404af2583c8Sdan 
1405b5f68b0cSdan       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
1406af2583c8Sdan       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
1407af2583c8Sdan       if( pRec ){
14082ec2fb22Sdrh         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
1409af2583c8Sdan         if( pRec->pKeyInfo ){
1410a485ad19Sdrh           assert( pRec->pKeyInfo->nAllField==nCol );
14112ec2fb22Sdrh           assert( pRec->pKeyInfo->enc==ENC(db) );
1412b5f68b0cSdan           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
1413af2583c8Sdan           for(i=0; i<nCol; i++){
1414af2583c8Sdan             pRec->aMem[i].flags = MEM_Null;
1415af2583c8Sdan             pRec->aMem[i].db = db;
1416af2583c8Sdan           }
1417af2583c8Sdan         }else{
1418dbd6a7dcSdrh           sqlite3DbFreeNN(db, pRec);
1419af2583c8Sdan           pRec = 0;
1420af2583c8Sdan         }
1421af2583c8Sdan       }
1422af2583c8Sdan       if( pRec==0 ) return 0;
1423af2583c8Sdan       p->ppRec[0] = pRec;
1424af2583c8Sdan     }
1425af2583c8Sdan 
1426af2583c8Sdan     pRec->nField = p->iVal+1;
1427af2583c8Sdan     return &pRec->aMem[p->iVal];
1428af2583c8Sdan   }
14294f991890Sdrh #else
14304f991890Sdrh   UNUSED_PARAMETER(p);
1431175b8f06Sdrh #endif /* defined(SQLITE_ENABLE_STAT4) */
1432af2583c8Sdan   return sqlite3ValueNew(db);
14337a419235Sdan }
14347a419235Sdan 
14356a6124e2Sdrh /*
143618bf8076Sdan ** The expression object indicated by the second argument is guaranteed
143718bf8076Sdan ** to be a scalar SQL function. If
143818bf8076Sdan **
143918bf8076Sdan **   * all function arguments are SQL literals,
1440e3a7307eSdrh **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
1441cdcc11d7Sdan **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
144218bf8076Sdan **
144318bf8076Sdan ** then this routine attempts to invoke the SQL function. Assuming no
144418bf8076Sdan ** error occurs, output parameter (*ppVal) is set to point to a value
144518bf8076Sdan ** object containing the result before returning SQLITE_OK.
144618bf8076Sdan **
144718bf8076Sdan ** Affinity aff is applied to the result of the function before returning.
144818bf8076Sdan ** If the result is a text value, the sqlite3_value object uses encoding
144918bf8076Sdan ** enc.
145018bf8076Sdan **
145118bf8076Sdan ** If the conditions above are not met, this function returns SQLITE_OK
145218bf8076Sdan ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
145318bf8076Sdan ** NULL and an SQLite error code returned.
145418bf8076Sdan */
1455175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
valueFromFunction(sqlite3 * db,const Expr * p,u8 enc,u8 aff,sqlite3_value ** ppVal,struct ValueNewStat4Ctx * pCtx)145618bf8076Sdan static int valueFromFunction(
145718bf8076Sdan   sqlite3 *db,                    /* The database connection */
14581580d50bSdrh   const Expr *p,                  /* The expression to evaluate */
145918bf8076Sdan   u8 enc,                         /* Encoding to use */
146018bf8076Sdan   u8 aff,                         /* Affinity to use */
146118bf8076Sdan   sqlite3_value **ppVal,          /* Write the new value here */
146218bf8076Sdan   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
146318bf8076Sdan ){
146418bf8076Sdan   sqlite3_context ctx;            /* Context object for function invocation */
146518bf8076Sdan   sqlite3_value **apVal = 0;      /* Function arguments */
146618bf8076Sdan   int nVal = 0;                   /* Size of apVal[] array */
146718bf8076Sdan   FuncDef *pFunc = 0;             /* Function definition */
146818bf8076Sdan   sqlite3_value *pVal = 0;        /* New value */
146918bf8076Sdan   int rc = SQLITE_OK;             /* Return code */
1470cdcc11d7Sdan   ExprList *pList = 0;            /* Function arguments */
147118bf8076Sdan   int i;                          /* Iterator variable */
147218bf8076Sdan 
147396f4ad20Sdrh   assert( pCtx!=0 );
147496f4ad20Sdrh   assert( (p->flags & EP_TokenOnly)==0 );
1475a4eeccdfSdrh   assert( ExprUseXList(p) );
147618bf8076Sdan   pList = p->x.pList;
147718bf8076Sdan   if( pList ) nVal = pList->nExpr;
1478f9751074Sdrh   assert( !ExprHasProperty(p, EP_IntValue) );
147980738d9cSdrh   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
148018bf8076Sdan   assert( pFunc );
1481e3a7307eSdrh   if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
148218bf8076Sdan    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
148318bf8076Sdan   ){
148418bf8076Sdan     return SQLITE_OK;
148518bf8076Sdan   }
148618bf8076Sdan 
148718bf8076Sdan   if( pList ){
148818bf8076Sdan     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
148918bf8076Sdan     if( apVal==0 ){
1490fad3039cSmistachkin       rc = SQLITE_NOMEM_BKPT;
149118bf8076Sdan       goto value_from_function_out;
149218bf8076Sdan     }
149318bf8076Sdan     for(i=0; i<nVal; i++){
149418bf8076Sdan       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
1495a9e03b1bSdrh       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
149618bf8076Sdan     }
149718bf8076Sdan   }
149818bf8076Sdan 
149918bf8076Sdan   pVal = valueNew(db, pCtx);
150018bf8076Sdan   if( pVal==0 ){
1501fad3039cSmistachkin     rc = SQLITE_NOMEM_BKPT;
150218bf8076Sdan     goto value_from_function_out;
150318bf8076Sdan   }
150418bf8076Sdan 
1505a36fedbdSdrh   testcase( pCtx->pParse->rc==SQLITE_ERROR );
1506a36fedbdSdrh   testcase( pCtx->pParse->rc==SQLITE_OK );
150718bf8076Sdan   memset(&ctx, 0, sizeof(ctx));
150818bf8076Sdan   ctx.pOut = pVal;
150918bf8076Sdan   ctx.pFunc = pFunc;
1510659fdb4dSdrh   ctx.enc = ENC(db);
15112d80151fSdrh   pFunc->xSFunc(&ctx, nVal, apVal);
151218bf8076Sdan   if( ctx.isError ){
151318bf8076Sdan     rc = ctx.isError;
151481367381Sdrh     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
151518bf8076Sdan   }else{
151618bf8076Sdan     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
151796f4ad20Sdrh     assert( rc==SQLITE_OK );
151818bf8076Sdan     rc = sqlite3VdbeChangeEncoding(pVal, enc);
151918bf8076Sdan     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
152018bf8076Sdan       rc = SQLITE_TOOBIG;
15213df30592Sdan       pCtx->pParse->nErr++;
152218bf8076Sdan     }
152318bf8076Sdan   }
15243df30592Sdan   pCtx->pParse->rc = rc;
152518bf8076Sdan 
152618bf8076Sdan  value_from_function_out:
152718bf8076Sdan   if( rc!=SQLITE_OK ){
152818bf8076Sdan     pVal = 0;
152918bf8076Sdan   }
1530a9e03b1bSdrh   if( apVal ){
153118bf8076Sdan     for(i=0; i<nVal; i++){
153218bf8076Sdan       sqlite3ValueFree(apVal[i]);
153318bf8076Sdan     }
1534dbd6a7dcSdrh     sqlite3DbFreeNN(db, apVal);
1535a9e03b1bSdrh   }
153618bf8076Sdan 
153718bf8076Sdan   *ppVal = pVal;
153818bf8076Sdan   return rc;
153918bf8076Sdan }
154018bf8076Sdan #else
154118bf8076Sdan # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
1542175b8f06Sdrh #endif /* defined(SQLITE_ENABLE_STAT4) */
154318bf8076Sdan 
154418bf8076Sdan /*
1545af2583c8Sdan ** Extract a value from the supplied expression in the manner described
1546af2583c8Sdan ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
1547af2583c8Sdan ** using valueNew().
1548af2583c8Sdan **
1549af2583c8Sdan ** If pCtx is NULL and an error occurs after the sqlite3_value object
1550af2583c8Sdan ** has been allocated, it is freed before returning. Or, if pCtx is not
1551af2583c8Sdan ** NULL, it is assumed that the caller will free any allocated object
1552af2583c8Sdan ** in all cases.
1553aee18ef8Sdanielk1977 */
valueFromExpr(sqlite3 * db,const Expr * pExpr,u8 enc,u8 affinity,sqlite3_value ** ppVal,struct ValueNewStat4Ctx * pCtx)1554a7f4bf3fSdrh static int valueFromExpr(
1555b21c8cd4Sdrh   sqlite3 *db,                    /* The database connection */
15561580d50bSdrh   const Expr *pExpr,              /* The expression to evaluate */
155717435752Sdrh   u8 enc,                         /* Encoding to use */
155817435752Sdrh   u8 affinity,                    /* Affinity to use */
155987cd9321Sdan   sqlite3_value **ppVal,          /* Write the new value here */
1560af2583c8Sdan   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
1561aee18ef8Sdanielk1977 ){
1562aee18ef8Sdanielk1977   int op;
1563aee18ef8Sdanielk1977   char *zVal = 0;
1564aee18ef8Sdanielk1977   sqlite3_value *pVal = 0;
15659351862bSdrh   int negInt = 1;
15669351862bSdrh   const char *zNeg = "";
15670e1f0029Sdrh   int rc = SQLITE_OK;
1568aee18ef8Sdanielk1977 
156942735c7dSdrh   assert( pExpr!=0 );
157094fa9c41Sdrh   while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
15717ac2d48eSdan   if( op==TK_REGISTER ) op = pExpr->op2;
1572aee18ef8Sdanielk1977 
157396f4ad20Sdrh   /* Compressed expressions only appear when parsing the DEFAULT clause
157496f4ad20Sdrh   ** on a table column definition, and hence only when pCtx==0.  This
157596f4ad20Sdrh   ** check ensures that an EP_TokenOnly expression is never passed down
157696f4ad20Sdrh   ** into valueFromFunction(). */
157796f4ad20Sdrh   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
157896f4ad20Sdrh 
15794169e430Sdrh   if( op==TK_CAST ){
1580f9751074Sdrh     u8 aff;
1581f9751074Sdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
1582f9751074Sdrh     aff = sqlite3AffinityType(pExpr->u.zToken,0);
15834169e430Sdrh     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
1584ec3e4f75Sdrh     testcase( rc!=SQLITE_OK );
1585ec3e4f75Sdrh     if( *ppVal ){
1586d580bea7Sdrh       sqlite3VdbeMemCast(*ppVal, aff, enc);
1587d580bea7Sdrh       sqlite3ValueApplyAffinity(*ppVal, affinity, enc);
15884169e430Sdrh     }
15894169e430Sdrh     return rc;
15904169e430Sdrh   }
15914169e430Sdrh 
15929351862bSdrh   /* Handle negative integers in a single step.  This is needed in the
15939351862bSdrh   ** case when the value is -9223372036854775808.
15949351862bSdrh   */
15959351862bSdrh   if( op==TK_UMINUS
15969351862bSdrh    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
15979351862bSdrh     pExpr = pExpr->pLeft;
15989351862bSdrh     op = pExpr->op;
15999351862bSdrh     negInt = -1;
16009351862bSdrh     zNeg = "-";
16019351862bSdrh   }
16029351862bSdrh 
1603aee18ef8Sdanielk1977   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
1604af2583c8Sdan     pVal = valueNew(db, pCtx);
160533e619fcSdrh     if( pVal==0 ) goto no_mem;
160633e619fcSdrh     if( ExprHasProperty(pExpr, EP_IntValue) ){
16079351862bSdrh       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
160833e619fcSdrh     }else{
16099351862bSdrh       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
161033e619fcSdrh       if( zVal==0 ) goto no_mem;
1611633e6d57Sdrh       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
161233e619fcSdrh     }
161305883a34Sdrh     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
1614e3b9bfe6Sdrh       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
1615aee18ef8Sdanielk1977     }else{
1616e3b9bfe6Sdrh       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
1617e3b9bfe6Sdrh     }
16183242c69cSdrh     assert( (pVal->flags & MEM_IntReal)==0 );
16193242c69cSdrh     if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
16203242c69cSdrh       testcase( pVal->flags & MEM_Int );
16213242c69cSdrh       testcase( pVal->flags & MEM_Real );
16223242c69cSdrh       pVal->flags &= ~MEM_Str;
16233242c69cSdrh     }
1624e3b9bfe6Sdrh     if( enc!=SQLITE_UTF8 ){
16250e1f0029Sdrh       rc = sqlite3VdbeChangeEncoding(pVal, enc);
1626aee18ef8Sdanielk1977     }
1627aee18ef8Sdanielk1977   }else if( op==TK_UMINUS ) {
16289351862bSdrh     /* This branch happens for multiple negative signs.  Ex: -(-5) */
16296e3bccd5Sdrh     if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
1630ad45ed74Sdan      && pVal!=0
1631ad45ed74Sdan     ){
16329351862bSdrh       sqlite3VdbeMemNumerify(pVal);
163374eaba4dSdrh       if( pVal->flags & MEM_Real ){
163474eaba4dSdrh         pVal->u.r = -pVal->u.r;
163574eaba4dSdrh       }else if( pVal->u.i==SMALLEST_INT64 ){
1636ef9f719dSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
163774eaba4dSdrh         pVal->u.r = -(double)SMALLEST_INT64;
1638ef9f719dSdrh #else
1639ef9f719dSdrh         pVal->u.r = LARGEST_INT64;
1640ef9f719dSdrh #endif
164174eaba4dSdrh         MemSetTypeFlag(pVal, MEM_Real);
1642d50ffc41Sdrh       }else{
1643d50ffc41Sdrh         pVal->u.i = -pVal->u.i;
1644d50ffc41Sdrh       }
16459351862bSdrh       sqlite3ValueApplyAffinity(pVal, affinity, enc);
1646aee18ef8Sdanielk1977     }
16479b3eb0adSdrh   }else if( op==TK_NULL ){
1648af2583c8Sdan     pVal = valueNew(db, pCtx);
1649b1aa0ab6Sdrh     if( pVal==0 ) goto no_mem;
16507a3e50dcSmistachkin     sqlite3VdbeMemSetNull(pVal);
1651aee18ef8Sdanielk1977   }
1652aee18ef8Sdanielk1977 #ifndef SQLITE_OMIT_BLOB_LITERAL
1653aee18ef8Sdanielk1977   else if( op==TK_BLOB ){
1654aee18ef8Sdanielk1977     int nVal;
1655f9751074Sdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
165633e619fcSdrh     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
165733e619fcSdrh     assert( pExpr->u.zToken[1]=='\'' );
1658af2583c8Sdan     pVal = valueNew(db, pCtx);
1659f150c9deSdanielk1977     if( !pVal ) goto no_mem;
166033e619fcSdrh     zVal = &pExpr->u.zToken[2];
1661b7916a78Sdrh     nVal = sqlite3Strlen30(zVal)-1;
1662b7916a78Sdrh     assert( zVal[nVal]=='\'' );
1663ca48c90fSdrh     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
1664633e6d57Sdrh                          0, SQLITE_DYNAMIC);
1665aee18ef8Sdanielk1977   }
1666aee18ef8Sdanielk1977 #endif
1667175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
166896f4ad20Sdrh   else if( op==TK_FUNCTION && pCtx!=0 ){
166918bf8076Sdan     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
167018bf8076Sdan   }
16718cdcd87cSdrh #endif
16723bc43155Sdrh   else if( op==TK_TRUEFALSE ){
1673f9751074Sdrh     assert( !ExprHasProperty(pExpr, EP_IntValue) );
16743bc43155Sdrh     pVal = valueNew(db, pCtx);
1675c2ea77e5Sdan     if( pVal ){
16763bc43155Sdrh       pVal->flags = MEM_Int;
16773bc43155Sdrh       pVal->u.i = pExpr->u.zToken[4]==0;
16783bc43155Sdrh     }
1679c2ea77e5Sdan   }
168018bf8076Sdan 
1681aee18ef8Sdanielk1977   *ppVal = pVal;
16820e1f0029Sdrh   return rc;
1683aee18ef8Sdanielk1977 
1684aee18ef8Sdanielk1977 no_mem:
1685175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
16861ff855b2Sdrh   if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
168784a6c85cSdrh #endif
16884a642b60Sdrh     sqlite3OomFault(db);
1689633e6d57Sdrh   sqlite3DbFree(db, zVal);
1690af2583c8Sdan   assert( *ppVal==0 );
1691175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
1692af2583c8Sdan   if( pCtx==0 ) sqlite3ValueFree(pVal);
16931435a9a1Sdrh #else
16941435a9a1Sdrh   assert( pCtx==0 ); sqlite3ValueFree(pVal);
16951435a9a1Sdrh #endif
1696fad3039cSmistachkin   return SQLITE_NOMEM_BKPT;
1697aee18ef8Sdanielk1977 }
1698aee18ef8Sdanielk1977 
1699aee18ef8Sdanielk1977 /*
170087cd9321Sdan ** Create a new sqlite3_value object, containing the value of pExpr.
170187cd9321Sdan **
170287cd9321Sdan ** This only works for very simple expressions that consist of one constant
170387cd9321Sdan ** token (i.e. "5", "5.1", "'a string'"). If the expression can
170487cd9321Sdan ** be converted directly into a value, then the value is allocated and
170587cd9321Sdan ** a pointer written to *ppVal. The caller is responsible for deallocating
170687cd9321Sdan ** the value by passing it to sqlite3ValueFree() later on. If the expression
170787cd9321Sdan ** cannot be converted to a value, then *ppVal is set to NULL.
170887cd9321Sdan */
sqlite3ValueFromExpr(sqlite3 * db,const Expr * pExpr,u8 enc,u8 affinity,sqlite3_value ** ppVal)170987cd9321Sdan int sqlite3ValueFromExpr(
171087cd9321Sdan   sqlite3 *db,              /* The database connection */
17111580d50bSdrh   const Expr *pExpr,        /* The expression to evaluate */
171287cd9321Sdan   u8 enc,                   /* Encoding to use */
171387cd9321Sdan   u8 affinity,              /* Affinity to use */
171487cd9321Sdan   sqlite3_value **ppVal     /* Write the new value here */
171587cd9321Sdan ){
171642735c7dSdrh   return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
171787cd9321Sdan }
171887cd9321Sdan 
1719175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
17200288b21eSdrh /*
17210288b21eSdrh ** Attempt to extract a value from pExpr and use it to construct *ppVal.
17220288b21eSdrh **
17230288b21eSdrh ** If pAlloc is not NULL, then an UnpackedRecord object is created for
17240288b21eSdrh ** pAlloc if one does not exist and the new value is added to the
17250288b21eSdrh ** UnpackedRecord object.
17260288b21eSdrh **
17270288b21eSdrh ** A value is extracted in the following cases:
17280288b21eSdrh **
17290288b21eSdrh **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
17300288b21eSdrh **
17310288b21eSdrh **  * The expression is a bound variable, and this is a reprepare, or
17320288b21eSdrh **
17330288b21eSdrh **  * The expression is a literal value.
17340288b21eSdrh **
17350288b21eSdrh ** On success, *ppVal is made to point to the extracted value.  The caller
17360288b21eSdrh ** is responsible for ensuring that the value is eventually freed.
17370288b21eSdrh */
stat4ValueFromExpr(Parse * pParse,Expr * pExpr,u8 affinity,struct ValueNewStat4Ctx * pAlloc,sqlite3_value ** ppVal)1738b0b8290eSdan static int stat4ValueFromExpr(
1739b0b8290eSdan   Parse *pParse,                  /* Parse context */
1740b0b8290eSdan   Expr *pExpr,                    /* The expression to extract a value from */
1741b0b8290eSdan   u8 affinity,                    /* Affinity to use */
17420288b21eSdrh   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
1743b0b8290eSdan   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
1744b0b8290eSdan ){
1745b0b8290eSdan   int rc = SQLITE_OK;
1746b0b8290eSdan   sqlite3_value *pVal = 0;
1747b0b8290eSdan   sqlite3 *db = pParse->db;
1748b0b8290eSdan 
1749b0b8290eSdan   /* Skip over any TK_COLLATE nodes */
1750b0b8290eSdan   pExpr = sqlite3ExprSkipCollate(pExpr);
1751b0b8290eSdan 
17527df7475dSdrh   assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
1753b0b8290eSdan   if( !pExpr ){
1754b0b8290eSdan     pVal = valueNew(db, pAlloc);
1755b0b8290eSdan     if( pVal ){
1756b0b8290eSdan       sqlite3VdbeMemSetNull((Mem*)pVal);
1757b0b8290eSdan     }
17587df7475dSdrh   }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
1759b0b8290eSdan     Vdbe *v;
1760b0b8290eSdan     int iBindVar = pExpr->iColumn;
1761b0b8290eSdan     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
17627df7475dSdrh     if( (v = pParse->pReprepare)!=0 ){
1763b0b8290eSdan       pVal = valueNew(db, pAlloc);
1764b0b8290eSdan       if( pVal ){
1765b0b8290eSdan         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
1766b0b8290eSdan         sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
1767b0b8290eSdan         pVal->db = pParse->db;
1768b0b8290eSdan       }
1769b0b8290eSdan     }
1770b0b8290eSdan   }else{
1771b0b8290eSdan     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
1772b0b8290eSdan   }
1773b0b8290eSdan 
1774b0b8290eSdan   assert( pVal==0 || pVal->db==db );
1775b0b8290eSdan   *ppVal = pVal;
1776b0b8290eSdan   return rc;
1777b0b8290eSdan }
1778b0b8290eSdan 
177987cd9321Sdan /*
178087cd9321Sdan ** This function is used to allocate and populate UnpackedRecord
178187cd9321Sdan ** structures intended to be compared against sample index keys stored
178287cd9321Sdan ** in the sqlite_stat4 table.
178387cd9321Sdan **
1784d66e5794Sdan ** A single call to this function populates zero or more fields of the
1785d66e5794Sdan ** record starting with field iVal (fields are numbered from left to
1786d66e5794Sdan ** right starting with 0). A single field is populated if:
178787cd9321Sdan **
178887cd9321Sdan **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
178987cd9321Sdan **
179087cd9321Sdan **  * The expression is a bound variable, and this is a reprepare, or
179187cd9321Sdan **
179287cd9321Sdan **  * The sqlite3ValueFromExpr() function is able to extract a value
179387cd9321Sdan **    from the expression (i.e. the expression is a literal value).
179487cd9321Sdan **
1795d66e5794Sdan ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
1796d66e5794Sdan ** vector components that match either of the two latter criteria listed
1797d66e5794Sdan ** above.
1798d66e5794Sdan **
1799d66e5794Sdan ** Before any value is appended to the record, the affinity of the
1800d66e5794Sdan ** corresponding column within index pIdx is applied to it. Before
1801d66e5794Sdan ** this function returns, output parameter *pnExtract is set to the
1802d66e5794Sdan ** number of values appended to the record.
180387cd9321Sdan **
180487cd9321Sdan ** When this function is called, *ppRec must either point to an object
180587cd9321Sdan ** allocated by an earlier call to this function, or must be NULL. If it
180687cd9321Sdan ** is NULL and a value can be successfully extracted, a new UnpackedRecord
180787cd9321Sdan ** is allocated (and *ppRec set to point to it) before returning.
180887cd9321Sdan **
180987cd9321Sdan ** Unless an error is encountered, SQLITE_OK is returned. It is not an
181087cd9321Sdan ** error if a value cannot be extracted from pExpr. If an error does
181187cd9321Sdan ** occur, an SQLite error code is returned.
181287cd9321Sdan */
sqlite3Stat4ProbeSetValue(Parse * pParse,Index * pIdx,UnpackedRecord ** ppRec,Expr * pExpr,int nElem,int iVal,int * pnExtract)18137a419235Sdan int sqlite3Stat4ProbeSetValue(
18147a419235Sdan   Parse *pParse,                  /* Parse context */
181587cd9321Sdan   Index *pIdx,                    /* Index being probed */
181687cd9321Sdan   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
18177a419235Sdan   Expr *pExpr,                    /* The expression to extract a value from */
1818d66e5794Sdan   int nElem,                      /* Maximum number of values to append */
18197a419235Sdan   int iVal,                       /* Array element to populate */
1820d66e5794Sdan   int *pnExtract                  /* OUT: Values appended to the record */
18217a419235Sdan ){
1822d66e5794Sdan   int rc = SQLITE_OK;
1823d66e5794Sdan   int nExtract = 0;
1824d66e5794Sdan 
1825d66e5794Sdan   if( pExpr==0 || pExpr->op!=TK_SELECT ){
1826d66e5794Sdan     int i;
182787cd9321Sdan     struct ValueNewStat4Ctx alloc;
1828b0b8290eSdan 
182987cd9321Sdan     alloc.pParse = pParse;
183087cd9321Sdan     alloc.pIdx = pIdx;
183187cd9321Sdan     alloc.ppRec = ppRec;
18327a419235Sdan 
1833d66e5794Sdan     for(i=0; i<nElem; i++){
1834d66e5794Sdan       sqlite3_value *pVal = 0;
1835fc7f27b9Sdrh       Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
1836d66e5794Sdan       u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
1837d66e5794Sdan       alloc.iVal = iVal+i;
1838d66e5794Sdan       rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
1839d66e5794Sdan       if( !pVal ) break;
1840d66e5794Sdan       nExtract++;
1841d66e5794Sdan     }
1842d66e5794Sdan   }
1843d66e5794Sdan 
1844d66e5794Sdan   *pnExtract = nExtract;
1845b0b8290eSdan   return rc;
1846b0b8290eSdan }
184787cd9321Sdan 
1848b0b8290eSdan /*
1849b0b8290eSdan ** Attempt to extract a value from expression pExpr using the methods
1850b0b8290eSdan ** as described for sqlite3Stat4ProbeSetValue() above.
1851b0b8290eSdan **
1852b0b8290eSdan ** If successful, set *ppVal to point to a new value object and return
1853b0b8290eSdan ** SQLITE_OK. If no value can be extracted, but no other error occurs
1854b0b8290eSdan ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
1855b0b8290eSdan ** does occur, return an SQLite error code. The final value of *ppVal
1856b0b8290eSdan ** is undefined in this case.
1857b0b8290eSdan */
sqlite3Stat4ValueFromExpr(Parse * pParse,Expr * pExpr,u8 affinity,sqlite3_value ** ppVal)1858b0b8290eSdan int sqlite3Stat4ValueFromExpr(
1859b0b8290eSdan   Parse *pParse,                  /* Parse context */
1860b0b8290eSdan   Expr *pExpr,                    /* The expression to extract a value from */
1861b0b8290eSdan   u8 affinity,                    /* Affinity to use */
1862b0b8290eSdan   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
1863b0b8290eSdan ){
1864b0b8290eSdan   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
1865b0b8290eSdan }
1866b0b8290eSdan 
18670288b21eSdrh /*
18680288b21eSdrh ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
18690288b21eSdrh ** the column value into *ppVal.  If *ppVal is initially NULL then a new
18700288b21eSdrh ** sqlite3_value object is allocated.
18710288b21eSdrh **
18720288b21eSdrh ** If *ppVal is initially NULL then the caller is responsible for
18730288b21eSdrh ** ensuring that the value written into *ppVal is eventually freed.
18740288b21eSdrh */
sqlite3Stat4Column(sqlite3 * db,const void * pRec,int nRec,int iCol,sqlite3_value ** ppVal)1875b0b8290eSdan int sqlite3Stat4Column(
1876b0b8290eSdan   sqlite3 *db,                    /* Database handle */
1877b0b8290eSdan   const void *pRec,               /* Pointer to buffer containing record */
1878b0b8290eSdan   int nRec,                       /* Size of buffer pRec in bytes */
1879b0b8290eSdan   int iCol,                       /* Column to extract */
1880b0b8290eSdan   sqlite3_value **ppVal           /* OUT: Extracted value */
1881b0b8290eSdan ){
1882ed5e7722Smistachkin   u32 t = 0;                      /* a column type code */
18830288b21eSdrh   int nHdr;                       /* Size of the header in the record */
18840288b21eSdrh   int iHdr;                       /* Next unread header byte */
18850288b21eSdrh   int iField;                     /* Next unread data byte */
1886ed5e7722Smistachkin   int szField = 0;                /* Size of the current data field */
18870288b21eSdrh   int i;                          /* Column index */
18880288b21eSdrh   u8 *a = (u8*)pRec;              /* Typecast byte array */
18890288b21eSdrh   Mem *pMem = *ppVal;             /* Write result into this Mem object */
1890b0b8290eSdan 
18910288b21eSdrh   assert( iCol>0 );
1892b0b8290eSdan   iHdr = getVarint32(a, nHdr);
18930288b21eSdrh   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
1894b0b8290eSdan   iField = nHdr;
18950288b21eSdrh   for(i=0; i<=iCol; i++){
18964e42ba4aSdan     iHdr += getVarint32(&a[iHdr], t);
18970288b21eSdrh     testcase( iHdr==nHdr );
18980288b21eSdrh     testcase( iHdr==nHdr+1 );
18990288b21eSdrh     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
19000288b21eSdrh     szField = sqlite3VdbeSerialTypeLen(t);
19010288b21eSdrh     iField += szField;
1902b0b8290eSdan   }
19030288b21eSdrh   testcase( iField==nRec );
19040288b21eSdrh   testcase( iField==nRec+1 );
19050288b21eSdrh   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
19060288b21eSdrh   if( pMem==0 ){
19070288b21eSdrh     pMem = *ppVal = sqlite3ValueNew(db);
1908fad3039cSmistachkin     if( pMem==0 ) return SQLITE_NOMEM_BKPT;
19090288b21eSdrh   }
19100288b21eSdrh   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
1911fa887454Sdan   pMem->enc = ENC(db);
19120288b21eSdrh   return SQLITE_OK;
19137a419235Sdan }
19147a419235Sdan 
191587cd9321Sdan /*
191687cd9321Sdan ** Unless it is NULL, the argument must be an UnpackedRecord object returned
191787cd9321Sdan ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
191887cd9321Sdan ** the object.
191987cd9321Sdan */
sqlite3Stat4ProbeFree(UnpackedRecord * pRec)19207a419235Sdan void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
19217a419235Sdan   if( pRec ){
19227a419235Sdan     int i;
1923a485ad19Sdrh     int nCol = pRec->pKeyInfo->nAllField;
19247a419235Sdan     Mem *aMem = pRec->aMem;
19257a419235Sdan     sqlite3 *db = aMem[0].db;
1926dd6e1f19Sdan     for(i=0; i<nCol; i++){
1927cef25843Sdrh       sqlite3VdbeMemRelease(&aMem[i]);
19287a419235Sdan     }
19292ec2fb22Sdrh     sqlite3KeyInfoUnref(pRec->pKeyInfo);
1930dbd6a7dcSdrh     sqlite3DbFreeNN(db, pRec);
19317a419235Sdan   }
19327a419235Sdan }
19337a419235Sdan #endif /* ifdef SQLITE_ENABLE_STAT4 */
19347a419235Sdan 
19354f26d6c4Sdrh /*
19364f26d6c4Sdrh ** Change the string value of an sqlite3_value object
19374f26d6c4Sdrh */
sqlite3ValueSetStr(sqlite3_value * v,int n,const void * z,u8 enc,void (* xDel)(void *))19384f26d6c4Sdrh void sqlite3ValueSetStr(
193917435752Sdrh   sqlite3_value *v,     /* Value to be set */
194017435752Sdrh   int n,                /* Length of string z */
194117435752Sdrh   const void *z,        /* Text of the new string */
194217435752Sdrh   u8 enc,               /* Encoding to use */
194317435752Sdrh   void (*xDel)(void*)   /* Destructor for the string */
19444f26d6c4Sdrh ){
1945b21c8cd4Sdrh   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
19464f26d6c4Sdrh }
19474f26d6c4Sdrh 
19484f26d6c4Sdrh /*
19494f26d6c4Sdrh ** Free an sqlite3_value object
19504f26d6c4Sdrh */
sqlite3ValueFree(sqlite3_value * v)19514f26d6c4Sdrh void sqlite3ValueFree(sqlite3_value *v){
19524f26d6c4Sdrh   if( !v ) return;
1953a7a8e14bSdanielk1977   sqlite3VdbeMemRelease((Mem *)v);
1954dbd6a7dcSdrh   sqlite3DbFreeNN(((Mem*)v)->db, v);
19554f26d6c4Sdrh }
19564f26d6c4Sdrh 
19574f26d6c4Sdrh /*
1958591909c3Sdrh ** The sqlite3ValueBytes() routine returns the number of bytes in the
1959591909c3Sdrh ** sqlite3_value object assuming that it uses the encoding "enc".
1960591909c3Sdrh ** The valueBytes() routine is a helper function.
19614f26d6c4Sdrh */
valueBytes(sqlite3_value * pVal,u8 enc)1962591909c3Sdrh static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
1963591909c3Sdrh   return valueToText(pVal, enc)!=0 ? pVal->n : 0;
1964591909c3Sdrh }
sqlite3ValueBytes(sqlite3_value * pVal,u8 enc)1965b21c8cd4Sdrh int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
19664f26d6c4Sdrh   Mem *p = (Mem*)pVal;
1967591909c3Sdrh   assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
1968591909c3Sdrh   if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
1969591909c3Sdrh     return p->n;
1970591909c3Sdrh   }
1971*47996ea7Sdrh   if( (p->flags & MEM_Str)!=0 && enc!=SQLITE_UTF8 && pVal->enc!=SQLITE_UTF8 ){
1972*47996ea7Sdrh     return p->n;
1973*47996ea7Sdrh   }
1974591909c3Sdrh   if( (p->flags & MEM_Blob)!=0 ){
1975b026e05eSdrh     if( p->flags & MEM_Zero ){
19768df32841Sdrh       return p->n + p->u.nZero;
1977b026e05eSdrh     }else{
19784f26d6c4Sdrh       return p->n;
19794f26d6c4Sdrh     }
1980b026e05eSdrh   }
1981591909c3Sdrh   if( p->flags & MEM_Null ) return 0;
1982591909c3Sdrh   return valueBytes(pVal, enc);
19834f26d6c4Sdrh }
1984