xref: /sqlite-3.40.0/src/vdbeblob.c (revision b80bb6ce)
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 nByte;              /* Size of open blob, in bytes */
27   int iOffset;            /* Byte offset of blob in cursor data */
28   u16 iCol;               /* Table column this handle is open on */
29   BtCursor *pCsr;         /* Cursor pointing at blob row */
30   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
31   sqlite3 *db;            /* The associated database */
32   char *zDb;              /* Database name */
33   Table *pTab;            /* Table object */
34 };
35 
36 
37 /*
38 ** This function is used by both blob_open() and blob_reopen(). It seeks
39 ** the b-tree cursor associated with blob handle p to point to row iRow.
40 ** If successful, SQLITE_OK is returned and subsequent calls to
41 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
42 **
43 ** If an error occurs, or if the specified row does not exist or does not
44 ** contain a value of type TEXT or BLOB in the column nominated when the
45 ** blob handle was opened, then an error code is returned and *pzErr may
46 ** be set to point to a buffer containing an error message. It is the
47 ** responsibility of the caller to free the error message buffer using
48 ** sqlite3DbFree().
49 **
50 ** If an error does occur, then the b-tree cursor is closed. All subsequent
51 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
52 ** immediately return SQLITE_ABORT.
53 */
54 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
55   int rc;                         /* Error code */
56   char *zErr = 0;                 /* Error message */
57   Vdbe *v = (Vdbe *)p->pStmt;
58 
59   /* Set the value of register r[1] in the SQL statement to integer iRow.
60   ** This is done directly as a performance optimization
61   */
62   v->aMem[1].flags = MEM_Int;
63   v->aMem[1].u.i = iRow;
64 
65   /* If the statement has been run before (and is paused at the OP_ResultRow)
66   ** then back it up to the point where it does the OP_NotExists.  This could
67   ** have been down with an extra OP_Goto, but simply setting the program
68   ** counter is faster. */
69   if( v->pc>4 ){
70     v->pc = 4;
71     assert( v->aOp[v->pc].opcode==OP_NotExists );
72     rc = sqlite3VdbeExec(v);
73   }else{
74     rc = sqlite3_step(p->pStmt);
75   }
76   if( rc==SQLITE_ROW ){
77     VdbeCursor *pC = v->apCsr[0];
78     u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
79     testcase( pC->nHdrParsed==p->iCol );
80     testcase( pC->nHdrParsed==p->iCol+1 );
81     if( type<12 ){
82       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
83           type==0?"null": type==7?"real": "integer"
84       );
85       rc = SQLITE_ERROR;
86       sqlite3_finalize(p->pStmt);
87       p->pStmt = 0;
88     }else{
89       p->iOffset = pC->aType[p->iCol + pC->nField];
90       p->nByte = sqlite3VdbeSerialTypeLen(type);
91       p->pCsr =  pC->uc.pCursor;
92       sqlite3BtreeIncrblobCursor(p->pCsr);
93     }
94   }
95 
96   if( rc==SQLITE_ROW ){
97     rc = SQLITE_OK;
98   }else if( p->pStmt ){
99     rc = sqlite3_finalize(p->pStmt);
100     p->pStmt = 0;
101     if( rc==SQLITE_OK ){
102       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
103       rc = SQLITE_ERROR;
104     }else{
105       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
106     }
107   }
108 
109   assert( rc!=SQLITE_OK || zErr==0 );
110   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
111 
112   *pzErr = zErr;
113   return rc;
114 }
115 
116 /*
117 ** Open a blob handle.
118 */
119 int sqlite3_blob_open(
120   sqlite3* db,            /* The database connection */
121   const char *zDb,        /* The attached database containing the blob */
122   const char *zTable,     /* The table containing the blob */
123   const char *zColumn,    /* The column containing the blob */
124   sqlite_int64 iRow,      /* The row containing the glob */
125   int wrFlag,             /* True -> read/write access, false -> read-only */
126   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
127 ){
128   int nAttempt = 0;
129   int iCol;               /* Index of zColumn in row-record */
130   int rc = SQLITE_OK;
131   char *zErr = 0;
132   Table *pTab;
133   Incrblob *pBlob = 0;
134   Parse sParse;
135 
136 #ifdef SQLITE_ENABLE_API_ARMOR
137   if( ppBlob==0 ){
138     return SQLITE_MISUSE_BKPT;
139   }
140 #endif
141   *ppBlob = 0;
142 #ifdef SQLITE_ENABLE_API_ARMOR
143   if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
144     return SQLITE_MISUSE_BKPT;
145   }
146 #endif
147   wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
148 
149   sqlite3_mutex_enter(db->mutex);
150 
151   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
152   do {
153     memset(&sParse, 0, sizeof(Parse));
154     if( !pBlob ) goto blob_open_out;
155     sParse.db = db;
156     sqlite3DbFree(db, zErr);
157     zErr = 0;
158 
159     sqlite3BtreeEnterAll(db);
160     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
161     if( pTab && IsVirtual(pTab) ){
162       pTab = 0;
163       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
164     }
165     if( pTab && !HasRowid(pTab) ){
166       pTab = 0;
167       sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
168     }
169 #ifndef SQLITE_OMIT_VIEW
170     if( pTab && pTab->pSelect ){
171       pTab = 0;
172       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
173     }
174 #endif
175     if( !pTab ){
176       if( sParse.zErrMsg ){
177         sqlite3DbFree(db, zErr);
178         zErr = sParse.zErrMsg;
179         sParse.zErrMsg = 0;
180       }
181       rc = SQLITE_ERROR;
182       sqlite3BtreeLeaveAll(db);
183       goto blob_open_out;
184     }
185     pBlob->pTab = pTab;
186     pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
187 
188     /* Now search pTab for the exact column. */
189     for(iCol=0; iCol<pTab->nCol; iCol++) {
190       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
191         break;
192       }
193     }
194     if( iCol==pTab->nCol ){
195       sqlite3DbFree(db, zErr);
196       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
197       rc = SQLITE_ERROR;
198       sqlite3BtreeLeaveAll(db);
199       goto blob_open_out;
200     }
201 
202     /* If the value is being opened for writing, check that the
203     ** column is not indexed, and that it is not part of a foreign key.
204     */
205     if( wrFlag ){
206       const char *zFault = 0;
207       Index *pIdx;
208 #ifndef SQLITE_OMIT_FOREIGN_KEY
209       if( db->flags&SQLITE_ForeignKeys ){
210         /* Check that the column is not part of an FK child key definition. It
211         ** is not necessary to check if it is part of a parent key, as parent
212         ** key columns must be indexed. The check below will pick up this
213         ** case.  */
214         FKey *pFKey;
215         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
216           int j;
217           for(j=0; j<pFKey->nCol; j++){
218             if( pFKey->aCol[j].iFrom==iCol ){
219               zFault = "foreign key";
220             }
221           }
222         }
223       }
224 #endif
225       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
226         int j;
227         for(j=0; j<pIdx->nKeyCol; j++){
228           /* FIXME: Be smarter about indexes that use expressions */
229           if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
230             zFault = "indexed";
231           }
232         }
233       }
234       if( zFault ){
235         sqlite3DbFree(db, zErr);
236         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
237         rc = SQLITE_ERROR;
238         sqlite3BtreeLeaveAll(db);
239         goto blob_open_out;
240       }
241     }
242 
243     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
244     assert( pBlob->pStmt || db->mallocFailed );
245     if( pBlob->pStmt ){
246 
247       /* This VDBE program seeks a btree cursor to the identified
248       ** db/table/row entry. The reason for using a vdbe program instead
249       ** of writing code to use the b-tree layer directly is that the
250       ** vdbe program will take advantage of the various transaction,
251       ** locking and error handling infrastructure built into the vdbe.
252       **
253       ** After seeking the cursor, the vdbe executes an OP_ResultRow.
254       ** Code external to the Vdbe then "borrows" the b-tree cursor and
255       ** uses it to implement the blob_read(), blob_write() and
256       ** blob_bytes() functions.
257       **
258       ** The sqlite3_blob_close() function finalizes the vdbe program,
259       ** which closes the b-tree cursor and (possibly) commits the
260       ** transaction.
261       */
262       static const int iLn = VDBE_OFFSET_LINENO(2);
263       static const VdbeOpList openBlob[] = {
264         {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
265         {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
266         /* blobSeekToRow() will initialize r[1] to the desired rowid */
267         {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
268         {OP_Column,         0, 0, 1},  /* 3  */
269         {OP_ResultRow,      1, 0, 0},  /* 4  */
270         {OP_Halt,           0, 0, 0},  /* 5  */
271       };
272       Vdbe *v = (Vdbe *)pBlob->pStmt;
273       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
274       VdbeOp *aOp;
275 
276       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
277                            pTab->pSchema->schema_cookie,
278                            pTab->pSchema->iGeneration);
279       sqlite3VdbeChangeP5(v, 1);
280       assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
281       aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
282 
283       /* Make sure a mutex is held on the table to be accessed */
284       sqlite3VdbeUsesBtree(v, iDb);
285 
286       if( db->mallocFailed==0 ){
287         assert( aOp!=0 );
288         /* Configure the OP_TableLock instruction */
289 #ifdef SQLITE_OMIT_SHARED_CACHE
290         aOp[0].opcode = OP_Noop;
291 #else
292         aOp[0].p1 = iDb;
293         aOp[0].p2 = pTab->tnum;
294         aOp[0].p3 = wrFlag;
295         sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
296       }
297       if( db->mallocFailed==0 ){
298 #endif
299 
300         /* Remove either the OP_OpenWrite or OpenRead. Set the P2
301         ** parameter of the other to pTab->tnum.  */
302         if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
303         aOp[1].p2 = pTab->tnum;
304         aOp[1].p3 = iDb;
305 
306         /* Configure the number of columns. Configure the cursor to
307         ** think that the table has one more column than it really
308         ** does. An OP_Column to retrieve this imaginary column will
309         ** always return an SQL NULL. This is useful because it means
310         ** we can invoke OP_Column to fill in the vdbe cursors type
311         ** and offset cache without causing any IO.
312         */
313         aOp[1].p4type = P4_INT32;
314         aOp[1].p4.i = pTab->nCol+1;
315         aOp[3].p2 = pTab->nCol;
316 
317         sParse.nVar = 0;
318         sParse.nMem = 1;
319         sParse.nTab = 1;
320         sqlite3VdbeMakeReady(v, &sParse);
321       }
322     }
323 
324     pBlob->iCol = iCol;
325     pBlob->db = db;
326     sqlite3BtreeLeaveAll(db);
327     if( db->mallocFailed ){
328       goto blob_open_out;
329     }
330     rc = blobSeekToRow(pBlob, iRow, &zErr);
331   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
332 
333 blob_open_out:
334   if( rc==SQLITE_OK && db->mallocFailed==0 ){
335     *ppBlob = (sqlite3_blob *)pBlob;
336   }else{
337     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
338     sqlite3DbFree(db, pBlob);
339   }
340   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
341   sqlite3DbFree(db, zErr);
342   sqlite3ParserReset(&sParse);
343   rc = sqlite3ApiExit(db, rc);
344   sqlite3_mutex_leave(db->mutex);
345   return rc;
346 }
347 
348 /*
349 ** Close a blob handle that was previously created using
350 ** sqlite3_blob_open().
351 */
352 int sqlite3_blob_close(sqlite3_blob *pBlob){
353   Incrblob *p = (Incrblob *)pBlob;
354   int rc;
355   sqlite3 *db;
356 
357   if( p ){
358     db = p->db;
359     sqlite3_mutex_enter(db->mutex);
360     rc = sqlite3_finalize(p->pStmt);
361     sqlite3DbFree(db, p);
362     sqlite3_mutex_leave(db->mutex);
363   }else{
364     rc = SQLITE_OK;
365   }
366   return rc;
367 }
368 
369 /*
370 ** Perform a read or write operation on a blob
371 */
372 static int blobReadWrite(
373   sqlite3_blob *pBlob,
374   void *z,
375   int n,
376   int iOffset,
377   int (*xCall)(BtCursor*, u32, u32, void*)
378 ){
379   int rc;
380   Incrblob *p = (Incrblob *)pBlob;
381   Vdbe *v;
382   sqlite3 *db;
383 
384   if( p==0 ) return SQLITE_MISUSE_BKPT;
385   db = p->db;
386   sqlite3_mutex_enter(db->mutex);
387   v = (Vdbe*)p->pStmt;
388 
389   if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
390     /* Request is out of range. Return a transient error. */
391     rc = SQLITE_ERROR;
392   }else if( v==0 ){
393     /* If there is no statement handle, then the blob-handle has
394     ** already been invalidated. Return SQLITE_ABORT in this case.
395     */
396     rc = SQLITE_ABORT;
397   }else{
398     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
399     ** returned, clean-up the statement handle.
400     */
401     assert( db == v->db );
402     sqlite3BtreeEnterCursor(p->pCsr);
403 
404 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
405     if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
406       /* If a pre-update hook is registered and this is a write cursor,
407       ** invoke it here.
408       **
409       ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
410       ** operation should really be an SQLITE_UPDATE. This is probably
411       ** incorrect, but is convenient because at this point the new.* values
412       ** are not easily obtainable. And for the sessions module, an
413       ** SQLITE_UPDATE where the PK columns do not change is handled in the
414       ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
415       ** slightly more efficient). Since you cannot write to a PK column
416       ** using the incremental-blob API, this works. For the sessions module
417       ** anyhow.
418       */
419       sqlite3_int64 iKey;
420       iKey = sqlite3BtreeIntegerKey(p->pCsr);
421       sqlite3VdbePreUpdateHook(
422           v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
423       );
424     }
425 #endif
426 
427     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
428     sqlite3BtreeLeaveCursor(p->pCsr);
429     if( rc==SQLITE_ABORT ){
430       sqlite3VdbeFinalize(v);
431       p->pStmt = 0;
432     }else{
433       v->rc = rc;
434     }
435   }
436   sqlite3Error(db, rc);
437   rc = sqlite3ApiExit(db, rc);
438   sqlite3_mutex_leave(db->mutex);
439   return rc;
440 }
441 
442 /*
443 ** Read data from a blob handle.
444 */
445 int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
446   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
447 }
448 
449 /*
450 ** Write data to a blob handle.
451 */
452 int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
453   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
454 }
455 
456 /*
457 ** Query a blob handle for the size of the data.
458 **
459 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
460 ** so no mutex is required for access.
461 */
462 int sqlite3_blob_bytes(sqlite3_blob *pBlob){
463   Incrblob *p = (Incrblob *)pBlob;
464   return (p && p->pStmt) ? p->nByte : 0;
465 }
466 
467 /*
468 ** Move an existing blob handle to point to a different row of the same
469 ** database table.
470 **
471 ** If an error occurs, or if the specified row does not exist or does not
472 ** contain a blob or text value, then an error code is returned and the
473 ** database handle error code and message set. If this happens, then all
474 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
475 ** immediately return SQLITE_ABORT.
476 */
477 int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
478   int rc;
479   Incrblob *p = (Incrblob *)pBlob;
480   sqlite3 *db;
481 
482   if( p==0 ) return SQLITE_MISUSE_BKPT;
483   db = p->db;
484   sqlite3_mutex_enter(db->mutex);
485 
486   if( p->pStmt==0 ){
487     /* If there is no statement handle, then the blob-handle has
488     ** already been invalidated. Return SQLITE_ABORT in this case.
489     */
490     rc = SQLITE_ABORT;
491   }else{
492     char *zErr;
493     rc = blobSeekToRow(p, iRow, &zErr);
494     if( rc!=SQLITE_OK ){
495       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
496       sqlite3DbFree(db, zErr);
497     }
498     assert( rc!=SQLITE_SCHEMA );
499   }
500 
501   rc = sqlite3ApiExit(db, rc);
502   assert( rc==SQLITE_OK || p->pStmt==0 );
503   sqlite3_mutex_leave(db->mutex);
504   return rc;
505 }
506 
507 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
508