Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sqlite: better queries #302

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Sqlite: better queries #302

wants to merge 4 commits into from

Conversation

bhansconnect
Copy link
Collaborator

The better query ideas from https://roc.zulipchat.com/#narrow/channel/383402-API-design/topic/Sqlite.20APIs

main! = \_args ->
    db_path = try Env.var! "DB_PATH"

    query_todos_by_status! = try Sqlite.prepare_query_many! {
        path: db_path,
        query: "SELECT id, task FROM todos WHERE status = :status;",
        bindings: \status -> [{ name: ":status", value: String status }],
        rows: { Sqlite.decode_record <-
            id: Sqlite.i64 "id" |> Sqlite.map_value Num.toStr,
            task: Sqlite.str "task",
        },
    }
    todo = try query_todos_by_status! "todo"

    try Stdout.line! "Todo Tasks:"
    try List.forEachTry! todo \{ id, task } ->
        Stdout.line! "\tid: $(id), task: $(task)"

    completed = try query_todos_by_status! "completed"

    try Stdout.line! "\nCompleted Tasks:"
    try List.forEachTry! completed \{ id, task } ->
        Stdout.line! "\tid: $(id), task: $(task)"

    Ok {}

and

exec_transaction! = try prepare_transaction! { path: "path/to/database.db" }

try exec_transaction! \{} ->
    try Sqlite.execute! {
        path: "path/to/database.db",
        query: "INSERT INTO users (first, last) VALUES (:first, :last);",
        bindings: [
            { name: ":first", value: String "John" },
            { name: ":last", value: String "Smith" },
        ],
    }

    # Oh no, hit an error. Need to rollback.
    # Note: Error could be anything.
    Err NeedToRollback

Comment on lines +577 to +590
decoder = \fn ->
\name ->
@SqlDecode \cols ->

found = List.findFirstIndex cols \x -> x == name
when found is
Ok index ->
\stmt ->
try column_value! stmt index
|> fn

Err NotFound ->
\_ ->
Err (FieldNotFound name)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why the formatter decided to change this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant