Published: 9th November 2026
In my previous article, I demonstrated how to emulate existential quantification with dependent types. That is, situations where types depend on values generally only known at runtime.
You may be unconvinced about the benefits of the whole machinery though. And honestly, I wouldn’t really blame you. A programming language is a tool and like any other tool, it has its appropriate as well as inappropriate uses. Is the introduction of the math-heavy terminology really worth it…?
So this time, I explore an area where I think dependent types really shine: modelling state machines. I describe a typical lifecycle of a database transaction, how to encode it as a data type in Idris 2 and enforce correct sequencing of operations on the type-level.
This article explains my motivation and covers definitions and a basic model of a transaction. Subsequent one(s) will cover more advanced topics like nesting, state transitions depending on the result of an operation and others.
Disclaimer: It’s a shame I need to even mention it,
but the year is 2026 and folks are trying to cut corners with their
(ab)use of generative AI. This article is written by me and me
only.
I prompted myself to “Make no mistakes.”. But I am just a guy on the Internet, so double-check everything.
Whether we like it or not, interaction with a database turns our program into a distributed system. That means actors we may not even be aware of can bring down our program or make it produce incorrect results.
Therefore, when interacting with a database, at minimum I want to know if I am in an active transaction and what’s the transaction isolation level. This tells me if I need to move my ass quickly and also the anomalies like Lost Update or Phantom Read I need to take into account.
To elaborate further, transactions create an illusion (which is stronger the higher the isolation level is) that a program is the sole client of the database management system (DBMS). This allows (to some degree!) reasoning about the program locally (still hard, don’t get me wrong), as opposed to conducting an analysis of a system as a whole (may be impossible due to incomplete knowledge).
However, even program analysis may be intractable. We want to be able to reason about an individual function, or any other unit of code that preferably fits on one screen, as much as possible.
In the context of databases, what I found helps local reasoning are nested transactions, if the DBMS supports them. (PostgreSQL and sqlite do)
Nested transactions are blocks inside a transaction that may be individually commited or aborted, yet the overall behaviour is still governed by the “host” transaction being committed or aborted. They simplify error handling needed to be performed by a program, because just a portion of a transaction may be aborted, as opposed to the transaction as a whole.
So in addition to the isolation level, I want to know if I am in a nested transaction or not. Because without this knowledge, I cannot reason about a piece of code locally, but need to inspect all the callers!
TL;DR: Interacting with a database is hard. I would welcome a tool that helps local reasoning about interactions with the DB, checks them before they are actually performed and emits a warning if something seems sketchy. To put my money where my mouth is, I am trying to build such a tool. This and following articles document my journey.
TxBasicTo explain the basic concepts first, I create a model of a transaction without nesting. In Idris, I represent it as:
module TxModelling
%default total
data TxPhase = INIT
| RUNNING
| COMMITTED
| ABORTED
-- `namespace` is a scoping mechanism allowing declarations of entities with
-- the same name, as long as they are defined in a different namespace.
-- Consult `:doc namespace` in the REPL for more info.
namespace TxBasic
-- `public export` makes the type as well as data constructors available
-- outside the namespace.
-- By default, all declarations within a namespace are `private`.
-- Consult `:doc export` in the REPL for more info.
public export
data TxOp : TxPhase -> TxPhase -> Type where
Begin : TxOp INIT RUNNING
Commit : TxOp RUNNING COMMITTED
Abort : TxOp RUNNING ABORTED
Execute : (s : String) -> TxOp RUNNING RUNNING
public export
data Tx : TxPhase -> TxPhase -> Type where
Op : TxOp inState outState -> Tx inState outState
Seq : Tx inState1 RUNNING ->
Tx RUNNING outState2 ->
Tx inState1 outState2Transaction state is modelled as an enumeration TxPhase.
INIT is the intial state, COMMITTED and
ABORTED are the terminal states.
I declare TxOp, a representation of a single transaction
operation, as a data type indexed by TxPhase twice. Its
data constructors model the state transition function and indexes denote
the state before and after transition.
As an example:
txOp1 : TxOp INIT RUNNING
txOp1 = Begin
txOp2 : TxOp RUNNING RUNNING
txOp2 = Execute "SELECT * FROM tbl;"txOp1 requires the transaction state to be
INIT. After txOp1 action, the state is changed
to RUNNING.
Similarly, txOp2 requires the
state to be RUNNING and its action does not change the
state.
I split the sequencing of TxOp operations into a
separate data type Tx. Tx.Op constructor lifts
the TxOp value into Tx.
The crucial insight here is that two transaction operations
(Tx values) can be sequenced by Tx.Seq only
when the first one ends in RUNNING state and the second one
begins in RUNNING state!
That alone statically rules out incorrect sequencing like multiple
BEGIN/COMMIT/ROLLBACK, statement execution without a
BEGIN, etc.
Consider the continuation of the code block above, where I show
examples of correct sequencing and use the failing blocks
as proofs that incorrect sequencing is rejected by the type-checker:
namespace TxBasic
-- ... snipped code ...
public export
begin : Tx INIT RUNNING
begin = Op Begin
public export
commit : Tx RUNNING COMMITTED
commit = Op Commit
public export
abort : Tx RUNNING ABORTED
abort = Op Abort
public export
execute : String -> Tx RUNNING RUNNING
execute s = Op (Execute s)
-- Namespaces can be nested.
namespace TxDo
-- Syntactic gadget that allows constructing `Tx.Seq` values in a `do`-block.
public export
(>>) : Tx inState1 RUNNING ->
Tx RUNNING outState2 ->
Tx inState1 outState2
(>>) = Seq
testTxHappyPath : Tx INIT COMMITTED
testTxHappyPath = do
begin
execute "SELECT 1;"
commit
failing "Mismatch between: INIT and RUNNING"
testTxDoubleBegin : Tx INIT COMMITTED
testTxDoubleBegin = do
begin
begin
failing "Mismatch between: RUNNING and COMMITTED"
testTxWithoutCommit : Tx INIT COMMITTED
testTxWithoutCommit = do
begin
execute "SELECT 1;"
execute "SELECT 2;"
-- As you can see, changing `COMMITTED` to `RUNNING` makes the type-checker
-- happy.
testTxWithoutCommitRunning : Tx INIT RUNNING
testTxWithoutCommitRunning = do
begin
execute "SELECT 1;"
execute "SELECT 2;"
failing "Mismatch between: RUNNING and INIT"
testTxExecuteWithoutBegin : Tx INIT COMMITTED
testTxExecuteWithoutBegin = do
execute "SELECT 1;"
commit
failing "Mismatch between: COMMITTED and RUNNING"
testTxBeginAfterCommit : Tx INIT RUNNING
testTxBeginAfterCommit = do
begin
commit
beginbegin/commit/abort/execute functions are provided as a
shortcut for returning a value of type Tx directly instead
of TxOp.
Of note is the (>>) operator, which allows writing
sequences of computations without binding the results in what is called
a do-block (yes, it’s the same do used in
monads and burritos…).
Binding requires the
(>>=) operator and it will be defined in later
articles. It is not needed now.
The testTxHappyPath is then desugared to:
namespace TxBasic
-- ... snipped code ...
testTxHappyPath : Tx INIT COMMITTED
testTxHappyPath = do
begin
execute "SELECT 1;"
commit
-- Desugaring of the `do`-block to a chain of `(>>)` operators.
-- Consult `:doc do` for more info.
testTxHappyPathDesugared : Tx INIT COMMITTED
testTxHappyPathDesugared =
begin >>
execute "SELECT 1;" >>
commit
testTxHappyPathDesugared2 : Tx INIT COMMITTED
testTxHappyPathDesugared2 =
Seq begin (
Seq (execute "SELECT 1;") commit
)That’s all there is to a model of a transaction without nesting. Very
similar model can be applied to socket operations -
BIND/SEND/RECV/ACCEPT/..., simple locking protocols -
ACQUIRE/RELEASE, etc.
Something to keep in mind when working with dependent types that took me some time to digest.
There is a distinction between constructing a type and constructing a value of said type. To represent an operation that takes a running transaction and produces a fresh one, nothing stops me from constructing a following type:
FunkyTransition : Type
FunkyTransition = TxOp RUNNING INITIt is a perfectly valid expression evaluating to a type.
However, with the way our data constructors are defined, there is no way
to construct a value of this type!
namespace TxBasic
-- ... snipped code ...
FunkyTransition : Type
FunkyTransition = TxOp RUNNING INIT
-- How to construct it though? All 4 data constructors report a type error.
funky : FunkyTransition
failing "Mismatch between: RUNNING and INIT"
funky = Begin
failing "Mismatch between: COMMITTED and INIT"
funky = Commit
failing "Mismatch between: ABORTED and INIT"
funky = Abort
failing "Mismatch between: RUNNING and INIT"
funky = Execute "SELECT 1;"If you look at this phenomenon through the “propositions as types” lens, types correspond to propositions and values correspond to their proofs. Therefore, constructing a value of an uninhabited type corresponds to “proving” false!
The model may seem trivial, but from my experience working on database-backed Python programs and applications, it is far from obvious when the program is in a transaction and what transaction isolation level it requires. Especially if it has been worked on for some time and by multiple people.
One of my original motivations for this research and seeking something better was precisely this: do I really need to keep the whole program in my head? How can I offload part of the burden to a computer?
Please note that in the basic form, it is something that mainstream programming languages are capable of as well. Techniques like “Typestate pattern” or “Phantom type” can solve precisely this use case. In Appendix B, I show you how to do it in Python.
I sincerely hope you learnt something new by reading this article and it wasn’t a complete waste of time.
I had originally planned to include transaction nesting in this
article. But the TxOp and Tx data types
indexed by the before&after value of type TxPhase can
be hard to grasp at first, just as the explanation of uninhabited types
and the (>>) syntactic gadget.
So I decided to split it. In next installment, I will augment the model to also account for (a simplified version of) transaction nesting. Stay tuned!
To have the complete program at hand, it is provided here in its
entirety. You can download it to TxModelling.idr and launch
a REPL:
module TxModelling
%default total
data TxPhase = INIT
| RUNNING
| COMMITTED
| ABORTED
-- `namespace` is a scoping mechanism allowing declarations of entities with
-- the same name, as long as they are defined in a different namespace.
-- Consult `:doc namespace` in the REPL for more info.
namespace TxBasic
-- `public export` makes the type as well as data constructors available
-- outside the namespace.
-- By default, all declarations within a namespace are `private`.
-- Consult `:doc export` in the REPL for more info.
public export
data TxOp : TxPhase -> TxPhase -> Type where
Begin : TxOp INIT RUNNING
Commit : TxOp RUNNING COMMITTED
Abort : TxOp RUNNING ABORTED
Execute : (s : String) -> TxOp RUNNING RUNNING
public export
data Tx : TxPhase -> TxPhase -> Type where
Op : TxOp inState outState -> Tx inState outState
Seq : Tx inState1 RUNNING ->
Tx RUNNING outState2 ->
Tx inState1 outState2
txOp1 : TxOp INIT RUNNING
txOp1 = Begin
txOp2 : TxOp RUNNING RUNNING
txOp2 = Execute "SELECT * FROM tbl;"
public export
begin : Tx INIT RUNNING
begin = Op Begin
public export
commit : Tx RUNNING COMMITTED
commit = Op Commit
public export
abort : Tx RUNNING ABORTED
abort = Op Abort
public export
execute : String -> Tx RUNNING RUNNING
execute s = Op (Execute s)
-- Namespaces can be nested.
namespace TxDo
-- Syntactic gadget that allows constructing `Tx.Seq` values in a `do`-block.
public export
(>>) : Tx inState1 RUNNING ->
Tx RUNNING outState2 ->
Tx inState1 outState2
(>>) = Seq
testTxHappyPath : Tx INIT COMMITTED
testTxHappyPath = do
begin
execute "SELECT 1;"
commit
-- Desugaring of the `do`-block to a chain of `(>>)` operators.
-- Consult `:doc do` for more info.
testTxHappyPathDesugared : Tx INIT COMMITTED
testTxHappyPathDesugared =
begin >>
execute "SELECT 1;" >>
commit
testTxHappyPathDesugared2 : Tx INIT COMMITTED
testTxHappyPathDesugared2 =
Seq begin (
Seq (execute "SELECT 1;") commit
)
failing "Mismatch between: INIT and RUNNING"
testTxDoubleBegin : Tx INIT COMMITTED
testTxDoubleBegin = do
begin
begin
failing "Mismatch between: RUNNING and COMMITTED"
testTxWithoutCommit : Tx INIT COMMITTED
testTxWithoutCommit = do
begin
execute "SELECT 1;"
execute "SELECT 2;"
-- As you can see, changing `COMMITTED` to `RUNNING` makes the type-checker
-- happy.
testTxWithoutCommitRunning : Tx INIT RUNNING
testTxWithoutCommitRunning = do
begin
execute "SELECT 1;"
execute "SELECT 2;"
failing "Mismatch between: RUNNING and INIT"
testTxExecuteWithoutBegin : Tx INIT COMMITTED
testTxExecuteWithoutBegin = do
execute "SELECT 1;"
commit
failing "Mismatch between: COMMITTED and RUNNING"
testTxBeginAfterCommit : Tx INIT RUNNING
testTxBeginAfterCommit = do
begin
commit
begin
-- A perfectly valid expression evaluating to a type...
FunkyTransition : Type
FunkyTransition = TxOp RUNNING INIT
-- ...how to construct it though? All 4 data constructors report a type error.
funky : FunkyTransition
failing "Mismatch between: RUNNING and INIT"
funky = Begin
failing "Mismatch between: COMMITTED and INIT"
funky = Commit
failing "Mismatch between: ABORTED and INIT"
funky = Abort
failing "Mismatch between: RUNNING and INIT"
funky = Execute "SELECT 1;"Here is a possible solution to typesafe sequencing of database operations in Python.
from __future__ import annotations
import abc
import typing as t
# Abstract base class to contrain the type states.
class _TxPhase(abc.ABC): ...
# Concrete states.
class Init(_TxPhase): ...
class Running(_TxPhase): ...
class Committed(_TxPhase): ...
class Aborted(_TxPhase): ...
# `default` keyword is available only on Python>=3.13
# https://docs.python.org/3/library/typing.html#typing.TypeVar
#
# On earlier versions, write
# T = t.TypeVar("T", bound=_TxPhase)
T = t.TypeVar("T", bound=_TxPhase, default=Init)
class Tx(t.Generic[T]):
def begin(self: Tx[Init]) -> Tx[Running]: ...
def execute(self: Tx[Running], q: str) -> Tx[Running]: ...
def commit(self: Tx[Running]) -> Tx[Committed]: ...
def abort(self: Tx[Running]) -> Tx[Aborted]: ...
def main() -> None:
# Without `TypeVar` default, you need to write
# tx: Tx[Init] = Tx()
tx = Tx()
t.reveal_type(tx) # Tx[Init]
t.reveal_type(tx.begin()) # Tx[Running]
t.reveal_type(tx.begin().execute("SELECT 1;")) # Tx[Running]
t.reveal_type(tx.begin().execute("SELECT 1;").commit()) # Tx[Committed]
# Type errors caught:
tx.begin().begin() # Double "BEGIN"
tx.commit() # "COMMIT" without "BEGIN"
tx.begin().commit().execute("SELECT 1;") # Execute after "COMMIT"You can see the type parameter T, bounded from above by
_TxPhase, is unused in the Tx class, yet we
can annotate individual methods of Tx to be applicable to
only some subclasses of _TxPhase.
Running mypy (version 2.4.1) on this file:
$ mypy --strict --disable-error-code empty-body typestate.py
typestate.py:41: note: Revealed type is "typestate.Tx[typestate.Init]"
typestate.py:42: note: Revealed type is "typestate.Tx[typestate.Running]"
typestate.py:43: note: Revealed type is "typestate.Tx[typestate.Running]"
typestate.py:44: note: Revealed type is "typestate.Tx[typestate.Committed]"
typestate.py:47: error: Invalid self argument "Tx[Running]" to attribute function "begin" with type "Callable[[Tx[Init]], Tx[Running]]" [misc]
typestate.py:48: error: Invalid self argument "Tx[Init]" to attribute function "commit" with type "Callable[[Tx[Running]], Tx[Committed]]" [misc]
typestate.py:49: error: Invalid self argument "Tx[Committed]" to attribute function "execute" with type "Callable[[Tx[Running], str], Tx[Running]]" [misc]
Found 3 errors in 1 file (checked 1 source file)You can see that mypy is able to deduce the type after
sequencing and reject incorrect sequencing.
This pattern can be viewed as creating a class for each
_TxPhase subclass that only has methods pertaining to the
concrete _TxPhase and methods return objects of the
different classes (monomorphization of sorts):
from __future__ import annotations
import typing as t
class TxCommitted: ...
class TxAborted: ...
class TxRunning:
def execute(self, q: str) -> TxRunning: ...
def commit(self) -> TxCommitted: ...
def abort(self) -> TxAborted: ...
class TxInit:
def begin(self) -> TxRunning: ...
def main() -> None:
tx = TxInit()
t.reveal_type(tx) # TxInit
t.reveal_type(tx.begin()) # TxRunning
t.reveal_type(tx.begin().execute("SELECT 1;")) # TxRunning
t.reveal_type(tx.begin().execute("SELECT 1;").commit()) # TxCommitted
# Type errors caught:
tx.begin().begin() # Double "BEGIN"
tx.commit() # "COMMIT" without "BEGIN"
tx.begin().commit().execute("SELECT 1;") # Execute after "COMMIT"Written this way, mypy complains about nonexistent
methods:
$ mypy --strict --disable-error-code empty-body typestate_mono.py
typestate_mono.py:25: note: Revealed type is "typestate_mono.TxInit"
typestate_mono.py:26: note: Revealed type is "typestate_mono.TxRunning"
typestate_mono.py:27: note: Revealed type is "typestate_mono.TxRunning"
typestate_mono.py:28: note: Revealed type is "typestate_mono.TxCommitted"
typestate_mono.py:31: error: "TxRunning" has no attribute "begin" [attr-defined]
typestate_mono.py:32: error: "TxInit" has no attribute "commit" [attr-defined]
typestate_mono.py:33: error: "TxCommitted" has no attribute "execute" [attr-defined]
Found 3 errors in 1 file (checked 1 source file)Alas, I did not see this pattern used in Python in the wild…