Revise variable declaration moved in the previous check-in so sqlite3VdbeReset()...
[sqlite.git] / src / vdbeblob.c
blob16a2c0f36fddeee2a51d89a4472ef250d6f05d5a
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.
11 *************************************************************************
13 ** This file contains code used to implement incremental BLOB I/O.
16 #include "sqliteInt.h"
17 #include "vdbeInt.h"
19 #ifndef SQLITE_OMIT_INCRBLOB
22 ** Valid sqlite3_blob* handles point to Incrblob structures.
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 */
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
48 ** sqlite3DbFree().
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_SeekRowid. This could
67 ** have been down with an extra OP_Goto, but simply setting the program
68 ** counter is faster. */
69 if( v->pc>3 ){
70 v->pc = 3;
71 rc = sqlite3VdbeExec(v);
72 }else{
73 rc = sqlite3_step(p->pStmt);
75 if( rc==SQLITE_ROW ){
76 VdbeCursor *pC = v->apCsr[0];
77 u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
78 testcase( pC->nHdrParsed==p->iCol );
79 testcase( pC->nHdrParsed==p->iCol+1 );
80 if( type<12 ){
81 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
82 type==0?"null": type==7?"real": "integer"
84 rc = SQLITE_ERROR;
85 sqlite3_finalize(p->pStmt);
86 p->pStmt = 0;
87 }else{
88 p->iOffset = pC->aType[p->iCol + pC->nField];
89 p->nByte = sqlite3VdbeSerialTypeLen(type);
90 p->pCsr = pC->uc.pCursor;
91 sqlite3BtreeIncrblobCursor(p->pCsr);
95 if( rc==SQLITE_ROW ){
96 rc = SQLITE_OK;
97 }else if( p->pStmt ){
98 rc = sqlite3_finalize(p->pStmt);
99 p->pStmt = 0;
100 if( rc==SQLITE_OK ){
101 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
102 rc = SQLITE_ERROR;
103 }else{
104 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
108 assert( rc!=SQLITE_OK || zErr==0 );
109 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
111 *pzErr = zErr;
112 return rc;
116 ** Open a blob handle.
118 int sqlite3_blob_open(
119 sqlite3* db, /* The database connection */
120 const char *zDb, /* The attached database containing the blob */
121 const char *zTable, /* The table containing the blob */
122 const char *zColumn, /* The column containing the blob */
123 sqlite_int64 iRow, /* The row containing the glob */
124 int wrFlag, /* True -> read/write access, false -> read-only */
125 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
127 int nAttempt = 0;
128 int iCol; /* Index of zColumn in row-record */
129 int rc = SQLITE_OK;
130 char *zErr = 0;
131 Table *pTab;
132 Incrblob *pBlob = 0;
133 Parse sParse;
135 #ifdef SQLITE_ENABLE_API_ARMOR
136 if( ppBlob==0 ){
137 return SQLITE_MISUSE_BKPT;
139 #endif
140 *ppBlob = 0;
141 #ifdef SQLITE_ENABLE_API_ARMOR
142 if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
143 return SQLITE_MISUSE_BKPT;
145 #endif
146 wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
148 sqlite3_mutex_enter(db->mutex);
150 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
151 do {
152 memset(&sParse, 0, sizeof(Parse));
153 if( !pBlob ) goto blob_open_out;
154 sParse.db = db;
155 sqlite3DbFree(db, zErr);
156 zErr = 0;
158 sqlite3BtreeEnterAll(db);
159 pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
160 if( pTab && IsVirtual(pTab) ){
161 pTab = 0;
162 sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
164 if( pTab && !HasRowid(pTab) ){
165 pTab = 0;
166 sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
168 #ifndef SQLITE_OMIT_VIEW
169 if( pTab && pTab->pSelect ){
170 pTab = 0;
171 sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
173 #endif
174 if( !pTab ){
175 if( sParse.zErrMsg ){
176 sqlite3DbFree(db, zErr);
177 zErr = sParse.zErrMsg;
178 sParse.zErrMsg = 0;
180 rc = SQLITE_ERROR;
181 sqlite3BtreeLeaveAll(db);
182 goto blob_open_out;
184 pBlob->pTab = pTab;
185 pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
187 /* Now search pTab for the exact column. */
188 for(iCol=0; iCol<pTab->nCol; iCol++) {
189 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
190 break;
193 if( iCol==pTab->nCol ){
194 sqlite3DbFree(db, zErr);
195 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
196 rc = SQLITE_ERROR;
197 sqlite3BtreeLeaveAll(db);
198 goto blob_open_out;
201 /* If the value is being opened for writing, check that the
202 ** column is not indexed, and that it is not part of a foreign key.
204 if( wrFlag ){
205 const char *zFault = 0;
206 Index *pIdx;
207 #ifndef SQLITE_OMIT_FOREIGN_KEY
208 if( db->flags&SQLITE_ForeignKeys ){
209 /* Check that the column is not part of an FK child key definition. It
210 ** is not necessary to check if it is part of a parent key, as parent
211 ** key columns must be indexed. The check below will pick up this
212 ** case. */
213 FKey *pFKey;
214 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
215 int j;
216 for(j=0; j<pFKey->nCol; j++){
217 if( pFKey->aCol[j].iFrom==iCol ){
218 zFault = "foreign key";
223 #endif
224 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
225 int j;
226 for(j=0; j<pIdx->nKeyCol; j++){
227 /* FIXME: Be smarter about indexes that use expressions */
228 if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
229 zFault = "indexed";
233 if( zFault ){
234 sqlite3DbFree(db, zErr);
235 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
236 rc = SQLITE_ERROR;
237 sqlite3BtreeLeaveAll(db);
238 goto blob_open_out;
242 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
243 assert( pBlob->pStmt || db->mallocFailed );
244 if( pBlob->pStmt ){
246 /* This VDBE program seeks a btree cursor to the identified
247 ** db/table/row entry. The reason for using a vdbe program instead
248 ** of writing code to use the b-tree layer directly is that the
249 ** vdbe program will take advantage of the various transaction,
250 ** locking and error handling infrastructure built into the vdbe.
252 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
253 ** Code external to the Vdbe then "borrows" the b-tree cursor and
254 ** uses it to implement the blob_read(), blob_write() and
255 ** blob_bytes() functions.
257 ** The sqlite3_blob_close() function finalizes the vdbe program,
258 ** which closes the b-tree cursor and (possibly) commits the
259 ** transaction.
261 static const int iLn = VDBE_OFFSET_LINENO(2);
262 static const VdbeOpList openBlob[] = {
263 {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
264 {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
265 /* blobSeekToRow() will initialize r[1] to the desired rowid */
266 {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
267 {OP_Column, 0, 0, 1}, /* 3 */
268 {OP_ResultRow, 1, 0, 0}, /* 4 */
269 {OP_Halt, 0, 0, 0}, /* 5 */
271 Vdbe *v = (Vdbe *)pBlob->pStmt;
272 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
273 VdbeOp *aOp;
275 sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
276 pTab->pSchema->schema_cookie,
277 pTab->pSchema->iGeneration);
278 sqlite3VdbeChangeP5(v, 1);
279 assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
280 aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
282 /* Make sure a mutex is held on the table to be accessed */
283 sqlite3VdbeUsesBtree(v, iDb);
285 if( db->mallocFailed==0 ){
286 assert( aOp!=0 );
287 /* Configure the OP_TableLock instruction */
288 #ifdef SQLITE_OMIT_SHARED_CACHE
289 aOp[0].opcode = OP_Noop;
290 #else
291 aOp[0].p1 = iDb;
292 aOp[0].p2 = pTab->tnum;
293 aOp[0].p3 = wrFlag;
294 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
296 if( db->mallocFailed==0 ){
297 #endif
299 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
300 ** parameter of the other to pTab->tnum. */
301 if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
302 aOp[1].p2 = pTab->tnum;
303 aOp[1].p3 = iDb;
305 /* Configure the number of columns. Configure the cursor to
306 ** think that the table has one more column than it really
307 ** does. An OP_Column to retrieve this imaginary column will
308 ** always return an SQL NULL. This is useful because it means
309 ** we can invoke OP_Column to fill in the vdbe cursors type
310 ** and offset cache without causing any IO.
312 aOp[1].p4type = P4_INT32;
313 aOp[1].p4.i = pTab->nCol+1;
314 aOp[3].p2 = pTab->nCol;
316 sParse.nVar = 0;
317 sParse.nMem = 1;
318 sParse.nTab = 1;
319 sqlite3VdbeMakeReady(v, &sParse);
323 pBlob->iCol = iCol;
324 pBlob->db = db;
325 sqlite3BtreeLeaveAll(db);
326 if( db->mallocFailed ){
327 goto blob_open_out;
329 rc = blobSeekToRow(pBlob, iRow, &zErr);
330 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
332 blob_open_out:
333 if( rc==SQLITE_OK && db->mallocFailed==0 ){
334 *ppBlob = (sqlite3_blob *)pBlob;
335 }else{
336 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
337 sqlite3DbFree(db, pBlob);
339 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
340 sqlite3DbFree(db, zErr);
341 sqlite3ParserReset(&sParse);
342 rc = sqlite3ApiExit(db, rc);
343 sqlite3_mutex_leave(db->mutex);
344 return rc;
348 ** Close a blob handle that was previously created using
349 ** sqlite3_blob_open().
351 int sqlite3_blob_close(sqlite3_blob *pBlob){
352 Incrblob *p = (Incrblob *)pBlob;
353 int rc;
354 sqlite3 *db;
356 if( p ){
357 db = p->db;
358 sqlite3_mutex_enter(db->mutex);
359 rc = sqlite3_finalize(p->pStmt);
360 sqlite3DbFree(db, p);
361 sqlite3_mutex_leave(db->mutex);
362 }else{
363 rc = SQLITE_OK;
365 return rc;
369 ** Perform a read or write operation on a blob
371 static int blobReadWrite(
372 sqlite3_blob *pBlob,
373 void *z,
374 int n,
375 int iOffset,
376 int (*xCall)(BtCursor*, u32, u32, void*)
378 int rc;
379 Incrblob *p = (Incrblob *)pBlob;
380 Vdbe *v;
381 sqlite3 *db;
383 if( p==0 ) return SQLITE_MISUSE_BKPT;
384 db = p->db;
385 sqlite3_mutex_enter(db->mutex);
386 v = (Vdbe*)p->pStmt;
388 if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
389 /* Request is out of range. Return a transient error. */
390 rc = SQLITE_ERROR;
391 }else if( v==0 ){
392 /* If there is no statement handle, then the blob-handle has
393 ** already been invalidated. Return SQLITE_ABORT in this case.
395 rc = SQLITE_ABORT;
396 }else{
397 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
398 ** returned, clean-up the statement handle.
400 assert( db == v->db );
401 sqlite3BtreeEnterCursor(p->pCsr);
403 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
404 if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
405 /* If a pre-update hook is registered and this is a write cursor,
406 ** invoke it here.
408 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
409 ** operation should really be an SQLITE_UPDATE. This is probably
410 ** incorrect, but is convenient because at this point the new.* values
411 ** are not easily obtainable. And for the sessions module, an
412 ** SQLITE_UPDATE where the PK columns do not change is handled in the
413 ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
414 ** slightly more efficient). Since you cannot write to a PK column
415 ** using the incremental-blob API, this works. For the sessions module
416 ** anyhow.
418 sqlite3_int64 iKey;
419 iKey = sqlite3BtreeIntegerKey(p->pCsr);
420 sqlite3VdbePreUpdateHook(
421 v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
424 #endif
426 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
427 sqlite3BtreeLeaveCursor(p->pCsr);
428 if( rc==SQLITE_ABORT ){
429 sqlite3VdbeFinalize(v);
430 p->pStmt = 0;
431 }else{
432 v->rc = rc;
435 sqlite3Error(db, rc);
436 rc = sqlite3ApiExit(db, rc);
437 sqlite3_mutex_leave(db->mutex);
438 return rc;
442 ** Read data from a blob handle.
444 int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
445 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
449 ** Write data to a blob handle.
451 int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
452 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
456 ** Query a blob handle for the size of the data.
458 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
459 ** so no mutex is required for access.
461 int sqlite3_blob_bytes(sqlite3_blob *pBlob){
462 Incrblob *p = (Incrblob *)pBlob;
463 return (p && p->pStmt) ? p->nByte : 0;
467 ** Move an existing blob handle to point to a different row of the same
468 ** database table.
470 ** If an error occurs, or if the specified row does not exist or does not
471 ** contain a blob or text value, then an error code is returned and the
472 ** database handle error code and message set. If this happens, then all
473 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
474 ** immediately return SQLITE_ABORT.
476 int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
477 int rc;
478 Incrblob *p = (Incrblob *)pBlob;
479 sqlite3 *db;
481 if( p==0 ) return SQLITE_MISUSE_BKPT;
482 db = p->db;
483 sqlite3_mutex_enter(db->mutex);
485 if( p->pStmt==0 ){
486 /* If there is no statement handle, then the blob-handle has
487 ** already been invalidated. Return SQLITE_ABORT in this case.
489 rc = SQLITE_ABORT;
490 }else{
491 char *zErr;
492 rc = blobSeekToRow(p, iRow, &zErr);
493 if( rc!=SQLITE_OK ){
494 sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
495 sqlite3DbFree(db, zErr);
497 assert( rc!=SQLITE_SCHEMA );
500 rc = sqlite3ApiExit(db, rc);
501 assert( rc==SQLITE_OK || p->pStmt==0 );
502 sqlite3_mutex_leave(db->mutex);
503 return rc;
506 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */