glimr/db/query


Query Execution

Provides a unified interface for executing database queries on both PostgreSQL and SQLite connections.

Types


QueryResult Type

The result of a database query, containing the number of affected/returned rows and the data.

pub type QueryResult(t) {
  QueryResult(count: Int, rows: List(t))
}

Constructors

  • QueryResult(count: Int, rows: List(t))

Values

pub fn execute(
  conn: connection.Connection,
  sql: String,
  params: List(connection.Value),
) -> Result(Int, connection.DbError)

Execute Statement

Executes a SQL statement that doesn’t return rows (INSERT, UPDATE, DELETE). Returns the number of affected rows.


Example:

query.execute(
  conn,
  "INSERT INTO users (name, email) VALUES ($1, $2)",
  [connection.string("Alice"), connection.string("alice@example.com")],
)
pub fn select(
  conn: connection.Connection,
  sql: String,
  params: List(connection.Value),
  decoder: decode.Decoder(t),
) -> Result(QueryResult(t), connection.DbError)

Execute Query

Executes a SQL query that returns rows. Use this for SELECT statements.

SQL should use PostgreSQL-style placeholders ($1, $2, etc.) which are automatically converted for SQLite.


Example:

let decoder = {
  use id <- decode.field(0, decode.int)
  use name <- decode.field(1, decode.string)
  decode.success(#(id, name))
}

query.select(
  conn,
  "SELECT id, name FROM users WHERE id = $1",
  [connection.int(1)],
  decoder,
)
pub fn select_all(
  conn: connection.Connection,
  sql: String,
  params: List(connection.Value),
  decoder: decode.Decoder(t),
) -> Result(List(t), connection.DbError)

Select All

Alias for select that emphasizes returning multiple rows.

pub fn select_one(
  conn: connection.Connection,
  sql: String,
  params: List(connection.Value),
  decoder: decode.Decoder(t),
) -> Result(Result(t, Nil), connection.DbError)

Select One

Executes a query expecting exactly zero or one row. Returns Error if more than one row is returned.

Search Document