Search code examples
objective-ciossqlitefmdb

iOS SQLite FMDB Transactions.. Correct usage?


I'm just going to try out using transactions with the FMDB SQLite iOS wrapper.

The documentation is a little vague on transactions but from having a quick look at some functions I have come up with the following logic:

[fmdb beginTransaction];
    // Run the following query
    BOOL res1 = [fmdb executeUpdate:@"query1"];
    BOOL res2 = [fmdb executeUpdate:@"query2"];

if(!res1 || !res2) [fmdb rollback];
else [fmdb commit];

Solution

  • I wouldn't try to do the second update if the first failed.

    bool ret = false;
    [fmdb beginTransaction];
    ret = [fmdb executeUpdate:@"query1"];
    if (ret)
    {
        ret = [fmdb executeUpdate:@"query2"];
        if (!ret)
        {
             // report error 2
        }
    }
    
    if(ret) 
    {
        if (![fmdb commit])
        {
            // panic!
        }
    }
    else
    {
        if (![fmdb rollback])
        {
            // panic!
        }
    }
    

    For paranoid robustness you should have a try ... catch block in case anything throws an exception. If you do, you can use it to your advantage.

    [fmdb beginTransaction];
    @try
    {
        if (![fmdb executeUpdate:@"query1"])
        {
            // report error
            @throw someExcpetion;
        }
        if (![fmdb executeUpdate:@"query2"])
        {
            // report error
            @throw someExcpetion;
        }
        [fmdb commit]
    }
    @catch(NSException* e)
    {
        [fmdb rollback];
        // rethrow if not one of the two exceptions above
    }