Skip to content

Add insert example to docs #18

@jrstrunk

Description

@jrstrunk

Hello! From experience, inserting into SQLite databases has been a common hurdle for people new to Gleam (for the people that are using SQLite of course). What do you think of updating the docs somewhere to show an example of running an insert statement with a sqlight.query call?

Maybe something like this, moving one part of the data into a separate insert statement?

import gleam/dynamic/decode
import sqlight

pub fn main() {
  use conn <- sqlight.with_connection(":memory:")
  let cat_decoder = {
    use name <- decode.field(0, decode.string)
    use age <- decode.field(1, decode.int)
    decode.success(#(name, age))
  }

  let sql = "
  create table cats (name text, age int);

  insert into cats (name, age) values 
  ('Nubi', 4),
  ('Biffy', 10);
  "

  let assert Ok(Nil) = sqlight.exec(sql, conn)

  let sql = "insert into cats (name, age) values (?, ?)"

  let assert Ok([]) =
    sqlight.query(
      sql,
      on: conn,
      with: [sqlight.text("Ginny"), sqlight.int(6)],
      expecting: decode.int,
    )

  let sql = "
  select name, age from cats
  where age < ?
  "

  let assert Ok([#("Nubi", 4), #("Ginny", 6)]) =
    sqlight.query(sql, on: conn, with: [sqlight.int(7)], expecting: cat_decoder)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions