vdbeblob.c

Go to the documentation of this file.
00001 /*
00002 ** 2007 May 1
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 **
00013 ** This file contains code used to implement incremental BLOB I/O.
00014 **
00015 ** $Id: vdbeblob.c,v 1.26 2008/10/02 14:49:02 danielk1977 Exp $
00016 */
00017 
00018 #include "sqliteInt.h"
00019 #include "vdbeInt.h"
00020 
00021 #ifndef SQLITE_OMIT_INCRBLOB
00022 
00023 /*
00024 ** Valid sqlite3_blob* handles point to Incrblob structures.
00025 */
00026 typedef struct Incrblob Incrblob;
00027 struct Incrblob {
00028   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
00029   int nByte;              /* Size of open blob, in bytes */
00030   int iOffset;            /* Byte offset of blob in cursor data */
00031   BtCursor *pCsr;         /* Cursor pointing at blob row */
00032   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
00033   sqlite3 *db;            /* The associated database */
00034 };
00035 
00036 /*
00037 ** Open a blob handle.
00038 */
00039 int sqlite3_blob_open(
00040   sqlite3* db,            /* The database connection */
00041   const char *zDb,        /* The attached database containing the blob */
00042   const char *zTable,     /* The table containing the blob */
00043   const char *zColumn,    /* The column containing the blob */
00044   sqlite_int64 iRow,      /* The row containing the glob */
00045   int flags,              /* True -> read/write access, false -> read-only */
00046   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
00047 ){
00048   int nAttempt = 0;
00049   int iCol;               /* Index of zColumn in row-record */
00050 
00051   /* This VDBE program seeks a btree cursor to the identified 
00052   ** db/table/row entry. The reason for using a vdbe program instead
00053   ** of writing code to use the b-tree layer directly is that the
00054   ** vdbe program will take advantage of the various transaction,
00055   ** locking and error handling infrastructure built into the vdbe.
00056   **
00057   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
00058   ** Code external to the Vdbe then "borrows" the b-tree cursor and
00059   ** uses it to implement the blob_read(), blob_write() and 
00060   ** blob_bytes() functions.
00061   **
00062   ** The sqlite3_blob_close() function finalizes the vdbe program,
00063   ** which closes the b-tree cursor and (possibly) commits the 
00064   ** transaction.
00065   */
00066   static const VdbeOpList openBlob[] = {
00067     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
00068     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
00069 
00070     /* One of the following two instructions is replaced by an
00071     ** OP_Noop before exection.
00072     */
00073     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
00074     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
00075     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
00076     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
00077 
00078     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
00079     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
00080     {OP_Column, 0, 0, 1},          /* 8  */
00081     {OP_ResultRow, 1, 0, 0},       /* 9  */
00082     {OP_Close, 0, 0, 0},           /* 10  */
00083     {OP_Halt, 0, 0, 0},            /* 11 */
00084   };
00085 
00086   Vdbe *v = 0;
00087   int rc = SQLITE_OK;
00088   char zErr[128];
00089 
00090   zErr[0] = 0;
00091   sqlite3_mutex_enter(db->mutex);
00092   do {
00093     Parse sParse;
00094     Table *pTab;
00095 
00096     memset(&sParse, 0, sizeof(Parse));
00097     sParse.db = db;
00098 
00099     if( sqlite3SafetyOn(db) ){
00100       sqlite3_mutex_leave(db->mutex);
00101       return SQLITE_MISUSE;
00102     }
00103 
00104     sqlite3BtreeEnterAll(db);
00105     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
00106     if( pTab && IsVirtual(pTab) ){
00107       pTab = 0;
00108       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
00109     }
00110 #ifndef SQLITE_OMIT_VIEW
00111     if( pTab && pTab->pSelect ){
00112       pTab = 0;
00113       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
00114     }
00115 #endif
00116     if( !pTab ){
00117       if( sParse.zErrMsg ){
00118         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
00119       }
00120       sqlite3DbFree(db, sParse.zErrMsg);
00121       rc = SQLITE_ERROR;
00122       (void)sqlite3SafetyOff(db);
00123       sqlite3BtreeLeaveAll(db);
00124       goto blob_open_out;
00125     }
00126 
00127     /* Now search pTab for the exact column. */
00128     for(iCol=0; iCol < pTab->nCol; iCol++) {
00129       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
00130         break;
00131       }
00132     }
00133     if( iCol==pTab->nCol ){
00134       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
00135       rc = SQLITE_ERROR;
00136       (void)sqlite3SafetyOff(db);
00137       sqlite3BtreeLeaveAll(db);
00138       goto blob_open_out;
00139     }
00140 
00141     /* If the value is being opened for writing, check that the
00142     ** column is not indexed. It is against the rules to open an
00143     ** indexed column for writing.
00144     */
00145     if( flags ){
00146       Index *pIdx;
00147       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00148         int j;
00149         for(j=0; j<pIdx->nColumn; j++){
00150           if( pIdx->aiColumn[j]==iCol ){
00151             sqlite3_snprintf(sizeof(zErr), zErr,
00152                              "cannot open indexed column for writing");
00153             rc = SQLITE_ERROR;
00154             (void)sqlite3SafetyOff(db);
00155             sqlite3BtreeLeaveAll(db);
00156             goto blob_open_out;
00157           }
00158         }
00159       }
00160     }
00161 
00162     v = sqlite3VdbeCreate(db);
00163     if( v ){
00164       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
00165       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
00166 
00167       /* Configure the OP_Transaction */
00168       sqlite3VdbeChangeP1(v, 0, iDb);
00169       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
00170 
00171       /* Configure the OP_VerifyCookie */
00172       sqlite3VdbeChangeP1(v, 1, iDb);
00173       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
00174 
00175       /* Make sure a mutex is held on the table to be accessed */
00176       sqlite3VdbeUsesBtree(v, iDb); 
00177 
00178       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
00179       ** parameter of the other to pTab->tnum. 
00180       */
00181       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
00182       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
00183       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
00184 
00185       /* Configure the OP_SetNumColumns. Configure the cursor to
00186       ** think that the table has one more column than it really
00187       ** does. An OP_Column to retrieve this imaginary column will
00188       ** always return an SQL NULL. This is useful because it means
00189       ** we can invoke OP_Column to fill in the vdbe cursors type 
00190       ** and offset cache without causing any IO.
00191       */
00192       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
00193       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
00194       if( !db->mallocFailed ){
00195         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
00196       }
00197     }
00198    
00199     sqlite3BtreeLeaveAll(db);
00200     rc = sqlite3SafetyOff(db);
00201     if( rc!=SQLITE_OK || db->mallocFailed ){
00202       goto blob_open_out;
00203     }
00204 
00205     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
00206     rc = sqlite3_step((sqlite3_stmt *)v);
00207     if( rc!=SQLITE_ROW ){
00208       nAttempt++;
00209       rc = sqlite3_finalize((sqlite3_stmt *)v);
00210       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
00211       v = 0;
00212     }
00213   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
00214 
00215   if( rc==SQLITE_ROW ){
00216     /* The row-record has been opened successfully. Check that the
00217     ** column in question contains text or a blob. If it contains
00218     ** text, it is up to the caller to get the encoding right.
00219     */
00220     Incrblob *pBlob;
00221     u32 type = v->apCsr[0]->aType[iCol];
00222 
00223     if( type<12 ){
00224       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
00225           type==0?"null": type==7?"real": "integer"
00226       );
00227       rc = SQLITE_ERROR;
00228       goto blob_open_out;
00229     }
00230     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
00231     if( db->mallocFailed ){
00232       sqlite3DbFree(db, pBlob);
00233       goto blob_open_out;
00234     }
00235     pBlob->flags = flags;
00236     pBlob->pCsr =  v->apCsr[0]->pCursor;
00237     sqlite3BtreeEnterCursor(pBlob->pCsr);
00238     sqlite3BtreeCacheOverflow(pBlob->pCsr);
00239     sqlite3BtreeLeaveCursor(pBlob->pCsr);
00240     pBlob->pStmt = (sqlite3_stmt *)v;
00241     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
00242     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
00243     pBlob->db = db;
00244     *ppBlob = (sqlite3_blob *)pBlob;
00245     rc = SQLITE_OK;
00246   }else if( rc==SQLITE_OK ){
00247     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
00248     rc = SQLITE_ERROR;
00249   }
00250 
00251 blob_open_out:
00252   zErr[sizeof(zErr)-1] = '\0';
00253   if( rc!=SQLITE_OK || db->mallocFailed ){
00254     sqlite3_finalize((sqlite3_stmt *)v);
00255   }
00256   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
00257   rc = sqlite3ApiExit(db, rc);
00258   sqlite3_mutex_leave(db->mutex);
00259   return rc;
00260 }
00261 
00262 /*
00263 ** Close a blob handle that was previously created using
00264 ** sqlite3_blob_open().
00265 */
00266 int sqlite3_blob_close(sqlite3_blob *pBlob){
00267   Incrblob *p = (Incrblob *)pBlob;
00268   int rc;
00269 
00270   rc = sqlite3_finalize(p->pStmt);
00271   sqlite3DbFree(p->db, p);
00272   return rc;
00273 }
00274 
00275 /*
00276 ** Perform a read or write operation on a blob
00277 */
00278 static int blobReadWrite(
00279   sqlite3_blob *pBlob, 
00280   void *z, 
00281   int n, 
00282   int iOffset, 
00283   int (*xCall)(BtCursor*, u32, u32, void*)
00284 ){
00285   int rc;
00286   Incrblob *p = (Incrblob *)pBlob;
00287   Vdbe *v;
00288   sqlite3 *db = p->db;  
00289 
00290   sqlite3_mutex_enter(db->mutex);
00291   v = (Vdbe*)p->pStmt;
00292 
00293   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
00294     /* Request is out of range. Return a transient error. */
00295     rc = SQLITE_ERROR;
00296     sqlite3Error(db, SQLITE_ERROR, 0);
00297   } else if( v==0 ){
00298     /* If there is no statement handle, then the blob-handle has
00299     ** already been invalidated. Return SQLITE_ABORT in this case.
00300     */
00301     rc = SQLITE_ABORT;
00302   }else{
00303     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
00304     ** returned, clean-up the statement handle.
00305     */
00306     assert( db == v->db );
00307     sqlite3BtreeEnterCursor(p->pCsr);
00308     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
00309     sqlite3BtreeLeaveCursor(p->pCsr);
00310     if( rc==SQLITE_ABORT ){
00311       sqlite3VdbeFinalize(v);
00312       p->pStmt = 0;
00313     }else{
00314       db->errCode = rc;
00315       v->rc = rc;
00316     }
00317   }
00318   rc = sqlite3ApiExit(db, rc);
00319   sqlite3_mutex_leave(db->mutex);
00320   return rc;
00321 }
00322 
00323 /*
00324 ** Read data from a blob handle.
00325 */
00326 int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
00327   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
00328 }
00329 
00330 /*
00331 ** Write data to a blob handle.
00332 */
00333 int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
00334   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
00335 }
00336 
00337 /*
00338 ** Query a blob handle for the size of the data.
00339 **
00340 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
00341 ** so no mutex is required for access.
00342 */
00343 int sqlite3_blob_bytes(sqlite3_blob *pBlob){
00344   Incrblob *p = (Incrblob *)pBlob;
00345   return p->nByte;
00346 }
00347 
00348 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:57 2011 by Doxygen 1.6.1