swiftsqlite.swift

How could I rollback a transaction when throwing custom errors


I have a bulk insert method that attempts to insert an array of items within a transaction. However, I have custom errors I throw based on the values being passed in. For example, strings can not be empty (which is a valid String value for sqlite).

How could I rollback the transaction if I throw my custom error?

Currently, when the error is throw, that insert operation is skipped. So if I am adding 10 items, and 1 item has a invalid empty string, my transaction is inserting 9 items.

https://gist.github.com/tinder-calebdavis/90b8658f6494e3f2836d9ab53391834c


Solution

  • This might not be the best answer, but I ended up running my own validation checks before starting the transaction.

    If my validation throws an error, the transaction will never begin.

    I considered adding a constraint to my column, or even a trigger, but it was not easy for me to figure out the syntax to do that. Having a constraint or trigger would of been nice because I could of received an actual SQL error causing the transaction to roll back.