liveBook · Manning

withTransaction

As explained in Learn Haskell by Example

withTransaction is a sqlite-simple function that runs an action within a database transaction and rolls it back if the action fails.

withTransaction runs an IO action inside a SQLite transaction: it begins the transaction, commits on success, and rolls back when the action throws an exception. Rollback leaves the database unchanged. section 16.3.3

Adding an entry safely

addEntry dbConn entry = try $ withTransaction dbConn $ do execute dbConn "INSERT INTO entries (id, text, checked, rank) VALUES (?,?,?,?)" entry newIdx <- lastInsertRowId dbConn return $ fromIntegral newIdx The surrounding try returns an SQLError instead of hiding a failed insert, while the transaction prevents a partial database change. section 16.3.3

How Learn Haskell by Example covers it

How deep it goes
Explains the begin-commit-rollback lifecycle and demonstrates it around insert and update actions.
Examples
Uses TodoEntry insertion, lastInsertRowId, duplicate identifiers, and checked-field updates as concrete transactional operations.
What it assumes
Assumes a SQLite Connection, IO actions, and basic database execution; teaches failure rollback through a concrete insert.
What you can do after
Operate SQLite writes transactionally and return database errors while preserving database consistency after failures.
How it connects
Connects database transactions with SQLite, exception handling, execute, INSERT statements, and primary-key failures.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.