1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 01:37:36 +00:00

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.
This commit is contained in:
Timothy Flynn 2022-02-10 14:43:00 -05:00 committed by Andreas Kling
parent 6409618413
commit 2397836f8e
15 changed files with 259 additions and 330 deletions

View file

@ -15,6 +15,7 @@
#include <LibSQL/AST/Token.h>
#include <LibSQL/Forward.h>
#include <LibSQL/Result.h>
#include <LibSQL/ResultSet.h>
#include <LibSQL/Type.h>
namespace SQL::AST {
@ -725,11 +726,11 @@ private:
class Statement : public ASTNode {
public:
Result execute(AK::NonnullRefPtr<Database> database) const;
ResultOr<ResultSet> execute(AK::NonnullRefPtr<Database> database) const;
virtual Result execute(ExecutionContext&) const
virtual ResultOr<ResultSet> execute(ExecutionContext&) const
{
return { SQLCommand::Unknown, SQLErrorCode::NotYetImplemented };
return Result { SQLCommand::Unknown, SQLErrorCode::NotYetImplemented };
}
};
@ -747,7 +748,7 @@ public:
const String& schema_name() const { return m_schema_name; }
bool is_error_if_schema_exists() const { return m_is_error_if_schema_exists; }
Result execute(ExecutionContext&) const override;
ResultOr<ResultSet> execute(ExecutionContext&) const override;
private:
String m_schema_name;
@ -786,7 +787,7 @@ public:
bool is_temporary() const { return m_is_temporary; }
bool is_error_if_table_exists() const { return m_is_error_if_table_exists; }
Result execute(ExecutionContext&) const override;
ResultOr<ResultSet> execute(ExecutionContext&) const override;
private:
String m_schema_name;
@ -949,7 +950,7 @@ public:
bool has_selection() const { return !m_select_statement.is_null(); }
const RefPtr<Select>& select_statement() const { return m_select_statement; }
virtual Result execute(ExecutionContext&) const override;
virtual ResultOr<ResultSet> execute(ExecutionContext&) const override;
private:
RefPtr<CommonTableExpressionList> m_common_table_expression_list;
@ -1042,7 +1043,7 @@ public:
const RefPtr<GroupByClause>& group_by_clause() const { return m_group_by_clause; }
const NonnullRefPtrVector<OrderingTerm>& ordering_term_list() const { return m_ordering_term_list; }
const RefPtr<LimitClause>& limit_clause() const { return m_limit_clause; }
Result execute(ExecutionContext&) const override;
ResultOr<ResultSet> execute(ExecutionContext&) const override;
private:
RefPtr<CommonTableExpressionList> m_common_table_expression_list;
@ -1063,7 +1064,7 @@ public:
}
NonnullRefPtr<QualifiedTableName> qualified_table_name() const { return m_qualified_table_name; }
Result execute(ExecutionContext&) const override;
ResultOr<ResultSet> execute(ExecutionContext&) const override;
private:
NonnullRefPtr<QualifiedTableName> m_qualified_table_name;

View file

@ -10,20 +10,20 @@
namespace SQL::AST {
Result CreateSchema::execute(ExecutionContext& context) const
ResultOr<ResultSet> CreateSchema::execute(ExecutionContext& context) const
{
auto schema_def = TRY(context.database->get_schema(m_schema_name));
if (schema_def) {
if (m_is_error_if_schema_exists)
return { SQLCommand::Create, SQLErrorCode::SchemaExists, m_schema_name };
return { SQLCommand::Create };
return Result { SQLCommand::Create, SQLErrorCode::SchemaExists, m_schema_name };
return ResultSet { SQLCommand::Create };
}
schema_def = SchemaDef::construct(m_schema_name);
TRY(context.database->add_schema(*schema_def));
return { SQLCommand::Create, 0, 1 };
return ResultSet { SQLCommand::Create };
}
}

View file

@ -9,19 +9,19 @@
namespace SQL::AST {
Result CreateTable::execute(ExecutionContext& context) const
ResultOr<ResultSet> CreateTable::execute(ExecutionContext& context) const
{
auto schema_name = m_schema_name.is_empty() ? String { "default"sv } : m_schema_name;
auto schema_def = TRY(context.database->get_schema(schema_name));
if (!schema_def)
return { SQLCommand::Create, SQLErrorCode::SchemaDoesNotExist, schema_name };
return Result { SQLCommand::Create, SQLErrorCode::SchemaDoesNotExist, schema_name };
auto table_def = TRY(context.database->get_table(schema_name, m_table_name));
if (table_def) {
if (m_is_error_if_table_exists)
return { SQLCommand::Create, SQLErrorCode::TableExists, m_table_name };
return { SQLCommand::Create };
return Result { SQLCommand::Create, SQLErrorCode::TableExists, m_table_name };
return ResultSet { SQLCommand::Create };
}
table_def = TableDef::construct(schema_def, m_table_name);
@ -36,13 +36,13 @@ Result CreateTable::execute(ExecutionContext& context) const
else if (column.type_name()->name().is_one_of("FLOAT"sv, "NUMBER"sv))
type = SQLType::Float;
else
return { SQLCommand::Create, SQLErrorCode::InvalidType, column.type_name()->name() };
return Result { SQLCommand::Create, SQLErrorCode::InvalidType, column.type_name()->name() };
table_def->append_column(column.name(), type);
}
TRY(context.database->add_table(*table_def));
return { SQLCommand::Create, 0, 1 };
return ResultSet { SQLCommand::Create };
}
}

View file

@ -7,11 +7,12 @@
#include <LibSQL/AST/AST.h>
#include <LibSQL/Database.h>
#include <LibSQL/Meta.h>
#include <LibSQL/ResultSet.h>
#include <LibSQL/Row.h>
namespace SQL::AST {
Result DescribeTable::execute(ExecutionContext& context) const
ResultOr<ResultSet> DescribeTable::execute(ExecutionContext& context) const
{
auto schema_name = m_qualified_table_name->schema_name();
auto table_name = m_qualified_table_name->table_name();
@ -20,19 +21,21 @@ Result DescribeTable::execute(ExecutionContext& context) const
if (!table_def) {
if (schema_name.is_empty())
schema_name = "default"sv;
return { SQLCommand::Describe, SQLErrorCode::TableDoesNotExist, String::formatted("{}.{}", schema_name, table_name) };
return Result { SQLCommand::Describe, SQLErrorCode::TableDoesNotExist, String::formatted("{}.{}", schema_name, table_name) };
}
auto describe_table_def = MUST(context.database->get_table("master"sv, "internal_describe_table"sv));
auto descriptor = describe_table_def->to_tuple_descriptor();
Result result { SQLCommand::Describe };
ResultSet result { SQLCommand::Describe };
TRY(result.try_ensure_capacity(table_def->columns().size()));
for (auto& column : table_def->columns()) {
Tuple tuple(descriptor);
tuple[0] = column.name();
tuple[1] = SQLType_name(column.type());
result.insert(tuple, Tuple {});
result.insert_row(tuple, Tuple {});
}
return result;

View file

@ -21,23 +21,23 @@ static bool does_value_data_type_match(SQLType expected, SQLType actual)
return expected == actual;
}
Result Insert::execute(ExecutionContext& context) const
ResultOr<ResultSet> Insert::execute(ExecutionContext& context) const
{
auto table_def = TRY(context.database->get_table(m_schema_name, m_table_name));
if (!table_def) {
auto schema_name = m_schema_name.is_empty() ? String("default"sv) : m_schema_name;
return { SQLCommand::Insert, SQLErrorCode::TableDoesNotExist, String::formatted("{}.{}", schema_name, m_table_name) };
return Result { SQLCommand::Insert, SQLErrorCode::TableDoesNotExist, String::formatted("{}.{}", schema_name, m_table_name) };
}
Row row(table_def);
for (auto& column : m_column_names) {
if (!row.has(column))
return { SQLCommand::Insert, SQLErrorCode::ColumnDoesNotExist, column };
return Result { SQLCommand::Insert, SQLErrorCode::ColumnDoesNotExist, column };
}
Vector<Row> inserted_rows;
TRY(inserted_rows.try_ensure_capacity(m_chained_expressions.size()));
ResultSet result { SQLCommand::Insert };
TRY(result.try_ensure_capacity(m_chained_expressions.size()));
context.result = Result { SQLCommand::Insert };
@ -55,7 +55,7 @@ Result Insert::execute(ExecutionContext& context) const
auto values = row_value.to_vector().value();
if (m_column_names.is_empty() && values.size() != row.size())
return { SQLCommand::Insert, SQLErrorCode::InvalidNumberOfValues, String::empty() };
return Result { SQLCommand::Insert, SQLErrorCode::InvalidNumberOfValues, String::empty() };
for (auto ix = 0u; ix < values.size(); ix++) {
auto input_value_type = values[ix].type();
@ -65,18 +65,16 @@ Result Insert::execute(ExecutionContext& context) const
auto element_type = tuple_descriptor[element_index].type;
if (!does_value_data_type_match(element_type, input_value_type))
return { SQLCommand::Insert, SQLErrorCode::InvalidValueType, table_def->columns()[element_index].name() };
return Result { SQLCommand::Insert, SQLErrorCode::InvalidValueType, table_def->columns()[element_index].name() };
row[element_index] = values[ix];
}
inserted_rows.append(row);
TRY(context.database->insert(row));
result.insert_row(row, {});
}
for (auto& inserted_row : inserted_rows)
TRY(context.database->insert(inserted_row));
return { SQLCommand::Insert, 0, m_chained_expressions.size() };
return result;
}
}

View file

@ -8,12 +8,11 @@
#include <LibSQL/AST/AST.h>
#include <LibSQL/Database.h>
#include <LibSQL/Meta.h>
#include <LibSQL/ResultSet.h>
#include <LibSQL/Row.h>
namespace SQL::AST {
Result Select::execute(ExecutionContext& context) const
ResultOr<ResultSet> Select::execute(ExecutionContext& context) const
{
NonnullRefPtrVector<ResultColumn> columns;
@ -22,11 +21,11 @@ Result Select::execute(ExecutionContext& context) const
for (auto& table_descriptor : table_or_subquery_list()) {
if (!table_descriptor.is_table())
return { SQLCommand::Select, SQLErrorCode::NotYetImplemented, "Sub-selects are not yet implemented"sv };
return Result { SQLCommand::Select, SQLErrorCode::NotYetImplemented, "Sub-selects are not yet implemented"sv };
auto table_def = TRY(context.database->get_table(table_descriptor.schema_name(), table_descriptor.table_name()));
if (!table_def)
return { SQLCommand::Select, SQLErrorCode::TableDoesNotExist, table_descriptor.table_name() };
return Result { SQLCommand::Select, SQLErrorCode::TableDoesNotExist, table_descriptor.table_name() };
if (result_column_list.size() == 1 && result_column_list[0].type() == ResultType::All) {
for (auto& col : table_def->columns()) {
@ -42,7 +41,7 @@ Result Select::execute(ExecutionContext& context) const
for (auto& col : result_column_list) {
if (col.type() == ResultType::All) {
// FIXME can have '*' for example in conjunction with computed columns
return { SQLCommand::Select, SQLErrorCode::SyntaxError, "*"sv };
return Result { SQLCommand::Select, SQLErrorCode::SyntaxError, "*"sv };
}
columns.append(col);
@ -50,6 +49,7 @@ Result Select::execute(ExecutionContext& context) const
}
context.result = Result { SQLCommand::Select };
ResultSet result { SQLCommand::Select };
auto descriptor = adopt_ref(*new TupleDescriptor);
Tuple tuple(descriptor);
@ -60,7 +60,7 @@ Result Select::execute(ExecutionContext& context) const
for (auto& table_descriptor : table_or_subquery_list()) {
if (!table_descriptor.is_table())
return { SQLCommand::Select, SQLErrorCode::NotYetImplemented, "Sub-selects are not yet implemented"sv };
return Result { SQLCommand::Select, SQLErrorCode::NotYetImplemented, "Sub-selects are not yet implemented"sv };
auto table_def = TRY(context.database->get_table(table_descriptor.schema_name(), table_descriptor.table_name()));
if (table_def->num_columns() == 0)
@ -119,7 +119,7 @@ Result Select::execute(ExecutionContext& context) const
}
}
context.result->insert(tuple, sort_key);
result.insert_row(tuple, sort_key);
}
if (m_limit_clause != nullptr) {
@ -130,7 +130,7 @@ Result Select::execute(ExecutionContext& context) const
if (!limit.is_null()) {
auto limit_value_maybe = limit.to_u32();
if (!limit_value_maybe.has_value())
return { SQLCommand::Select, SQLErrorCode::SyntaxError, "LIMIT clause must evaluate to an integer value"sv };
return Result { SQLCommand::Select, SQLErrorCode::SyntaxError, "LIMIT clause must evaluate to an integer value"sv };
limit_value = limit_value_maybe.value();
}
@ -140,16 +140,16 @@ Result Select::execute(ExecutionContext& context) const
if (!offset.is_null()) {
auto offset_value_maybe = offset.to_u32();
if (!offset_value_maybe.has_value())
return { SQLCommand::Select, SQLErrorCode::SyntaxError, "OFFSET clause must evaluate to an integer value"sv };
return Result { SQLCommand::Select, SQLErrorCode::SyntaxError, "OFFSET clause must evaluate to an integer value"sv };
offset_value = offset_value_maybe.value();
}
}
context.result->limit(offset_value, limit_value);
result.limit(offset_value, limit_value);
}
return context.result.release_value();
return result;
}
}

View file

@ -11,7 +11,7 @@
namespace SQL::AST {
Result Statement::execute(AK::NonnullRefPtr<Database> database) const
ResultOr<ResultSet> Statement::execute(AK::NonnullRefPtr<Database> database) const
{
ExecutionContext context { move(database), {}, this, nullptr };
return execute(context);

View file

@ -23,6 +23,7 @@ class Key;
class KeyPartDef;
class Relation;
class Result;
class ResultSet;
class Row;
class SchemaDef;
class Serializer;

View file

@ -9,30 +9,6 @@
namespace SQL {
void Result::insert(Tuple const& row, Tuple const& sort_key)
{
if (!m_result_set.has_value())
m_result_set = ResultSet {};
m_result_set->insert_row(row, sort_key);
}
void Result::limit(size_t offset, size_t limit)
{
VERIFY(has_results());
if (offset > 0) {
if (offset > m_result_set->size()) {
m_result_set->clear();
return;
}
m_result_set->remove(0, offset);
}
if (m_result_set->size() > limit)
m_result_set->remove(limit, m_result_set->size() - limit);
}
String Result::error_string() const
{
VERIFY(is_error());

View file

@ -9,8 +9,6 @@
#include <AK/Error.h>
#include <AK/Noncopyable.h>
#include <LibSQL/ResultSet.h>
#include <LibSQL/Tuple.h>
#include <LibSQL/Type.h>
namespace SQL {
@ -75,11 +73,8 @@ enum class SQLErrorCode {
class [[nodiscard]] Result {
public:
ALWAYS_INLINE Result(SQLCommand command, size_t update_count = 0, size_t insert_count = 0, size_t delete_count = 0)
ALWAYS_INLINE Result(SQLCommand command)
: m_command(command)
, m_update_count(update_count)
, m_insert_count(insert_count)
, m_delete_count(delete_count)
{
}
@ -109,19 +104,9 @@ public:
SQLErrorCode error() const { return m_error; }
String error_string() const;
void insert(Tuple const& row, Tuple const& sort_key);
void limit(size_t offset, size_t limit);
bool has_results() const { return m_result_set.has_value(); }
ResultSet const& results() const { return m_result_set.value(); }
size_t updated() const { return m_update_count; }
size_t inserted() const { return m_insert_count; }
size_t deleted() const { return m_delete_count; }
// These are for compatibility with the TRY() macro in AK.
[[nodiscard]] bool is_error() const { return m_error != SQLErrorCode::NoError; }
[[nodiscard]] ResultSet release_value() { return m_result_set.release_value(); }
[[nodiscard]] Result release_value() { return move(*this); }
Result release_error()
{
VERIFY(is_error());
@ -138,11 +123,9 @@ private:
SQLErrorCode m_error { SQLErrorCode::NoError };
Optional<String> m_error_message {};
Optional<ResultSet> m_result_set {};
size_t m_update_count { 0 };
size_t m_insert_count { 0 };
size_t m_delete_count { 0 };
};
template<typename ValueType>
using ResultOr = ErrorOr<ValueType, Result>;
}

View file

@ -35,4 +35,19 @@ void ResultSet::insert_row(Tuple const& row, Tuple const& sort_key)
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);
}
}

View file

@ -7,6 +7,7 @@
#pragma once
#include <AK/Vector.h>
#include <LibSQL/Result.h>
#include <LibSQL/Tuple.h>
#include <LibSQL/Type.h>
@ -19,11 +20,20 @@ struct ResultRow {
class ResultSet : public Vector<ResultRow> {
public:
ResultSet() = default;
ALWAYS_INLINE ResultSet(SQLCommand command)
: m_command(command)
{
}
SQLCommand command() const { return m_command; }
void insert_row(Tuple const& row, Tuple const& sort_key);
void limit(size_t offset, size_t limit);
private:
size_t binary_search(Tuple const& sort_key, size_t low, size_t high);
SQLCommand m_command { SQLCommand::Unknown };
};
}