|
| 1 | +defmodule Electric.ShapeCache.ShapeStatus.ShapeDb.Sqlite3 do |
| 2 | + @moduledoc """ |
| 3 | + Drop-in shim over `:esqlite3` that mirrors the subset of the `Exqlite.Sqlite3` API |
| 4 | + used by `Connection` and `Query`. |
| 5 | +
|
| 6 | + Only `Connection` and `Query` hold an `alias` to this module. All other code |
| 7 | + continues to call those two modules unchanged, so swapping the underlying SQLite |
| 8 | + NIF is fully contained here. |
| 9 | +
|
| 10 | + ## API mapping |
| 11 | +
|
| 12 | + | Exqlite.Sqlite3 | :esqlite3 / notes | |
| 13 | + |-------------------------------------|--------------------------------------------| |
| 14 | + | open(path, opts) | open(uri) – opts encoded as URI params | |
| 15 | + | close(conn) | close(conn) | |
| 16 | + | execute(conn, sql) | exec(conn, sql) | |
| 17 | + | prepare(conn, sql) | prepare(conn, sql) | |
| 18 | + | release(conn, stmt) | no-op – GC'd by esqlite | |
| 19 | + | bind(stmt, binds) | bind(stmt, binds) | |
| 20 | + | step(conn, stmt) | step(stmt) – conn arg dropped | |
| 21 | + | reset(stmt) | reset(stmt) | |
| 22 | + | fetch_all(conn, stmt) | fetchall(stmt) | |
| 23 | + | changes(conn) | {:ok, changes(conn)} | |
| 24 | + | multi_step(conn, stmt) | step loop; returns {:rows, rows}/{:done, rows} | |
| 25 | + | enable_load_extension(conn, bool) | not supported – always returns error | |
| 26 | + | bind_parameter_count(stmt) | column_names heuristic (explain only) | |
| 27 | + """ |
| 28 | + |
| 29 | + # ── Types ────────────────────────────────────────────────────────────────── |
| 30 | + |
| 31 | + @type connection :: :esqlite3.esqlite3() |
| 32 | + @type statement :: :esqlite3.esqlite3_stmt() |
| 33 | + |
| 34 | + # ── Connection lifecycle ─────────────────────────────────────────────────── |
| 35 | + |
| 36 | + @doc """ |
| 37 | + Opens a SQLite database. |
| 38 | +
|
| 39 | + `opts` follows the exqlite convention: |
| 40 | + - `[mode: [:readonly, :nomutex]]` → opens as `file:<path>?mode=ro` |
| 41 | + - `[]` (default) → opens as `file:<path>?mode=rwc` |
| 42 | +
|
| 43 | + The `:memory:` path is passed through unchanged. |
| 44 | + """ |
| 45 | + @spec open(String.t(), keyword()) :: {:ok, connection()} | {:error, term()} |
| 46 | + def open(path, opts \\ []) do |
| 47 | + uri = build_uri(path, opts) |
| 48 | + :esqlite3.open(String.to_charlist(uri)) |
| 49 | + end |
| 50 | + |
| 51 | + @spec close(connection()) :: :ok | {:error, term()} |
| 52 | + def close(conn) do |
| 53 | + :esqlite3.close(conn) |
| 54 | + end |
| 55 | + |
| 56 | + # ── DDL / raw execution ──────────────────────────────────────────────────── |
| 57 | + |
| 58 | + @doc "Execute a raw SQL statement (no results returned)." |
| 59 | + @spec execute(connection(), String.t()) :: :ok | {:error, term()} |
| 60 | + def execute(conn, sql) do |
| 61 | + :esqlite3.exec(conn, sql) |
| 62 | + end |
| 63 | + |
| 64 | + # ── Prepared statements ──────────────────────────────────────────────────── |
| 65 | + |
| 66 | + @spec prepare(connection(), String.t()) :: {:ok, statement()} | {:error, term()} |
| 67 | + def prepare(conn, sql) do |
| 68 | + :esqlite3.prepare(conn, sql) |
| 69 | + end |
| 70 | + |
| 71 | + @doc "Release a prepared statement. esqlite relies on GC; this is a no-op." |
| 72 | + @spec release(connection(), statement()) :: :ok |
| 73 | + def release(_conn, _stmt), do: :ok |
| 74 | + |
| 75 | + @doc """ |
| 76 | + Bind positional or named parameters to a prepared statement. |
| 77 | +
|
| 78 | + Accepts the exqlite bind list format including `{:blob, value}` tagged tuples, |
| 79 | + plain integers, binaries, and named `{"@name", value}` pairs. |
| 80 | + """ |
| 81 | + @spec bind(statement(), list()) :: :ok | {:error, term()} |
| 82 | + def bind(stmt, binds) do |
| 83 | + converted = Enum.map(binds, &convert_bind/1) |
| 84 | + :esqlite3.bind(stmt, converted) |
| 85 | + end |
| 86 | + |
| 87 | + @doc """ |
| 88 | + Step a prepared statement once. |
| 89 | +
|
| 90 | + Returns `{:row, row}` or `:done` (matching the exqlite contract). |
| 91 | + The `conn` argument is accepted for API compatibility but ignored. |
| 92 | + """ |
| 93 | + @spec step(connection(), statement()) :: {:row, list()} | :done | {:error, term()} |
| 94 | + def step(_conn, stmt) do |
| 95 | + case :esqlite3.step(stmt) do |
| 96 | + :"$done" -> :done |
| 97 | + row when is_list(row) -> {:row, row} |
| 98 | + {:error, _} = err -> err |
| 99 | + end |
| 100 | + end |
| 101 | + |
| 102 | + @spec reset(statement()) :: :ok | {:error, term()} |
| 103 | + def reset(stmt) do |
| 104 | + :esqlite3.reset(stmt) |
| 105 | + end |
| 106 | + |
| 107 | + @doc "Fetch all remaining rows from a prepared statement." |
| 108 | + @spec fetch_all(connection(), statement()) :: {:ok, list(list())} | {:error, term()} |
| 109 | + def fetch_all(_conn, stmt) do |
| 110 | + case :esqlite3.fetchall(stmt) do |
| 111 | + rows when is_list(rows) -> {:ok, rows} |
| 112 | + {:error, _} = err -> err |
| 113 | + end |
| 114 | + end |
| 115 | + |
| 116 | + @doc "Return `{:ok, n}` for the number of rows changed by the last DML statement." |
| 117 | + @spec changes(connection()) :: {:ok, non_neg_integer()} |
| 118 | + def changes(conn) do |
| 119 | + {:ok, :esqlite3.changes(conn)} |
| 120 | + end |
| 121 | + |
| 122 | + @doc """ |
| 123 | + Step through a prepared statement in chunks. |
| 124 | +
|
| 125 | + Returns `{:rows, rows}` when there are more rows to fetch, or |
| 126 | + `{:done, rows}` when the cursor is exhausted. |
| 127 | +
|
| 128 | + The `conn` argument is accepted for API compatibility but ignored. |
| 129 | + The chunk size matches exqlite's default (50 rows per call). |
| 130 | + """ |
| 131 | + @spec multi_step(connection(), statement()) :: |
| 132 | + {:rows, list(list())} | {:done, list(list())} | {:error, term()} |
| 133 | + def multi_step(_conn, stmt, chunk_size \\ 50) do |
| 134 | + do_multi_step(stmt, chunk_size, []) |
| 135 | + end |
| 136 | + |
| 137 | + defp do_multi_step(_stmt, 0, acc) do |
| 138 | + {:rows, Enum.reverse(acc)} |
| 139 | + end |
| 140 | + |
| 141 | + defp do_multi_step(stmt, remaining, acc) do |
| 142 | + case :esqlite3.step(stmt) do |
| 143 | + :"$done" -> |
| 144 | + {:done, Enum.reverse(acc)} |
| 145 | + |
| 146 | + row when is_list(row) -> |
| 147 | + do_multi_step(stmt, remaining - 1, [row | acc]) |
| 148 | + |
| 149 | + {:error, _} = err -> |
| 150 | + err |
| 151 | + end |
| 152 | + end |
| 153 | + |
| 154 | + @doc """ |
| 155 | + Enable or disable SQLite extension loading. |
| 156 | +
|
| 157 | + esqlite does not expose `sqlite3_enable_load_extension`. |
| 158 | + Returns `{:error, :not_supported}` so callers can handle gracefully. |
| 159 | + """ |
| 160 | + @spec enable_load_extension(connection(), boolean()) :: :ok | {:error, :not_supported} |
| 161 | + def enable_load_extension(_conn, _enable), do: {:error, :not_supported} |
| 162 | + |
| 163 | + @doc """ |
| 164 | + Return the number of bind parameters in a prepared statement. |
| 165 | +
|
| 166 | + Used only by the `explain/2` diagnostic path. esqlite does not expose |
| 167 | + `sqlite3_bind_parameter_count` directly, so we derive it from column names |
| 168 | + of the statement. For `EXPLAIN QUERY PLAN` usage the count just needs to |
| 169 | + be non-negative; we fall back to 0. |
| 170 | + """ |
| 171 | + @spec bind_parameter_count(statement()) :: non_neg_integer() |
| 172 | + def bind_parameter_count(_stmt) do |
| 173 | + # esqlite does not expose sqlite3_bind_parameter_count. |
| 174 | + # The explain path just needs a list of empty-string binds for EXPLAIN |
| 175 | + # QUERY PLAN to succeed; returning 0 is safe for that path. |
| 176 | + 0 |
| 177 | + end |
| 178 | + |
| 179 | + # ── Private helpers ──────────────────────────────────────────────────────── |
| 180 | + |
| 181 | + # Build a SQLite URI from a file path and exqlite-style opts. |
| 182 | + defp build_uri(":memory:", _opts), do: "file:memory?mode=memory&cache=shared" |
| 183 | + |
| 184 | + defp build_uri(path, opts) do |
| 185 | + mode = |
| 186 | + case Keyword.get(opts, :mode, []) do |
| 187 | + modes when is_list(modes) -> |
| 188 | + if :readonly in modes, do: "ro", else: "rwc" |
| 189 | + |
| 190 | + :readonly -> |
| 191 | + "ro" |
| 192 | + |
| 193 | + _ -> |
| 194 | + "rwc" |
| 195 | + end |
| 196 | + |
| 197 | + "file:#{URI.encode(path)}?mode=#{mode}" |
| 198 | + end |
| 199 | + |
| 200 | + # Convert an exqlite bind value to an esqlite bind value. |
| 201 | + # esqlite's bind/2 supports: integers, floats, binaries (text), and |
| 202 | + # {:blob, binary} tuples for BLOBs. nil/null map to undefined. |
| 203 | + defp convert_bind(nil), do: :undefined |
| 204 | + defp convert_bind(:null), do: :undefined |
| 205 | + defp convert_bind(value), do: value |
| 206 | +end |
0 commit comments