0

I have a simple todos table in SQLite that I'm trying to query using Gleam. My code is as follows:

pub type Todo {
  Todo(id: Int, title: String, completed: Int)
}

fn todo_encoder() -> decode.Decoder(Todo) {
  let encoder = {
    use id <- decode.field("id", decode.int)
    use title <- decode.field("title", decode.string)
    use completed <- decode.field("completed", decode.int)
    decode.success(Todo(id: id, title: title, completed: completed))
  }
  encoder
}

fn db_directory() {
  let assert Ok(priv_directory) = wisp.priv_directory("app")
  echo "Private directory: " <> priv_directory
  priv_directory <> "/data/"
}


fn open_db_conn() {
  let db_conn = sqlight.open(db_directory() <> "app.db")
  case db_conn {
    Ok(conn) -> {
      echo "Database connection established."
      Ok(conn)
    }
    Error(err) -> {
      Error(err)
    }
  }
}

pub fn get_todos() -> Result(List(Todo), sqlight.Error) {
  let assert Ok(conn) = open_db_conn()
  let todos = sqlight.query("SELECT * FROM todos", conn, [], todo_encoder())

  case todos {
    Ok(results) -> {
      echo "Retrieved todos successfully."
      Ok(results)
    }
    Error(error) -> {
      echo "Error retrieving todos: " <> error.message
      Error(error)
    }
  }
}

I keep seeing this error when I call get_todos:

"Error retrieving todos: Decoder failed, expected Dict, got Tuple of 3 elements in "

My decoder seems correct, and my call to open the db also looks correct. What am I doing wrong?

1
  • The error message suggests that your decoder is expecting a Dict (key-value pairs), but the SQLite query is returning a Tuple (list of values) instead. Commented Mar 29 at 4:29

1 Answer 1

1

Updated the decoder code:

fn todo_decoder() -> decode.Decoder(Todo) {
  {
    use id <- decode.field(0, decode.int)
    use title <- decode.field(1, decode.string)
    use completed <- decode.field(2, decode.int)
    decode.success(Todo(id: id, title: title, completed: completed))
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.