//// Executes statements on a supplied SQLite connection and manages its //// native lifetime. A `sqlight.Connection` is esqlite's connection. import gleam/dynamic/decode import gleam/list import gleam/option.{type Option} import gleam/result import sqlight /// Runs one statement and decodes its rows on the caller's connection. pub fn rows( sql: String, on connection: sqlight.Connection, with arguments: List(sqlight.Value), expecting decoder: decode.Decoder(row), ) -> Result(List(row), String) { rows_native(sql, on: connection, with: arguments, expecting: decoder) |> result.map_error(fn(error) { error.message }) } pub fn rows_native( sql: String, on connection: sqlight.Connection, with arguments: List(sqlight.Value), expecting decoder: decode.Decoder(row), ) -> Result(List(row), sqlight.Error) { sqlight.query(sql, on: connection, with: arguments, expecting: decoder) } /// Runs a parameterized statement for its effect, discarding any rows. pub fn run( sql: String, on connection: sqlight.Connection, with arguments: List(sqlight.Value), ) -> Result(Nil, String) { run_native(sql, on: connection, with: arguments) |> result.map_error(fn(error) { error.message }) } pub fn run_native( sql: String, on connection: sqlight.Connection, with arguments: List(sqlight.Value), ) -> Result(Nil, sqlight.Error) { rows_native( sql, on: connection, with: arguments, expecting: decode.success(Nil), ) |> result.replace(Nil) } /// Executes an ordered SQL script on the caller's connection. SQLite stops /// at the first error. The script runs inside any transaction already open. pub fn exec( sql: String, on connection: sqlight.Connection, ) -> Result(Nil, String) { exec_native(sql, on: connection) |> result.map_error(fn(error) { error.message }) } pub fn exec_native( sql: String, on connection: sqlight.Connection, ) -> Result(Nil, sqlight.Error) { sqlight.exec(sql, on: connection) } /// Whether `connection` is outside every transaction and savepoint, SQLite's /// autocommit mode. @external(erlang, "esqlite3", "get_autocommit") pub fn autocommit(connection: sqlight.Connection) -> Bool /// Closes `connection` before it returns. Call it from the process that ran /// the connection's queries, and use it instead of `sqlight.close`. /// /// esqlite finalizes a statement only when the garbage collector frees its /// term, and `sqlight.query` leaves every statement to it. `sqlight.close` /// calls `sqlite3_close_v2`, which keeps a connection with a statement not /// yet finalized open until that statement is. The connection's file /// handles and locks stay open meanwhile. If it is the database's last /// connection, its checkpoint and its removal of the `-shm` and then the /// `-wal` file run whenever the statement is finalized. A reader of the files /// at that moment can find a log that holds commits but has no index. If it /// is not the last, the last one cannot take the database's exclusive lock, /// so neither removes the files. /// /// So the close first finalizes every statement the calling process no /// longer references, then closes. See `finalize_unreferenced`. A statement /// the caller still holds keeps the connection open, as before. sqlight /// never hands one out. pub fn close(connection: sqlight.Connection) -> Result(Nil, sqlight.Error) { finalize_unreferenced() sqlight.close(connection) } /// Frees the statements the calling process left on `connection`. A process /// that ran queries on a connection another process owns calls it before it /// hands the connection back: the owner's `close` collects only the owner's /// garbage, so a statement left in the borrower would keep the connection /// open after that close returns. The owner's close waits for the /// finalizers this queues, so `release` itself need not. pub fn release(_connection: sqlight.Connection) -> Nil { let _ = garbage_collect() Nil } /// Collects the calling process's garbage and returns once the finalizer of /// every statement it freed has run, along with those of statements other /// processes freed before this was called. /// /// A collection does not run a NIF resource's destructor: OTP queues it as /// aux work on the scheduler that collected, or on scheduler 1 when the /// collection ran on a dirty scheduler. That scheduler runs it when it next /// passes through its scheduling loop. `sqlight.close` runs on a dirty I/O /// scheduler, so the scheduler the closer left runs the queue while /// `sqlite3_close_v2` runs, and the close can come first. /// /// OTP 29's runtime gives the wait below: /// /// - Each scheduler runs its queue in order, and runs all of it at every /// pass through its loop before it picks a process. /// - `erlang:yield` sends the caller through such a pass, so if the caller /// resumes on the scheduler that queued the finalizers, they have run. /// - `erlang:statistics(garbage_collection)` queues a request behind the /// finalizers on every other normal scheduler, and returns once each has /// answered it. fn finalize_unreferenced() -> Nil { let _ = garbage_collect() let _ = yield() let _ = statistics(GarbageCollection) Nil } @external(erlang, "erlang", "garbage_collect") fn garbage_collect() -> Bool @external(erlang, "erlang", "yield") fn yield() -> Bool /// The `erlang:statistics` item, spelt as its atom. type Statistic { GarbageCollection } @external(erlang, "erlang", "statistics") fn statistics(item: Statistic) -> #(Int, Int, Int) /// Takes the first row, using missing when the query found no rows. pub fn first( rows: Result(List(row), error), missing missing: error, ) -> Result(row, error) { use rows <- result.try(rows) list.first(rows) |> result.replace_error(missing) } /// Takes the first row if present. A failed query remains an error. pub fn optional_first( rows: Result(List(row), error), ) -> Result(Option(row), error) { use rows <- result.map(rows) list.first(rows) |> option.from_result }