TypedSQL
Let’s read a row from PostgreSQL in a Bend function. We can write the query next to the code that uses it and have the build check the fields we get back.
Let PostgreSQL describe the query
Start with the columns you want in your result. During the build PostgreSQL describes their types and labels. For a query returning a named Bend record, Bwf checks that description against the record so the action can use the result directly.
Bind a value to the query
Read the query below with the migrated database in mind. At build time Bwf asks PostgreSQL to prepare the statement against that schema. PostgreSQL resolves the names, expressions and parameter types. Bwf can then generate a Bend binding for this particular statement.
title <- sql """
SELECT title
FROM articles
WHERE slug = ${slug}
"""
Inside do IO<…>, pass slug as a bound parameter. With sql as shown, the execution uses the application pool initialized by Server.serve_with_refresh. A standalone script can supply its connection with sql(database).
Read the result as a scalar, tuple or record
Start with a single selected column and each row gives you a scalar. Add a second column and you can read the pair as a tuple. For a named record, use as RecordName and match its fields with the SQL column labels. When a join gives you two columns called id, give each its own alias.
A unique lookup can return Maybe for a missing row. A nullable column has a separate Maybe for its value. An ungrouped COUNT(*) can return one value. A query with no narrow cardinality gives the action a list.
type ArticleTitle is Data:
ArticleTitle{id: Sql.Id<"articles">, title: String}
def titles(database: String) -> IO(Sql.Outcome(List<&2, ArticleTitle>)):
do IO<Sql.Outcome(List<&2, ArticleTitle>)>:
rows <- sql(database) as ArticleTitle """
SELECT title, id FROM articles ORDER BY title
"""
return rowsIn this example, the record and query put the fields in different orders. The decoder uses their names. To select a full row, import Bwf.Db and use table_alias.* with the generated table model where supported.
See a schema error before starting the server
Change a column name and run scripts/bwf check. PostgreSQL reports the missing column as it describes the SQL. Bend reports a wrong parameter or record field type. When you run the app, Sql.Outcome(A) still handles failures such as a dropped connection or a rejected write.
For related operations on one connection, see transactions and SQL sessions.
Try the check in a scratch copy. Change a selected column to a name that isn’t in your migrations, then restore it after you see the error.
./scripts/bwf check --entry examples/canonical/main.bend