Running two queries in one transaction
In the example below, the first query returns an email address. The second counts the articles written by the account at that address. Follow the value called email from one query into the other.
Keep the queries together
Use a Sql.Session when several steps belong on the same connection. It’s fine for a helper to return a session. The helper describes the work, and its caller decides which other steps should commit along with it.
Start the transaction
Each separate sql block in do IO<…> runs in its own transaction. To give several steps one commit, put them in do Sql.Session<A>. In a Bwf server, run the session on the application pool with Sql.application_transaction. With your own pool, use Sql.transaction(A, pool, action).
Sql.application_transaction(Sql.Integer, author_article_count())Follow the email address
Read the line beginning email <-. For this little example it selects a literal, so we know exactly what it will return. In the next query, ${email} is a bound parameter. Try substituting the address of an author in your own Journal in that first line.
Within the session you can use the integer count directly. Outside it you get IO(Sql.Outcome(A)), since running the transaction can fail. An unhandled failure rolls back the transaction. To ask for a rollback yourself, use Sql.Session.fail(A, message).
def author_article_count() -> Sql.Session<Sql.Integer>:
do Sql.Session<Sql.Integer>:
email <- sql """SELECT 'reader@example.test'::text"""
count <- sql """
SELECT COUNT(*) FROM articles
JOIN users ON users.id = articles.author_id
WHERE users.email = ${email}
"""
return countHere the second statement needs the first one’s result. For independent statements you can also use a typed pipeline.
Recover from one failed step
Imagine one update is optional. If you need to inspect its failure and carry on, wrap the update in Sql.Session.attempt(A, action). That gives you its outcome after rolling the failed step back to a savepoint. Sql.Session.transaction(A, action) also uses a savepoint, but propagates the error. A successful inner step still depends on the outer commit.
Inside a session the optional update looks like this.
result <- Sql.Session.attempt(Sql.Integer, Sql.execute(Sql.Integer, update))