xref: /sqlite-3.40.0/src/vdbeblob.c (revision a3fdec71)
1 /*
2 ** 2007 May 1
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 **
13 ** This file contains code used to implement incremental BLOB I/O.
14 */
15 
16 #include "sqliteInt.h"
17 #include "vdbeInt.h"
18 
19 #ifndef SQLITE_OMIT_INCRBLOB
20 
21 /*
22 ** Valid sqlite3_blob* handles point to Incrblob structures.
23 */
24 typedef struct Incrblob Incrblob;
25 struct Incrblob {
26   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
27   int nByte;              /* Size of open blob, in bytes */
28   int iOffset;            /* Byte offset of blob in cursor data */
29   int iCol;               /* Table column this handle is open on */
30   BtCursor *pCsr;         /* Cursor pointing at blob row */
31   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
32   sqlite3 *db;            /* The associated database */
33 };
34 
35 
36 /*
37 ** This function is used by both blob_open() and blob_reopen(). It seeks
38 ** the b-tree cursor associated with blob handle p to point to row iRow.
39 ** If successful, SQLITE_OK is returned and subsequent calls to
40 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
41 **
42 ** If an error occurs, or if the specified row does not exist or does not
43 ** contain a value of type TEXT or BLOB in the column nominated when the
44 ** blob handle was opened, then an error code is returned and *pzErr may
45 ** be set to point to a buffer containing an error message. It is the
46 ** responsibility of the caller to free the error message buffer using
47 ** sqlite3DbFree().
48 **
49 ** If an error does occur, then the b-tree cursor is closed. All subsequent
50 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
51 ** immediately return SQLITE_ABORT.
52 */
53 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
54   int rc;                         /* Error code */
55   char *zErr = 0;                 /* Error message */
56   Vdbe *v = (Vdbe *)p->pStmt;
57 
58   /* Set the value of the SQL statements only variable to integer iRow.
59   ** This is done directly instead of using sqlite3_bind_int64() to avoid
60   ** triggering asserts related to mutexes.
61   */
62   assert( v->aVar[0].flags&MEM_Int );
63   v->aVar[0].u.i = iRow;
64 
65   rc = sqlite3_step(p->pStmt);
66   if( rc==SQLITE_ROW ){
67     VdbeCursor *pC = v->apCsr[0];
68     u32 type = pC->aType[p->iCol];
69     if( type<12 ){
70       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71           type==0?"null": type==7?"real": "integer"
72       );
73       rc = SQLITE_ERROR;
74       sqlite3_finalize(p->pStmt);
75       p->pStmt = 0;
76     }else{
77       p->iOffset = pC->aType[p->iCol + pC->nField];
78       p->nByte = sqlite3VdbeSerialTypeLen(type);
79       p->pCsr =  pC->pCursor;
80       sqlite3BtreeEnterCursor(p->pCsr);
81       sqlite3BtreeCacheOverflow(p->pCsr);
82       sqlite3BtreeLeaveCursor(p->pCsr);
83     }
84   }
85 
86   if( rc==SQLITE_ROW ){
87     rc = SQLITE_OK;
88   }else if( p->pStmt ){
89     rc = sqlite3_finalize(p->pStmt);
90     p->pStmt = 0;
91     if( rc==SQLITE_OK ){
92       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
93       rc = SQLITE_ERROR;
94     }else{
95       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
96     }
97   }
98 
99   assert( rc!=SQLITE_OK || zErr==0 );
100   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
101 
102   *pzErr = zErr;
103   return rc;
104 }
105 
106 /*
107 ** Open a blob handle.
108 */
109 int sqlite3_blob_open(
110   sqlite3* db,            /* The database connection */
111   const char *zDb,        /* The attached database containing the blob */
112   const char *zTable,     /* The table containing the blob */
113   const char *zColumn,    /* The column containing the blob */
114   sqlite_int64 iRow,      /* The row containing the glob */
115   int flags,              /* True -> read/write access, false -> read-only */
116   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
117 ){
118   int nAttempt = 0;
119   int iCol;               /* Index of zColumn in row-record */
120 
121   /* This VDBE program seeks a btree cursor to the identified
122   ** db/table/row entry. The reason for using a vdbe program instead
123   ** of writing code to use the b-tree layer directly is that the
124   ** vdbe program will take advantage of the various transaction,
125   ** locking and error handling infrastructure built into the vdbe.
126   **
127   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
128   ** Code external to the Vdbe then "borrows" the b-tree cursor and
129   ** uses it to implement the blob_read(), blob_write() and
130   ** blob_bytes() functions.
131   **
132   ** The sqlite3_blob_close() function finalizes the vdbe program,
133   ** which closes the b-tree cursor and (possibly) commits the
134   ** transaction.
135   */
136   static const VdbeOpList openBlob[] = {
137     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
138     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
139     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
140 
141     /* One of the following two instructions is replaced by an OP_Noop. */
142     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
143     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
144 
145     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
146     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
147     {OP_Column, 0, 0, 1},          /* 7  */
148     {OP_ResultRow, 1, 0, 0},       /* 8  */
149     {OP_Goto, 0, 5, 0},            /* 9  */
150     {OP_Close, 0, 0, 0},           /* 10 */
151     {OP_Halt, 0, 0, 0},            /* 11 */
152   };
153 
154   int rc = SQLITE_OK;
155   char *zErr = 0;
156   Table *pTab;
157   Parse *pParse = 0;
158   Incrblob *pBlob = 0;
159 
160   flags = !!flags;                /* flags = (flags ? 1 : 0); */
161   *ppBlob = 0;
162 
163   sqlite3_mutex_enter(db->mutex);
164 
165   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
166   if( !pBlob ) goto blob_open_out;
167   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
168   if( !pParse ) goto blob_open_out;
169 
170   do {
171     memset(pParse, 0, sizeof(Parse));
172     pParse->db = db;
173     sqlite3DbFree(db, zErr);
174     zErr = 0;
175 
176     sqlite3BtreeEnterAll(db);
177     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
178     if( pTab && IsVirtual(pTab) ){
179       pTab = 0;
180       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
181     }
182     if( pTab && !HasRowid(pTab) ){
183       pTab = 0;
184       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
185     }
186 #ifndef SQLITE_OMIT_VIEW
187     if( pTab && pTab->pSelect ){
188       pTab = 0;
189       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
190     }
191 #endif
192     if( !pTab ){
193       if( pParse->zErrMsg ){
194         sqlite3DbFree(db, zErr);
195         zErr = pParse->zErrMsg;
196         pParse->zErrMsg = 0;
197       }
198       rc = SQLITE_ERROR;
199       sqlite3BtreeLeaveAll(db);
200       goto blob_open_out;
201     }
202 
203     /* Now search pTab for the exact column. */
204     for(iCol=0; iCol<pTab->nCol; iCol++) {
205       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
206         break;
207       }
208     }
209     if( iCol==pTab->nCol ){
210       sqlite3DbFree(db, zErr);
211       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
212       rc = SQLITE_ERROR;
213       sqlite3BtreeLeaveAll(db);
214       goto blob_open_out;
215     }
216 
217     /* If the value is being opened for writing, check that the
218     ** column is not indexed, and that it is not part of a foreign key.
219     ** It is against the rules to open a column to which either of these
220     ** descriptions applies for writing.  */
221     if( flags ){
222       const char *zFault = 0;
223       Index *pIdx;
224 #ifndef SQLITE_OMIT_FOREIGN_KEY
225       if( db->flags&SQLITE_ForeignKeys ){
226         /* Check that the column is not part of an FK child key definition. It
227         ** is not necessary to check if it is part of a parent key, as parent
228         ** key columns must be indexed. The check below will pick up this
229         ** case.  */
230         FKey *pFKey;
231         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
232           int j;
233           for(j=0; j<pFKey->nCol; j++){
234             if( pFKey->aCol[j].iFrom==iCol ){
235               zFault = "foreign key";
236             }
237           }
238         }
239       }
240 #endif
241       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
242         int j;
243         for(j=0; j<pIdx->nKeyCol; j++){
244           if( pIdx->aiColumn[j]==iCol ){
245             zFault = "indexed";
246           }
247         }
248       }
249       if( zFault ){
250         sqlite3DbFree(db, zErr);
251         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
252         rc = SQLITE_ERROR;
253         sqlite3BtreeLeaveAll(db);
254         goto blob_open_out;
255       }
256     }
257 
258     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
259     assert( pBlob->pStmt || db->mallocFailed );
260     if( pBlob->pStmt ){
261       Vdbe *v = (Vdbe *)pBlob->pStmt;
262       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
263 
264       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
265 
266 
267       /* Configure the OP_Transaction */
268       sqlite3VdbeChangeP1(v, 0, iDb);
269       sqlite3VdbeChangeP2(v, 0, flags);
270 
271       /* Configure the OP_VerifyCookie */
272       sqlite3VdbeChangeP1(v, 1, iDb);
273       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
274       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
275 
276       /* Make sure a mutex is held on the table to be accessed */
277       sqlite3VdbeUsesBtree(v, iDb);
278 
279       /* Configure the OP_TableLock instruction */
280 #ifdef SQLITE_OMIT_SHARED_CACHE
281       sqlite3VdbeChangeToNoop(v, 2);
282 #else
283       sqlite3VdbeChangeP1(v, 2, iDb);
284       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
285       sqlite3VdbeChangeP3(v, 2, flags);
286       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
287 #endif
288 
289       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
290       ** parameter of the other to pTab->tnum.  */
291       sqlite3VdbeChangeToNoop(v, 4 - flags);
292       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
293       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
294 
295       /* Configure the number of columns. Configure the cursor to
296       ** think that the table has one more column than it really
297       ** does. An OP_Column to retrieve this imaginary column will
298       ** always return an SQL NULL. This is useful because it means
299       ** we can invoke OP_Column to fill in the vdbe cursors type
300       ** and offset cache without causing any IO.
301       */
302       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
303       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
304       if( !db->mallocFailed ){
305         pParse->nVar = 1;
306         pParse->nMem = 1;
307         pParse->nTab = 1;
308         sqlite3VdbeMakeReady(v, pParse);
309       }
310     }
311 
312     pBlob->flags = flags;
313     pBlob->iCol = iCol;
314     pBlob->db = db;
315     sqlite3BtreeLeaveAll(db);
316     if( db->mallocFailed ){
317       goto blob_open_out;
318     }
319     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
320     rc = blobSeekToRow(pBlob, iRow, &zErr);
321   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
322 
323 blob_open_out:
324   if( rc==SQLITE_OK && db->mallocFailed==0 ){
325     *ppBlob = (sqlite3_blob *)pBlob;
326   }else{
327     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
328     sqlite3DbFree(db, pBlob);
329   }
330   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
331   sqlite3DbFree(db, zErr);
332   sqlite3ParserReset(pParse);
333   sqlite3StackFree(db, pParse);
334   rc = sqlite3ApiExit(db, rc);
335   sqlite3_mutex_leave(db->mutex);
336   return rc;
337 }
338 
339 /*
340 ** Close a blob handle that was previously created using
341 ** sqlite3_blob_open().
342 */
343 int sqlite3_blob_close(sqlite3_blob *pBlob){
344   Incrblob *p = (Incrblob *)pBlob;
345   int rc;
346   sqlite3 *db;
347 
348   if( p ){
349     db = p->db;
350     sqlite3_mutex_enter(db->mutex);
351     rc = sqlite3_finalize(p->pStmt);
352     sqlite3DbFree(db, p);
353     sqlite3_mutex_leave(db->mutex);
354   }else{
355     rc = SQLITE_OK;
356   }
357   return rc;
358 }
359 
360 /*
361 ** Perform a read or write operation on a blob
362 */
363 static int blobReadWrite(
364   sqlite3_blob *pBlob,
365   void *z,
366   int n,
367   int iOffset,
368   int (*xCall)(BtCursor*, u32, u32, void*)
369 ){
370   int rc;
371   Incrblob *p = (Incrblob *)pBlob;
372   Vdbe *v;
373   sqlite3 *db;
374 
375   if( p==0 ) return SQLITE_MISUSE_BKPT;
376   db = p->db;
377   sqlite3_mutex_enter(db->mutex);
378   v = (Vdbe*)p->pStmt;
379 
380   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
381     /* Request is out of range. Return a transient error. */
382     rc = SQLITE_ERROR;
383     sqlite3Error(db, SQLITE_ERROR, 0);
384   }else if( v==0 ){
385     /* If there is no statement handle, then the blob-handle has
386     ** already been invalidated. Return SQLITE_ABORT in this case.
387     */
388     rc = SQLITE_ABORT;
389   }else{
390     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
391     ** returned, clean-up the statement handle.
392     */
393     assert( db == v->db );
394     sqlite3BtreeEnterCursor(p->pCsr);
395     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
396     sqlite3BtreeLeaveCursor(p->pCsr);
397     if( rc==SQLITE_ABORT ){
398       sqlite3VdbeFinalize(v);
399       p->pStmt = 0;
400     }else{
401       db->errCode = rc;
402       v->rc = rc;
403     }
404   }
405   rc = sqlite3ApiExit(db, rc);
406   sqlite3_mutex_leave(db->mutex);
407   return rc;
408 }
409 
410 /*
411 ** Read data from a blob handle.
412 */
413 int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
414   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
415 }
416 
417 /*
418 ** Write data to a blob handle.
419 */
420 int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
421   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
422 }
423 
424 /*
425 ** Query a blob handle for the size of the data.
426 **
427 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
428 ** so no mutex is required for access.
429 */
430 int sqlite3_blob_bytes(sqlite3_blob *pBlob){
431   Incrblob *p = (Incrblob *)pBlob;
432   return (p && p->pStmt) ? p->nByte : 0;
433 }
434 
435 /*
436 ** Move an existing blob handle to point to a different row of the same
437 ** database table.
438 **
439 ** If an error occurs, or if the specified row does not exist or does not
440 ** contain a blob or text value, then an error code is returned and the
441 ** database handle error code and message set. If this happens, then all
442 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
443 ** immediately return SQLITE_ABORT.
444 */
445 int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
446   int rc;
447   Incrblob *p = (Incrblob *)pBlob;
448   sqlite3 *db;
449 
450   if( p==0 ) return SQLITE_MISUSE_BKPT;
451   db = p->db;
452   sqlite3_mutex_enter(db->mutex);
453 
454   if( p->pStmt==0 ){
455     /* If there is no statement handle, then the blob-handle has
456     ** already been invalidated. Return SQLITE_ABORT in this case.
457     */
458     rc = SQLITE_ABORT;
459   }else{
460     char *zErr;
461     rc = blobSeekToRow(p, iRow, &zErr);
462     if( rc!=SQLITE_OK ){
463       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
464       sqlite3DbFree(db, zErr);
465     }
466     assert( rc!=SQLITE_SCHEMA );
467   }
468 
469   rc = sqlite3ApiExit(db, rc);
470   assert( rc==SQLITE_OK || p->pStmt==0 );
471   sqlite3_mutex_leave(db->mutex);
472   return rc;
473 }
474 
475 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
476