Thursday, April 26, 2012

sqlite+iPhone - Check if table exists

 

Progressing now with implementing db schema/data version upgrade for one of my iPhone apps – Here&Near. Location notes and tools. So I thought I’d share a snippet for checking if table exists:

+(bool) tableExistsWithName: (NSString *) name dbPath: (NSString *) dbPath error: (NSError **) error
{
    sqlite3 *db;
    sqlite3_stmt *checkStmt;
    
    int dbrc;
    const char* dbFilePathUTF8 = [dbPath UTF8String]; 
    dbrc = sqlite3_open_v2(dbFilePathUTF8, &db, SQLITE_OPEN_READONLY, nil); 
    
    const char *sql = "select count(*) from sqlite_master where type='table' AND name=?";
    
    if(sqlite3_prepare_v2(db, sql, -1, &checkStmt, NULL) == SQLITE_OK)
    {
        const char *cname = [name UTF8String];
        
        sqlite3_bind_text(checkStmt, 1, cname, -1, SQLITE_TRANSIENT);
        
        int retCode = sqlite3_step(checkStmt);
        
        if(SQLITE_ROW == retCode)
        {
            int count = sqlite3_column_int(checkStmt, 0);
            sqlite3_finalize(checkStmt);
            sqlite3_close(db);
            
            return count == 1;
        }
        else 
        {
            
            [DbHelper convertSqlError:db error:error];
            
            sqlite3_finalize(checkStmt);
            sqlite3_close(db);
            return false;
        }
    }
    else {
        [DbHelper convertSqlError:db error:error];
        
        sqlite3_finalize(checkStmt);
        sqlite3_close(db);
        
        return false;
    }
    
    return false;
}

Where [DbHelper convertSqlError:db error:error] is explained in the previous entry.

I guess I have some semantic mess with NSError in the above code, but providing as it is right now…

No comments: