Skip to content

Commit 05ff3fa

Browse files
Improve performance of fetch_all/4 (#200)
1 parent ac4977b commit 05ff3fa

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

lib/exqlite/sqlite3.ex

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,10 +135,13 @@ defmodule Exqlite.Sqlite3 do
135135
defp fetch_all(conn, statement, chunk_size, accum) do
136136
case multi_step(conn, statement, chunk_size) do
137137
{:done, rows} ->
138-
{:ok, accum ++ rows}
138+
case accum do
139+
[] -> {:ok, rows}
140+
accum -> {:ok, (rows ++ accum) |> Enum.reverse()}
141+
end
139142

140143
{:rows, rows} ->
141-
fetch_all(conn, statement, chunk_size, accum ++ rows)
144+
fetch_all(conn, statement, chunk_size, (rows |> Enum.reverse()) ++ accum)
142145

143146
{:error, reason} ->
144147
{:error, reason}

test/exqlite/connection_test.exs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,43 @@ defmodule Exqlite.ConnectionTest do
157157

158158
File.rm(path)
159159
end
160+
161+
test "returns timely and in order for big data sets" do
162+
path = Temp.path!()
163+
164+
{:ok, db} = Sqlite3.open(path)
165+
166+
:ok =
167+
Sqlite3.execute(db, "create table users (id integer primary key, name text)")
168+
169+
Enum.each(1..10_000, fn i ->
170+
:ok =
171+
Sqlite3.execute(db, "insert into users (id, name) values (#{i}, 'User-#{i}')")
172+
end)
173+
174+
:ok = Exqlite.Sqlite3.close(db)
175+
176+
{:ok, conn} = Connection.connect(database: path)
177+
178+
{:ok, _query, result, _conn} =
179+
Connection.handle_execute(
180+
%Exqlite.Query{
181+
statement: "SELECT * FROM users"
182+
},
183+
[],
184+
[timeout: 1],
185+
conn
186+
)
187+
188+
assert result.command == :execute
189+
assert length(result.rows) == 10_000
190+
191+
Enum.with_index(result.rows, fn row, i ->
192+
assert row == [i + 1, "User-#{i + 1}"]
193+
end)
194+
195+
File.rm(path)
196+
end
160197
end
161198

162199
describe ".handle_prepare/3" do

0 commit comments

Comments
 (0)