liveBook · Manning

Database transaction

As explained in Learn Haskell by Example

A database transaction is a sequence of operations treated as one atomic unit that can be committed or rolled back.

A database transaction groups operations into one unit: successful actions are committed, while exceptions roll them back so the database remains unchanged. section 16.3.3

Adding a todo entry safely

Wrap the INSERT and last-inserted-ID lookup in withTransaction. Catch SQLError with try, returning either the error or the new row ID; duplicate primary keys therefore do not leave a partial change. section 16.3.3

Listing 16.10 A function to add a TodoEntry to the database
import Control.Exception (try)

...

addEntry :: Connection -> TodoEntry -> IO (Either SQLError Int)
addEntry dbConn entry = try $  #1
  withTransaction dbConn $ do  #2
    execute  #3
      dbConn
      "INSERT INTO entries (id, text, checked, rank) \
      \ VALUES (?,?,?,?)"
      entry
    newIdx <- lastInsertRowId dbConn  #4
    return $ fromIntegral newIdx  #5

See the complete Haskell implementation combining try, withTransaction, INSERT, and lastInsertRowId. section 16.3.3

How Learn Haskell by Example covers it

How deep it goes
Explains the BEGIN, action, COMMIT, and ROLLBACK sequence and stops short of broader transaction management.
Examples
Uses todo-entry insertion, duplicate IDs, last-inserted row IDs, and checked-field updates as concrete cases.
What it assumes
Assumes a SQLite connection, SQL statements, table constraints, and Control.Exception's try function.
What you can do after
Apply it via Database.SQLite.Simple to commit grouped actions or roll them back after exceptions.
How it connects
Connects transactions with SQLite, SQL INSERT and UPDATE statements, primary keys, exceptions, and error results.

Also explained in

Compare how 14 books explain database transaction →

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.