liveBook · Manning

executeNamed

As explained in Learn Haskell by Example

executeNamed is a sqlite-simple function that executes an SQL statement using named parameters supplied from a Haskell value.

executeNamed executes a SQL statement that does not return rows, filling named placeholders from a list of NamedParam values. Its type is Connection -> Query -> [NamedParam] -> IO (). section 16.3.1

Use executeNamed when:

  • The statement is an INSERT, UPDATE, or DELETE rather than a row-returning SELECT. section 16.3.1
  • The SQL identifies values with named placeholders such as :checked or @checked. section 16.3.3
  • The Haskell code supplies matching parameters with the (:=) syntax, such as [":id" := entryId entry]. section 16.3.3

Updating one TodoEntry

updateEntry dbConn entry = withTransaction dbConn $ executeNamed dbConn "UPDATE entries SET checked = :checked WHERE id = :id" [":checked" := checked entry, ":id" := entryId entry] The SQL names the values it needs, while the parameter list takes them from the TodoEntry. If a placeholder appears in the query without a matching parameter, executeNamed raises a FormatError exception. section 16.3.3

Listing 16.11 Functions to retrieve a TodoEntry from the database and update it
getEntryById :: Connection -> Int -> IO (Maybe TodoEntry)
getEntryById dbConn rowId = do
  entries <- query dbConn "SELECT * from entries
 where id = ?" (Only rowId)  #1
  case entries of
    [x] -> return $ Just x     #2
    _ -> return Nothing        #2

updateEntry :: Connection -> TodoEntry -> IO ()
updateEntry dbConn entry =
  withTransaction dbConn $  #3
    executeNamed  #4
      dbConn
      "UPDATE entries SET checked =
 :checked WHERE id = :id"  #5
      [":checked" := checked entry,
 ":id" := entryId entry]   #5

Inspect the complete getEntryById and updateEntry implementation, including the transaction boundary and named parameter list. section 16.3.3

How Learn Haskell by Example covers it

How deep it goes
Explains the type, placeholder syntax, parameter construction, and missing-parameter failure through a working update.
Examples
Uses a TodoEntry update that assigns checked by id and a GHCi update of rows using :data and :id.
What it assumes
Assumes a sqlite-simple Connection and basic SQL, while demonstrating parameter binding through a concrete TodoEntry update.
What you can do after
Apply it via sqlite-simple to update database rows using readable named placeholders and matching Haskell values.
How it connects
Connects named parameters with SQL UPDATE statements, Haskell records, database connections, and transactions.

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.