4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** This file contains code used to implement incremental BLOB I/O.
16 #include "sqliteInt.h"
19 #ifndef SQLITE_OMIT_INCRBLOB
22 ** Valid sqlite3_blob* handles point to Incrblob structures.
24 typedef struct Incrblob 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 */
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.
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
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.
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
;
59 /* Set the value of register r[1] in the SQL statement to integer iRow.
60 ** This is done directly as a performance optimization
62 v
->aMem
[1].flags
= MEM_Int
;
63 v
->aMem
[1].u
.i
= iRow
;
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. */
71 assert( v
->aOp
[v
->pc
].opcode
==OP_NotExists
);
72 rc
= sqlite3VdbeExec(v
);
74 rc
= sqlite3_step(p
->pStmt
);
77 VdbeCursor
*pC
= v
->apCsr
[0];
80 assert( pC
->eCurType
==CURTYPE_BTREE
);
81 type
= pC
->nHdrParsed
>p
->iCol
? pC
->aType
[p
->iCol
] : 0;
82 testcase( pC
->nHdrParsed
==p
->iCol
);
83 testcase( pC
->nHdrParsed
==p
->iCol
+1 );
85 zErr
= sqlite3MPrintf(p
->db
, "cannot open value of type %s",
86 type
==0?"null": type
==7?"real": "integer"
89 sqlite3_finalize(p
->pStmt
);
92 p
->iOffset
= pC
->aType
[p
->iCol
+ pC
->nField
];
93 p
->nByte
= sqlite3VdbeSerialTypeLen(type
);
94 p
->pCsr
= pC
->uc
.pCursor
;
95 sqlite3BtreeIncrblobCursor(p
->pCsr
);
101 }else if( p
->pStmt
){
102 rc
= sqlite3_finalize(p
->pStmt
);
105 zErr
= sqlite3MPrintf(p
->db
, "no such rowid: %lld", iRow
);
108 zErr
= sqlite3MPrintf(p
->db
, "%s", sqlite3_errmsg(p
->db
));
112 assert( rc
!=SQLITE_OK
|| zErr
==0 );
113 assert( rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
);
120 ** Open a blob handle.
122 int sqlite3_blob_open(
123 sqlite3
* db
, /* The database connection */
124 const char *zDb
, /* The attached database containing the blob */
125 const char *zTable
, /* The table containing the blob */
126 const char *zColumn
, /* The column containing the blob */
127 sqlite_int64 iRow
, /* The row containing the glob */
128 int wrFlag
, /* True -> read/write access, false -> read-only */
129 sqlite3_blob
**ppBlob
/* Handle for accessing the blob returned here */
132 int iCol
; /* Index of zColumn in row-record */
139 #ifdef SQLITE_ENABLE_API_ARMOR
141 return SQLITE_MISUSE_BKPT
;
145 #ifdef SQLITE_ENABLE_API_ARMOR
146 if( !sqlite3SafetyCheckOk(db
) || zTable
==0 ){
147 return SQLITE_MISUSE_BKPT
;
150 wrFlag
= !!wrFlag
; /* wrFlag = (wrFlag ? 1 : 0); */
152 sqlite3_mutex_enter(db
->mutex
);
154 pBlob
= (Incrblob
*)sqlite3DbMallocZero(db
, sizeof(Incrblob
));
156 memset(&sParse
, 0, sizeof(Parse
));
157 if( !pBlob
) goto blob_open_out
;
159 sqlite3DbFree(db
, zErr
);
162 sqlite3BtreeEnterAll(db
);
163 pTab
= sqlite3LocateTable(&sParse
, 0, zTable
, zDb
);
164 if( pTab
&& IsVirtual(pTab
) ){
166 sqlite3ErrorMsg(&sParse
, "cannot open virtual table: %s", zTable
);
168 if( pTab
&& !HasRowid(pTab
) ){
170 sqlite3ErrorMsg(&sParse
, "cannot open table without rowid: %s", zTable
);
172 #ifndef SQLITE_OMIT_VIEW
173 if( pTab
&& IsView(pTab
) ){
175 sqlite3ErrorMsg(&sParse
, "cannot open view: %s", zTable
);
179 if( sParse
.zErrMsg
){
180 sqlite3DbFree(db
, zErr
);
181 zErr
= sParse
.zErrMsg
;
185 sqlite3BtreeLeaveAll(db
);
189 pBlob
->zDb
= db
->aDb
[sqlite3SchemaToIndex(db
, pTab
->pSchema
)].zDbSName
;
191 /* Now search pTab for the exact column. */
192 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++) {
193 if( sqlite3StrICmp(pTab
->aCol
[iCol
].zCnName
, zColumn
)==0 ){
197 if( iCol
==pTab
->nCol
){
198 sqlite3DbFree(db
, zErr
);
199 zErr
= sqlite3MPrintf(db
, "no such column: \"%s\"", zColumn
);
201 sqlite3BtreeLeaveAll(db
);
205 /* If the value is being opened for writing, check that the
206 ** column is not indexed, and that it is not part of a foreign key.
209 const char *zFault
= 0;
211 #ifndef SQLITE_OMIT_FOREIGN_KEY
212 if( db
->flags
&SQLITE_ForeignKeys
){
213 /* Check that the column is not part of an FK child key definition. It
214 ** is not necessary to check if it is part of a parent key, as parent
215 ** key columns must be indexed. The check below will pick up this
218 assert( IsOrdinaryTable(pTab
) );
219 for(pFKey
=pTab
->u
.tab
.pFKey
; pFKey
; pFKey
=pFKey
->pNextFrom
){
221 for(j
=0; j
<pFKey
->nCol
; j
++){
222 if( pFKey
->aCol
[j
].iFrom
==iCol
){
223 zFault
= "foreign key";
229 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
231 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
232 /* FIXME: Be smarter about indexes that use expressions */
233 if( pIdx
->aiColumn
[j
]==iCol
|| pIdx
->aiColumn
[j
]==XN_EXPR
){
239 sqlite3DbFree(db
, zErr
);
240 zErr
= sqlite3MPrintf(db
, "cannot open %s column for writing", zFault
);
242 sqlite3BtreeLeaveAll(db
);
247 pBlob
->pStmt
= (sqlite3_stmt
*)sqlite3VdbeCreate(&sParse
);
248 assert( pBlob
->pStmt
|| db
->mallocFailed
);
251 /* This VDBE program seeks a btree cursor to the identified
252 ** db/table/row entry. The reason for using a vdbe program instead
253 ** of writing code to use the b-tree layer directly is that the
254 ** vdbe program will take advantage of the various transaction,
255 ** locking and error handling infrastructure built into the vdbe.
257 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
258 ** Code external to the Vdbe then "borrows" the b-tree cursor and
259 ** uses it to implement the blob_read(), blob_write() and
260 ** blob_bytes() functions.
262 ** The sqlite3_blob_close() function finalizes the vdbe program,
263 ** which closes the b-tree cursor and (possibly) commits the
266 static const int iLn
= VDBE_OFFSET_LINENO(2);
267 static const VdbeOpList openBlob
[] = {
268 {OP_TableLock
, 0, 0, 0}, /* 0: Acquire a read or write lock */
269 {OP_OpenRead
, 0, 0, 0}, /* 1: Open a cursor */
270 /* blobSeekToRow() will initialize r[1] to the desired rowid */
271 {OP_NotExists
, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
272 {OP_Column
, 0, 0, 1}, /* 3 */
273 {OP_ResultRow
, 1, 0, 0}, /* 4 */
274 {OP_Halt
, 0, 0, 0}, /* 5 */
276 Vdbe
*v
= (Vdbe
*)pBlob
->pStmt
;
277 int iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
280 sqlite3VdbeAddOp4Int(v
, OP_Transaction
, iDb
, wrFlag
,
281 pTab
->pSchema
->schema_cookie
,
282 pTab
->pSchema
->iGeneration
);
283 sqlite3VdbeChangeP5(v
, 1);
284 assert( sqlite3VdbeCurrentAddr(v
)==2 || db
->mallocFailed
);
285 aOp
= sqlite3VdbeAddOpList(v
, ArraySize(openBlob
), openBlob
, iLn
);
287 /* Make sure a mutex is held on the table to be accessed */
288 sqlite3VdbeUsesBtree(v
, iDb
);
290 if( db
->mallocFailed
==0 ){
292 /* Configure the OP_TableLock instruction */
293 #ifdef SQLITE_OMIT_SHARED_CACHE
294 aOp
[0].opcode
= OP_Noop
;
297 aOp
[0].p2
= pTab
->tnum
;
299 sqlite3VdbeChangeP4(v
, 2, pTab
->zName
, P4_TRANSIENT
);
301 if( db
->mallocFailed
==0 ){
304 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
305 ** parameter of the other to pTab->tnum. */
306 if( wrFlag
) aOp
[1].opcode
= OP_OpenWrite
;
307 aOp
[1].p2
= pTab
->tnum
;
310 /* Configure the number of columns. Configure the cursor to
311 ** think that the table has one more column than it really
312 ** does. An OP_Column to retrieve this imaginary column will
313 ** always return an SQL NULL. This is useful because it means
314 ** we can invoke OP_Column to fill in the vdbe cursors type
315 ** and offset cache without causing any IO.
317 aOp
[1].p4type
= P4_INT32
;
318 aOp
[1].p4
.i
= pTab
->nCol
+1;
319 aOp
[3].p2
= pTab
->nCol
;
324 sqlite3VdbeMakeReady(v
, &sParse
);
330 sqlite3BtreeLeaveAll(db
);
331 if( db
->mallocFailed
){
334 rc
= blobSeekToRow(pBlob
, iRow
, &zErr
);
335 } while( (++nAttempt
)<SQLITE_MAX_SCHEMA_RETRY
&& rc
==SQLITE_SCHEMA
);
338 if( rc
==SQLITE_OK
&& db
->mallocFailed
==0 ){
339 *ppBlob
= (sqlite3_blob
*)pBlob
;
341 if( pBlob
&& pBlob
->pStmt
) sqlite3VdbeFinalize((Vdbe
*)pBlob
->pStmt
);
342 sqlite3DbFree(db
, pBlob
);
344 sqlite3ErrorWithMsg(db
, rc
, (zErr
? "%s" : 0), zErr
);
345 sqlite3DbFree(db
, zErr
);
346 sqlite3ParserReset(&sParse
);
347 rc
= sqlite3ApiExit(db
, rc
);
348 sqlite3_mutex_leave(db
->mutex
);
353 ** Close a blob handle that was previously created using
354 ** sqlite3_blob_open().
356 int sqlite3_blob_close(sqlite3_blob
*pBlob
){
357 Incrblob
*p
= (Incrblob
*)pBlob
;
362 sqlite3_stmt
*pStmt
= p
->pStmt
;
364 sqlite3_mutex_enter(db
->mutex
);
365 sqlite3DbFree(db
, p
);
366 sqlite3_mutex_leave(db
->mutex
);
367 rc
= sqlite3_finalize(pStmt
);
375 ** Perform a read or write operation on a blob
377 static int blobReadWrite(
382 int (*xCall
)(BtCursor
*, u32
, u32
, void*)
385 Incrblob
*p
= (Incrblob
*)pBlob
;
389 if( p
==0 ) return SQLITE_MISUSE_BKPT
;
391 sqlite3_mutex_enter(db
->mutex
);
394 if( n
<0 || iOffset
<0 || ((sqlite3_int64
)iOffset
+n
)>p
->nByte
){
395 /* Request is out of range. Return a transient error. */
398 /* If there is no statement handle, then the blob-handle has
399 ** already been invalidated. Return SQLITE_ABORT in this case.
403 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
404 ** returned, clean-up the statement handle.
406 assert( db
== v
->db
);
407 sqlite3BtreeEnterCursor(p
->pCsr
);
409 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
410 if( xCall
==sqlite3BtreePutData
&& db
->xPreUpdateCallback
){
411 /* If a pre-update hook is registered and this is a write cursor,
414 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
415 ** operation should really be an SQLITE_UPDATE. This is probably
416 ** incorrect, but is convenient because at this point the new.* values
417 ** are not easily obtainable. And for the sessions module, an
418 ** SQLITE_UPDATE where the PK columns do not change is handled in the
419 ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
420 ** slightly more efficient). Since you cannot write to a PK column
421 ** using the incremental-blob API, this works. For the sessions module
425 iKey
= sqlite3BtreeIntegerKey(p
->pCsr
);
426 assert( v
->apCsr
[0]!=0 );
427 assert( v
->apCsr
[0]->eCurType
==CURTYPE_BTREE
);
428 sqlite3VdbePreUpdateHook(
429 v
, v
->apCsr
[0], SQLITE_DELETE
, p
->zDb
, p
->pTab
, iKey
, -1, p
->iCol
434 rc
= xCall(p
->pCsr
, iOffset
+p
->iOffset
, n
, z
);
435 sqlite3BtreeLeaveCursor(p
->pCsr
);
436 if( rc
==SQLITE_ABORT
){
437 sqlite3VdbeFinalize(v
);
443 sqlite3Error(db
, rc
);
444 rc
= sqlite3ApiExit(db
, rc
);
445 sqlite3_mutex_leave(db
->mutex
);
450 ** Read data from a blob handle.
452 int sqlite3_blob_read(sqlite3_blob
*pBlob
, void *z
, int n
, int iOffset
){
453 return blobReadWrite(pBlob
, z
, n
, iOffset
, sqlite3BtreePayloadChecked
);
457 ** Write data to a blob handle.
459 int sqlite3_blob_write(sqlite3_blob
*pBlob
, const void *z
, int n
, int iOffset
){
460 return blobReadWrite(pBlob
, (void *)z
, n
, iOffset
, sqlite3BtreePutData
);
464 ** Query a blob handle for the size of the data.
466 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
467 ** so no mutex is required for access.
469 int sqlite3_blob_bytes(sqlite3_blob
*pBlob
){
470 Incrblob
*p
= (Incrblob
*)pBlob
;
471 return (p
&& p
->pStmt
) ? p
->nByte
: 0;
475 ** Move an existing blob handle to point to a different row of the same
478 ** If an error occurs, or if the specified row does not exist or does not
479 ** contain a blob or text value, then an error code is returned and the
480 ** database handle error code and message set. If this happens, then all
481 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
482 ** immediately return SQLITE_ABORT.
484 int sqlite3_blob_reopen(sqlite3_blob
*pBlob
, sqlite3_int64 iRow
){
486 Incrblob
*p
= (Incrblob
*)pBlob
;
489 if( p
==0 ) return SQLITE_MISUSE_BKPT
;
491 sqlite3_mutex_enter(db
->mutex
);
494 /* If there is no statement handle, then the blob-handle has
495 ** already been invalidated. Return SQLITE_ABORT in this case.
500 ((Vdbe
*)p
->pStmt
)->rc
= SQLITE_OK
;
501 rc
= blobSeekToRow(p
, iRow
, &zErr
);
503 sqlite3ErrorWithMsg(db
, rc
, (zErr
? "%s" : 0), zErr
);
504 sqlite3DbFree(db
, zErr
);
506 assert( rc
!=SQLITE_SCHEMA
);
509 rc
= sqlite3ApiExit(db
, rc
);
510 assert( rc
==SQLITE_OK
|| p
->pStmt
==0 );
511 sqlite3_mutex_leave(db
->mutex
);
515 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */