Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.5 kB
7
Indexable
Never
#pragma once

#include "ast.h"
#include "schema.h"
#include "table.h"

#include <stdexcept>

namespace shdb {

namespace {
    using BitColumn = std::vector<uint8_t>;

    struct ColumnOrRef {
        const Column* column_ptr_ = nullptr;
        Column column_;
        std::optional<int> const_;
        std::optional<int> precalculated_;

        ColumnOrRef() {}
        ColumnOrRef(Column&& column) : column_(column) {}
        ColumnOrRef(const Column* column) : column_ptr_(column) {}

        bool is_ref() const {
            return column_ptr_ != nullptr;
        }

        const Column& get_ref() const {
            if (precalculated_) {
                throw std::runtime_error("cannot get ref from precalculated column");
            }
            if (column_ptr_) {
                return *column_ptr_;
            }
            return column_;
        }
    };

    ColumnOrRef column_or_ref_from_const(int value) {
        ColumnOrRef res;
        res.const_ = value;
        return res;
    }

    ColumnOrRef column_or_ref_from_precalculted(int precalculated) {
        ColumnOrRef res;
        res.precalculated_ = precalculated;
        return res;
    }

}

class Eval {
    std::shared_ptr<Schema> schema_;
    std::shared_ptr<Table> table_;
    std::shared_ptr<Select> select_;

    BitColumn eval_logical_binary(std::shared_ptr<Binary> binary) const;
    BitColumn eval_logical_unary(std::shared_ptr<Unary> unary) const;
    BitColumn eval_logical_expression(std::shared_ptr<Ast> expr) const;

    ColumnOrRef eval_binary(
        std::shared_ptr<Binary> binary,
        const std::optional<BitColumn>& where,
        bool& was_function,
        const std::string& precalculate = ""
    ) const;

    ColumnOrRef eval_unary(
        std::shared_ptr<Unary> unary,
        const std::optional<BitColumn>& where,
        bool& was_function,
        const std::string& precalculate = ""
    ) const;

    Column eval_function(
        std::shared_ptr<Function> function,
        const std::optional<BitColumn>& where,
        bool& was_function
    ) const;

    ColumnOrRef  eval_expression(
        std::shared_ptr<Ast> expr,
        const std::optional<BitColumn>& where,
        bool& was_function,
        const std::string& precalculate = ""
    ) const;
    
public:
    Eval(
        std::shared_ptr<Schema> schema,
        std::shared_ptr<Table> table
    );

    std::shared_ptr<Table> run(std::shared_ptr<Select> select);
};

}    // namespace shdb
Leave a Comment