this project is currently pre-alpha. it will be released under v1.0.0 once ready for usage.
This library makes use of a sqlc-gen-json plugin, which it then converts into gleam code.
So in a simplified manner, the pipeline looks like this:
graph LR
SQL[SQL Queries] -- sqlc-gen-json --> JSON[JSON Schema]
JSON -- sql-gen-gleam --> Gleam[Gleam Code]
Let's take the following SQL queries as an example:
-- name: GetAuthor :one
SELECT
*
FROM
authors
WHERE
id = ?
LIMIT
1;
-- name: ListAuthors :many
SELECT
*
FROM
authors
ORDER BY
name;
The --name: GetAuthor :one
comment is part of sqlc and will be used to generate the
name and return type of the wrapper.
Given the queries above, the following code will be generated:
//// file: src/gen/sqlc_mysql.gleam
import gleam/option.{type Option}
pub type GetAuthor {
GetAuthor(
id: Int,
created_at: Int,
name: String,
bio: Option(String)
)
}
pub fn get_author_sql(id: Int) {
let sql = "
SELECT
*
FROM
authors
WHERE
id = ?
LIMIT
1;
"
#(sql, #(id))
}
pub type ListAuthorRow {
ListAuthorRow(
id: Int,
created_at: Int,
name: String,
bio: Option(String)
)
}
pub type ListAuthors = List(ListAuthorRow)
pub fn list_authors_sql(id: Int) {
let sql = "
SELECT
*
FROM
authors
ORDER BY
name;
"
#(sql, Nil)
}
Every SQL query wrapper follows the schema of #(SQL, Params). So the first element is the raw SQL that can be executed by your database driver and the second element is a tuple of all of the parameters that you need for this query.
If you're using one of the supported drivers, we can also generate the query execution parsing of the return type for you. If you are using a custom driver, you will have to do that yourself using the gleam/dynamic package.
- MySQL: https://github.com/VioletBuse/gmysql
- PostgreSQL: https://github.com/lpil/pog
- SQlite: https://github.com/lpil/sqlight
- Install
$ gleam add sqlc_gen_gleam@1
- Setup sqlc
Now setup your sqlc.yaml
, schema.sql
and query.sql
like in any other sqlc project.
Here are some links to help you start out:
- Generate Gleam code
# we first need the json from sqlc
$ sqlc generate
# then we use this library to turn it into gleam code
$ gleam run -m sqlc_gen_gleam
Further documentation can be found at https://hexdocs.pm/sqlc_gen_gleam.
There are scripts to spawn MySQL or PostgreSQL docker container:
For example:
$ ./scripts/mysql/docker.sh
# or
$ ./scripts/psql/docker.sh
This library uses the JSON schema, generated by sqlc, to generate gleam code. To generate the JSON with the example schema & queries:
$ ./scripts/sqlc.sh # wrapper for "sqlc generate" with additional parameters
$ gleam run # Run the project
$ gleam test # Run the tests
This plugin supports everything that sqlc supports. As the time of this writing that would be MySQL, PostgreSQL and SQlite.
You can read more on language & SQL support here: https://docs.sqlc.dev/en/stable/reference/language-support.html
- embeddeding structs (https://docs.sqlc.dev/en/stable/howto/embedding.html)