1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 12:38:12 +00:00

LibSQL+SQLServer: Implement first cut of SELECT ... ORDER BY foo

Ordering is done by replacing the straight Vector holding the query
result in the SQLResult object with a dedicated Vector subclass that
inserts result rows according to their sort key using a binary search.
This is done in the ResultSet class.

There are limitations:
- "SELECT ... ORDER BY 1" (or 2 or 3 etc) is supposed to sort by the
n-th result column. This doesn't work yet
- "SELECT ... column-expression alias ... ORDER BY alias" is supposed to
sort by the column with the given alias. This doesn't work yet

What does work however is something like
```SELECT foo FROM bar SORT BY quux```
i.e. sorted by a column not in the result set. Once functions are
supported it should be possible to sort by random functions.
This commit is contained in:
Jan de Visser 2022-01-12 09:49:43 -05:00 committed by Andreas Kling
parent 53cd87cc1d
commit 7fc901d1b3
7 changed files with 205 additions and 17 deletions

View file

@ -7,6 +7,7 @@
#include <LibSQL/AST/AST.h>
#include <LibSQL/Database.h>
#include <LibSQL/Meta.h>
#include <LibSQL/ResultSet.h>
#include <LibSQL/Row.h>
namespace SQL::AST {
@ -77,6 +78,14 @@ RefPtr<SQLResult> Select::execute(ExecutionContext& context) const
}
}
bool has_ordering { false };
AK::NonnullRefPtr<TupleDescriptor> sort_descriptor = AK::adopt_ref(*new TupleDescriptor);
for (auto& term : m_ordering_term_list) {
sort_descriptor->append(TupleElementDescriptor { .order = term.order() });
has_ordering = true;
}
Tuple sort_key(sort_descriptor);
for (auto& row : rows) {
context.current_row = &row;
if (where_clause()) {
@ -93,7 +102,17 @@ RefPtr<SQLResult> Select::execute(ExecutionContext& context) const
return context.result;
tuple.append(value);
}
context.result->append(tuple);
if (has_ordering) {
sort_key.clear();
for (auto& term : m_ordering_term_list) {
auto value = term.expression()->evaluate(context);
if (context.result->has_error())
return context.result;
sort_key.append(value);
}
}
context.result->insert(tuple, sort_key);
}
return context.result;
}