ladybird/Userland/Libraries/LibSQL/ResultSet.cpp
Timothy Flynn 2397836f8e LibSQL+SQLServer: Introduce and use ResultOr<ValueType>
The result of a SQL statement execution is either:
    1. An error.
    2. The list of rows inserted, deleted, selected, etc.

(2) is currently represented by a combination of the Result class and
the ResultSet list it holds. This worked okay, but issues start to
arise when trying to use Result in non-statement contexts (for example,
when introducing Result to SQL expression execution).

What we really need is for Result to be a thin wrapper that represents
both (1) and (2), and to not have any explicit members like a ResultSet.
So this commit removes ResultSet from Result, and introduces ResultOr,
which is just an alias for AK::ErrorOrr. Statement execution now returns
ResultOr<ResultSet> instead of Result. This further opens the door for
expression execution to return ResultOr<Value> in the future.

Lastly, this moves some other context held by Result over to ResultSet.
This includes the row count (which is really just the size of ResultSet)
and the command for which the result is for.
2022-02-10 23:11:13 +01:00

54 lines
1.1 KiB
C++

/*
* Copyright (c) 2022, Jan de Visser <jan@de-visser.net>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibSQL/ResultSet.h>
namespace SQL {
size_t ResultSet::binary_search(Tuple const& sort_key, size_t low, size_t high)
{
if (high <= low) {
auto compare = sort_key.compare(at(low).sort_key);
return (compare > 0) ? low + 1 : low;
}
auto mid = (low + high) / 2;
auto compare = sort_key.compare(at(mid).sort_key);
if (compare == 0)
return mid + 1;
if (compare > 0)
return binary_search(sort_key, mid + 1, high);
return binary_search(sort_key, low, mid);
}
void ResultSet::insert_row(Tuple const& row, Tuple const& sort_key)
{
if ((sort_key.size() == 0) || is_empty()) {
empend(row, sort_key);
return;
}
auto ix = binary_search(sort_key, 0, size() - 1);
insert(ix, ResultRow { row, sort_key });
}
void ResultSet::limit(size_t offset, size_t limit)
{
if (offset > 0) {
if (offset > size()) {
clear();
return;
}
remove(0, offset);
}
if (size() > limit)
remove(limit, size() - limit);
}
}