Initial commit
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
|
||||
cc_library(
|
||||
NAME zvec_parser STATIC STRICT
|
||||
SRCS common/*.cc antlr/gen/*.cc parser/*.cc
|
||||
LIBS zvec_common
|
||||
antlr4
|
||||
zvec_index
|
||||
INCS ${PROJECT_ROOT_DIR}/src
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
|
||||
cc_library(
|
||||
NAME zvec_sqlengine STATIC STRICT
|
||||
SRCS *.cc analyzer/*.cc planner/*.cc planner/ops/*.cc planner/physical_rules/*.cc
|
||||
LIBS zvec_index
|
||||
zvec_common
|
||||
zvec_parser
|
||||
antlr4
|
||||
Arrow::arrow_acero
|
||||
INCS . ${PROJECT_ROOT_DIR}/src
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
@@ -0,0 +1,552 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_analyzer.h"
|
||||
#include <cstddef>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "analyzer/query_node.h"
|
||||
#include "core/framework/index_meta.h"
|
||||
#include "db/common/config.h"
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/error_code.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/index/common/type_helper.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/parser/select_info.h"
|
||||
#include "query_info_helper.h"
|
||||
#include "simple_rewriter.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
const std::map<NodeOp, QueryNodeOp> QueryAnalyzer::opMap_ = {
|
||||
{NodeOp::T_AND, QueryNodeOp::Q_AND},
|
||||
{NodeOp::T_OR, QueryNodeOp::Q_OR},
|
||||
{NodeOp::T_EQ, QueryNodeOp::Q_EQ},
|
||||
{NodeOp::T_NE, QueryNodeOp::Q_NE},
|
||||
{NodeOp::T_GT, QueryNodeOp::Q_GT},
|
||||
{NodeOp::T_GE, QueryNodeOp::Q_GE},
|
||||
{NodeOp::T_LT, QueryNodeOp::Q_LT},
|
||||
{NodeOp::T_LE, QueryNodeOp::Q_LE},
|
||||
{NodeOp::T_LIKE, QueryNodeOp::Q_LIKE},
|
||||
{NodeOp::T_IN, QueryNodeOp::Q_IN},
|
||||
{NodeOp::T_CONTAIN_ALL, QueryNodeOp::Q_CONTAIN_ALL},
|
||||
{NodeOp::T_CONTAIN_ANY, QueryNodeOp::Q_CONTAIN_ANY},
|
||||
{NodeOp::T_PLUS, QueryNodeOp::Q_PLUS},
|
||||
{NodeOp::T_MINUS, QueryNodeOp::Q_MINUS},
|
||||
{NodeOp::T_MUL, QueryNodeOp::Q_MUL},
|
||||
{NodeOp::T_DIV, QueryNodeOp::Q_DIV},
|
||||
{NodeOp::T_FUNCTION_CALL, QueryNodeOp::Q_FUNCTION_CALL},
|
||||
{NodeOp::T_RANGE_VALUE, QueryNodeOp::Q_RANGE_VALUE},
|
||||
{NodeOp::T_LIST_VALUE, QueryNodeOp::Q_LIST_VALUE},
|
||||
{NodeOp::T_VECTOR_MATRIX_VALUE, QueryNodeOp::Q_VECTOR_MATRIX_VALUE},
|
||||
{NodeOp::T_INT_VALUE, QueryNodeOp::Q_INT_VALUE},
|
||||
{NodeOp::T_FLOAT_VALUE, QueryNodeOp::Q_FLOAT_VALUE},
|
||||
{NodeOp::T_STRING_VALUE, QueryNodeOp::Q_STRING_VALUE},
|
||||
{NodeOp::T_NULL_VALUE, QueryNodeOp::Q_NULL_VALUE},
|
||||
{NodeOp::T_ID, QueryNodeOp::Q_ID},
|
||||
{NodeOp::T_BOOL_VALUE, QueryNodeOp::Q_BOOL_VALUE},
|
||||
{NodeOp::T_IS_NULL, QueryNodeOp::Q_IS_NULL},
|
||||
{NodeOp::T_IS_NOT_NULL, QueryNodeOp::Q_IS_NOT_NULL},
|
||||
};
|
||||
|
||||
Result<QueryInfo::Ptr> QueryAnalyzer::analyze(const CollectionSchema &schema,
|
||||
SQLInfo::Ptr sql_info) {
|
||||
// create query_info from sql_info. The purpose:
|
||||
// 1. Keep module isolated
|
||||
// 2. Everything in sql_info should be read-only, any potential changes
|
||||
// should apply to query_info. Especially for changes about syntax
|
||||
// optimization applied to query_info.
|
||||
// 3. add more necessary information and more analyzing
|
||||
// result to QueryInfo, so as to ease plan and execution.
|
||||
auto query_info_ret = create_queryinfo_from_sqlinfo(schema, *sql_info);
|
||||
if (!query_info_ret) {
|
||||
return query_info_ret;
|
||||
}
|
||||
auto query_info = std::move(query_info_ret.value());
|
||||
|
||||
// select list check
|
||||
for (auto &query_field_info : query_info->query_fields()) {
|
||||
const std::string &field_name = query_field_info->field_name();
|
||||
auto forward_field = schema.get_field(field_name);
|
||||
if (!forward_field) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument(field_name, " not defined in schema"));
|
||||
}
|
||||
|
||||
// set forward field info as reference
|
||||
query_field_info->set_field_schema_ptr(forward_field);
|
||||
|
||||
// add forward field info
|
||||
query_info->add_select_item_schema_ptr(field_name, forward_field);
|
||||
}
|
||||
|
||||
// condition check & decide index/filter condition
|
||||
if (query_info->search_cond() != nullptr) {
|
||||
// rewrite query by rule
|
||||
SimpleRewriter rewriter;
|
||||
rewriter.rewrite(query_info.get());
|
||||
|
||||
SearchCondCheckWalker search_cond_check_walker(schema);
|
||||
search_cond_check_walker.traverse_cond_node(query_info->search_cond());
|
||||
if (!search_cond_check_walker.err_msg().empty()) {
|
||||
return tl::make_unexpected(
|
||||
Status::NotSupported(search_cond_check_walker.err_msg()));
|
||||
}
|
||||
|
||||
size_t num_of_filters = search_cond_check_walker.filter_rels().size() +
|
||||
search_cond_check_walker.invert_rels().size();
|
||||
if (num_of_filters > kMaxNumOfFilters) {
|
||||
return tl::make_unexpected(
|
||||
Status::NotSupported("max number of filters is "
|
||||
"limited to 4096"));
|
||||
}
|
||||
|
||||
auto st = decide_filter_index_cond(schema, search_cond_check_walker,
|
||||
query_info.get());
|
||||
if (!st.ok()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("decide_filter_index_cond failed"));
|
||||
}
|
||||
// add forward filter meta according to final result
|
||||
auto status = set_forward_filter_meta(schema, query_info.get(),
|
||||
query_info->filter_cond().get());
|
||||
if (!status.ok()) {
|
||||
return tl::make_unexpected(status);
|
||||
}
|
||||
|
||||
// for special feature: post filtering, move filters to post filters
|
||||
if (query_info->vector_cond_info() &&
|
||||
query_info->vector_cond_info()->post_filter_topk() > 0) {
|
||||
query_info->set_post_invert_cond(query_info->invert_cond());
|
||||
query_info->set_invert_cond(nullptr);
|
||||
query_info->set_post_filter_cond(query_info->filter_cond());
|
||||
query_info->set_filter_cond(nullptr);
|
||||
LOG_DEBUG("post filter is applied. %u",
|
||||
query_info->vector_cond_info()->post_filter_topk());
|
||||
}
|
||||
}
|
||||
|
||||
// orderby list check
|
||||
for (auto &query_orderby_info : query_info->query_orderbys()) {
|
||||
const std::string &field_name = query_orderby_info->field_name();
|
||||
auto forward_field = schema.get_forward_field(field_name);
|
||||
|
||||
if (forward_field == nullptr) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument(field_name, " not defined in schema"));
|
||||
}
|
||||
|
||||
if (forward_field->is_array_type()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"order by fields should not be array data type"));
|
||||
}
|
||||
|
||||
// set forward field info as reference
|
||||
query_orderby_info->set_field_schema_ptr(forward_field);
|
||||
|
||||
// add forward field info
|
||||
query_info->add_orderby_item_schema_ptr(field_name, forward_field);
|
||||
}
|
||||
|
||||
// group by check
|
||||
if (const auto &group = query_info->group_by(); group != nullptr) {
|
||||
if (!query_info->vector_cond_info()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("group by should has vector query"));
|
||||
}
|
||||
if (!query_info->query_orderbys().empty()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("group by not "
|
||||
"support order by forward"));
|
||||
}
|
||||
auto forward_field = schema.get_forward_field(group->group_by_field);
|
||||
if (!forward_field) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
group->group_by_field, "not defined in schema"));
|
||||
}
|
||||
if (forward_field->is_array_type()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("group by fields "
|
||||
"should not be array data type"));
|
||||
}
|
||||
if (forward_field->is_vector_field()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("group by fields "
|
||||
"should not be vector data type"));
|
||||
}
|
||||
query_info->set_group_by_schema_ptr(forward_field);
|
||||
}
|
||||
return query_info;
|
||||
}
|
||||
|
||||
Status QueryAnalyzer::set_forward_filter_meta(const CollectionSchema &schema,
|
||||
QueryInfo *query_info,
|
||||
QueryNode *filter_cond) {
|
||||
if (filter_cond == nullptr) {
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
if (filter_cond->type() == QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
QueryNode *left_node = filter_cond->left().get();
|
||||
QueryNode *right_node = filter_cond->right().get();
|
||||
if (filter_cond->left() != nullptr) {
|
||||
auto ret = set_forward_filter_meta(schema, query_info, left_node);
|
||||
if (!ret.ok()) {
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
if (filter_cond->right() != nullptr) {
|
||||
return set_forward_filter_meta(schema, query_info, right_node);
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
QueryRelNode *query_rel_node = reinterpret_cast<QueryRelNode *>(filter_cond);
|
||||
query_rel_node->set_forward();
|
||||
std::string forward_field_name;
|
||||
auto *left_node = query_rel_node->left_node();
|
||||
if (left_node->op() == QueryNodeOp::Q_ID) {
|
||||
forward_field_name = left_node->text();
|
||||
} else if (left_node->op() == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
const QueryFuncNode *func_node =
|
||||
dynamic_cast<const QueryFuncNode *>(left_node);
|
||||
const auto &arguments = func_node->arguments();
|
||||
auto func_name = func_node->get_func_name();
|
||||
if (func_name == kFuncArrayLength) {
|
||||
forward_field_name = arguments[0]->text();
|
||||
} else {
|
||||
return Status::NotSupported("function ", func_name, " is not supported");
|
||||
}
|
||||
} else {
|
||||
return Status::NotSupported("left node ", left_node->op(),
|
||||
" is not supported");
|
||||
}
|
||||
auto forward_field = schema.get_forward_field(forward_field_name);
|
||||
if (forward_field == nullptr) {
|
||||
return Status::InvalidArgument(forward_field_name, " not found in schema");
|
||||
}
|
||||
if (forward_field->has_invert_index()) {
|
||||
// invert condition to forward condition
|
||||
QueryNode *right_node =
|
||||
std::dynamic_pointer_cast<QueryNode>(query_rel_node->right()).get();
|
||||
// Revert numeric buf to numeric text
|
||||
QueryInfoHelper::constant_node_data_buf_2_text(
|
||||
forward_field->element_data_type(), forward_field->is_array_type(),
|
||||
right_node);
|
||||
}
|
||||
|
||||
// forward_field is nullptr for schema free field
|
||||
query_info->add_forward_filter_schema_ptr(forward_field_name, forward_field);
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
// decide filter or index condition according to data collected from
|
||||
// search_cond_check_walker
|
||||
Status QueryAnalyzer::decide_filter_index_cond(
|
||||
const CollectionSchema &schema,
|
||||
const SearchCondCheckWalker &search_cond_check_walker,
|
||||
QueryInfo *query_info) {
|
||||
const std::vector<QueryRelNode *> &filter_rels =
|
||||
search_cond_check_walker.filter_rels();
|
||||
const std::vector<QueryRelNode *> &invert_rels =
|
||||
search_cond_check_walker.invert_rels();
|
||||
QueryRelNode *vector_rel = search_cond_check_walker.vector_rel();
|
||||
uint32_t vector_rel_size = (vector_rel != nullptr) ? 1 : 0;
|
||||
uint32_t invert_size = (uint32_t)invert_rels.size();
|
||||
uint32_t filter_size = (uint32_t)filter_rels.size();
|
||||
|
||||
LOG_DEBUG("vector_rel_size[%u] invert[%u] filter[%u]", vector_rel_size,
|
||||
invert_size, filter_size);
|
||||
|
||||
// sanity check
|
||||
// check if all invert conds exist in one sub-tree, if yes,
|
||||
// move the sub-tree as final invert cond for query.
|
||||
if (invert_size > 0) {
|
||||
QueryNode *invert_subroot =
|
||||
get_invert_subroot(query_info->search_cond().get());
|
||||
if (invert_subroot != nullptr) {
|
||||
LOG_DEBUG(
|
||||
"all invert conds are under one sub-root, invert query applied. "
|
||||
"[%s]",
|
||||
invert_subroot->text().c_str());
|
||||
query_info->set_invert_cond(
|
||||
invert_subroot->detach_from_search_cond(query_info));
|
||||
}
|
||||
}
|
||||
|
||||
if (vector_rel_size > 0) {
|
||||
if (vector_rel->or_ancestor()) {
|
||||
return Status::InvalidArgument(
|
||||
"vector condition must NOT be OR ancestor.");
|
||||
}
|
||||
std::shared_ptr<QueryInfo::QueryVectorCondInfo> vector_cond_info;
|
||||
Status st = check_and_convert_vector(schema, vector_rel, &vector_cond_info);
|
||||
if (!st.ok()) {
|
||||
return st;
|
||||
}
|
||||
vector_rel->detach_from_search_cond(query_info);
|
||||
query_info->set_vector_cond_info(std::move(vector_cond_info));
|
||||
}
|
||||
|
||||
// after set invert and vector well, the left conds are filter cond if any
|
||||
if (query_info->search_cond() != nullptr) {
|
||||
if (filter_size != 0) { // optimize
|
||||
query_info->set_filter_cond(query_info->search_cond());
|
||||
}
|
||||
// after above steps, all conds are moved to vector/invert/forward,
|
||||
// so clear search cond finally.
|
||||
query_info->set_search_cond(nullptr);
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
QueryNode *QueryAnalyzer::get_invert_subroot(QueryNode *search_cond) {
|
||||
SubRootResult subroot_result;
|
||||
std::function<bool(QueryRelNode * node)> rule = [](QueryRelNode *rel_node) {
|
||||
return rel_node->is_invert();
|
||||
};
|
||||
QueryInfoHelper::find_subroot_by_rule(search_cond, rule, &subroot_result);
|
||||
return subroot_result.subroot;
|
||||
}
|
||||
|
||||
Result<QueryInfo::Ptr> QueryAnalyzer::create_queryinfo_from_sqlinfo(
|
||||
const CollectionSchema &schema, const SQLInfo &sql_info) {
|
||||
QueryInfo::Ptr query_info = std::make_shared<QueryInfo>();
|
||||
|
||||
if (sql_info.type() != SQLInfo::SQLType::SELECT) {
|
||||
return tl::make_unexpected(
|
||||
Status::NotSupported("only select is "
|
||||
"supported"));
|
||||
}
|
||||
|
||||
SelectInfo::Ptr select_info =
|
||||
std::dynamic_pointer_cast<SelectInfo>(sql_info.base_info());
|
||||
if (select_info == nullptr) {
|
||||
return tl::make_unexpected(Status::InternalError("select_info is null"));
|
||||
}
|
||||
|
||||
// copy search and filter
|
||||
std::string err;
|
||||
query_info->set_search_cond(
|
||||
create_querynode_from_node(select_info->search_cond(), 0, &err));
|
||||
if (!err.empty()) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("create querynode from node failed: ", err));
|
||||
}
|
||||
|
||||
// set select element info
|
||||
for (const auto &select_elem_info : select_info->selected_elems()) {
|
||||
if (select_elem_info->is_empty()) {
|
||||
continue; // leave query_field to be null
|
||||
}
|
||||
|
||||
if (select_elem_info->is_asterisk()) {
|
||||
query_info->set_asterisk(true);
|
||||
for (auto &forward_field : schema.forward_fields()) {
|
||||
if (!zvec::FieldSchema::is_vector_field(
|
||||
forward_field->element_data_type())) {
|
||||
query_info->add_query_field(std::make_shared<QueryFieldInfo>(
|
||||
forward_field->name(), "", "", "", false));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
query_info->add_query_field(std::make_shared<QueryFieldInfo>(
|
||||
select_elem_info->field_name(), select_elem_info->alias(),
|
||||
select_elem_info->func_name(), select_elem_info->func_param(),
|
||||
select_elem_info->is_func_param_asterisk()));
|
||||
}
|
||||
|
||||
if (select_info->include_vector()) {
|
||||
query_info->set_include_vector(true);
|
||||
for (auto &index_field : schema.vector_fields()) {
|
||||
if (!query_info->exists_in_query_fields(index_field->name())) {
|
||||
query_info->add_query_field(std::make_shared<QueryFieldInfo>(
|
||||
index_field->name(), "", "", "", false));
|
||||
}
|
||||
}
|
||||
}
|
||||
query_info->set_include_doc_id(select_info->is_include_doc_id());
|
||||
|
||||
// set order by element info
|
||||
for (auto &orderby_elem_info : select_info->orderby_elems()) {
|
||||
query_info->add_query_orderby(std::make_shared<QueryOrderbyInfo>(
|
||||
orderby_elem_info->field_name(), orderby_elem_info->is_desc()));
|
||||
}
|
||||
|
||||
// set topN
|
||||
if (select_info->limit() > 0) {
|
||||
query_info->set_query_topn(select_info->limit());
|
||||
} else {
|
||||
query_info->set_query_topn(DEFAULT_TOPN);
|
||||
}
|
||||
|
||||
// set group by
|
||||
query_info->set_group_by(select_info->group_by());
|
||||
|
||||
return query_info;
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryAnalyzer::create_querynode_from_node(const Node::Ptr &node,
|
||||
uint32_t level,
|
||||
std::string *err) {
|
||||
QueryNode::Ptr query_node = nullptr;
|
||||
|
||||
if (node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// copy subclass object according to node op
|
||||
if (node->type() == Node::NodeType::REL_EXPR) {
|
||||
// REL_EXPR include T_EQ, T_NE, T_LT, T_GT, T_LE, T_GE, T_LIKE, T_IN,
|
||||
// T_CONTAIN_ALL, T_CONTAIN_ANY, T_IS_NULL, T_IS_NOT_NULL
|
||||
// use type == REL_EXPR to simplify */
|
||||
query_node = std::make_shared<QueryRelNode>();
|
||||
} else {
|
||||
if (node->op() == NodeOp::T_INT_VALUE ||
|
||||
node->op() == NodeOp::T_FLOAT_VALUE ||
|
||||
node->op() == NodeOp::T_STRING_VALUE ||
|
||||
node->op() == NodeOp::T_NULL_VALUE ||
|
||||
node->op() == NodeOp::T_BOOL_VALUE) {
|
||||
ConstantNode::Ptr constant_node =
|
||||
std::dynamic_pointer_cast<ConstantNode>(node);
|
||||
query_node = std::make_shared<QueryConstantNode>(constant_node->value());
|
||||
} else if (node->op() == NodeOp::T_ID) {
|
||||
IDNode::Ptr id_node = std::dynamic_pointer_cast<IDNode>(node);
|
||||
query_node = std::make_shared<QueryIDNode>(id_node->value());
|
||||
} else if (node->op() == NodeOp::T_VECTOR_MATRIX_VALUE) {
|
||||
VectorMatrixNode::Ptr vector_node =
|
||||
std::dynamic_pointer_cast<VectorMatrixNode>(node);
|
||||
query_node =
|
||||
std::make_shared<QueryVectorMatrixNode>(std::move(vector_node));
|
||||
} else if (node->op() == NodeOp::T_FUNCTION_CALL) {
|
||||
FuncNode::Ptr func_node = std::dynamic_pointer_cast<FuncNode>(node);
|
||||
QueryFuncNode::Ptr query_func_node = std::make_shared<QueryFuncNode>();
|
||||
query_func_node->set_func_name_node(create_querynode_from_node(
|
||||
func_node->get_func_name_node(), level + 1, err));
|
||||
for (auto argument : func_node->arguments()) {
|
||||
query_func_node->add_argument(
|
||||
create_querynode_from_node(argument, level + 1, err));
|
||||
}
|
||||
query_node = std::move(query_func_node);
|
||||
} else if (node->op() == NodeOp::T_LIST_VALUE) {
|
||||
InValueExprListNode::Ptr in_value_expr_list_node =
|
||||
std::dynamic_pointer_cast<InValueExprListNode>(node);
|
||||
QueryListNode::Ptr query_in_value_expr_node =
|
||||
std::make_shared<QueryListNode>();
|
||||
|
||||
for (auto in_value_expr : in_value_expr_list_node->in_value_expr_list()) {
|
||||
query_in_value_expr_node->add_value_expr(
|
||||
create_querynode_from_node(in_value_expr, level, err));
|
||||
}
|
||||
query_in_value_expr_node->set_exclude(in_value_expr_list_node->exclude());
|
||||
query_node = std::move(query_in_value_expr_node);
|
||||
} else { /* others are normal Node */
|
||||
query_node = std::make_shared<QueryNode>();
|
||||
}
|
||||
}
|
||||
|
||||
if (query_node == nullptr) {
|
||||
*err = "node op is not handled. " + node->type_to_str(node->op());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// copy nodeOp
|
||||
QueryNodeOp query_node_op = nodeop_2_query_nodeop(node->op());
|
||||
if (query_node_op == QueryNodeOp::Q_NONE) {
|
||||
*err = "cannot find query node op " + Node::type_to_str(node->op());
|
||||
return nullptr;
|
||||
}
|
||||
query_node->set_op(query_node_op);
|
||||
|
||||
// set & increment level
|
||||
query_node->set_level(level++);
|
||||
|
||||
// copy left & right
|
||||
if (node->left() != nullptr) {
|
||||
query_node->set_left(create_querynode_from_node(node->left(), level, err));
|
||||
}
|
||||
if (node->right() != nullptr) {
|
||||
query_node->set_right(
|
||||
create_querynode_from_node(node->right(), level, err));
|
||||
}
|
||||
|
||||
return query_node;
|
||||
}
|
||||
|
||||
QueryNodeOp QueryAnalyzer::nodeop_2_query_nodeop(NodeOp op) {
|
||||
auto iter = opMap_.find(op);
|
||||
if (iter == opMap_.end()) {
|
||||
return QueryNodeOp::Q_NONE;
|
||||
}
|
||||
return iter->second;
|
||||
}
|
||||
|
||||
Status QueryAnalyzer::check_and_convert_vector(
|
||||
const CollectionSchema &schema, const QueryRelNode *query_rel_node,
|
||||
std::shared_ptr<QueryInfo::QueryVectorCondInfo> *vector_cond) {
|
||||
const QueryNode::Ptr &vector_field_node = query_rel_node->left();
|
||||
const auto &vector_field_name = vector_field_node->text();
|
||||
|
||||
auto vector_meta = schema.get_vector_field(vector_field_name);
|
||||
if (vector_meta == nullptr) {
|
||||
return Status::InvalidArgument("vector field not found:",
|
||||
vector_field_name);
|
||||
}
|
||||
|
||||
std::string vector_term;
|
||||
uint32_t dimension = vector_meta->dimension();
|
||||
std::string vector_sparse_indices;
|
||||
std::string vector_sparse_values;
|
||||
QueryParams::Ptr query_params;
|
||||
|
||||
const QueryNode::Ptr &vector_value_node = query_rel_node->right();
|
||||
|
||||
// for pb request
|
||||
if (vector_value_node->op() == QueryNodeOp::Q_VECTOR_MATRIX_VALUE) {
|
||||
// for format vector = [,,,]
|
||||
const QueryVectorMatrixNode::Ptr &vector_node =
|
||||
std::dynamic_pointer_cast<QueryVectorMatrixNode>(vector_value_node);
|
||||
// we only have vector matrix, other info is not available
|
||||
vector_term = vector_node->matrix();
|
||||
vector_sparse_indices = vector_node->sparse_indices();
|
||||
vector_sparse_values = vector_node->sparse_values();
|
||||
query_params = vector_node->query_params();
|
||||
} else {
|
||||
return Status::InvalidArgument("invalid vector value node. op[",
|
||||
vector_value_node->op_name(), "], text[",
|
||||
vector_value_node->text(), "]");
|
||||
}
|
||||
|
||||
auto core_data_type =
|
||||
DataTypeCodeBook::to_data_type(vector_meta->data_type());
|
||||
if (core_data_type == core::IndexMeta::DataType::DT_UNDEFINED) {
|
||||
return Status::InvalidArgument("invalid data type:",
|
||||
(int)vector_meta->data_type());
|
||||
}
|
||||
|
||||
*vector_cond = std::make_shared<QueryInfo::QueryVectorCondInfo>(
|
||||
vector_meta, vector_term, core_data_type, dimension,
|
||||
std::move(vector_sparse_indices), std::move(vector_sparse_values),
|
||||
std::move(query_params));
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "db/common/status.h"
|
||||
#include "db/sqlengine/parser/sql_info.h"
|
||||
#include "query_info.h"
|
||||
#include "query_node_walker.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class QueryAnalyzer {
|
||||
public:
|
||||
QueryAnalyzer() = default;
|
||||
|
||||
Result<QueryInfo::Ptr> analyze(const CollectionSchema &schema,
|
||||
SQLInfo::Ptr sql_info);
|
||||
const std::string &err_msg();
|
||||
int err_code();
|
||||
|
||||
private:
|
||||
Result<QueryInfo::Ptr> create_queryinfo_from_sqlinfo(
|
||||
const CollectionSchema &schema, const SQLInfo &sql_info);
|
||||
QueryNode::Ptr create_querynode_from_node(const Node::Ptr &node,
|
||||
uint32_t level, std::string *err);
|
||||
QueryNodeOp nodeop_2_query_nodeop(NodeOp op);
|
||||
Status decide_filter_index_cond(
|
||||
const CollectionSchema &schema,
|
||||
const SearchCondCheckWalker &search_cond_check_walker,
|
||||
QueryInfo *query_info);
|
||||
QueryNode *get_invert_subroot(QueryNode *node);
|
||||
Status check_and_convert_vector(
|
||||
const CollectionSchema &schema, const QueryRelNode *query_rel_node,
|
||||
std::shared_ptr<QueryInfo::QueryVectorCondInfo> *vector_cond);
|
||||
|
||||
Status set_forward_filter_meta(const CollectionSchema &schema,
|
||||
QueryInfo *query_info, QueryNode *filter_cond);
|
||||
|
||||
private:
|
||||
static const std::map<NodeOp, QueryNodeOp> opMap_;
|
||||
static const int DEFAULT_TOPN = 20;
|
||||
static const size_t kMaxNumOfFilters = 4096;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_field_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
std::string QueryFieldInfo::to_string() const {
|
||||
std::string str = "";
|
||||
if (is_func_call()) {
|
||||
if (is_func_param_asterisk()) {
|
||||
str += func_name_ + "(*)";
|
||||
} else {
|
||||
str += func_name_ + "(" + func_param_ + ")";
|
||||
}
|
||||
} else {
|
||||
str = field_name_;
|
||||
if (!alias_.empty()) {
|
||||
str += " as " + alias_;
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,103 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "db/index/common/schema.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class QueryFieldInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryFieldInfo>;
|
||||
|
||||
QueryFieldInfo() {}
|
||||
|
||||
QueryFieldInfo(const std::string &m_field_name, const std::string &m_alias,
|
||||
const std::string &m_func_name,
|
||||
const std::string &m_func_param, bool m_func_param_asterisk)
|
||||
: field_name_(m_field_name),
|
||||
alias_(m_alias),
|
||||
func_name_(m_func_name),
|
||||
func_param_(m_func_param),
|
||||
func_param_asterisk_(m_func_param_asterisk) {}
|
||||
|
||||
~QueryFieldInfo() {}
|
||||
|
||||
void set_field_name(const std::string &value) {
|
||||
field_name_ = value;
|
||||
}
|
||||
|
||||
const std::string &field_name() const {
|
||||
return field_name_;
|
||||
}
|
||||
|
||||
void set_alias(const std::string &value) {
|
||||
alias_ = value;
|
||||
}
|
||||
const std::string &alias() const {
|
||||
return alias_;
|
||||
}
|
||||
|
||||
const std::string &func_name() const {
|
||||
return func_name_;
|
||||
}
|
||||
|
||||
void set_func_name(const std::string &value) {
|
||||
func_name_ = value;
|
||||
}
|
||||
|
||||
const std::string &func_param() const {
|
||||
return func_param_;
|
||||
}
|
||||
|
||||
void set_func_param(const std::string &value) {
|
||||
func_param_ = value;
|
||||
}
|
||||
|
||||
bool is_func_call() const {
|
||||
return (!func_name_.empty());
|
||||
}
|
||||
|
||||
void set_func_param_asterisk(bool value) {
|
||||
func_param_asterisk_ = value;
|
||||
}
|
||||
bool is_func_param_asterisk() const {
|
||||
return func_param_asterisk_;
|
||||
}
|
||||
|
||||
void set_field_schema_ptr(const zvec::FieldSchema *field_schema_ptr) {
|
||||
field_schema_ptr_ = field_schema_ptr;
|
||||
}
|
||||
const zvec::FieldSchema *field_schema_ptr() {
|
||||
return field_schema_ptr_;
|
||||
}
|
||||
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
std::string field_name_{""};
|
||||
std::string alias_{""};
|
||||
|
||||
std::string func_name_{""};
|
||||
std::string func_param_{""};
|
||||
bool func_param_asterisk_{false};
|
||||
|
||||
const zvec::FieldSchema *field_schema_ptr_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,116 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_info.h"
|
||||
#include <ailego/utility/float_helper.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "db/common/constants.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
std::string QueryInfo::to_string() const {
|
||||
std::string str = "Query Info: {\n";
|
||||
|
||||
if (!query_fields_.empty()) {
|
||||
str += "query_fields: ";
|
||||
for (auto iter = query_fields_.begin(); iter != query_fields_.end();
|
||||
iter++) {
|
||||
if (iter != query_fields_.begin()) {
|
||||
str += ", ";
|
||||
}
|
||||
QueryFieldInfo::Ptr query_field_info_ptr = *iter;
|
||||
str += query_field_info_ptr->to_string();
|
||||
}
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (!query_orderbys_.empty()) {
|
||||
str += "query_orderbys: ";
|
||||
for (auto iter = query_orderbys_.begin(); iter != query_orderbys_.end();
|
||||
iter++) {
|
||||
if (iter != query_orderbys_.begin()) {
|
||||
str += ", ";
|
||||
}
|
||||
QueryOrderbyInfo::Ptr query_orderby_info_ptr = *iter;
|
||||
str += query_orderby_info_ptr->to_string();
|
||||
}
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (!all_fetched_schema_schemas_.empty()) {
|
||||
str += "all_fetched_field_schemas: ";
|
||||
for (auto iter = all_fetched_schema_schemas_.begin();
|
||||
iter != all_fetched_schema_schemas_.end(); iter++) {
|
||||
if (iter != all_fetched_schema_schemas_.begin()) {
|
||||
str += ", ";
|
||||
}
|
||||
str += iter->first;
|
||||
}
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (group_by_ != nullptr) {
|
||||
str += "group_by: " + group_by_->to_string() + "\n";
|
||||
}
|
||||
|
||||
str += "query_topn: " + std::to_string(query_topn_) + " ";
|
||||
str += "\n";
|
||||
|
||||
str += "search_cond:\n";
|
||||
if (search_cond_ != nullptr) {
|
||||
str += search_cond_->text();
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
str += "vector_cond:\n";
|
||||
if (vector_cond_info_ != nullptr) {
|
||||
ailego::StringHelper::Append(
|
||||
&str, vector_cond_info_->vector_field_name(), "=", "feature(",
|
||||
vector_cond_info_->batch() > 1 ? "matrix[[...],...]" : "vector[...]",
|
||||
", ", vector_cond_info_->data_type(), ",", vector_cond_info_->batch(),
|
||||
")(FEATURE",
|
||||
vector_cond_info_->vector_sparse_indices().empty() ? ""
|
||||
: "_WITH_SPARSE",
|
||||
")\n");
|
||||
}
|
||||
|
||||
str += "filter_cond:\n";
|
||||
if (filter_cond_ != nullptr) {
|
||||
str += filter_cond_->text();
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
str += "invert_cond:\n";
|
||||
if (invert_cond_ != nullptr) {
|
||||
str += invert_cond_->text();
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
str += "}";
|
||||
return str;
|
||||
}
|
||||
|
||||
bool QueryInfo::is_filter_unsatisfiable() const {
|
||||
if (invert_cond_ && invert_cond_->predictate_result().has_value() &&
|
||||
!invert_cond_->predictate_result().value()) {
|
||||
return true;
|
||||
}
|
||||
if (filter_cond_ && filter_cond_->predictate_result().has_value() &&
|
||||
!filter_cond_->predictate_result().value()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,375 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <core/framework/index_meta.h>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "db/sqlengine/common/group_by.h"
|
||||
#include "query_field_info.h"
|
||||
#include "query_node.h"
|
||||
#include "query_orderby_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
struct FieldAndSchema {
|
||||
FieldAndSchema(std::string field, const FieldSchema *schema)
|
||||
: field_name(std::move(field)), field_schema_ptr(schema) {}
|
||||
|
||||
std::string field_name;
|
||||
const FieldSchema *field_schema_ptr;
|
||||
};
|
||||
|
||||
class QueryInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryInfo>;
|
||||
|
||||
class QueryVectorCondInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryVectorCondInfo>;
|
||||
|
||||
QueryVectorCondInfo(const FieldSchema *vector_schema,
|
||||
const std::string &vector_term,
|
||||
core::IndexMeta::DataType core_data_type, int dimension,
|
||||
std::string vector_sparse_indices,
|
||||
std::string vector_sparse_values,
|
||||
QueryParams::Ptr query_params)
|
||||
: vector_schema_(vector_schema),
|
||||
vector_term_(vector_term),
|
||||
data_type_(core_data_type),
|
||||
dimension_(dimension),
|
||||
vector_sparse_indices_(std::move(vector_sparse_indices)),
|
||||
vector_sparse_values_(std::move(vector_sparse_values)),
|
||||
query_params_(std::move(query_params)) {
|
||||
auto *vector_params = dynamic_cast<VectorIndexParams *>(
|
||||
vector_schema_->index_params().get());
|
||||
if (vector_params && vector_params->metric_type() == MetricType::IP) {
|
||||
reverse_sort_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
std::string vector_field_name() const {
|
||||
return vector_schema_->name();
|
||||
}
|
||||
|
||||
const FieldSchema *vector_schema() const {
|
||||
return vector_schema_;
|
||||
}
|
||||
|
||||
const std::string &vector_term() const {
|
||||
return vector_term_;
|
||||
}
|
||||
|
||||
core::IndexMeta::DataType data_type() const {
|
||||
return data_type_;
|
||||
}
|
||||
|
||||
uint32_t dimension() const {
|
||||
return dimension_;
|
||||
}
|
||||
|
||||
uint32_t post_filter_topk() const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int batch() const {
|
||||
return 1;
|
||||
}
|
||||
|
||||
uint32_t sparse_count() const {
|
||||
return vector_sparse_indices_.size() / sizeof(uint32_t);
|
||||
}
|
||||
|
||||
const std::string &vector_sparse_indices() const {
|
||||
return vector_sparse_indices_;
|
||||
}
|
||||
|
||||
const std::string &vector_sparse_values() const {
|
||||
return vector_sparse_values_;
|
||||
}
|
||||
|
||||
bool is_reverse_sort() const {
|
||||
return reverse_sort_;
|
||||
}
|
||||
|
||||
const QueryParams::Ptr &query_params() const {
|
||||
return query_params_;
|
||||
}
|
||||
|
||||
private:
|
||||
const FieldSchema *vector_schema_{nullptr};
|
||||
std::string vector_term_{""};
|
||||
core::IndexMeta::DataType data_type_;
|
||||
uint32_t dimension_{0};
|
||||
std::string vector_sparse_indices_{""};
|
||||
std::string vector_sparse_values_{""};
|
||||
QueryParams::Ptr query_params_;
|
||||
bool reverse_sort_{false};
|
||||
};
|
||||
|
||||
public:
|
||||
QueryInfo() = default;
|
||||
~QueryInfo() = default;
|
||||
|
||||
void set_search_cond(QueryNode::Ptr value) {
|
||||
search_cond_ = std::move(value);
|
||||
}
|
||||
|
||||
QueryNode::Ptr search_cond() const {
|
||||
return search_cond_;
|
||||
}
|
||||
|
||||
void set_invert_cond(QueryNode::Ptr value) {
|
||||
invert_cond_ = std::move(value);
|
||||
}
|
||||
|
||||
QueryNode::Ptr invert_cond() const {
|
||||
return invert_cond_;
|
||||
}
|
||||
|
||||
void set_filter_cond(QueryNode::Ptr value) {
|
||||
filter_cond_ = std::move(value);
|
||||
}
|
||||
|
||||
QueryNode::Ptr filter_cond() const {
|
||||
return filter_cond_;
|
||||
}
|
||||
|
||||
void set_vector_cond_info(QueryVectorCondInfo::Ptr value) {
|
||||
vector_cond_info_ = std::move(value);
|
||||
}
|
||||
|
||||
const QueryVectorCondInfo::Ptr &vector_cond_info() const {
|
||||
return vector_cond_info_;
|
||||
}
|
||||
|
||||
void set_query_topn(uint32_t value) {
|
||||
query_topn_ = value;
|
||||
}
|
||||
|
||||
uint32_t query_topn() const {
|
||||
return query_topn_;
|
||||
}
|
||||
|
||||
const std::vector<QueryFieldInfo::Ptr> &query_fields() const {
|
||||
return query_fields_;
|
||||
}
|
||||
|
||||
void add_query_field(QueryFieldInfo::Ptr &&query_field_info) {
|
||||
query_fields_.emplace_back(query_field_info);
|
||||
}
|
||||
|
||||
const std::vector<QueryOrderbyInfo::Ptr> &query_orderbys() const {
|
||||
return query_orderbys_;
|
||||
}
|
||||
|
||||
void add_query_orderby(QueryOrderbyInfo::Ptr &&query_orderby_info) {
|
||||
query_orderbys_.emplace_back(query_orderby_info);
|
||||
}
|
||||
|
||||
void add_select_item_schema_ptr(
|
||||
std::string field, const zvec::FieldSchema *select_item_schema_ptr) {
|
||||
bool is_vector_field = false;
|
||||
if (select_item_schema_ptr != nullptr &&
|
||||
FieldSchema::is_vector_field(select_item_schema_ptr->data_type())) {
|
||||
is_vector_field = true;
|
||||
}
|
||||
add_fetched_schema(field, select_item_schema_ptr);
|
||||
if (is_vector_field) {
|
||||
selected_vector_fields_.emplace_back(field, select_item_schema_ptr);
|
||||
} else {
|
||||
selectd_scalar_field_names_.emplace_back(field);
|
||||
}
|
||||
select_item_schema_ptrs_.emplace_back(std::move(field),
|
||||
std::move(select_item_schema_ptr));
|
||||
}
|
||||
|
||||
const std::vector<FieldAndSchema> &select_item_schema_ptrs() const {
|
||||
return select_item_schema_ptrs_;
|
||||
}
|
||||
|
||||
void add_forward_filter_schema_ptr(
|
||||
std::string field, const zvec::FieldSchema *forward_filter_schema_ptr) {
|
||||
add_fetched_schema(field, forward_filter_schema_ptr);
|
||||
if (forward_filter_field_names_set_.emplace(field).second) {
|
||||
forward_filter_field_names_.emplace_back(std::move(field));
|
||||
}
|
||||
}
|
||||
|
||||
void add_orderby_item_schema_ptr(
|
||||
std::string field, const zvec::FieldSchema *orderby_item_schema_ptr) {
|
||||
add_fetched_schema(field, orderby_item_schema_ptr);
|
||||
orderby_item_schema_ptrs_.emplace_back(std::move(field),
|
||||
orderby_item_schema_ptr);
|
||||
}
|
||||
|
||||
const std::vector<FieldAndSchema> &orderby_item_schema_ptrs() const {
|
||||
return orderby_item_schema_ptrs_;
|
||||
}
|
||||
|
||||
void add_fetched_schema(std::string field,
|
||||
const zvec::FieldSchema *other_item_schema_ptr) {
|
||||
auto res = all_fetched_schema_schemas_.emplace(std::move(field),
|
||||
other_item_schema_ptr);
|
||||
if (res.second &&
|
||||
!FieldSchema::is_vector_field(other_item_schema_ptr->data_type())) {
|
||||
all_fetched_scalar_field_names_.emplace_back(
|
||||
other_item_schema_ptr->name());
|
||||
}
|
||||
}
|
||||
|
||||
const std::unordered_map<std::string, const FieldSchema *> &
|
||||
all_fetched_schemas() const {
|
||||
return all_fetched_schema_schemas_;
|
||||
}
|
||||
|
||||
bool is_field_fetched(const std::string &field) const {
|
||||
return all_fetched_schema_schemas_.count(field) > 0;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &get_selected_scalar_field_names() {
|
||||
return selectd_scalar_field_names_;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &get_all_fetched_scalar_field_names() {
|
||||
return all_fetched_scalar_field_names_;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &get_forward_filter_field_names() {
|
||||
return forward_filter_field_names_;
|
||||
};
|
||||
|
||||
|
||||
bool exists_in_query_fields(const std::string &field_name) {
|
||||
for (auto query_field_info : query_fields_) {
|
||||
if (field_name == query_field_info->field_name()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void set_post_invert_cond(const QueryNode::Ptr &value) {
|
||||
post_invert_cond_ = value;
|
||||
}
|
||||
|
||||
const QueryNode::Ptr &post_invert_cond() const {
|
||||
return post_invert_cond_;
|
||||
}
|
||||
|
||||
void set_post_filter_cond(const QueryNode::Ptr &value) {
|
||||
post_filter_cond_ = value;
|
||||
}
|
||||
|
||||
const QueryNode::Ptr &post_filter_cond() const {
|
||||
return post_filter_cond_;
|
||||
}
|
||||
|
||||
void set_asterisk(bool value) {
|
||||
asterisk_ = value;
|
||||
}
|
||||
|
||||
bool is_asterisk() const {
|
||||
return asterisk_;
|
||||
}
|
||||
|
||||
void set_include_vector(bool value) {
|
||||
include_vector_ = value;
|
||||
}
|
||||
|
||||
bool is_include_vector() const {
|
||||
return include_vector_;
|
||||
}
|
||||
|
||||
void set_include_doc_id(bool value) {
|
||||
include_doc_id_ = value;
|
||||
if (include_doc_id_) {
|
||||
selectd_scalar_field_names_.emplace_back(GLOBAL_DOC_ID);
|
||||
all_fetched_scalar_field_names_.emplace_back(GLOBAL_DOC_ID);
|
||||
}
|
||||
}
|
||||
|
||||
bool is_include_doc_id() const {
|
||||
return include_doc_id_;
|
||||
}
|
||||
|
||||
const std::vector<FieldAndSchema> &selected_vector_fields() const {
|
||||
return selected_vector_fields_;
|
||||
}
|
||||
|
||||
void set_group_by(GroupBy::Ptr group_by) {
|
||||
group_by_ = std::move(group_by);
|
||||
}
|
||||
const GroupBy::Ptr &group_by() const {
|
||||
return group_by_;
|
||||
}
|
||||
|
||||
void set_group_by_schema_ptr(const FieldSchema *group_by_schema_ptr) {
|
||||
group_by_schema_ptr_ = group_by_schema_ptr;
|
||||
}
|
||||
const FieldSchema *group_by_schema_ptr() const {
|
||||
return group_by_schema_ptr_;
|
||||
}
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
bool is_filter_unsatisfiable() const;
|
||||
|
||||
private:
|
||||
QueryNode::Ptr search_cond_{nullptr};
|
||||
|
||||
QueryNode::Ptr invert_cond_{nullptr};
|
||||
QueryNode::Ptr filter_cond_{nullptr};
|
||||
|
||||
QueryVectorCondInfo::Ptr vector_cond_info_{nullptr};
|
||||
|
||||
// these two are for post filtering only
|
||||
QueryNode::Ptr post_invert_cond_{nullptr};
|
||||
QueryNode::Ptr post_filter_cond_{nullptr};
|
||||
|
||||
uint32_t query_topn_{0};
|
||||
std::vector<QueryFieldInfo::Ptr> query_fields_{};
|
||||
std::vector<QueryOrderbyInfo::Ptr> query_orderbys_{};
|
||||
|
||||
GroupBy::Ptr group_by_{};
|
||||
|
||||
// from analyzing
|
||||
std::unordered_set<std::string> forward_filter_field_names_set_{};
|
||||
std::vector<std::string> forward_filter_field_names_{};
|
||||
// USER_ID are system needed fields
|
||||
std::vector<std::string> selectd_scalar_field_names_{USER_ID};
|
||||
std::vector<FieldAndSchema> select_item_schema_ptrs_{};
|
||||
std::vector<FieldAndSchema> orderby_item_schema_ptrs_{};
|
||||
// all fetched field schemas from forward, including user select fields and
|
||||
// system needed fields
|
||||
std::unordered_map<std::string, const FieldSchema *>
|
||||
all_fetched_schema_schemas_{};
|
||||
std::vector<std::string> all_fetched_scalar_field_names_{USER_ID,
|
||||
LOCAL_ROW_ID};
|
||||
|
||||
bool asterisk_{false};
|
||||
bool include_vector_{false};
|
||||
bool include_doc_id_{false};
|
||||
std::vector<FieldAndSchema> selected_vector_fields_{};
|
||||
const FieldSchema *group_by_schema_ptr_{};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,193 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_info_helper.h"
|
||||
#include <memory>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
|
||||
bool QueryInfoHelper::text_2_data_buf(const std::string &text,
|
||||
zvec::DataType data_type,
|
||||
std::string *data_buf) {
|
||||
if (data_type == zvec::DataType::INT32) {
|
||||
int32_t int32_val;
|
||||
if (!ailego::StringHelper::ToInt32(text, &int32_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&int32_val, sizeof(int32_t));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::UINT32) {
|
||||
uint32_t uint32_val;
|
||||
if (!ailego::StringHelper::ToUint32(text, &uint32_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&uint32_val, sizeof(uint32_t));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::INT64) {
|
||||
int64_t int64_val;
|
||||
if (!ailego::StringHelper::ToInt64(text, &int64_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&int64_val, sizeof(int64_t));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::UINT64) {
|
||||
uint64_t uint64_val;
|
||||
if (!ailego::StringHelper::ToUint64(text, &uint64_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&uint64_val, sizeof(uint64_t));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::FLOAT) {
|
||||
float float_val;
|
||||
if (!ailego::StringHelper::ToFloat(text, &float_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&float_val, sizeof(float));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::DOUBLE) {
|
||||
double double_val;
|
||||
if (!ailego::StringHelper::ToDouble(text, &double_val)) {
|
||||
return false;
|
||||
}
|
||||
data_buf->assign((const char *)&double_val, sizeof(double));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool QueryInfoHelper::data_buf_2_text(const std::string &data_buf,
|
||||
zvec::DataType data_type,
|
||||
std::string *text) {
|
||||
if (data_type == zvec::DataType::INT32) {
|
||||
*text = ailego::StringHelper::ToString(*(int32_t *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::UINT32) {
|
||||
*text = ailego::StringHelper::ToString(*(uint32_t *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::INT64) {
|
||||
*text = ailego::StringHelper::ToString(*(int64_t *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::UINT64) {
|
||||
*text = ailego::StringHelper::ToString(*(uint64_t *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::FLOAT) {
|
||||
*text = ailego::StringHelper::ToString(*(float *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::DOUBLE) {
|
||||
*text = ailego::StringHelper::ToString(*(double *)data_buf.data());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void QueryInfoHelper::constant_node_data_buf_2_text(DataType data_type,
|
||||
bool is_array_type,
|
||||
QueryNode *node) {
|
||||
if (is_array_type) { // node->op() == QueryNodeOp::Q_LIST_VALUE
|
||||
QueryListNode *list_node = reinterpret_cast<QueryListNode *>(node);
|
||||
for (auto &child_node : list_node->value_expr_list()) {
|
||||
if (std::string numeric_text{""};
|
||||
data_buf_2_text(child_node->text(), data_type, &numeric_text)) {
|
||||
child_node->set_text(std::move(numeric_text));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (std::string numeric_text{""};
|
||||
data_buf_2_text(node->text(), data_type, &numeric_text)) {
|
||||
node->set_text(std::move(numeric_text));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// rule in argument is for rel_expr in children.
|
||||
// rule !or_ancestor is for result.
|
||||
// !or_ancestor is shared and enough as fixed result rule for current rules
|
||||
bool QueryInfoHelper::traverse_node_by_rule(
|
||||
QueryNode *node, const std::function<bool(QueryRelNode *node)> &rule,
|
||||
SubRootResult *subroot_result, int32_t *num_of_child) {
|
||||
if (node->type() == QueryNode::QueryNodeType::REL_EXPR) {
|
||||
QueryRelNode *rel_node = dynamic_cast<QueryRelNode *>(node);
|
||||
rel_node->set_rule_result(false); // clear previous if any
|
||||
*num_of_child = 1;
|
||||
bool result = rule(rel_node);
|
||||
if (result) {
|
||||
if (!node->or_ancestor()) {
|
||||
subroot_result->set_result(rel_node, *num_of_child);
|
||||
}
|
||||
rel_node->set_rule_result(true);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int32_t left_num_of_child = 0;
|
||||
int32_t right_num_of_child = 0;
|
||||
QueryNode *left_node = node->left().get();
|
||||
QueryNode *right_node = node->right().get();
|
||||
|
||||
bool left_ok = traverse_node_by_rule(left_node, rule, subroot_result,
|
||||
&left_num_of_child);
|
||||
// if (!left_ok) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
bool right_ok = traverse_node_by_rule(right_node, rule, subroot_result,
|
||||
&right_num_of_child);
|
||||
|
||||
*num_of_child = left_num_of_child + right_num_of_child;
|
||||
|
||||
if (left_ok && right_ok) {
|
||||
if (!node->or_ancestor()) {
|
||||
subroot_result->set_result(node, *num_of_child);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void QueryInfoHelper::find_subroot_by_rule(
|
||||
QueryNode *root, const std::function<bool(QueryRelNode *node)> &rule,
|
||||
SubRootResult *subroot_result) {
|
||||
int32_t num_of_child = 0;
|
||||
traverse_node_by_rule(root, rule, subroot_result, &num_of_child);
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
#include "query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
struct SubRootResult {
|
||||
QueryNode *subroot;
|
||||
int32_t num_of_child;
|
||||
|
||||
SubRootResult() : subroot(nullptr), num_of_child(0) {}
|
||||
|
||||
SubRootResult(QueryNode *node, int32_t num)
|
||||
: subroot(node), num_of_child(num) {}
|
||||
|
||||
void set_result(QueryNode *node, int32_t num) {
|
||||
if (subroot == nullptr || num_of_child < num) {
|
||||
subroot = node;
|
||||
num_of_child = num;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class QueryInfoHelper {
|
||||
public:
|
||||
static bool text_2_data_buf(const std::string &text, zvec::DataType data_type,
|
||||
std::string *data_buf);
|
||||
static bool data_buf_2_text(const std::string &data_buf,
|
||||
zvec::DataType data_type, std::string *text);
|
||||
static void constant_node_data_buf_2_text(DataType data_type,
|
||||
bool is_array_type,
|
||||
QueryNode *node);
|
||||
|
||||
static void find_subroot_by_rule(
|
||||
QueryNode *root, const std::function<bool(QueryRelNode *node)> &rule,
|
||||
SubRootResult *subroot_result);
|
||||
|
||||
static bool traverse_node_by_rule(
|
||||
QueryNode *node, const std::function<bool(QueryRelNode *node)> &rule,
|
||||
SubRootResult *subroot_result, int32_t *num_of_child);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,331 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_node.h"
|
||||
#include <assert.h>
|
||||
#include <sstream>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
void QueryNode::set_type_by_op() {
|
||||
QueryNodeType node_type = QueryNodeType::NO_TYPE;
|
||||
switch (op()) {
|
||||
case QueryNodeOp::Q_AND:
|
||||
case QueryNodeOp::Q_OR:
|
||||
node_type = QueryNodeType::LOGIC_EXPR;
|
||||
break;
|
||||
|
||||
case QueryNodeOp::Q_EQ:
|
||||
case QueryNodeOp::Q_NE:
|
||||
case QueryNodeOp::Q_GT:
|
||||
case QueryNodeOp::Q_GE:
|
||||
case QueryNodeOp::Q_LT:
|
||||
case QueryNodeOp::Q_LE:
|
||||
case QueryNodeOp::Q_LIKE:
|
||||
case QueryNodeOp::Q_IN:
|
||||
case QueryNodeOp::Q_CONTAIN_ANY:
|
||||
case QueryNodeOp::Q_CONTAIN_ALL:
|
||||
case QueryNodeOp::Q_IS_NULL:
|
||||
case QueryNodeOp::Q_IS_NOT_NULL:
|
||||
node_type = QueryNodeType::REL_EXPR;
|
||||
break;
|
||||
|
||||
case QueryNodeOp::Q_PLUS:
|
||||
case QueryNodeOp::Q_MINUS:
|
||||
case QueryNodeOp::Q_MUL:
|
||||
case QueryNodeOp::Q_DIV:
|
||||
node_type = QueryNodeType::ARITH_EXPR;
|
||||
break;
|
||||
|
||||
case QueryNodeOp::Q_FUNCTION_CALL:
|
||||
node_type = QueryNodeType::FUNC;
|
||||
break;
|
||||
|
||||
case QueryNodeOp::Q_RANGE_VALUE:
|
||||
case QueryNodeOp::Q_LIST_VALUE:
|
||||
case QueryNodeOp::Q_VECTOR_MATRIX_VALUE:
|
||||
case QueryNodeOp::Q_INT_VALUE:
|
||||
case QueryNodeOp::Q_FLOAT_VALUE:
|
||||
case QueryNodeOp::Q_STRING_VALUE:
|
||||
case QueryNodeOp::Q_BOOL_VALUE:
|
||||
case QueryNodeOp::Q_NULL_VALUE:
|
||||
node_type = QueryNodeType::CONST;
|
||||
break;
|
||||
case QueryNodeOp::Q_ID:
|
||||
node_type = QueryNodeType::ID;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
type_ = node_type;
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryNode::detach_from_parent() {
|
||||
if (parent_->left().get() == this) {
|
||||
QueryNode::Ptr tmp = parent_->left();
|
||||
parent_->set_left(nullptr);
|
||||
return tmp;
|
||||
} else { // if (parent_->right().get() == this)
|
||||
QueryNode::Ptr tmp = parent_->right();
|
||||
parent_->set_right(nullptr);
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryNode::replace_from_parent(QueryNode::Ptr new_node_ptr) {
|
||||
new_node_ptr->set_parent(parent_);
|
||||
if (parent_->left().get() == this) {
|
||||
QueryNode::Ptr tmp = parent_->left();
|
||||
parent_->set_left(std::move(new_node_ptr));
|
||||
tmp->set_parent(nullptr);
|
||||
return tmp;
|
||||
} else { // if (parent_->right().get() == this)
|
||||
QueryNode::Ptr tmp = parent_->right();
|
||||
parent_->set_right(std::move(new_node_ptr));
|
||||
tmp->set_parent(nullptr);
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryNode::replace_from_search_cond(QueryNode::Ptr new_node_ptr,
|
||||
QueryInfo *query_info) {
|
||||
if (parent_ == nullptr) {
|
||||
new_node_ptr->set_parent(parent_);
|
||||
QueryNode::Ptr tmp = query_info->search_cond();
|
||||
query_info->set_search_cond(std::move(new_node_ptr));
|
||||
return tmp;
|
||||
}
|
||||
return replace_from_parent(std::move(new_node_ptr));
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryNode::detach_from_search_cond(QueryInfo *query_info) {
|
||||
if (parent_ == nullptr) {
|
||||
QueryNode::Ptr tmp = query_info->search_cond();
|
||||
query_info->set_search_cond(nullptr);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
return detach_from_parent();
|
||||
}
|
||||
|
||||
QueryNode::Ptr QueryNode::detach_from_invert_cond(QueryInfo *query_info) {
|
||||
if (parent_ == nullptr) {
|
||||
QueryNode::Ptr tmp = query_info->invert_cond();
|
||||
query_info->set_invert_cond(nullptr);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
return detach_from_parent();
|
||||
}
|
||||
|
||||
std::string QueryNode::text() const {
|
||||
std::stringstream stream;
|
||||
switch (type_) {
|
||||
case QueryNodeType::LOGIC_EXPR:
|
||||
stream << "(" << left_text() << ") " << op_name() << " (" << right_text()
|
||||
<< ")";
|
||||
break;
|
||||
case QueryNodeType::REL_EXPR:
|
||||
stream << left()->text() << op_name() << right()->text();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
bool QueryNode::is_matched(const QueryNode &) const {
|
||||
LOG_ERROR("Not implementated. op[%s]", op_name().c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
std::string QueryVectorMatrixNode::text() const {
|
||||
return node_->text();
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
QueryConstantNode::QueryConstantNode(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
|
||||
std::string QueryConstantNode::value() {
|
||||
return value_;
|
||||
}
|
||||
|
||||
std::string QueryConstantNode::text() const {
|
||||
return value_;
|
||||
}
|
||||
|
||||
void QueryConstantNode::set_text(std::string new_val) {
|
||||
value_ = std::move(new_val);
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
QueryIDNode::QueryIDNode(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
|
||||
void QueryIDNode::set_value(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
|
||||
std::string QueryIDNode::value() {
|
||||
return value_;
|
||||
}
|
||||
|
||||
std::string QueryIDNode::text() const {
|
||||
return value_;
|
||||
}
|
||||
|
||||
bool QueryIDNode::is_matched(const QueryNode &other) const {
|
||||
if (other.op() != op()) {
|
||||
return false;
|
||||
}
|
||||
auto &other_id_node = dynamic_cast<const QueryIDNode &>(other);
|
||||
return value_ == other_id_node.value_;
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
QueryFuncNode::QueryFuncNode() {
|
||||
set_op(QueryNodeOp::Q_FUNCTION_CALL);
|
||||
}
|
||||
|
||||
void QueryFuncNode::set_func_name_node(QueryNode::Ptr func_name_node) {
|
||||
func_name_node_ = std::move(func_name_node);
|
||||
if (func_name_node_->text() == "feature") {
|
||||
func_type_ = QueryFuncType::FEATURE;
|
||||
} else {
|
||||
func_type_ = QueryFuncType::NON_FEATURE;
|
||||
}
|
||||
}
|
||||
|
||||
const QueryNode::Ptr &QueryFuncNode::get_func_name_node() const {
|
||||
return func_name_node_;
|
||||
}
|
||||
|
||||
void QueryFuncNode::add_argument(QueryNode::Ptr argument_node) {
|
||||
arguments_.emplace_back(std::move(argument_node));
|
||||
}
|
||||
|
||||
const std::vector<QueryNode::Ptr> &QueryFuncNode::arguments() const {
|
||||
return arguments_;
|
||||
}
|
||||
|
||||
std::string QueryFuncNode::text() const {
|
||||
std::stringstream stream;
|
||||
stream << func_name_node_->text();
|
||||
stream << "(";
|
||||
|
||||
int i = 0;
|
||||
for (auto argument : arguments_) {
|
||||
if (i > 0) {
|
||||
stream << ", ";
|
||||
}
|
||||
stream << argument->text();
|
||||
i++;
|
||||
}
|
||||
stream << ")";
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
bool QueryFuncNode::is_matched(const QueryNode &other) const {
|
||||
if (other.op() != op()) {
|
||||
return false;
|
||||
}
|
||||
auto &other_func_node = dynamic_cast<const QueryFuncNode &>(other);
|
||||
if (!func_name_node_->is_matched(*other_func_node.func_name_node_)) {
|
||||
return false;
|
||||
}
|
||||
// only id() function with zero arguments is considered matched
|
||||
if (arguments_.empty() && other_func_node.arguments_.empty() &&
|
||||
func_name_node_->text() == "id") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
//========================================================================
|
||||
|
||||
QueryRelNode::QueryRelNode() {}
|
||||
|
||||
void QueryRelNode::set_rel_type(RelType value) {
|
||||
rel_type_ = value;
|
||||
}
|
||||
|
||||
QueryRelNode::RelType QueryRelNode::rel_type() {
|
||||
return rel_type_;
|
||||
}
|
||||
|
||||
std::string QueryRelNode::text() const {
|
||||
std::stringstream stream;
|
||||
stream << QueryNode::text();
|
||||
if (rel_type_ == RelType::NO_TYPE) {
|
||||
stream << "(NO_REL_TYPE)";
|
||||
} else if (is_feature()) {
|
||||
stream << "(FEATURE)";
|
||||
} else if (is_invert()) {
|
||||
stream << "(INVERT)";
|
||||
} else if (is_forward()) {
|
||||
stream << "(FORWARD)";
|
||||
}
|
||||
if (or_ancestor()) {
|
||||
stream << "(OR_A)";
|
||||
}
|
||||
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
std::string QueryListNode::text() const {
|
||||
std::stringstream stream;
|
||||
if (exclude_) {
|
||||
stream << "NOT ";
|
||||
}
|
||||
|
||||
stream << "(";
|
||||
|
||||
int i = 0;
|
||||
for (auto value_expr : value_expr_list_) {
|
||||
if (i > 0) {
|
||||
stream << ", ";
|
||||
}
|
||||
stream << value_expr->text();
|
||||
i++;
|
||||
}
|
||||
stream << ")";
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::vector<std::string> QueryListNode::to_value_list() {
|
||||
std::vector<std::string> value_list;
|
||||
for (auto &value_expr : value_expr_list_) {
|
||||
value_list.emplace_back(value_expr->text());
|
||||
}
|
||||
|
||||
return value_list;
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,369 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include "db/index/common/query_params.h"
|
||||
#include "db/sqlengine/common/generic_node.h"
|
||||
#include "db/sqlengine/parser/node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
enum class QueryNodeOp {
|
||||
Q_NONE,
|
||||
Q_AND,
|
||||
Q_OR,
|
||||
Q_EQ,
|
||||
Q_NE,
|
||||
Q_GT,
|
||||
Q_GE,
|
||||
Q_LT,
|
||||
Q_LE,
|
||||
Q_LIKE,
|
||||
Q_IN,
|
||||
Q_CONTAIN_ALL,
|
||||
Q_CONTAIN_ANY,
|
||||
Q_PLUS,
|
||||
Q_MINUS,
|
||||
Q_MUL,
|
||||
Q_DIV,
|
||||
Q_FUNCTION_CALL,
|
||||
Q_RANGE_VALUE,
|
||||
Q_LIST_VALUE,
|
||||
Q_VECTOR_MATRIX_VALUE,
|
||||
Q_INT_VALUE,
|
||||
Q_FLOAT_VALUE,
|
||||
Q_STRING_VALUE,
|
||||
Q_NULL_VALUE,
|
||||
Q_ID,
|
||||
Q_BOOL_VALUE,
|
||||
Q_IS_NULL,
|
||||
Q_IS_NOT_NULL,
|
||||
};
|
||||
|
||||
class QueryInfo;
|
||||
class QueryNode : public Generic_Node<QueryNodeOp, QueryNode> {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryNode>;
|
||||
|
||||
static inline std::string type_to_str(QueryNodeOp c) {
|
||||
static std::string names[] = {"NONE",
|
||||
"and",
|
||||
"or",
|
||||
"=",
|
||||
"!=",
|
||||
">",
|
||||
">=",
|
||||
"<",
|
||||
"<=",
|
||||
" LIKE ",
|
||||
" in ",
|
||||
" contain_all ",
|
||||
" contain_any ",
|
||||
"+",
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"FUNCTION_CALL",
|
||||
"RANGE_VALUE",
|
||||
"LIST_VALUE",
|
||||
"VECTOR_MATRIX_VALUE",
|
||||
"INT_VALUE",
|
||||
"FLOAT_VALUE",
|
||||
"STRING_VALUE",
|
||||
"NULL_VALUE",
|
||||
"ID",
|
||||
"BOOL_VALUE",
|
||||
" IS_NULL ",
|
||||
" IS_NOT_NULL "};
|
||||
|
||||
return names[static_cast<int>(c)];
|
||||
}
|
||||
|
||||
enum class QueryNodeType {
|
||||
NO_TYPE,
|
||||
LOGIC_EXPR,
|
||||
REL_EXPR,
|
||||
ARITH_EXPR,
|
||||
FUNC,
|
||||
CONST,
|
||||
ID
|
||||
};
|
||||
|
||||
public:
|
||||
QueryNode() : Generic_Node(QueryNodeOp::Q_NONE) {}
|
||||
QueryNode(QueryNodeOp m_op) : Generic_Node(m_op) {
|
||||
set_op(m_op);
|
||||
}
|
||||
~QueryNode() override = default;
|
||||
|
||||
std::string left_text() const {
|
||||
if (left_ == nullptr) {
|
||||
return "nullptr";
|
||||
}
|
||||
return left_->text();
|
||||
}
|
||||
std::string right_text() const {
|
||||
if (right_ == nullptr) {
|
||||
return "nullptr";
|
||||
}
|
||||
return right_->text();
|
||||
}
|
||||
|
||||
|
||||
virtual bool is_matched(const QueryNode &other) const;
|
||||
|
||||
void set_op(QueryNodeOp value) override {
|
||||
Generic_Node<QueryNodeOp, QueryNode>::set_op(value);
|
||||
set_type_by_op();
|
||||
}
|
||||
|
||||
std::string op_name() const {
|
||||
return type_to_str(op_);
|
||||
}
|
||||
|
||||
QueryNode::QueryNodeType type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
void set_level(uint32_t value) {
|
||||
level_ = value;
|
||||
}
|
||||
uint32_t level() {
|
||||
return level_;
|
||||
}
|
||||
|
||||
void set_or_ancestor(bool val = true) {
|
||||
or_ancestor_ = val;
|
||||
}
|
||||
|
||||
bool or_ancestor() const {
|
||||
return or_ancestor_;
|
||||
}
|
||||
|
||||
QueryNode::Ptr detach_from_parent();
|
||||
|
||||
QueryNode::Ptr replace_from_parent(QueryNode::Ptr new_query_node);
|
||||
|
||||
QueryNode::Ptr replace_from_search_cond(QueryNode::Ptr new_query_node,
|
||||
QueryInfo *query_info);
|
||||
|
||||
QueryNode::Ptr detach_from_search_cond(QueryInfo *query_info_ptr);
|
||||
|
||||
QueryNode::Ptr detach_from_invert_cond(QueryInfo *query_info_ptr);
|
||||
|
||||
virtual std::string text() const override;
|
||||
|
||||
virtual void set_text(std::string /*new_val*/) {
|
||||
/* for QueryConstantNode only */
|
||||
return;
|
||||
}
|
||||
|
||||
std::optional<bool> predictate_result() const {
|
||||
return predictate_result_;
|
||||
}
|
||||
void set_predictate_result(bool result) {
|
||||
predictate_result_ = result;
|
||||
}
|
||||
|
||||
protected:
|
||||
void set_type_by_op();
|
||||
|
||||
protected:
|
||||
QueryNodeType type_{QueryNodeType::NO_TYPE};
|
||||
|
||||
private:
|
||||
uint32_t level_{0};
|
||||
bool or_ancestor_{false};
|
||||
// evaluation result of predication, maybe true, false or unknown
|
||||
std::optional<bool> predictate_result_{std::nullopt};
|
||||
};
|
||||
|
||||
class QueryVectorMatrixNode : public QueryNode {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryVectorMatrixNode>;
|
||||
|
||||
QueryVectorMatrixNode(std::shared_ptr<VectorMatrixNode> node)
|
||||
: node_(std::move(node)) {}
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
const std::string &matrix() const {
|
||||
return node_->matrix();
|
||||
}
|
||||
|
||||
const std::string &sparse_indices() const {
|
||||
return node_->sparse_indices();
|
||||
}
|
||||
|
||||
const std::string &sparse_values() const {
|
||||
return node_->sparse_values();
|
||||
}
|
||||
|
||||
const QueryParams::Ptr &query_params() const {
|
||||
return node_->query_params();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<const VectorMatrixNode> node_{nullptr};
|
||||
};
|
||||
|
||||
class QueryConstantNode : public QueryNode {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryConstantNode>;
|
||||
|
||||
QueryConstantNode(const std::string &m_value);
|
||||
|
||||
std::string value();
|
||||
std::string text() const override;
|
||||
|
||||
void set_text(std::string new_val) override;
|
||||
|
||||
private:
|
||||
std::string value_;
|
||||
};
|
||||
|
||||
class QueryIDNode : public QueryNode {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryIDNode>;
|
||||
|
||||
QueryIDNode(const std::string &m_value);
|
||||
|
||||
void set_value(const std::string &m_value);
|
||||
|
||||
std::string value();
|
||||
std::string text() const override;
|
||||
|
||||
bool is_matched(const QueryNode &other) const override;
|
||||
|
||||
private:
|
||||
std::string value_;
|
||||
};
|
||||
|
||||
class QueryFuncNode : public QueryNode {
|
||||
enum class QueryFuncType { FEATURE = 0, NON_FEATURE = 1 };
|
||||
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryFuncNode>;
|
||||
|
||||
QueryFuncNode();
|
||||
virtual ~QueryFuncNode() = default;
|
||||
|
||||
void set_func_name_node(QueryNode::Ptr func_name_node);
|
||||
const QueryNode::Ptr &get_func_name_node() const;
|
||||
|
||||
std::string get_func_name() const {
|
||||
return func_name_node_->text();
|
||||
}
|
||||
|
||||
void add_argument(QueryNode::Ptr argument_node);
|
||||
const std::vector<QueryNode::Ptr> &arguments() const;
|
||||
|
||||
std::string text() const override;
|
||||
bool is_feature_func() {
|
||||
return func_type_ == QueryFuncType::FEATURE;
|
||||
}
|
||||
|
||||
bool is_matched(const QueryNode &other) const override;
|
||||
|
||||
private:
|
||||
QueryNode::Ptr func_name_node_{nullptr};
|
||||
std::vector<QueryNode::Ptr> arguments_{};
|
||||
QueryFuncType func_type_{QueryFuncType::FEATURE};
|
||||
};
|
||||
|
||||
class QueryRelNode : public QueryNode {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryRelNode>;
|
||||
|
||||
enum class RelType { NO_TYPE, FEATURE, INVERT, FORWARD };
|
||||
|
||||
QueryRelNode();
|
||||
|
||||
bool is_feature() const {
|
||||
return rel_type_ == RelType::FEATURE;
|
||||
}
|
||||
bool is_invert() const {
|
||||
return rel_type_ == RelType::INVERT;
|
||||
}
|
||||
bool is_forward() const {
|
||||
return rel_type_ == RelType::FORWARD;
|
||||
}
|
||||
|
||||
void set_vector() {
|
||||
rel_type_ = RelType::FEATURE;
|
||||
}
|
||||
void set_invert() {
|
||||
rel_type_ = RelType::INVERT;
|
||||
}
|
||||
void set_forward() {
|
||||
rel_type_ = RelType::FORWARD;
|
||||
}
|
||||
|
||||
void set_rel_type(RelType value);
|
||||
RelType rel_type();
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
bool rule_result() {
|
||||
return rule_result_;
|
||||
}
|
||||
|
||||
void set_rule_result(bool result) {
|
||||
rule_result_ = result;
|
||||
}
|
||||
|
||||
private:
|
||||
RelType rel_type_{RelType::NO_TYPE};
|
||||
// rule result is intermediate result for evalute rules
|
||||
bool rule_result_{false};
|
||||
};
|
||||
|
||||
class QueryListNode : public QueryNode {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryListNode>;
|
||||
|
||||
QueryListNode() {
|
||||
set_op(QueryNodeOp::Q_LIST_VALUE);
|
||||
}
|
||||
|
||||
void add_value_expr(QueryNode::Ptr value_expr) {
|
||||
value_expr_list_.emplace_back(std::move(value_expr));
|
||||
}
|
||||
|
||||
const std::vector<QueryNode::Ptr> &value_expr_list() const {
|
||||
return value_expr_list_;
|
||||
}
|
||||
|
||||
bool exclude() const {
|
||||
return exclude_;
|
||||
}
|
||||
|
||||
void set_exclude(bool val) {
|
||||
exclude_ = val;
|
||||
}
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
std::vector<std::string> to_value_list();
|
||||
|
||||
private:
|
||||
std::vector<QueryNode::Ptr> value_expr_list_{};
|
||||
bool exclude_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,696 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_node_walker.h"
|
||||
#include <cstddef>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/float_helper.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "analyzer/query_node.h"
|
||||
#include "db/common/constants.h"
|
||||
#include "db/index/common/index_params.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "query_info_helper.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
inline bool is_numeric_type(zvec::DataType data_type) {
|
||||
// include INT32, INT64, UINT32, UINT64, FLOAT, DOUBLE
|
||||
// use following code to reduce the runtime comparison cost
|
||||
return (data_type >= zvec::DataType::INT32 &&
|
||||
data_type <= zvec::DataType::DOUBLE);
|
||||
}
|
||||
|
||||
SearchCondCheckWalker::SearchCondCheckWalker(const CollectionSchema &table_ptr)
|
||||
: table_ptr_(table_ptr) {}
|
||||
|
||||
ControlOp SearchCondCheckWalker::traverse_cond_node(
|
||||
const QueryNode::Ptr &query_node, bool or_ancestor) {
|
||||
if (query_node == nullptr) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
ControlOp ret = access(query_node, or_ancestor);
|
||||
if (ret == ControlOp::BREAK) {
|
||||
// finish traversing
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
if (query_node->op() == QueryNodeOp::Q_OR) {
|
||||
or_ancestor = true;
|
||||
}
|
||||
|
||||
if (query_node->left() != nullptr) {
|
||||
ControlOp ret2 = traverse_cond_node(query_node->left(), or_ancestor);
|
||||
if (ret2 == ControlOp::BREAK) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
if (query_node->right() != nullptr) {
|
||||
ControlOp ret2 = traverse_cond_node(query_node->right(), or_ancestor);
|
||||
if (ret2 == ControlOp::BREAK) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
ControlOp SearchCondCheckWalker::access(const QueryNode::Ptr &query_node,
|
||||
bool or_ancestor) {
|
||||
// set all types of child node or ancestor if it does,
|
||||
// besides query_rel_node, mainly for logic node invert_subroot_node_
|
||||
if (or_ancestor) {
|
||||
query_node->set_or_ancestor();
|
||||
}
|
||||
|
||||
if (query_node->type() != QueryNode::QueryNodeType::REL_EXPR) {
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
const QueryRelNode::Ptr &query_rel_node =
|
||||
std::dynamic_pointer_cast<QueryRelNode>(query_node);
|
||||
|
||||
const QueryNode::Ptr &left = query_rel_node->left();
|
||||
const QueryNode::Ptr &right = query_rel_node->right();
|
||||
|
||||
// left side must be single field name or function
|
||||
if (left->op() != QueryNodeOp::Q_ID &&
|
||||
left->op() != QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
err_msg_ =
|
||||
"left side in relation expr must be single field name or function "
|
||||
"call. " +
|
||||
query_node->text();
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
if (left->op() == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
if (!left_op_func_check(query_rel_node)) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
// right side support constant value only
|
||||
if (right->type() != QueryNode::QueryNodeType::CONST &&
|
||||
right->type() != QueryNode::QueryNodeType::FUNC) {
|
||||
err_msg_ =
|
||||
"right side in relation expr support constant value or function "
|
||||
"only. " +
|
||||
query_node->text();
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// Function check
|
||||
if (right->type() == QueryNode::QueryNodeType::FUNC) {
|
||||
if (func_check(right) != 0) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
// In phrase check, IN only work with list value
|
||||
if (query_node->op() == QueryNodeOp::Q_IN) {
|
||||
if (right->op() != QueryNodeOp::Q_LIST_VALUE) {
|
||||
err_msg_ =
|
||||
"In rel expr only works with list value. " + query_node->text();
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
QueryListNode::Ptr list_node =
|
||||
std::dynamic_pointer_cast<QueryListNode>(right);
|
||||
if (list_node->value_expr_list().size() > 20000) {
|
||||
err_msg_ = "In rel expr only support list size no more than 20000 " +
|
||||
query_node->text();
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
std::string field_name = left->text();
|
||||
|
||||
const zvec::FieldSchema *vector_field =
|
||||
table_ptr_.get_vector_field(field_name);
|
||||
|
||||
// check vector index cond
|
||||
if (vector_field != nullptr) {
|
||||
// vector supports eq only.
|
||||
if (query_node->op() != QueryNodeOp::Q_EQ) {
|
||||
err_msg_ = ailego::StringHelper::Concat("vector field only support EQ. ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
// more than one vector query check.
|
||||
if (vector_rel_ != NULL) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"more than one vector search is not supported. ", vector_rel_->text(),
|
||||
" ", query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
vector_rel_ = query_rel_node.get();
|
||||
query_rel_node->set_vector();
|
||||
// arrive here, it is a index condition.
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
const zvec::FieldSchema *forward_field =
|
||||
table_ptr_.get_forward_field(field_name);
|
||||
// field must have schema
|
||||
if (!forward_field) {
|
||||
err_msg_ = ailego::StringHelper::Concat("field not found in table schema: ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// only string field or is null allow empty string value
|
||||
if (right->text().empty() &&
|
||||
(forward_field->element_data_type() != DataType::STRING &&
|
||||
query_node->op() != QueryNodeOp::Q_IS_NULL &&
|
||||
query_node->op() != QueryNodeOp::Q_IS_NOT_NULL)) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"right side in relation expr is empty: ", query_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
if (query_node->op() == QueryNodeOp::Q_IS_NULL ||
|
||||
query_node->op() == QueryNodeOp::Q_IS_NOT_NULL) {
|
||||
if (forward_field->index_params() != nullptr) {
|
||||
add_invert_filter(query_rel_node.get());
|
||||
} else {
|
||||
add_forward_filter(query_rel_node.get(), field_name);
|
||||
}
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
// Like phrase check
|
||||
if (query_node->op() == QueryNodeOp::Q_LIKE) {
|
||||
if (!check_like(*forward_field, query_rel_node.get())) {
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
|
||||
// invert index analysis, if field exists on both forward and index,
|
||||
// as long as the cond conform to index cond criteria,
|
||||
// it is regarded as index cond, not forward cond.
|
||||
if (forward_field->index_params() != nullptr) {
|
||||
if (const auto ret = check_array_and_contain_compatible(
|
||||
query_rel_node, forward_field, true);
|
||||
ret != std::nullopt) {
|
||||
return ret.value();
|
||||
}
|
||||
// data type of index only support string, numeric and vector, and:
|
||||
// string supports all op,
|
||||
const auto field_data_type = forward_field->element_data_type();
|
||||
const bool is_string_field = field_data_type == zvec::DataType::STRING;
|
||||
// numeric supports all op except like, ( as well as bool )
|
||||
const bool is_numeric_field_without_like =
|
||||
query_node->op() != QueryNodeOp::Q_LIKE &&
|
||||
(is_numeric_type(field_data_type) ||
|
||||
field_data_type == zvec::DataType::BOOL);
|
||||
|
||||
// if not satisfy, fall back to forward analysis
|
||||
if (is_string_field || is_numeric_field_without_like) {
|
||||
if (!check_and_convert_value_type(field_data_type, right)) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"field type and value type not match in relation expr. ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// bool op check
|
||||
if (field_data_type == zvec::DataType::BOOL) {
|
||||
if (query_node->op() != QueryNodeOp::Q_EQ &&
|
||||
query_node->op() != QueryNodeOp::Q_NE) {
|
||||
err_msg_ = "bool type only support EQ and NQ";
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
add_invert_filter(query_rel_node.get());
|
||||
// arrive here, it is a index condition.
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
}
|
||||
|
||||
// compared with index_field's check, following check for forward_field:
|
||||
// 1. support BINARY type
|
||||
// 2. validate `like op only on str` in body instead of `if` condition block
|
||||
// 3. use check_and_convert_value_type() instead of field_type_vs_value_type()
|
||||
// to convert numeric values to str & not support BINARY
|
||||
if (forward_field != nullptr) {
|
||||
if (const auto ret = check_array_and_contain_compatible(
|
||||
query_rel_node, forward_field, false);
|
||||
ret != std::nullopt) {
|
||||
return ret.value();
|
||||
}
|
||||
// data type of forward only support binary, string, bool, int and float
|
||||
if (forward_field->element_data_type() == zvec::DataType::BINARY ||
|
||||
forward_field->element_data_type() == zvec::DataType::STRING ||
|
||||
forward_field->element_data_type() == zvec::DataType::BOOL ||
|
||||
is_numeric_type(forward_field->element_data_type())) {
|
||||
if (!field_type_vs_value_type(forward_field->element_data_type(),
|
||||
right)) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"forward field type and value type not match in relation expr. ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// bool op check
|
||||
if (forward_field->element_data_type() == zvec::DataType::BOOL) {
|
||||
if (query_node->op() != QueryNodeOp::Q_EQ &&
|
||||
query_node->op() != QueryNodeOp::Q_NE) {
|
||||
err_msg_ = "bool type only support EQ and NQ";
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
// like only works on string
|
||||
if (query_node->op() == QueryNodeOp::Q_LIKE &&
|
||||
forward_field->element_data_type() != zvec::DataType::STRING) {
|
||||
err_msg_ = "operator LIKE only works on string";
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
add_forward_filter(query_rel_node.get(), field_name);
|
||||
// arrive here, it is a forward.
|
||||
return ControlOp::CONTINUE;
|
||||
} else {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"unsupported data type in relation expr: ", query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
} else {
|
||||
if (right->op() == QueryNodeOp::Q_VECTOR_MATRIX_VALUE) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"vector vector not supported for schema free field in relation "
|
||||
"expr: ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
if (right->type() != QueryNode::QueryNodeType::CONST) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"only support const for schema free field in relation expr: ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
add_forward_filter(query_rel_node.get(), field_name);
|
||||
// treat as schema free field forward
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
}
|
||||
|
||||
int SearchCondCheckWalker::func_check(const QueryNode::Ptr &func_node) {
|
||||
const QueryFuncNode::Ptr &func_node_ptr =
|
||||
std::dynamic_pointer_cast<QueryFuncNode>(func_node);
|
||||
const QueryNode::Ptr &func_name_node_ptr =
|
||||
func_node_ptr->get_func_name_node();
|
||||
/* function must be feature */
|
||||
std::string func_name = func_name_node_ptr->text();
|
||||
if (func_name != kFeature) {
|
||||
err_msg_ = "Function is not supported. " + func_name;
|
||||
return -1;
|
||||
}
|
||||
size_t size = func_node_ptr->arguments().size();
|
||||
if (size < 1 || size > 4) {
|
||||
err_msg_ = "vector function has wrong number of arguments. ";
|
||||
return -1;
|
||||
}
|
||||
// do not check arguments here, check during vector transforming
|
||||
return 0;
|
||||
}
|
||||
|
||||
tl::expected<void, std::string> SearchCondCheckWalker::array_length_func_check(
|
||||
const QueryFuncNode::Ptr &func_node_ptr,
|
||||
const QueryRelNode::Ptr &query_node) {
|
||||
const auto &arguments = func_node_ptr->arguments();
|
||||
if (arguments.size() != 1) {
|
||||
return tl::make_unexpected(
|
||||
"array_length function should have only one argument. ");
|
||||
}
|
||||
auto &arg0 = arguments[0];
|
||||
if (arg0->op() != QueryNodeOp::Q_ID) {
|
||||
return tl::make_unexpected(
|
||||
"array_length function argument must be a field name, got " +
|
||||
arg0->op_name());
|
||||
}
|
||||
auto *arg0_schema = table_ptr_.get_field(arg0->text());
|
||||
if (arg0_schema == nullptr) {
|
||||
return tl::make_unexpected(
|
||||
"array_length argument not found in schema, with " + arg0->text());
|
||||
}
|
||||
if (!arg0_schema->is_array_type()) {
|
||||
return tl::make_unexpected(
|
||||
"array_length only support array, got " +
|
||||
DataTypeCodeBook::AsString(arg0_schema->data_type()));
|
||||
}
|
||||
if (!is_arithematic_compare_op(query_node->op())) {
|
||||
return tl::make_unexpected(
|
||||
"array_length only support arithematic "
|
||||
"compare op, got " +
|
||||
query_node->op_name());
|
||||
}
|
||||
// only allow integer
|
||||
auto &right_node = query_node->right();
|
||||
if (right_node->op() != QueryNodeOp::Q_INT_VALUE) {
|
||||
return tl::make_unexpected(
|
||||
"array_length right side only support integer, got " +
|
||||
right_node->op_name());
|
||||
}
|
||||
|
||||
if (arg0_schema->index_params() != nullptr) {
|
||||
if (!check_and_convert_value_type(DataType::UINT32, right_node)) {
|
||||
return tl::make_unexpected(
|
||||
"array_length right side only support integer, got " +
|
||||
right_node->op_name());
|
||||
}
|
||||
add_invert_filter(query_node.get());
|
||||
} else {
|
||||
add_forward_filter(query_node.get(), arg0->text());
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::is_arithematic_compare_op(QueryNodeOp op) {
|
||||
return op == QueryNodeOp::Q_EQ || op == QueryNodeOp::Q_NE ||
|
||||
op == QueryNodeOp::Q_GT || op == QueryNodeOp::Q_GE ||
|
||||
op == QueryNodeOp::Q_LT || op == QueryNodeOp::Q_LE;
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::left_op_func_check(
|
||||
const QueryRelNode::Ptr &query_node) {
|
||||
const QueryFuncNode::Ptr &func_node_ptr =
|
||||
std::dynamic_pointer_cast<QueryFuncNode>(query_node->left());
|
||||
const QueryNode::Ptr &func_name_node_ptr =
|
||||
func_node_ptr->get_func_name_node();
|
||||
/* function must be feature */
|
||||
std::string func_name = func_name_node_ptr->text();
|
||||
tl::expected<void, std::string> res;
|
||||
if (func_name == kFuncArrayLength) {
|
||||
res = array_length_func_check(func_node_ptr, query_node);
|
||||
} else {
|
||||
err_msg_ = "Function is not supported. " + func_name;
|
||||
return false;
|
||||
}
|
||||
if (!res.has_value()) {
|
||||
err_msg_ = res.error();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::check_like(const zvec::FieldSchema &field,
|
||||
QueryRelNode *query_node) {
|
||||
auto *like_value_node = query_node->right_node();
|
||||
if (like_value_node->op() != QueryNodeOp::Q_STRING_VALUE) {
|
||||
err_msg_ = "like phrase only support string now.";
|
||||
return false;
|
||||
}
|
||||
std::string field_name = query_node->left_node()->text();
|
||||
const InvertIndexParams *param =
|
||||
dynamic_cast<InvertIndexParams *>(field.index_params().get());
|
||||
if (param == nullptr) {
|
||||
add_forward_filter(query_node, std::move(field_name));
|
||||
return true;
|
||||
}
|
||||
int percent_count = 0;
|
||||
int underscore_count = 0;
|
||||
std::string text = like_value_node->text();
|
||||
size_t percent_loc = std::string::npos;
|
||||
for (size_t i = 0; i < text.size(); i++) {
|
||||
char c = text[i];
|
||||
if (c == '\\') {
|
||||
// just ignore next character
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '%') {
|
||||
percent_count++;
|
||||
percent_loc = i;
|
||||
} else if (c == '_') {
|
||||
underscore_count++;
|
||||
}
|
||||
}
|
||||
// invert support at most one '%', not support '_'
|
||||
if (percent_count > 1 || underscore_count > 0) {
|
||||
add_forward_filter(query_node, std::move(field_name));
|
||||
return true;
|
||||
}
|
||||
// invert only support % at the end if extended wildcard is not enabled
|
||||
if (param->enable_extended_wildcard() || percent_loc == text.size() - 1) {
|
||||
add_invert_filter(query_node);
|
||||
} else {
|
||||
add_forward_filter(query_node, std::move(field_name));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::field_type_vs_value_type(
|
||||
zvec::DataType data_type, const QueryNode::Ptr &node) {
|
||||
QueryNodeOp value_type = node->op();
|
||||
if (value_type == QueryNodeOp::Q_LIST_VALUE) {
|
||||
return field_type_vs_list_value_type(data_type, node);
|
||||
}
|
||||
|
||||
if ((data_type == zvec::DataType::BINARY ||
|
||||
data_type == zvec::DataType::STRING) &&
|
||||
value_type != QueryNodeOp::Q_STRING_VALUE) {
|
||||
return false;
|
||||
}
|
||||
if (data_type == zvec::DataType::BOOL &&
|
||||
value_type != QueryNodeOp::Q_BOOL_VALUE) {
|
||||
return false;
|
||||
}
|
||||
if ((data_type == zvec::DataType::INT32 ||
|
||||
data_type == zvec::DataType::INT64 ||
|
||||
data_type == zvec::DataType::UINT32 ||
|
||||
data_type == zvec::DataType::UINT64) &&
|
||||
value_type != QueryNodeOp::Q_INT_VALUE) {
|
||||
return false;
|
||||
}
|
||||
if ((data_type == zvec::DataType::FLOAT ||
|
||||
data_type == zvec::DataType::DOUBLE) &&
|
||||
(value_type != QueryNodeOp::Q_FLOAT_VALUE &&
|
||||
value_type != QueryNodeOp::Q_INT_VALUE)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (zvec::FieldSchema::is_vector_field(data_type)) {
|
||||
if (value_type != QueryNodeOp::Q_VECTOR_MATRIX_VALUE &&
|
||||
value_type != QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
return false;
|
||||
}
|
||||
if (value_type == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
QueryFuncNode::Ptr func_node =
|
||||
std::dynamic_pointer_cast<QueryFuncNode>(node);
|
||||
if (!func_node->is_feature_func()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::field_type_vs_list_value_type(
|
||||
zvec::DataType data_type, const QueryNode::Ptr &node) {
|
||||
/* list value only support field with data type string, numeric and bool */
|
||||
if (!(data_type == zvec::DataType::STRING || is_numeric_type(data_type) ||
|
||||
data_type == zvec::DataType::BOOL)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QueryListNode::Ptr list_node = std::dynamic_pointer_cast<QueryListNode>(node);
|
||||
for (auto &value : list_node->value_expr_list()) {
|
||||
// recursively call single value check and convert
|
||||
if (bool ret = field_type_vs_value_type(data_type, value); !ret) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// use for invert index, compared with field_type_vs_value_type:
|
||||
// 1. not support DataType::BINARY, for the invert index doesn't support it
|
||||
// 2. convert numeric to str, for the invert index is based on text
|
||||
bool SearchCondCheckWalker::check_and_convert_value_type(
|
||||
zvec::DataType data_type, const QueryNode::Ptr &node) {
|
||||
QueryNodeOp value_type = node->op();
|
||||
|
||||
if (value_type == QueryNodeOp::Q_LIST_VALUE) {
|
||||
return check_and_convert_list_value_type(data_type, node);
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::STRING &&
|
||||
value_type != QueryNodeOp::Q_STRING_VALUE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (data_type == zvec::DataType::BOOL &&
|
||||
value_type != QueryNodeOp::Q_BOOL_VALUE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((data_type == zvec::DataType::INT32 ||
|
||||
data_type == zvec::DataType::INT64 ||
|
||||
data_type == zvec::DataType::UINT32 ||
|
||||
data_type == zvec::DataType::UINT64) &&
|
||||
value_type != QueryNodeOp::Q_INT_VALUE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((data_type == zvec::DataType::FLOAT ||
|
||||
data_type == zvec::DataType::DOUBLE) &&
|
||||
(value_type != QueryNodeOp::Q_FLOAT_VALUE &&
|
||||
value_type != QueryNodeOp::Q_INT_VALUE)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (zvec::FieldSchema::is_vector_field(data_type)) {
|
||||
if (value_type != QueryNodeOp::Q_VECTOR_MATRIX_VALUE &&
|
||||
value_type != QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
return false;
|
||||
}
|
||||
if (value_type == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
QueryFuncNode::Ptr func_node =
|
||||
std::dynamic_pointer_cast<QueryFuncNode>(node);
|
||||
if (!func_node->is_feature_func()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (is_numeric_type(data_type)) {
|
||||
std::string numeric_buf;
|
||||
if (!QueryInfoHelper::text_2_data_buf(node->text(), data_type,
|
||||
&numeric_buf)) {
|
||||
return false;
|
||||
}
|
||||
node->set_text(std::move(numeric_buf));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SearchCondCheckWalker::check_and_convert_list_value_type(
|
||||
zvec::DataType data_type, const QueryNode::Ptr &node) {
|
||||
/* list value only support field with data type string and numeric */
|
||||
if (!(data_type == zvec::DataType::STRING || is_numeric_type(data_type) ||
|
||||
data_type == DataType::BOOL)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QueryListNode::Ptr list_node = std::dynamic_pointer_cast<QueryListNode>(node);
|
||||
for (auto &value : list_node->value_expr_list()) {
|
||||
// recursively call single value check and convert
|
||||
if (bool ret = check_and_convert_value_type(data_type, value); !ret) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// RULEs for contain_* operator & array_* data type
|
||||
// 1. **only** array__dt supports contain_* op
|
||||
// && array__dt **only** supports contain_* op
|
||||
// 2. right hand value should be a list
|
||||
// 3. list size should be no more than MAX_ARRAY_FIELD_LEN
|
||||
// 4. list value type should be same as index field's sub type
|
||||
// e.g., array_int32 containing a list of int64 is invalid
|
||||
// 5. following the restriction of `in`, only string & numeric list is allowed
|
||||
// 6. (same with other field) if field exists on both forward and index,
|
||||
// the cond should be index one, aka invert index has higher priority
|
||||
std::optional<ControlOp>
|
||||
SearchCondCheckWalker::check_array_and_contain_compatible(
|
||||
const QueryRelNode::Ptr &query_rel_node, const FieldSchema *field,
|
||||
bool is_invert_field) {
|
||||
const QueryNode::Ptr &left = query_rel_node->left();
|
||||
const QueryNode::Ptr &right = query_rel_node->right();
|
||||
|
||||
const bool is_contain_op =
|
||||
query_rel_node->op() == QueryNodeOp::Q_CONTAIN_ALL ||
|
||||
query_rel_node->op() == QueryNodeOp::Q_CONTAIN_ANY;
|
||||
|
||||
// not check here
|
||||
if (!(field->is_array_type() || is_contain_op)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// rule 1, which can be expressed in an alternative way:
|
||||
// is_array & is_contain_op must have same value
|
||||
if (field->is_array_type() ^ is_contain_op) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"Contain_* rel expr only works with array data type and "
|
||||
"array data type only works with contain_* op. filter: ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
// rule 2
|
||||
if (right->op() != QueryNodeOp::Q_LIST_VALUE) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"Contain_* rel expr only works with list value. filter: ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
// rule 3
|
||||
QueryListNode::Ptr list_node =
|
||||
std::dynamic_pointer_cast<QueryListNode>(right);
|
||||
if (list_node->value_expr_list().size() > MAX_ARRAY_FIELD_LEN) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"Contain_* rel expr only support list size no more than ",
|
||||
ailego::StringHelper::ToString(MAX_ARRAY_FIELD_LEN), ": ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// rule 4, check if list value type matches field's sub type
|
||||
// rule 5 is enforced by check_and_convert_value_type(), inside which
|
||||
// will call check_and_convert_list_value_type() to constrain
|
||||
// the list value type
|
||||
// Similarly to field_type_vs_value_type() func for forward index
|
||||
if (!(is_invert_field
|
||||
? check_and_convert_value_type(field->element_data_type(), right)
|
||||
: field_type_vs_value_type(field->element_data_type(), right))) {
|
||||
err_msg_ = ailego::StringHelper::Concat(
|
||||
"field type and value type not match in relation expr. ",
|
||||
query_rel_node->text());
|
||||
return ControlOp::BREAK;
|
||||
}
|
||||
|
||||
// pass all these checks
|
||||
if (is_invert_field) {
|
||||
add_invert_filter(query_rel_node.get());
|
||||
} else {
|
||||
add_forward_filter(query_rel_node.get(), left->text());
|
||||
}
|
||||
return ControlOp::CONTINUE;
|
||||
}
|
||||
|
||||
void SearchCondCheckWalker::add_forward_filter(QueryRelNode *query_rel_node,
|
||||
std::string forward_field_name) {
|
||||
forward_filter_field_names_.emplace_back(std::move(forward_field_name));
|
||||
filter_rels_.push_back(query_rel_node);
|
||||
query_rel_node->set_forward();
|
||||
}
|
||||
|
||||
void SearchCondCheckWalker::add_invert_filter(QueryRelNode *query_rel_node) {
|
||||
invert_rels_.push_back(query_rel_node);
|
||||
query_rel_node->set_invert();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "analyzer/query_node.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
enum class ControlOp { CONTINUE, BREAK };
|
||||
|
||||
class SearchCondCheckWalker {
|
||||
public:
|
||||
SearchCondCheckWalker(const zvec::CollectionSchema &table_ptr);
|
||||
ControlOp traverse_cond_node(const QueryNode::Ptr &query_node,
|
||||
bool or_ancestor = false);
|
||||
|
||||
|
||||
const std::vector<std::string> &forward_filter_field_names() {
|
||||
return forward_filter_field_names_;
|
||||
}
|
||||
|
||||
QueryRelNode *vector_rel() const {
|
||||
return vector_rel_;
|
||||
}
|
||||
|
||||
const std::vector<QueryRelNode *> &invert_rels() const {
|
||||
return invert_rels_;
|
||||
}
|
||||
|
||||
const std::vector<QueryRelNode *> &filter_rels() const {
|
||||
return filter_rels_;
|
||||
}
|
||||
|
||||
const std::string err_msg() {
|
||||
return err_msg_;
|
||||
}
|
||||
|
||||
private:
|
||||
ControlOp access(const QueryNode::Ptr &query_node, bool or_ancestor);
|
||||
|
||||
std::optional<ControlOp> check_array_and_contain_compatible(
|
||||
const QueryRelNode::Ptr &query_rel_node, const FieldSchema *field,
|
||||
bool is_invert_field);
|
||||
|
||||
int func_check(const QueryNode::Ptr &func_node);
|
||||
bool left_op_func_check(const QueryRelNode::Ptr &query_node);
|
||||
tl::expected<void, std::string> array_length_func_check(
|
||||
const QueryFuncNode::Ptr &func_node, const QueryRelNode::Ptr &query_node);
|
||||
bool is_arithematic_compare_op(QueryNodeOp op);
|
||||
bool check_like(const zvec::FieldSchema &field, QueryRelNode *query_node);
|
||||
|
||||
bool field_type_vs_value_type(zvec::DataType data_type,
|
||||
const QueryNode::Ptr &node);
|
||||
|
||||
bool field_type_vs_list_value_type(zvec::DataType data_type,
|
||||
const QueryNode::Ptr &node);
|
||||
|
||||
bool check_and_convert_value_type(zvec::DataType data_type,
|
||||
const QueryNode::Ptr &node);
|
||||
|
||||
bool check_and_convert_list_value_type(zvec::DataType data_type,
|
||||
const QueryNode::Ptr &node);
|
||||
void add_forward_filter(QueryRelNode *query_rel_node,
|
||||
std::string forward_field_name);
|
||||
void add_invert_filter(QueryRelNode *query_rel_node);
|
||||
|
||||
private:
|
||||
std::string err_msg_;
|
||||
const CollectionSchema &table_ptr_;
|
||||
std::vector<std::string> forward_filter_field_names_{};
|
||||
|
||||
QueryRelNode *vector_rel_{nullptr};
|
||||
std::vector<QueryRelNode *> filter_rels_{};
|
||||
std::vector<QueryRelNode *> invert_rels_{};
|
||||
|
||||
static inline const std::string kFeature = "feature";
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_orderby_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
QueryOrderbyInfo::QueryOrderbyInfo() {}
|
||||
|
||||
QueryOrderbyInfo::QueryOrderbyInfo(const std::string &m_field_name, bool m_desc)
|
||||
: field_name_(m_field_name), desc_(m_desc) {}
|
||||
|
||||
|
||||
std::string QueryOrderbyInfo::to_string() const {
|
||||
std::string str = field_name_;
|
||||
str = str + " " + (desc_ ? "DESC" : "ASC");
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "db/index/common/schema.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class QueryOrderbyInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<QueryOrderbyInfo>;
|
||||
|
||||
QueryOrderbyInfo();
|
||||
QueryOrderbyInfo(const std::string &m_field_name, bool m_desc);
|
||||
~QueryOrderbyInfo() = default;
|
||||
|
||||
void set_field_name(const std::string &value) {
|
||||
field_name_ = value;
|
||||
}
|
||||
|
||||
const std::string &field_name() const {
|
||||
return field_name_;
|
||||
}
|
||||
|
||||
void set_desc() {
|
||||
desc_ = true;
|
||||
}
|
||||
bool is_desc() const {
|
||||
return desc_;
|
||||
}
|
||||
|
||||
void set_field_schema_ptr(const zvec::FieldSchema *field_schema_ptr) {
|
||||
field_schema_ptr_ = field_schema_ptr;
|
||||
}
|
||||
const zvec::FieldSchema *field_schema_ptr() {
|
||||
return field_schema_ptr_;
|
||||
}
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
std::string field_name_{""};
|
||||
bool desc_{false};
|
||||
|
||||
const zvec::FieldSchema *field_schema_ptr_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,198 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "simple_rewriter.h"
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "analyzer/query_node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
void SimpleRewriter::rewrite(QueryInfo *query_info) {
|
||||
auto query_node = query_info->search_cond();
|
||||
if (query_node == nullptr) {
|
||||
return;
|
||||
}
|
||||
std::string before_rewrite = query_node->text();
|
||||
|
||||
EqualOrRewriteRule equal_or_rule;
|
||||
ContainRewriteRule contain_rule;
|
||||
std::array<RewriteRule *, 2> rewrite_rules{
|
||||
&equal_or_rule,
|
||||
&contain_rule,
|
||||
};
|
||||
bool rewrited = false;
|
||||
for (auto &rule : rewrite_rules) {
|
||||
rewrited = rule->rewrite(query_node) || rewrited;
|
||||
}
|
||||
if (rewrited) {
|
||||
simplify_tree(query_node, query_info);
|
||||
std::string after_rewrite = query_info->search_cond()->text();
|
||||
LOG_INFO("Rewrite filter. before[%s] after[%s]", before_rewrite.c_str(),
|
||||
after_rewrite.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleRewriter::simplify_tree(QueryNode::Ptr query_node,
|
||||
QueryInfo *query_info) {
|
||||
if (query_node == nullptr ||
|
||||
query_node->type() != QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
return;
|
||||
}
|
||||
simplify_tree(query_node->left(), query_info);
|
||||
simplify_tree(query_node->right(), query_info);
|
||||
if (query_node->left() == nullptr) {
|
||||
if (query_node->right() == nullptr) {
|
||||
query_node->detach_from_search_cond(query_info);
|
||||
} else {
|
||||
query_node->replace_from_search_cond(query_node->right(), query_info);
|
||||
}
|
||||
} else {
|
||||
if (query_node->right() == nullptr) {
|
||||
query_node->replace_from_search_cond(query_node->left(), query_info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool EqualOrRewriteRule::rewrite(QueryNode::Ptr query_node) {
|
||||
rewrite_impl(false, std::move(query_node));
|
||||
return rewrited_;
|
||||
}
|
||||
|
||||
void EqualOrRewriteRule::rewrite_impl(bool is_or, QueryNode::Ptr query_node) {
|
||||
if (query_node == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (query_node->type() == QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
bool is_cur_or = query_node->op() == QueryNodeOp::Q_OR;
|
||||
if (!is_cur_or) {
|
||||
cur_ = nullptr;
|
||||
}
|
||||
rewrite_impl(is_cur_or, query_node->left());
|
||||
rewrite_impl(is_cur_or, query_node->right());
|
||||
return;
|
||||
}
|
||||
if (!is_or) {
|
||||
return;
|
||||
}
|
||||
if (query_node->op() == QueryNodeOp::Q_EQ ||
|
||||
query_node->op() == QueryNodeOp::Q_NE) {
|
||||
bool is_ne = query_node->op() == QueryNodeOp::Q_NE;
|
||||
if (cur_ == nullptr || !cur_->left()->is_matched(*query_node->left())) {
|
||||
cur_ = query_node;
|
||||
} else {
|
||||
if (cur_->op() == QueryNodeOp::Q_IN) {
|
||||
QueryListNode::Ptr list =
|
||||
std::dynamic_pointer_cast<QueryListNode>(cur_->right());
|
||||
if (is_ne == list->exclude()) {
|
||||
list->add_value_expr(query_node->right());
|
||||
// detach from parent
|
||||
query_node->detach_from_parent();
|
||||
} else {
|
||||
cur_ = query_node;
|
||||
}
|
||||
} else { // EQ || NE
|
||||
if (query_node->op() == cur_->op()) {
|
||||
// create in node
|
||||
QueryListNode::Ptr list = std::make_shared<QueryListNode>();
|
||||
list->add_value_expr(cur_->right());
|
||||
list->add_value_expr(query_node->right());
|
||||
list->set_exclude(is_ne);
|
||||
auto in_node = std::make_shared<QueryRelNode>();
|
||||
in_node->set_left(cur_->left());
|
||||
in_node->set_right(std::move(list));
|
||||
in_node->set_op(QueryNodeOp::Q_IN);
|
||||
// detach from parent
|
||||
query_node->detach_from_parent();
|
||||
cur_->replace_from_parent(in_node);
|
||||
cur_ = std::move(in_node);
|
||||
rewrited_ = true;
|
||||
} else {
|
||||
cur_ = query_node;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<bool> get_predicate_result(const QueryNode *ptr) {
|
||||
if (ptr == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return ptr->predictate_result();
|
||||
}
|
||||
|
||||
bool ContainRewriteRule::rewrite(QueryNode::Ptr query_node) {
|
||||
if (query_node == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (query_node->type() == QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
bool rewrited = rewrite(query_node->left()) || rewrite(query_node->right());
|
||||
auto left_result = get_predicate_result(query_node->left().get());
|
||||
auto right_result = get_predicate_result(query_node->right().get());
|
||||
// ContainRewrite can only generate false predict result value
|
||||
if (left_result.has_value() || right_result.has_value()) {
|
||||
if (query_node->op() == QueryNodeOp::Q_AND) {
|
||||
query_node->set_predictate_result(false);
|
||||
} else if (query_node->op() == QueryNodeOp::Q_OR) {
|
||||
// if left is false
|
||||
if (left_result.has_value()) {
|
||||
// if right is null or false
|
||||
if (right_result.has_value() || query_node->right() == nullptr) {
|
||||
query_node->set_predictate_result(false);
|
||||
} else { // if right is not null and not false
|
||||
query_node->left()->detach_from_parent();
|
||||
}
|
||||
} else {
|
||||
if (right_result.has_value()) {
|
||||
if (query_node->left() == nullptr) {
|
||||
// set predict result to false if left is null
|
||||
query_node->set_predictate_result(false);
|
||||
} else {
|
||||
// detach right if left is not null and not false
|
||||
query_node->right()->detach_from_parent();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rewrited;
|
||||
}
|
||||
auto op = query_node->op();
|
||||
if (op != QueryNodeOp::Q_CONTAIN_ALL && op != QueryNodeOp::Q_CONTAIN_ANY) {
|
||||
return false;
|
||||
}
|
||||
auto list_node =
|
||||
std::dynamic_pointer_cast<QueryListNode>(query_node->right());
|
||||
if (!list_node->value_expr_list().empty()) {
|
||||
return false;
|
||||
}
|
||||
if ((list_node->exclude() && op == QueryNodeOp::Q_CONTAIN_ALL) ||
|
||||
(!list_node->exclude() && op == QueryNodeOp::Q_CONTAIN_ANY)) {
|
||||
// `not contain_all ()` evaluates to false
|
||||
// `contain_any ()` evaluates to false
|
||||
query_node->set_predictate_result(false);
|
||||
return true;
|
||||
}
|
||||
// `contain_all()` or `not contain_any()` rewrite to `is not null`
|
||||
query_node->set_op(QueryNodeOp::Q_IS_NOT_NULL);
|
||||
auto right = std::make_shared<QueryConstantNode>("");
|
||||
right->set_op(QueryNodeOp::Q_NULL_VALUE);
|
||||
query_node->set_right(std::move(right));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,61 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SimpleRewriter {
|
||||
public:
|
||||
SimpleRewriter() = default;
|
||||
|
||||
//! Rewrite query_info->search_cond and simplify tree
|
||||
void rewrite(QueryInfo *query_info);
|
||||
|
||||
private:
|
||||
void simplify_tree(QueryNode::Ptr query_node, QueryInfo *query_info);
|
||||
};
|
||||
|
||||
class RewriteRule {
|
||||
public:
|
||||
RewriteRule() = default;
|
||||
//! Rewrite filter, return whether successfully rewrited.
|
||||
virtual bool rewrite(QueryNode::Ptr query_node) = 0;
|
||||
|
||||
protected:
|
||||
bool rewrited_{false};
|
||||
};
|
||||
|
||||
class EqualOrRewriteRule : public RewriteRule {
|
||||
public:
|
||||
EqualOrRewriteRule() = default;
|
||||
|
||||
bool rewrite(QueryNode::Ptr query_node) override;
|
||||
|
||||
private:
|
||||
void rewrite_impl(bool is_or, QueryNode::Ptr query_node);
|
||||
|
||||
private:
|
||||
QueryNode::Ptr cur_;
|
||||
};
|
||||
|
||||
// ContainRewriteRule rewrites contain_all/any ()
|
||||
class ContainRewriteRule : public RewriteRule {
|
||||
public:
|
||||
ContainRewriteRule() = default;
|
||||
|
||||
bool rewrite(QueryNode::Ptr query_node) override;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,95 @@
|
||||
lexer grammar SQLLexer;
|
||||
|
||||
channels{COMMENTS}
|
||||
|
||||
OR: 'OR';
|
||||
AND: 'AND';
|
||||
NOT: 'NOT';
|
||||
IN: 'IN';
|
||||
CONTAIN_ALL: 'CONTAIN_ALL';
|
||||
CONTAIN_ANY: 'CONTAIN_ANY';
|
||||
BETWEEN: 'BETWEEN';
|
||||
LIKE: 'LIKE';
|
||||
WHERE: 'WHERE';
|
||||
SELECT: 'SELECT';
|
||||
FROM: 'FROM';
|
||||
AS: 'AS';
|
||||
BY: 'BY';
|
||||
ORDER: 'ORDER';
|
||||
ASC: 'ASC';
|
||||
DESC: 'DESC';
|
||||
LIMIT: 'LIMIT';
|
||||
TRUE_V: 'TRUE';
|
||||
FALSE_V: 'FALSE';
|
||||
IS: 'IS';
|
||||
NULL_V: 'NULL';
|
||||
|
||||
fragment
|
||||
UNSIGNED_INTEGER: UNSIGNED_INTEGER_FRAGMENT;
|
||||
INTEGER: MINUS_SIGN? UNSIGNED_INTEGER;
|
||||
|
||||
fragment
|
||||
APPROXIMATE_NUM_LIT: FLOAT_FRAGMENT ('E' ('+'|'-')? (FLOAT_FRAGMENT | UNSIGNED_INTEGER_FRAGMENT))? ('D' | 'F')?;
|
||||
FLOAT: MINUS_SIGN? APPROXIMATE_NUM_LIT;
|
||||
|
||||
SQUOTA_STRING: '\'' (~('\'' | '\\') | '\\'. )* '\'';
|
||||
DQUOTA_STRING: '"' (~('"' | '\\') | '\\'. )* '"';
|
||||
|
||||
|
||||
DOT: '.';
|
||||
LP: '(';
|
||||
RP: ')';
|
||||
LMP: '[';
|
||||
RMP: ']';
|
||||
ASTERISK: '*';
|
||||
PLUS_SIGN: '+';
|
||||
MINUS_SIGN: '-';
|
||||
COMMA: ',';
|
||||
SOLIDUS: '/';
|
||||
MOD: '%';
|
||||
AT_SIGN: '@';
|
||||
ASSIGN_OP: ':=';
|
||||
SHARP_SIGN: '#';
|
||||
|
||||
COLON: ':';
|
||||
SEMI: ';';
|
||||
LE_OP: '<=';
|
||||
GE_OP: '>=';
|
||||
NE_OP: '!=';
|
||||
CARET_OP: '^';
|
||||
TILDE_OP: '~';
|
||||
L_OP: '<';
|
||||
G_OP: '>';
|
||||
E_OP: '=';
|
||||
CONCAT_OP: '||';
|
||||
UNDERSCORE: '_';
|
||||
|
||||
SPACES: [ \t\r\n]+ -> skip;
|
||||
|
||||
fragment
|
||||
SIMPLE_LETTER
|
||||
: [A-Z]
|
||||
;
|
||||
|
||||
fragment
|
||||
UNSIGNED_INTEGER_FRAGMENT: [0-9]+ ;
|
||||
|
||||
fragment
|
||||
FLOAT_FRAGMENT
|
||||
: UNSIGNED_INTEGER* '.'? UNSIGNED_INTEGER+
|
||||
;
|
||||
|
||||
|
||||
VECTOR
|
||||
: LMP (MINUS_SIGN|UNSIGNED_INTEGER_FRAGMENT|FLOAT_FRAGMENT|','| SPACES)+ RMP
|
||||
;
|
||||
|
||||
SINGLE_LINE_COMMENT: '--' ~('\r' | '\n')* (NEWLINE | EOF) -> channel(COMMENTS);
|
||||
MULTI_LINE_COMMENT: '/*' .*? '*/' -> channel(COMMENTS);
|
||||
|
||||
fragment
|
||||
NEWLINE: '\r'? '\n';
|
||||
|
||||
REGULAR_ID: (SIMPLE_LETTER | '_' | '-' | [0-9])+;
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
parser grammar SQLParser;
|
||||
|
||||
options {tokenVocab=SQLLexer;}
|
||||
|
||||
swallow_to_semi
|
||||
: ~SEMI+
|
||||
;
|
||||
|
||||
compilation_unit
|
||||
: (unit_statement (SOLIDUS | SEMI)?)+ EOF
|
||||
;
|
||||
|
||||
logic_expr_unit
|
||||
: logic_expr EOF
|
||||
;
|
||||
|
||||
unit_statement
|
||||
: dql_statement
|
||||
;
|
||||
|
||||
where_clause
|
||||
: WHERE logic_expr
|
||||
;
|
||||
|
||||
logic_expr
|
||||
: relation_expr
|
||||
| logic_expr AND logic_expr
|
||||
| logic_expr OR logic_expr
|
||||
| enclosed_expr
|
||||
;
|
||||
|
||||
enclosed_expr
|
||||
: LP logic_expr RP
|
||||
;
|
||||
|
||||
relation_expr
|
||||
: identifier rel_oper value_expr
|
||||
| identifier LIKE value_expr
|
||||
| identifier NOT? IN LP in_value_expr_list RP
|
||||
//LMP'[' RMP']' only used in vector representation
|
||||
| identifier NOT? (CONTAIN_ALL | CONTAIN_ANY) LP in_value_expr_list? RP
|
||||
| identifier IS NOT? NULL_V
|
||||
| function_call rel_oper value_expr
|
||||
;
|
||||
|
||||
rel_oper
|
||||
: E_OP
|
||||
| ne_op
|
||||
| L_OP
|
||||
| G_OP
|
||||
| le_op
|
||||
| ge_op
|
||||
;
|
||||
|
||||
value_expr
|
||||
: constant
|
||||
| function_call
|
||||
;
|
||||
|
||||
in_value_expr_list
|
||||
: in_value_expr (COMMA in_value_expr)*
|
||||
;
|
||||
|
||||
in_value_expr
|
||||
: constant_num_and_str
|
||||
| bool_value
|
||||
;
|
||||
|
||||
constant
|
||||
: numeric
|
||||
| quoted_string
|
||||
| vector_expr
|
||||
| bool_value
|
||||
;
|
||||
|
||||
constant_num_and_str
|
||||
: numeric
|
||||
| quoted_string
|
||||
;
|
||||
|
||||
matrix
|
||||
: LMP VECTOR (COMMA VECTOR)* RMP
|
||||
;
|
||||
|
||||
vector_expr
|
||||
: VECTOR
|
||||
| matrix
|
||||
;
|
||||
|
||||
function_value_expr
|
||||
: value_expr
|
||||
| identifier
|
||||
;
|
||||
|
||||
function_call
|
||||
: identifier LP (function_value_expr (COMMA function_value_expr)*)? RP
|
||||
;
|
||||
|
||||
dql_statement
|
||||
: select_statement
|
||||
;
|
||||
|
||||
select_statement
|
||||
: SELECT selected_elements from_clause where_clause? order_by_clause? limit_clause?
|
||||
;
|
||||
|
||||
selected_elements
|
||||
: selected_element (COMMA selected_element)*
|
||||
;
|
||||
|
||||
selected_element
|
||||
: ASTERISK
|
||||
| field_name AS? field_alias?
|
||||
;
|
||||
|
||||
from_clause
|
||||
: FROM tableview_name
|
||||
;
|
||||
|
||||
order_by_clause
|
||||
: ORDER BY order_by_element (COMMA order_by_element)*
|
||||
;
|
||||
|
||||
order_by_element
|
||||
: field_name (ASC | DESC)?
|
||||
;
|
||||
|
||||
limit_clause
|
||||
: LIMIT int_value
|
||||
;
|
||||
|
||||
|
||||
// $>
|
||||
|
||||
/********* schema objects names *********/
|
||||
|
||||
|
||||
tableview_name
|
||||
: identifier
|
||||
;
|
||||
|
||||
field_name
|
||||
: identifier
|
||||
;
|
||||
|
||||
table_alias
|
||||
: identifier
|
||||
;
|
||||
|
||||
field_alias
|
||||
: AS? identifier
|
||||
;
|
||||
|
||||
numeric
|
||||
: int_value
|
||||
| float_value
|
||||
;
|
||||
|
||||
int_value
|
||||
: INTEGER
|
||||
;
|
||||
|
||||
float_value
|
||||
: FLOAT
|
||||
;
|
||||
|
||||
quoted_string
|
||||
: SQUOTA_STRING
|
||||
| DQUOTA_STRING
|
||||
;
|
||||
bool_value
|
||||
: TRUE_V
|
||||
| FALSE_V
|
||||
;
|
||||
|
||||
identifier
|
||||
: regular_id
|
||||
;
|
||||
|
||||
ne_op
|
||||
: NE_OP
|
||||
;
|
||||
|
||||
ge_op
|
||||
: GE_OP
|
||||
| G_OP E_OP
|
||||
;
|
||||
|
||||
le_op
|
||||
: LE_OP
|
||||
| L_OP E_OP
|
||||
;
|
||||
|
||||
regular_id
|
||||
: REGULAR_ID
|
||||
| OR
|
||||
| AND
|
||||
| NOT
|
||||
| IN
|
||||
| BETWEEN
|
||||
| LIKE
|
||||
| WHERE
|
||||
| SELECT
|
||||
| AS
|
||||
| BY
|
||||
| ORDER
|
||||
| ASC
|
||||
| DESC
|
||||
| LIMIT
|
||||
;
|
||||
@@ -0,0 +1,694 @@
|
||||
|
||||
// Generated from SQLLexer.g4 by ANTLR 4.8
|
||||
|
||||
|
||||
#include "SQLLexer.h"
|
||||
|
||||
|
||||
using namespace antlr4;
|
||||
|
||||
using namespace antlr4;
|
||||
|
||||
SQLLexer::SQLLexer(CharStream *input) : Lexer(input) {
|
||||
_interpreter = new atn::LexerATNSimulator(this, _atn, _decisionToDFA,
|
||||
_sharedContextCache);
|
||||
}
|
||||
|
||||
SQLLexer::~SQLLexer() {
|
||||
delete _interpreter;
|
||||
}
|
||||
|
||||
std::string SQLLexer::getGrammarFileName() const {
|
||||
return "SQLLexer.g4";
|
||||
}
|
||||
|
||||
const std::vector<std::string> &SQLLexer::getRuleNames() const {
|
||||
return _ruleNames;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &SQLLexer::getChannelNames() const {
|
||||
return _channelNames;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &SQLLexer::getModeNames() const {
|
||||
return _modeNames;
|
||||
}
|
||||
|
||||
const std::vector<std::string> &SQLLexer::getTokenNames() const {
|
||||
return _tokenNames;
|
||||
}
|
||||
|
||||
dfa::Vocabulary &SQLLexer::getVocabulary() const {
|
||||
return _vocabulary;
|
||||
}
|
||||
|
||||
const std::vector<uint16_t> SQLLexer::getSerializedATN() const {
|
||||
return _serializedATN;
|
||||
}
|
||||
|
||||
const atn::ATN &SQLLexer::getATN() const {
|
||||
return _atn;
|
||||
}
|
||||
|
||||
|
||||
// Static vars and initialization.
|
||||
std::vector<dfa::DFA> SQLLexer::_decisionToDFA;
|
||||
atn::PredictionContextCache SQLLexer::_sharedContextCache;
|
||||
|
||||
// We own the ATN which in turn owns the ATN states.
|
||||
atn::ATN SQLLexer::_atn;
|
||||
std::vector<uint16_t> SQLLexer::_serializedATN;
|
||||
|
||||
std::vector<std::string> SQLLexer::_ruleNames = {"OR",
|
||||
"AND",
|
||||
"NOT",
|
||||
"IN",
|
||||
"CONTAIN_ALL",
|
||||
"CONTAIN_ANY",
|
||||
"BETWEEN",
|
||||
"LIKE",
|
||||
"WHERE",
|
||||
"SELECT",
|
||||
"FROM",
|
||||
"AS",
|
||||
"BY",
|
||||
"ORDER",
|
||||
"ASC",
|
||||
"DESC",
|
||||
"LIMIT",
|
||||
"TRUE_V",
|
||||
"FALSE_V",
|
||||
"IS",
|
||||
"NULL_V",
|
||||
"UNSIGNED_INTEGER",
|
||||
"INTEGER",
|
||||
"APPROXIMATE_NUM_LIT",
|
||||
"FLOAT",
|
||||
"SQUOTA_STRING",
|
||||
"DQUOTA_STRING",
|
||||
"DOT",
|
||||
"LP",
|
||||
"RP",
|
||||
"LMP",
|
||||
"RMP",
|
||||
"ASTERISK",
|
||||
"PLUS_SIGN",
|
||||
"MINUS_SIGN",
|
||||
"COMMA",
|
||||
"SOLIDUS",
|
||||
"MOD",
|
||||
"AT_SIGN",
|
||||
"ASSIGN_OP",
|
||||
"SHARP_SIGN",
|
||||
"COLON",
|
||||
"SEMI",
|
||||
"LE_OP",
|
||||
"GE_OP",
|
||||
"NE_OP",
|
||||
"CARET_OP",
|
||||
"TILDE_OP",
|
||||
"L_OP",
|
||||
"G_OP",
|
||||
"E_OP",
|
||||
"CONCAT_OP",
|
||||
"UNDERSCORE",
|
||||
"SPACES",
|
||||
"SIMPLE_LETTER",
|
||||
"UNSIGNED_INTEGER_FRAGMENT",
|
||||
"FLOAT_FRAGMENT",
|
||||
"VECTOR",
|
||||
"SINGLE_LINE_COMMENT",
|
||||
"MULTI_LINE_COMMENT",
|
||||
"NEWLINE",
|
||||
"REGULAR_ID"};
|
||||
|
||||
std::vector<std::string> SQLLexer::_channelNames = {"DEFAULT_TOKEN_CHANNEL",
|
||||
"HIDDEN", "COMMENTS"};
|
||||
|
||||
std::vector<std::string> SQLLexer::_modeNames = {"DEFAULT_MODE"};
|
||||
|
||||
std::vector<std::string> SQLLexer::_literalNames = {"",
|
||||
"'OR'",
|
||||
"'AND'",
|
||||
"'NOT'",
|
||||
"'IN'",
|
||||
"'CONTAIN_ALL'",
|
||||
"'CONTAIN_ANY'",
|
||||
"'BETWEEN'",
|
||||
"'LIKE'",
|
||||
"'WHERE'",
|
||||
"'SELECT'",
|
||||
"'FROM'",
|
||||
"'AS'",
|
||||
"'BY'",
|
||||
"'ORDER'",
|
||||
"'ASC'",
|
||||
"'DESC'",
|
||||
"'LIMIT'",
|
||||
"'TRUE'",
|
||||
"'FALSE'",
|
||||
"'IS'",
|
||||
"'NULL'",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"'.'",
|
||||
"'('",
|
||||
"')'",
|
||||
"'['",
|
||||
"']'",
|
||||
"'*'",
|
||||
"'+'",
|
||||
"'-'",
|
||||
"','",
|
||||
"'/'",
|
||||
"'%'",
|
||||
"'@'",
|
||||
"':='",
|
||||
"'#'",
|
||||
"':'",
|
||||
"';'",
|
||||
"'<='",
|
||||
"'>='",
|
||||
"'!='",
|
||||
"'^'",
|
||||
"'~'",
|
||||
"'<'",
|
||||
"'>'",
|
||||
"'='",
|
||||
"'||'",
|
||||
"'_'"};
|
||||
|
||||
std::vector<std::string> SQLLexer::_symbolicNames = {"",
|
||||
"OR",
|
||||
"AND",
|
||||
"NOT",
|
||||
"IN",
|
||||
"CONTAIN_ALL",
|
||||
"CONTAIN_ANY",
|
||||
"BETWEEN",
|
||||
"LIKE",
|
||||
"WHERE",
|
||||
"SELECT",
|
||||
"FROM",
|
||||
"AS",
|
||||
"BY",
|
||||
"ORDER",
|
||||
"ASC",
|
||||
"DESC",
|
||||
"LIMIT",
|
||||
"TRUE_V",
|
||||
"FALSE_V",
|
||||
"IS",
|
||||
"NULL_V",
|
||||
"INTEGER",
|
||||
"FLOAT",
|
||||
"SQUOTA_STRING",
|
||||
"DQUOTA_STRING",
|
||||
"DOT",
|
||||
"LP",
|
||||
"RP",
|
||||
"LMP",
|
||||
"RMP",
|
||||
"ASTERISK",
|
||||
"PLUS_SIGN",
|
||||
"MINUS_SIGN",
|
||||
"COMMA",
|
||||
"SOLIDUS",
|
||||
"MOD",
|
||||
"AT_SIGN",
|
||||
"ASSIGN_OP",
|
||||
"SHARP_SIGN",
|
||||
"COLON",
|
||||
"SEMI",
|
||||
"LE_OP",
|
||||
"GE_OP",
|
||||
"NE_OP",
|
||||
"CARET_OP",
|
||||
"TILDE_OP",
|
||||
"L_OP",
|
||||
"G_OP",
|
||||
"E_OP",
|
||||
"CONCAT_OP",
|
||||
"UNDERSCORE",
|
||||
"SPACES",
|
||||
"VECTOR",
|
||||
"SINGLE_LINE_COMMENT",
|
||||
"MULTI_LINE_COMMENT",
|
||||
"REGULAR_ID"};
|
||||
|
||||
dfa::Vocabulary SQLLexer::_vocabulary(_literalNames, _symbolicNames);
|
||||
|
||||
std::vector<std::string> SQLLexer::_tokenNames;
|
||||
|
||||
SQLLexer::Initializer::Initializer() {
|
||||
// This code could be in a static initializer lambda, but VS doesn't allow
|
||||
// access to private class members from there.
|
||||
for (size_t i = 0; i < _symbolicNames.size(); ++i) {
|
||||
std::string name = _vocabulary.getLiteralName(i);
|
||||
if (name.empty()) {
|
||||
name = _vocabulary.getSymbolicName(i);
|
||||
}
|
||||
|
||||
if (name.empty()) {
|
||||
_tokenNames.push_back("<INVALID>");
|
||||
} else {
|
||||
_tokenNames.push_back(name);
|
||||
}
|
||||
}
|
||||
|
||||
_serializedATN = {
|
||||
0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964,
|
||||
0x2, 0x3a, 0x1ab, 0x8, 0x1, 0x4, 0x2, 0x9, 0x2,
|
||||
0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, 0x4, 0x4,
|
||||
0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7,
|
||||
0x9, 0x7, 0x4, 0x8, 0x9, 0x8, 0x4, 0x9, 0x9,
|
||||
0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, 0xb,
|
||||
0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4,
|
||||
0xe, 0x9, 0xe, 0x4, 0xf, 0x9, 0xf, 0x4, 0x10,
|
||||
0x9, 0x10, 0x4, 0x11, 0x9, 0x11, 0x4, 0x12, 0x9,
|
||||
0x12, 0x4, 0x13, 0x9, 0x13, 0x4, 0x14, 0x9, 0x14,
|
||||
0x4, 0x15, 0x9, 0x15, 0x4, 0x16, 0x9, 0x16, 0x4,
|
||||
0x17, 0x9, 0x17, 0x4, 0x18, 0x9, 0x18, 0x4, 0x19,
|
||||
0x9, 0x19, 0x4, 0x1a, 0x9, 0x1a, 0x4, 0x1b, 0x9,
|
||||
0x1b, 0x4, 0x1c, 0x9, 0x1c, 0x4, 0x1d, 0x9, 0x1d,
|
||||
0x4, 0x1e, 0x9, 0x1e, 0x4, 0x1f, 0x9, 0x1f, 0x4,
|
||||
0x20, 0x9, 0x20, 0x4, 0x21, 0x9, 0x21, 0x4, 0x22,
|
||||
0x9, 0x22, 0x4, 0x23, 0x9, 0x23, 0x4, 0x24, 0x9,
|
||||
0x24, 0x4, 0x25, 0x9, 0x25, 0x4, 0x26, 0x9, 0x26,
|
||||
0x4, 0x27, 0x9, 0x27, 0x4, 0x28, 0x9, 0x28, 0x4,
|
||||
0x29, 0x9, 0x29, 0x4, 0x2a, 0x9, 0x2a, 0x4, 0x2b,
|
||||
0x9, 0x2b, 0x4, 0x2c, 0x9, 0x2c, 0x4, 0x2d, 0x9,
|
||||
0x2d, 0x4, 0x2e, 0x9, 0x2e, 0x4, 0x2f, 0x9, 0x2f,
|
||||
0x4, 0x30, 0x9, 0x30, 0x4, 0x31, 0x9, 0x31, 0x4,
|
||||
0x32, 0x9, 0x32, 0x4, 0x33, 0x9, 0x33, 0x4, 0x34,
|
||||
0x9, 0x34, 0x4, 0x35, 0x9, 0x35, 0x4, 0x36, 0x9,
|
||||
0x36, 0x4, 0x37, 0x9, 0x37, 0x4, 0x38, 0x9, 0x38,
|
||||
0x4, 0x39, 0x9, 0x39, 0x4, 0x3a, 0x9, 0x3a, 0x4,
|
||||
0x3b, 0x9, 0x3b, 0x4, 0x3c, 0x9, 0x3c, 0x4, 0x3d,
|
||||
0x9, 0x3d, 0x4, 0x3e, 0x9, 0x3e, 0x4, 0x3f, 0x9,
|
||||
0x3f, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x3,
|
||||
0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3,
|
||||
0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x5, 0x3, 0x5,
|
||||
0x3, 0x5, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3,
|
||||
0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6,
|
||||
0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3, 0x6, 0x3,
|
||||
0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7,
|
||||
0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3,
|
||||
0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x8, 0x3, 0x8,
|
||||
0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3,
|
||||
0x8, 0x3, 0x8, 0x3, 0x9, 0x3, 0x9, 0x3, 0x9,
|
||||
0x3, 0x9, 0x3, 0x9, 0x3, 0xa, 0x3, 0xa, 0x3,
|
||||
0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xb,
|
||||
0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3,
|
||||
0xb, 0x3, 0xb, 0x3, 0xc, 0x3, 0xc, 0x3, 0xc,
|
||||
0x3, 0xc, 0x3, 0xc, 0x3, 0xd, 0x3, 0xd, 0x3,
|
||||
0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xf,
|
||||
0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3,
|
||||
0xf, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10,
|
||||
0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3,
|
||||
0x11, 0x3, 0x12, 0x3, 0x12, 0x3, 0x12, 0x3, 0x12,
|
||||
0x3, 0x12, 0x3, 0x12, 0x3, 0x13, 0x3, 0x13, 0x3,
|
||||
0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x14, 0x3, 0x14,
|
||||
0x3, 0x14, 0x3, 0x14, 0x3, 0x14, 0x3, 0x14, 0x3,
|
||||
0x15, 0x3, 0x15, 0x3, 0x15, 0x3, 0x16, 0x3, 0x16,
|
||||
0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x17, 0x3,
|
||||
0x17, 0x3, 0x18, 0x5, 0x18, 0xf6, 0xa, 0x18, 0x3,
|
||||
0x18, 0x3, 0x18, 0x3, 0x19, 0x3, 0x19, 0x3, 0x19,
|
||||
0x5, 0x19, 0xfd, 0xa, 0x19, 0x3, 0x19, 0x3, 0x19,
|
||||
0x5, 0x19, 0x101, 0xa, 0x19, 0x5, 0x19, 0x103, 0xa,
|
||||
0x19, 0x3, 0x19, 0x5, 0x19, 0x106, 0xa, 0x19, 0x3,
|
||||
0x1a, 0x5, 0x1a, 0x109, 0xa, 0x1a, 0x3, 0x1a, 0x3,
|
||||
0x1a, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1b,
|
||||
0x7, 0x1b, 0x111, 0xa, 0x1b, 0xc, 0x1b, 0xe, 0x1b,
|
||||
0x114, 0xb, 0x1b, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1c,
|
||||
0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1c, 0x7, 0x1c, 0x11c,
|
||||
0xa, 0x1c, 0xc, 0x1c, 0xe, 0x1c, 0x11f, 0xb, 0x1c,
|
||||
0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1d, 0x3, 0x1d, 0x3,
|
||||
0x1e, 0x3, 0x1e, 0x3, 0x1f, 0x3, 0x1f, 0x3, 0x20,
|
||||
0x3, 0x20, 0x3, 0x21, 0x3, 0x21, 0x3, 0x22, 0x3,
|
||||
0x22, 0x3, 0x23, 0x3, 0x23, 0x3, 0x24, 0x3, 0x24,
|
||||
0x3, 0x25, 0x3, 0x25, 0x3, 0x26, 0x3, 0x26, 0x3,
|
||||
0x27, 0x3, 0x27, 0x3, 0x28, 0x3, 0x28, 0x3, 0x29,
|
||||
0x3, 0x29, 0x3, 0x29, 0x3, 0x2a, 0x3, 0x2a, 0x3,
|
||||
0x2b, 0x3, 0x2b, 0x3, 0x2c, 0x3, 0x2c, 0x3, 0x2d,
|
||||
0x3, 0x2d, 0x3, 0x2d, 0x3, 0x2e, 0x3, 0x2e, 0x3,
|
||||
0x2e, 0x3, 0x2f, 0x3, 0x2f, 0x3, 0x2f, 0x3, 0x30,
|
||||
0x3, 0x30, 0x3, 0x31, 0x3, 0x31, 0x3, 0x32, 0x3,
|
||||
0x32, 0x3, 0x33, 0x3, 0x33, 0x3, 0x34, 0x3, 0x34,
|
||||
0x3, 0x35, 0x3, 0x35, 0x3, 0x35, 0x3, 0x36, 0x3,
|
||||
0x36, 0x3, 0x37, 0x6, 0x37, 0x15d, 0xa, 0x37, 0xd,
|
||||
0x37, 0xe, 0x37, 0x15e, 0x3, 0x37, 0x3, 0x37, 0x3,
|
||||
0x38, 0x3, 0x38, 0x3, 0x39, 0x6, 0x39, 0x166, 0xa,
|
||||
0x39, 0xd, 0x39, 0xe, 0x39, 0x167, 0x3, 0x3a, 0x7,
|
||||
0x3a, 0x16b, 0xa, 0x3a, 0xc, 0x3a, 0xe, 0x3a, 0x16e,
|
||||
0xb, 0x3a, 0x3, 0x3a, 0x5, 0x3a, 0x171, 0xa, 0x3a,
|
||||
0x3, 0x3a, 0x6, 0x3a, 0x174, 0xa, 0x3a, 0xd, 0x3a,
|
||||
0xe, 0x3a, 0x175, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b,
|
||||
0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b, 0x6, 0x3b, 0x17e,
|
||||
0xa, 0x3b, 0xd, 0x3b, 0xe, 0x3b, 0x17f, 0x3, 0x3b,
|
||||
0x3, 0x3b, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3,
|
||||
0x3c, 0x7, 0x3c, 0x188, 0xa, 0x3c, 0xc, 0x3c, 0xe,
|
||||
0x3c, 0x18b, 0xb, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x5,
|
||||
0x3c, 0x18f, 0xa, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3,
|
||||
0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x7, 0x3d,
|
||||
0x197, 0xa, 0x3d, 0xc, 0x3d, 0xe, 0x3d, 0x19a, 0xb,
|
||||
0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d,
|
||||
0x3, 0x3d, 0x3, 0x3e, 0x5, 0x3e, 0x1a2, 0xa, 0x3e,
|
||||
0x3, 0x3e, 0x3, 0x3e, 0x3, 0x3f, 0x3, 0x3f, 0x6,
|
||||
0x3f, 0x1a8, 0xa, 0x3f, 0xd, 0x3f, 0xe, 0x3f, 0x1a9,
|
||||
0x3, 0x198, 0x2, 0x40, 0x3, 0x3, 0x5, 0x4, 0x7,
|
||||
0x5, 0x9, 0x6, 0xb, 0x7, 0xd, 0x8, 0xf, 0x9,
|
||||
0x11, 0xa, 0x13, 0xb, 0x15, 0xc, 0x17, 0xd, 0x19,
|
||||
0xe, 0x1b, 0xf, 0x1d, 0x10, 0x1f, 0x11, 0x21, 0x12,
|
||||
0x23, 0x13, 0x25, 0x14, 0x27, 0x15, 0x29, 0x16, 0x2b,
|
||||
0x17, 0x2d, 0x2, 0x2f, 0x18, 0x31, 0x2, 0x33, 0x19,
|
||||
0x35, 0x1a, 0x37, 0x1b, 0x39, 0x1c, 0x3b, 0x1d, 0x3d,
|
||||
0x1e, 0x3f, 0x1f, 0x41, 0x20, 0x43, 0x21, 0x45, 0x22,
|
||||
0x47, 0x23, 0x49, 0x24, 0x4b, 0x25, 0x4d, 0x26, 0x4f,
|
||||
0x27, 0x51, 0x28, 0x53, 0x29, 0x55, 0x2a, 0x57, 0x2b,
|
||||
0x59, 0x2c, 0x5b, 0x2d, 0x5d, 0x2e, 0x5f, 0x2f, 0x61,
|
||||
0x30, 0x63, 0x31, 0x65, 0x32, 0x67, 0x33, 0x69, 0x34,
|
||||
0x6b, 0x35, 0x6d, 0x36, 0x6f, 0x2, 0x71, 0x2, 0x73,
|
||||
0x2, 0x75, 0x37, 0x77, 0x38, 0x79, 0x39, 0x7b, 0x2,
|
||||
0x7d, 0x3a, 0x3, 0x2, 0xb, 0x4, 0x2, 0x2d, 0x2d,
|
||||
0x2f, 0x2f, 0x4, 0x2, 0x46, 0x46, 0x48, 0x48, 0x4,
|
||||
0x2, 0x29, 0x29, 0x5e, 0x5e, 0x4, 0x2, 0x24, 0x24,
|
||||
0x5e, 0x5e, 0x5, 0x2, 0xb, 0xc, 0xf, 0xf, 0x22,
|
||||
0x22, 0x3, 0x2, 0x43, 0x5c, 0x3, 0x2, 0x32, 0x3b,
|
||||
0x4, 0x2, 0xc, 0xc, 0xf, 0xf, 0x5, 0x2, 0x2f,
|
||||
0x2f, 0x32, 0x3b, 0x61, 0x61, 0x2, 0x1be, 0x2, 0x3,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x5, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x7, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0xb, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0xd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x11, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x13, 0x3, 0x2, 0x2, 0x2, 0x2, 0x15,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x17, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x19, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1b,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x1d, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x21,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x23, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x25, 0x3, 0x2, 0x2, 0x2, 0x2, 0x27,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x29, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x2b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2f,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x33, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x35, 0x3, 0x2, 0x2, 0x2, 0x2, 0x37,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x39, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x3d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x3f, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x41, 0x3, 0x2, 0x2, 0x2, 0x2, 0x43,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x45, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x47, 0x3, 0x2, 0x2, 0x2, 0x2, 0x49,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x4b, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x4d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x4f,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x51, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x53, 0x3, 0x2, 0x2, 0x2, 0x2, 0x55,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x57, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x59, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5b,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x5d, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x5f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x61,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x63, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x65, 0x3, 0x2, 0x2, 0x2, 0x2, 0x67,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x69, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x6b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x6d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x75, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2, 0x77, 0x3, 0x2, 0x2, 0x2, 0x2, 0x79,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2, 0x7d, 0x3, 0x2, 0x2,
|
||||
0x2, 0x3, 0x7f, 0x3, 0x2, 0x2, 0x2, 0x5, 0x82,
|
||||
0x3, 0x2, 0x2, 0x2, 0x7, 0x86, 0x3, 0x2, 0x2,
|
||||
0x2, 0x9, 0x8a, 0x3, 0x2, 0x2, 0x2, 0xb, 0x8d,
|
||||
0x3, 0x2, 0x2, 0x2, 0xd, 0x99, 0x3, 0x2, 0x2,
|
||||
0x2, 0xf, 0xa5, 0x3, 0x2, 0x2, 0x2, 0x11, 0xad,
|
||||
0x3, 0x2, 0x2, 0x2, 0x13, 0xb2, 0x3, 0x2, 0x2,
|
||||
0x2, 0x15, 0xb8, 0x3, 0x2, 0x2, 0x2, 0x17, 0xbf,
|
||||
0x3, 0x2, 0x2, 0x2, 0x19, 0xc4, 0x3, 0x2, 0x2,
|
||||
0x2, 0x1b, 0xc7, 0x3, 0x2, 0x2, 0x2, 0x1d, 0xca,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1f, 0xd0, 0x3, 0x2, 0x2,
|
||||
0x2, 0x21, 0xd4, 0x3, 0x2, 0x2, 0x2, 0x23, 0xd9,
|
||||
0x3, 0x2, 0x2, 0x2, 0x25, 0xdf, 0x3, 0x2, 0x2,
|
||||
0x2, 0x27, 0xe4, 0x3, 0x2, 0x2, 0x2, 0x29, 0xea,
|
||||
0x3, 0x2, 0x2, 0x2, 0x2b, 0xed, 0x3, 0x2, 0x2,
|
||||
0x2, 0x2d, 0xf2, 0x3, 0x2, 0x2, 0x2, 0x2f, 0xf5,
|
||||
0x3, 0x2, 0x2, 0x2, 0x31, 0xf9, 0x3, 0x2, 0x2,
|
||||
0x2, 0x33, 0x108, 0x3, 0x2, 0x2, 0x2, 0x35, 0x10c,
|
||||
0x3, 0x2, 0x2, 0x2, 0x37, 0x117, 0x3, 0x2, 0x2,
|
||||
0x2, 0x39, 0x122, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x124,
|
||||
0x3, 0x2, 0x2, 0x2, 0x3d, 0x126, 0x3, 0x2, 0x2,
|
||||
0x2, 0x3f, 0x128, 0x3, 0x2, 0x2, 0x2, 0x41, 0x12a,
|
||||
0x3, 0x2, 0x2, 0x2, 0x43, 0x12c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x45, 0x12e, 0x3, 0x2, 0x2, 0x2, 0x47, 0x130,
|
||||
0x3, 0x2, 0x2, 0x2, 0x49, 0x132, 0x3, 0x2, 0x2,
|
||||
0x2, 0x4b, 0x134, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x136,
|
||||
0x3, 0x2, 0x2, 0x2, 0x4f, 0x138, 0x3, 0x2, 0x2,
|
||||
0x2, 0x51, 0x13a, 0x3, 0x2, 0x2, 0x2, 0x53, 0x13d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x55, 0x13f, 0x3, 0x2, 0x2,
|
||||
0x2, 0x57, 0x141, 0x3, 0x2, 0x2, 0x2, 0x59, 0x143,
|
||||
0x3, 0x2, 0x2, 0x2, 0x5b, 0x146, 0x3, 0x2, 0x2,
|
||||
0x2, 0x5d, 0x149, 0x3, 0x2, 0x2, 0x2, 0x5f, 0x14c,
|
||||
0x3, 0x2, 0x2, 0x2, 0x61, 0x14e, 0x3, 0x2, 0x2,
|
||||
0x2, 0x63, 0x150, 0x3, 0x2, 0x2, 0x2, 0x65, 0x152,
|
||||
0x3, 0x2, 0x2, 0x2, 0x67, 0x154, 0x3, 0x2, 0x2,
|
||||
0x2, 0x69, 0x156, 0x3, 0x2, 0x2, 0x2, 0x6b, 0x159,
|
||||
0x3, 0x2, 0x2, 0x2, 0x6d, 0x15c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x6f, 0x162, 0x3, 0x2, 0x2, 0x2, 0x71, 0x165,
|
||||
0x3, 0x2, 0x2, 0x2, 0x73, 0x16c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x75, 0x177, 0x3, 0x2, 0x2, 0x2, 0x77, 0x183,
|
||||
0x3, 0x2, 0x2, 0x2, 0x79, 0x192, 0x3, 0x2, 0x2,
|
||||
0x2, 0x7b, 0x1a1, 0x3, 0x2, 0x2, 0x2, 0x7d, 0x1a7,
|
||||
0x3, 0x2, 0x2, 0x2, 0x7f, 0x80, 0x7, 0x51, 0x2,
|
||||
0x2, 0x80, 0x81, 0x7, 0x54, 0x2, 0x2, 0x81, 0x4,
|
||||
0x3, 0x2, 0x2, 0x2, 0x82, 0x83, 0x7, 0x43, 0x2,
|
||||
0x2, 0x83, 0x84, 0x7, 0x50, 0x2, 0x2, 0x84, 0x85,
|
||||
0x7, 0x46, 0x2, 0x2, 0x85, 0x6, 0x3, 0x2, 0x2,
|
||||
0x2, 0x86, 0x87, 0x7, 0x50, 0x2, 0x2, 0x87, 0x88,
|
||||
0x7, 0x51, 0x2, 0x2, 0x88, 0x89, 0x7, 0x56, 0x2,
|
||||
0x2, 0x89, 0x8, 0x3, 0x2, 0x2, 0x2, 0x8a, 0x8b,
|
||||
0x7, 0x4b, 0x2, 0x2, 0x8b, 0x8c, 0x7, 0x50, 0x2,
|
||||
0x2, 0x8c, 0xa, 0x3, 0x2, 0x2, 0x2, 0x8d, 0x8e,
|
||||
0x7, 0x45, 0x2, 0x2, 0x8e, 0x8f, 0x7, 0x51, 0x2,
|
||||
0x2, 0x8f, 0x90, 0x7, 0x50, 0x2, 0x2, 0x90, 0x91,
|
||||
0x7, 0x56, 0x2, 0x2, 0x91, 0x92, 0x7, 0x43, 0x2,
|
||||
0x2, 0x92, 0x93, 0x7, 0x4b, 0x2, 0x2, 0x93, 0x94,
|
||||
0x7, 0x50, 0x2, 0x2, 0x94, 0x95, 0x7, 0x61, 0x2,
|
||||
0x2, 0x95, 0x96, 0x7, 0x43, 0x2, 0x2, 0x96, 0x97,
|
||||
0x7, 0x4e, 0x2, 0x2, 0x97, 0x98, 0x7, 0x4e, 0x2,
|
||||
0x2, 0x98, 0xc, 0x3, 0x2, 0x2, 0x2, 0x99, 0x9a,
|
||||
0x7, 0x45, 0x2, 0x2, 0x9a, 0x9b, 0x7, 0x51, 0x2,
|
||||
0x2, 0x9b, 0x9c, 0x7, 0x50, 0x2, 0x2, 0x9c, 0x9d,
|
||||
0x7, 0x56, 0x2, 0x2, 0x9d, 0x9e, 0x7, 0x43, 0x2,
|
||||
0x2, 0x9e, 0x9f, 0x7, 0x4b, 0x2, 0x2, 0x9f, 0xa0,
|
||||
0x7, 0x50, 0x2, 0x2, 0xa0, 0xa1, 0x7, 0x61, 0x2,
|
||||
0x2, 0xa1, 0xa2, 0x7, 0x43, 0x2, 0x2, 0xa2, 0xa3,
|
||||
0x7, 0x50, 0x2, 0x2, 0xa3, 0xa4, 0x7, 0x5b, 0x2,
|
||||
0x2, 0xa4, 0xe, 0x3, 0x2, 0x2, 0x2, 0xa5, 0xa6,
|
||||
0x7, 0x44, 0x2, 0x2, 0xa6, 0xa7, 0x7, 0x47, 0x2,
|
||||
0x2, 0xa7, 0xa8, 0x7, 0x56, 0x2, 0x2, 0xa8, 0xa9,
|
||||
0x7, 0x59, 0x2, 0x2, 0xa9, 0xaa, 0x7, 0x47, 0x2,
|
||||
0x2, 0xaa, 0xab, 0x7, 0x47, 0x2, 0x2, 0xab, 0xac,
|
||||
0x7, 0x50, 0x2, 0x2, 0xac, 0x10, 0x3, 0x2, 0x2,
|
||||
0x2, 0xad, 0xae, 0x7, 0x4e, 0x2, 0x2, 0xae, 0xaf,
|
||||
0x7, 0x4b, 0x2, 0x2, 0xaf, 0xb0, 0x7, 0x4d, 0x2,
|
||||
0x2, 0xb0, 0xb1, 0x7, 0x47, 0x2, 0x2, 0xb1, 0x12,
|
||||
0x3, 0x2, 0x2, 0x2, 0xb2, 0xb3, 0x7, 0x59, 0x2,
|
||||
0x2, 0xb3, 0xb4, 0x7, 0x4a, 0x2, 0x2, 0xb4, 0xb5,
|
||||
0x7, 0x47, 0x2, 0x2, 0xb5, 0xb6, 0x7, 0x54, 0x2,
|
||||
0x2, 0xb6, 0xb7, 0x7, 0x47, 0x2, 0x2, 0xb7, 0x14,
|
||||
0x3, 0x2, 0x2, 0x2, 0xb8, 0xb9, 0x7, 0x55, 0x2,
|
||||
0x2, 0xb9, 0xba, 0x7, 0x47, 0x2, 0x2, 0xba, 0xbb,
|
||||
0x7, 0x4e, 0x2, 0x2, 0xbb, 0xbc, 0x7, 0x47, 0x2,
|
||||
0x2, 0xbc, 0xbd, 0x7, 0x45, 0x2, 0x2, 0xbd, 0xbe,
|
||||
0x7, 0x56, 0x2, 0x2, 0xbe, 0x16, 0x3, 0x2, 0x2,
|
||||
0x2, 0xbf, 0xc0, 0x7, 0x48, 0x2, 0x2, 0xc0, 0xc1,
|
||||
0x7, 0x54, 0x2, 0x2, 0xc1, 0xc2, 0x7, 0x51, 0x2,
|
||||
0x2, 0xc2, 0xc3, 0x7, 0x4f, 0x2, 0x2, 0xc3, 0x18,
|
||||
0x3, 0x2, 0x2, 0x2, 0xc4, 0xc5, 0x7, 0x43, 0x2,
|
||||
0x2, 0xc5, 0xc6, 0x7, 0x55, 0x2, 0x2, 0xc6, 0x1a,
|
||||
0x3, 0x2, 0x2, 0x2, 0xc7, 0xc8, 0x7, 0x44, 0x2,
|
||||
0x2, 0xc8, 0xc9, 0x7, 0x5b, 0x2, 0x2, 0xc9, 0x1c,
|
||||
0x3, 0x2, 0x2, 0x2, 0xca, 0xcb, 0x7, 0x51, 0x2,
|
||||
0x2, 0xcb, 0xcc, 0x7, 0x54, 0x2, 0x2, 0xcc, 0xcd,
|
||||
0x7, 0x46, 0x2, 0x2, 0xcd, 0xce, 0x7, 0x47, 0x2,
|
||||
0x2, 0xce, 0xcf, 0x7, 0x54, 0x2, 0x2, 0xcf, 0x1e,
|
||||
0x3, 0x2, 0x2, 0x2, 0xd0, 0xd1, 0x7, 0x43, 0x2,
|
||||
0x2, 0xd1, 0xd2, 0x7, 0x55, 0x2, 0x2, 0xd2, 0xd3,
|
||||
0x7, 0x45, 0x2, 0x2, 0xd3, 0x20, 0x3, 0x2, 0x2,
|
||||
0x2, 0xd4, 0xd5, 0x7, 0x46, 0x2, 0x2, 0xd5, 0xd6,
|
||||
0x7, 0x47, 0x2, 0x2, 0xd6, 0xd7, 0x7, 0x55, 0x2,
|
||||
0x2, 0xd7, 0xd8, 0x7, 0x45, 0x2, 0x2, 0xd8, 0x22,
|
||||
0x3, 0x2, 0x2, 0x2, 0xd9, 0xda, 0x7, 0x4e, 0x2,
|
||||
0x2, 0xda, 0xdb, 0x7, 0x4b, 0x2, 0x2, 0xdb, 0xdc,
|
||||
0x7, 0x4f, 0x2, 0x2, 0xdc, 0xdd, 0x7, 0x4b, 0x2,
|
||||
0x2, 0xdd, 0xde, 0x7, 0x56, 0x2, 0x2, 0xde, 0x24,
|
||||
0x3, 0x2, 0x2, 0x2, 0xdf, 0xe0, 0x7, 0x56, 0x2,
|
||||
0x2, 0xe0, 0xe1, 0x7, 0x54, 0x2, 0x2, 0xe1, 0xe2,
|
||||
0x7, 0x57, 0x2, 0x2, 0xe2, 0xe3, 0x7, 0x47, 0x2,
|
||||
0x2, 0xe3, 0x26, 0x3, 0x2, 0x2, 0x2, 0xe4, 0xe5,
|
||||
0x7, 0x48, 0x2, 0x2, 0xe5, 0xe6, 0x7, 0x43, 0x2,
|
||||
0x2, 0xe6, 0xe7, 0x7, 0x4e, 0x2, 0x2, 0xe7, 0xe8,
|
||||
0x7, 0x55, 0x2, 0x2, 0xe8, 0xe9, 0x7, 0x47, 0x2,
|
||||
0x2, 0xe9, 0x28, 0x3, 0x2, 0x2, 0x2, 0xea, 0xeb,
|
||||
0x7, 0x4b, 0x2, 0x2, 0xeb, 0xec, 0x7, 0x55, 0x2,
|
||||
0x2, 0xec, 0x2a, 0x3, 0x2, 0x2, 0x2, 0xed, 0xee,
|
||||
0x7, 0x50, 0x2, 0x2, 0xee, 0xef, 0x7, 0x57, 0x2,
|
||||
0x2, 0xef, 0xf0, 0x7, 0x4e, 0x2, 0x2, 0xf0, 0xf1,
|
||||
0x7, 0x4e, 0x2, 0x2, 0xf1, 0x2c, 0x3, 0x2, 0x2,
|
||||
0x2, 0xf2, 0xf3, 0x5, 0x71, 0x39, 0x2, 0xf3, 0x2e,
|
||||
0x3, 0x2, 0x2, 0x2, 0xf4, 0xf6, 0x5, 0x47, 0x24,
|
||||
0x2, 0xf5, 0xf4, 0x3, 0x2, 0x2, 0x2, 0xf5, 0xf6,
|
||||
0x3, 0x2, 0x2, 0x2, 0xf6, 0xf7, 0x3, 0x2, 0x2,
|
||||
0x2, 0xf7, 0xf8, 0x5, 0x2d, 0x17, 0x2, 0xf8, 0x30,
|
||||
0x3, 0x2, 0x2, 0x2, 0xf9, 0x102, 0x5, 0x73, 0x3a,
|
||||
0x2, 0xfa, 0xfc, 0x7, 0x47, 0x2, 0x2, 0xfb, 0xfd,
|
||||
0x9, 0x2, 0x2, 0x2, 0xfc, 0xfb, 0x3, 0x2, 0x2,
|
||||
0x2, 0xfc, 0xfd, 0x3, 0x2, 0x2, 0x2, 0xfd, 0x100,
|
||||
0x3, 0x2, 0x2, 0x2, 0xfe, 0x101, 0x5, 0x73, 0x3a,
|
||||
0x2, 0xff, 0x101, 0x5, 0x71, 0x39, 0x2, 0x100, 0xfe,
|
||||
0x3, 0x2, 0x2, 0x2, 0x100, 0xff, 0x3, 0x2, 0x2,
|
||||
0x2, 0x101, 0x103, 0x3, 0x2, 0x2, 0x2, 0x102, 0xfa,
|
||||
0x3, 0x2, 0x2, 0x2, 0x102, 0x103, 0x3, 0x2, 0x2,
|
||||
0x2, 0x103, 0x105, 0x3, 0x2, 0x2, 0x2, 0x104, 0x106,
|
||||
0x9, 0x3, 0x2, 0x2, 0x105, 0x104, 0x3, 0x2, 0x2,
|
||||
0x2, 0x105, 0x106, 0x3, 0x2, 0x2, 0x2, 0x106, 0x32,
|
||||
0x3, 0x2, 0x2, 0x2, 0x107, 0x109, 0x5, 0x47, 0x24,
|
||||
0x2, 0x108, 0x107, 0x3, 0x2, 0x2, 0x2, 0x108, 0x109,
|
||||
0x3, 0x2, 0x2, 0x2, 0x109, 0x10a, 0x3, 0x2, 0x2,
|
||||
0x2, 0x10a, 0x10b, 0x5, 0x31, 0x19, 0x2, 0x10b, 0x34,
|
||||
0x3, 0x2, 0x2, 0x2, 0x10c, 0x112, 0x7, 0x29, 0x2,
|
||||
0x2, 0x10d, 0x111, 0xa, 0x4, 0x2, 0x2, 0x10e, 0x10f,
|
||||
0x7, 0x5e, 0x2, 0x2, 0x10f, 0x111, 0xb, 0x2, 0x2,
|
||||
0x2, 0x110, 0x10d, 0x3, 0x2, 0x2, 0x2, 0x110, 0x10e,
|
||||
0x3, 0x2, 0x2, 0x2, 0x111, 0x114, 0x3, 0x2, 0x2,
|
||||
0x2, 0x112, 0x110, 0x3, 0x2, 0x2, 0x2, 0x112, 0x113,
|
||||
0x3, 0x2, 0x2, 0x2, 0x113, 0x115, 0x3, 0x2, 0x2,
|
||||
0x2, 0x114, 0x112, 0x3, 0x2, 0x2, 0x2, 0x115, 0x116,
|
||||
0x7, 0x29, 0x2, 0x2, 0x116, 0x36, 0x3, 0x2, 0x2,
|
||||
0x2, 0x117, 0x11d, 0x7, 0x24, 0x2, 0x2, 0x118, 0x11c,
|
||||
0xa, 0x5, 0x2, 0x2, 0x119, 0x11a, 0x7, 0x5e, 0x2,
|
||||
0x2, 0x11a, 0x11c, 0xb, 0x2, 0x2, 0x2, 0x11b, 0x118,
|
||||
0x3, 0x2, 0x2, 0x2, 0x11b, 0x119, 0x3, 0x2, 0x2,
|
||||
0x2, 0x11c, 0x11f, 0x3, 0x2, 0x2, 0x2, 0x11d, 0x11b,
|
||||
0x3, 0x2, 0x2, 0x2, 0x11d, 0x11e, 0x3, 0x2, 0x2,
|
||||
0x2, 0x11e, 0x120, 0x3, 0x2, 0x2, 0x2, 0x11f, 0x11d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x120, 0x121, 0x7, 0x24, 0x2,
|
||||
0x2, 0x121, 0x38, 0x3, 0x2, 0x2, 0x2, 0x122, 0x123,
|
||||
0x7, 0x30, 0x2, 0x2, 0x123, 0x3a, 0x3, 0x2, 0x2,
|
||||
0x2, 0x124, 0x125, 0x7, 0x2a, 0x2, 0x2, 0x125, 0x3c,
|
||||
0x3, 0x2, 0x2, 0x2, 0x126, 0x127, 0x7, 0x2b, 0x2,
|
||||
0x2, 0x127, 0x3e, 0x3, 0x2, 0x2, 0x2, 0x128, 0x129,
|
||||
0x7, 0x5d, 0x2, 0x2, 0x129, 0x40, 0x3, 0x2, 0x2,
|
||||
0x2, 0x12a, 0x12b, 0x7, 0x5f, 0x2, 0x2, 0x12b, 0x42,
|
||||
0x3, 0x2, 0x2, 0x2, 0x12c, 0x12d, 0x7, 0x2c, 0x2,
|
||||
0x2, 0x12d, 0x44, 0x3, 0x2, 0x2, 0x2, 0x12e, 0x12f,
|
||||
0x7, 0x2d, 0x2, 0x2, 0x12f, 0x46, 0x3, 0x2, 0x2,
|
||||
0x2, 0x130, 0x131, 0x7, 0x2f, 0x2, 0x2, 0x131, 0x48,
|
||||
0x3, 0x2, 0x2, 0x2, 0x132, 0x133, 0x7, 0x2e, 0x2,
|
||||
0x2, 0x133, 0x4a, 0x3, 0x2, 0x2, 0x2, 0x134, 0x135,
|
||||
0x7, 0x31, 0x2, 0x2, 0x135, 0x4c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x136, 0x137, 0x7, 0x27, 0x2, 0x2, 0x137, 0x4e,
|
||||
0x3, 0x2, 0x2, 0x2, 0x138, 0x139, 0x7, 0x42, 0x2,
|
||||
0x2, 0x139, 0x50, 0x3, 0x2, 0x2, 0x2, 0x13a, 0x13b,
|
||||
0x7, 0x3c, 0x2, 0x2, 0x13b, 0x13c, 0x7, 0x3f, 0x2,
|
||||
0x2, 0x13c, 0x52, 0x3, 0x2, 0x2, 0x2, 0x13d, 0x13e,
|
||||
0x7, 0x25, 0x2, 0x2, 0x13e, 0x54, 0x3, 0x2, 0x2,
|
||||
0x2, 0x13f, 0x140, 0x7, 0x3c, 0x2, 0x2, 0x140, 0x56,
|
||||
0x3, 0x2, 0x2, 0x2, 0x141, 0x142, 0x7, 0x3d, 0x2,
|
||||
0x2, 0x142, 0x58, 0x3, 0x2, 0x2, 0x2, 0x143, 0x144,
|
||||
0x7, 0x3e, 0x2, 0x2, 0x144, 0x145, 0x7, 0x3f, 0x2,
|
||||
0x2, 0x145, 0x5a, 0x3, 0x2, 0x2, 0x2, 0x146, 0x147,
|
||||
0x7, 0x40, 0x2, 0x2, 0x147, 0x148, 0x7, 0x3f, 0x2,
|
||||
0x2, 0x148, 0x5c, 0x3, 0x2, 0x2, 0x2, 0x149, 0x14a,
|
||||
0x7, 0x23, 0x2, 0x2, 0x14a, 0x14b, 0x7, 0x3f, 0x2,
|
||||
0x2, 0x14b, 0x5e, 0x3, 0x2, 0x2, 0x2, 0x14c, 0x14d,
|
||||
0x7, 0x60, 0x2, 0x2, 0x14d, 0x60, 0x3, 0x2, 0x2,
|
||||
0x2, 0x14e, 0x14f, 0x7, 0x80, 0x2, 0x2, 0x14f, 0x62,
|
||||
0x3, 0x2, 0x2, 0x2, 0x150, 0x151, 0x7, 0x3e, 0x2,
|
||||
0x2, 0x151, 0x64, 0x3, 0x2, 0x2, 0x2, 0x152, 0x153,
|
||||
0x7, 0x40, 0x2, 0x2, 0x153, 0x66, 0x3, 0x2, 0x2,
|
||||
0x2, 0x154, 0x155, 0x7, 0x3f, 0x2, 0x2, 0x155, 0x68,
|
||||
0x3, 0x2, 0x2, 0x2, 0x156, 0x157, 0x7, 0x7e, 0x2,
|
||||
0x2, 0x157, 0x158, 0x7, 0x7e, 0x2, 0x2, 0x158, 0x6a,
|
||||
0x3, 0x2, 0x2, 0x2, 0x159, 0x15a, 0x7, 0x61, 0x2,
|
||||
0x2, 0x15a, 0x6c, 0x3, 0x2, 0x2, 0x2, 0x15b, 0x15d,
|
||||
0x9, 0x6, 0x2, 0x2, 0x15c, 0x15b, 0x3, 0x2, 0x2,
|
||||
0x2, 0x15d, 0x15e, 0x3, 0x2, 0x2, 0x2, 0x15e, 0x15c,
|
||||
0x3, 0x2, 0x2, 0x2, 0x15e, 0x15f, 0x3, 0x2, 0x2,
|
||||
0x2, 0x15f, 0x160, 0x3, 0x2, 0x2, 0x2, 0x160, 0x161,
|
||||
0x8, 0x37, 0x2, 0x2, 0x161, 0x6e, 0x3, 0x2, 0x2,
|
||||
0x2, 0x162, 0x163, 0x9, 0x7, 0x2, 0x2, 0x163, 0x70,
|
||||
0x3, 0x2, 0x2, 0x2, 0x164, 0x166, 0x9, 0x8, 0x2,
|
||||
0x2, 0x165, 0x164, 0x3, 0x2, 0x2, 0x2, 0x166, 0x167,
|
||||
0x3, 0x2, 0x2, 0x2, 0x167, 0x165, 0x3, 0x2, 0x2,
|
||||
0x2, 0x167, 0x168, 0x3, 0x2, 0x2, 0x2, 0x168, 0x72,
|
||||
0x3, 0x2, 0x2, 0x2, 0x169, 0x16b, 0x5, 0x2d, 0x17,
|
||||
0x2, 0x16a, 0x169, 0x3, 0x2, 0x2, 0x2, 0x16b, 0x16e,
|
||||
0x3, 0x2, 0x2, 0x2, 0x16c, 0x16a, 0x3, 0x2, 0x2,
|
||||
0x2, 0x16c, 0x16d, 0x3, 0x2, 0x2, 0x2, 0x16d, 0x170,
|
||||
0x3, 0x2, 0x2, 0x2, 0x16e, 0x16c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x16f, 0x171, 0x7, 0x30, 0x2, 0x2, 0x170, 0x16f,
|
||||
0x3, 0x2, 0x2, 0x2, 0x170, 0x171, 0x3, 0x2, 0x2,
|
||||
0x2, 0x171, 0x173, 0x3, 0x2, 0x2, 0x2, 0x172, 0x174,
|
||||
0x5, 0x2d, 0x17, 0x2, 0x173, 0x172, 0x3, 0x2, 0x2,
|
||||
0x2, 0x174, 0x175, 0x3, 0x2, 0x2, 0x2, 0x175, 0x173,
|
||||
0x3, 0x2, 0x2, 0x2, 0x175, 0x176, 0x3, 0x2, 0x2,
|
||||
0x2, 0x176, 0x74, 0x3, 0x2, 0x2, 0x2, 0x177, 0x17d,
|
||||
0x5, 0x3f, 0x20, 0x2, 0x178, 0x17e, 0x5, 0x47, 0x24,
|
||||
0x2, 0x179, 0x17e, 0x5, 0x71, 0x39, 0x2, 0x17a, 0x17e,
|
||||
0x5, 0x73, 0x3a, 0x2, 0x17b, 0x17e, 0x7, 0x2e, 0x2,
|
||||
0x2, 0x17c, 0x17e, 0x5, 0x6d, 0x37, 0x2, 0x17d, 0x178,
|
||||
0x3, 0x2, 0x2, 0x2, 0x17d, 0x179, 0x3, 0x2, 0x2,
|
||||
0x2, 0x17d, 0x17a, 0x3, 0x2, 0x2, 0x2, 0x17d, 0x17b,
|
||||
0x3, 0x2, 0x2, 0x2, 0x17d, 0x17c, 0x3, 0x2, 0x2,
|
||||
0x2, 0x17e, 0x17f, 0x3, 0x2, 0x2, 0x2, 0x17f, 0x17d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x17f, 0x180, 0x3, 0x2, 0x2,
|
||||
0x2, 0x180, 0x181, 0x3, 0x2, 0x2, 0x2, 0x181, 0x182,
|
||||
0x5, 0x41, 0x21, 0x2, 0x182, 0x76, 0x3, 0x2, 0x2,
|
||||
0x2, 0x183, 0x184, 0x7, 0x2f, 0x2, 0x2, 0x184, 0x185,
|
||||
0x7, 0x2f, 0x2, 0x2, 0x185, 0x189, 0x3, 0x2, 0x2,
|
||||
0x2, 0x186, 0x188, 0xa, 0x9, 0x2, 0x2, 0x187, 0x186,
|
||||
0x3, 0x2, 0x2, 0x2, 0x188, 0x18b, 0x3, 0x2, 0x2,
|
||||
0x2, 0x189, 0x187, 0x3, 0x2, 0x2, 0x2, 0x189, 0x18a,
|
||||
0x3, 0x2, 0x2, 0x2, 0x18a, 0x18e, 0x3, 0x2, 0x2,
|
||||
0x2, 0x18b, 0x189, 0x3, 0x2, 0x2, 0x2, 0x18c, 0x18f,
|
||||
0x5, 0x7b, 0x3e, 0x2, 0x18d, 0x18f, 0x7, 0x2, 0x2,
|
||||
0x3, 0x18e, 0x18c, 0x3, 0x2, 0x2, 0x2, 0x18e, 0x18d,
|
||||
0x3, 0x2, 0x2, 0x2, 0x18f, 0x190, 0x3, 0x2, 0x2,
|
||||
0x2, 0x190, 0x191, 0x8, 0x3c, 0x3, 0x2, 0x191, 0x78,
|
||||
0x3, 0x2, 0x2, 0x2, 0x192, 0x193, 0x7, 0x31, 0x2,
|
||||
0x2, 0x193, 0x194, 0x7, 0x2c, 0x2, 0x2, 0x194, 0x198,
|
||||
0x3, 0x2, 0x2, 0x2, 0x195, 0x197, 0xb, 0x2, 0x2,
|
||||
0x2, 0x196, 0x195, 0x3, 0x2, 0x2, 0x2, 0x197, 0x19a,
|
||||
0x3, 0x2, 0x2, 0x2, 0x198, 0x199, 0x3, 0x2, 0x2,
|
||||
0x2, 0x198, 0x196, 0x3, 0x2, 0x2, 0x2, 0x199, 0x19b,
|
||||
0x3, 0x2, 0x2, 0x2, 0x19a, 0x198, 0x3, 0x2, 0x2,
|
||||
0x2, 0x19b, 0x19c, 0x7, 0x2c, 0x2, 0x2, 0x19c, 0x19d,
|
||||
0x7, 0x31, 0x2, 0x2, 0x19d, 0x19e, 0x3, 0x2, 0x2,
|
||||
0x2, 0x19e, 0x19f, 0x8, 0x3d, 0x3, 0x2, 0x19f, 0x7a,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1a0, 0x1a2, 0x7, 0xf, 0x2,
|
||||
0x2, 0x1a1, 0x1a0, 0x3, 0x2, 0x2, 0x2, 0x1a1, 0x1a2,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1a2, 0x1a3, 0x3, 0x2, 0x2,
|
||||
0x2, 0x1a3, 0x1a4, 0x7, 0xc, 0x2, 0x2, 0x1a4, 0x7c,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1a5, 0x1a8, 0x5, 0x6f, 0x38,
|
||||
0x2, 0x1a6, 0x1a8, 0x9, 0xa, 0x2, 0x2, 0x1a7, 0x1a5,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1a7, 0x1a6, 0x3, 0x2, 0x2,
|
||||
0x2, 0x1a8, 0x1a9, 0x3, 0x2, 0x2, 0x2, 0x1a9, 0x1a7,
|
||||
0x3, 0x2, 0x2, 0x2, 0x1a9, 0x1aa, 0x3, 0x2, 0x2,
|
||||
0x2, 0x1aa, 0x7e, 0x3, 0x2, 0x2, 0x2, 0x1a, 0x2,
|
||||
0xf5, 0xfc, 0x100, 0x102, 0x105, 0x108, 0x110, 0x112, 0x11b,
|
||||
0x11d, 0x15e, 0x167, 0x16c, 0x170, 0x175, 0x17d, 0x17f, 0x189,
|
||||
0x18e, 0x198, 0x1a1, 0x1a7, 0x1a9, 0x4, 0x8, 0x2, 0x2,
|
||||
0x2, 0x4, 0x2,
|
||||
};
|
||||
|
||||
atn::ATNDeserializer deserializer;
|
||||
_atn = deserializer.deserialize(_serializedATN);
|
||||
|
||||
size_t count = _atn.getNumberOfDecisions();
|
||||
_decisionToDFA.reserve(count);
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
_decisionToDFA.emplace_back(_atn.getDecisionState(i), i);
|
||||
}
|
||||
}
|
||||
|
||||
SQLLexer::Initializer SQLLexer::_init;
|
||||
@@ -0,0 +1,116 @@
|
||||
|
||||
// Generated from SQLLexer.g4 by ANTLR 4.8
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
|
||||
|
||||
namespace antlr4 {
|
||||
|
||||
|
||||
class SQLLexer : public antlr4::Lexer {
|
||||
public:
|
||||
enum {
|
||||
OR = 1,
|
||||
AND = 2,
|
||||
NOT = 3,
|
||||
IN = 4,
|
||||
CONTAIN_ALL = 5,
|
||||
CONTAIN_ANY = 6,
|
||||
BETWEEN = 7,
|
||||
LIKE = 8,
|
||||
WHERE = 9,
|
||||
SELECT = 10,
|
||||
FROM = 11,
|
||||
AS = 12,
|
||||
BY = 13,
|
||||
ORDER = 14,
|
||||
ASC = 15,
|
||||
DESC = 16,
|
||||
LIMIT = 17,
|
||||
TRUE_V = 18,
|
||||
FALSE_V = 19,
|
||||
IS = 20,
|
||||
NULL_V = 21,
|
||||
INTEGER = 22,
|
||||
FLOAT = 23,
|
||||
SQUOTA_STRING = 24,
|
||||
DQUOTA_STRING = 25,
|
||||
DOT = 26,
|
||||
LP = 27,
|
||||
RP = 28,
|
||||
LMP = 29,
|
||||
RMP = 30,
|
||||
ASTERISK = 31,
|
||||
PLUS_SIGN = 32,
|
||||
MINUS_SIGN = 33,
|
||||
COMMA = 34,
|
||||
SOLIDUS = 35,
|
||||
MOD = 36,
|
||||
AT_SIGN = 37,
|
||||
ASSIGN_OP = 38,
|
||||
SHARP_SIGN = 39,
|
||||
COLON = 40,
|
||||
SEMI = 41,
|
||||
LE_OP = 42,
|
||||
GE_OP = 43,
|
||||
NE_OP = 44,
|
||||
CARET_OP = 45,
|
||||
TILDE_OP = 46,
|
||||
L_OP = 47,
|
||||
G_OP = 48,
|
||||
E_OP = 49,
|
||||
CONCAT_OP = 50,
|
||||
UNDERSCORE = 51,
|
||||
SPACES = 52,
|
||||
VECTOR = 53,
|
||||
SINGLE_LINE_COMMENT = 54,
|
||||
MULTI_LINE_COMMENT = 55,
|
||||
REGULAR_ID = 56
|
||||
};
|
||||
|
||||
enum { COMMENTS = 2 };
|
||||
|
||||
SQLLexer(antlr4::CharStream *input);
|
||||
~SQLLexer();
|
||||
|
||||
virtual std::string getGrammarFileName() const override;
|
||||
virtual const std::vector<std::string> &getRuleNames() const override;
|
||||
|
||||
virtual const std::vector<std::string> &getChannelNames() const override;
|
||||
virtual const std::vector<std::string> &getModeNames() const override;
|
||||
virtual const std::vector<std::string> &getTokenNames()
|
||||
const override; // deprecated, use vocabulary instead
|
||||
virtual antlr4::dfa::Vocabulary &getVocabulary() const override;
|
||||
|
||||
virtual const std::vector<uint16_t> getSerializedATN() const override;
|
||||
virtual const antlr4::atn::ATN &getATN() const override;
|
||||
|
||||
private:
|
||||
static std::vector<antlr4::dfa::DFA> _decisionToDFA;
|
||||
static antlr4::atn::PredictionContextCache _sharedContextCache;
|
||||
static std::vector<std::string> _ruleNames;
|
||||
static std::vector<std::string> _tokenNames;
|
||||
static std::vector<std::string> _channelNames;
|
||||
static std::vector<std::string> _modeNames;
|
||||
|
||||
static std::vector<std::string> _literalNames;
|
||||
static std::vector<std::string> _symbolicNames;
|
||||
static antlr4::dfa::Vocabulary _vocabulary;
|
||||
static antlr4::atn::ATN _atn;
|
||||
static std::vector<uint16_t> _serializedATN;
|
||||
|
||||
|
||||
// Individual action functions triggered by action() above.
|
||||
|
||||
// Individual semantic predicate functions triggered by sempred() above.
|
||||
|
||||
struct Initializer {
|
||||
Initializer();
|
||||
};
|
||||
static Initializer _init;
|
||||
};
|
||||
|
||||
} // namespace antlr4
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,103 @@
|
||||
OR=1
|
||||
AND=2
|
||||
NOT=3
|
||||
IN=4
|
||||
CONTAIN_ALL=5
|
||||
CONTAIN_ANY=6
|
||||
BETWEEN=7
|
||||
LIKE=8
|
||||
WHERE=9
|
||||
SELECT=10
|
||||
FROM=11
|
||||
AS=12
|
||||
BY=13
|
||||
ORDER=14
|
||||
ASC=15
|
||||
DESC=16
|
||||
LIMIT=17
|
||||
TRUE_V=18
|
||||
FALSE_V=19
|
||||
IS=20
|
||||
NULL_V=21
|
||||
INTEGER=22
|
||||
FLOAT=23
|
||||
SQUOTA_STRING=24
|
||||
DQUOTA_STRING=25
|
||||
DOT=26
|
||||
LP=27
|
||||
RP=28
|
||||
LMP=29
|
||||
RMP=30
|
||||
ASTERISK=31
|
||||
PLUS_SIGN=32
|
||||
MINUS_SIGN=33
|
||||
COMMA=34
|
||||
SOLIDUS=35
|
||||
MOD=36
|
||||
AT_SIGN=37
|
||||
ASSIGN_OP=38
|
||||
SHARP_SIGN=39
|
||||
COLON=40
|
||||
SEMI=41
|
||||
LE_OP=42
|
||||
GE_OP=43
|
||||
NE_OP=44
|
||||
CARET_OP=45
|
||||
TILDE_OP=46
|
||||
L_OP=47
|
||||
G_OP=48
|
||||
E_OP=49
|
||||
CONCAT_OP=50
|
||||
UNDERSCORE=51
|
||||
SPACES=52
|
||||
VECTOR=53
|
||||
SINGLE_LINE_COMMENT=54
|
||||
MULTI_LINE_COMMENT=55
|
||||
REGULAR_ID=56
|
||||
'OR'=1
|
||||
'AND'=2
|
||||
'NOT'=3
|
||||
'IN'=4
|
||||
'CONTAIN_ALL'=5
|
||||
'CONTAIN_ANY'=6
|
||||
'BETWEEN'=7
|
||||
'LIKE'=8
|
||||
'WHERE'=9
|
||||
'SELECT'=10
|
||||
'FROM'=11
|
||||
'AS'=12
|
||||
'BY'=13
|
||||
'ORDER'=14
|
||||
'ASC'=15
|
||||
'DESC'=16
|
||||
'LIMIT'=17
|
||||
'TRUE'=18
|
||||
'FALSE'=19
|
||||
'IS'=20
|
||||
'NULL'=21
|
||||
'.'=26
|
||||
'('=27
|
||||
')'=28
|
||||
'['=29
|
||||
']'=30
|
||||
'*'=31
|
||||
'+'=32
|
||||
'-'=33
|
||||
','=34
|
||||
'/'=35
|
||||
'%'=36
|
||||
'@'=37
|
||||
':='=38
|
||||
'#'=39
|
||||
':'=40
|
||||
';'=41
|
||||
'<='=42
|
||||
'>='=43
|
||||
'!='=44
|
||||
'^'=45
|
||||
'~'=46
|
||||
'<'=47
|
||||
'>'=48
|
||||
'='=49
|
||||
'||'=50
|
||||
'_'=51
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,811 @@
|
||||
|
||||
// Generated from SQLParser.g4 by ANTLR 4.8
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
|
||||
|
||||
namespace antlr4 {
|
||||
|
||||
|
||||
class SQLParser : public antlr4::Parser {
|
||||
public:
|
||||
enum {
|
||||
OR = 1,
|
||||
AND = 2,
|
||||
NOT = 3,
|
||||
IN = 4,
|
||||
CONTAIN_ALL = 5,
|
||||
CONTAIN_ANY = 6,
|
||||
BETWEEN = 7,
|
||||
LIKE = 8,
|
||||
WHERE = 9,
|
||||
SELECT = 10,
|
||||
FROM = 11,
|
||||
AS = 12,
|
||||
BY = 13,
|
||||
ORDER = 14,
|
||||
ASC = 15,
|
||||
DESC = 16,
|
||||
LIMIT = 17,
|
||||
TRUE_V = 18,
|
||||
FALSE_V = 19,
|
||||
IS = 20,
|
||||
NULL_V = 21,
|
||||
INTEGER = 22,
|
||||
FLOAT = 23,
|
||||
SQUOTA_STRING = 24,
|
||||
DQUOTA_STRING = 25,
|
||||
DOT = 26,
|
||||
LP = 27,
|
||||
RP = 28,
|
||||
LMP = 29,
|
||||
RMP = 30,
|
||||
ASTERISK = 31,
|
||||
PLUS_SIGN = 32,
|
||||
MINUS_SIGN = 33,
|
||||
COMMA = 34,
|
||||
SOLIDUS = 35,
|
||||
MOD = 36,
|
||||
AT_SIGN = 37,
|
||||
ASSIGN_OP = 38,
|
||||
SHARP_SIGN = 39,
|
||||
COLON = 40,
|
||||
SEMI = 41,
|
||||
LE_OP = 42,
|
||||
GE_OP = 43,
|
||||
NE_OP = 44,
|
||||
CARET_OP = 45,
|
||||
TILDE_OP = 46,
|
||||
L_OP = 47,
|
||||
G_OP = 48,
|
||||
E_OP = 49,
|
||||
CONCAT_OP = 50,
|
||||
UNDERSCORE = 51,
|
||||
SPACES = 52,
|
||||
VECTOR = 53,
|
||||
SINGLE_LINE_COMMENT = 54,
|
||||
MULTI_LINE_COMMENT = 55,
|
||||
REGULAR_ID = 56
|
||||
};
|
||||
|
||||
enum {
|
||||
RuleSwallow_to_semi = 0,
|
||||
RuleCompilation_unit = 1,
|
||||
RuleLogic_expr_unit = 2,
|
||||
RuleUnit_statement = 3,
|
||||
RuleWhere_clause = 4,
|
||||
RuleLogic_expr = 5,
|
||||
RuleEnclosed_expr = 6,
|
||||
RuleRelation_expr = 7,
|
||||
RuleRel_oper = 8,
|
||||
RuleValue_expr = 9,
|
||||
RuleIn_value_expr_list = 10,
|
||||
RuleIn_value_expr = 11,
|
||||
RuleConstant = 12,
|
||||
RuleConstant_num_and_str = 13,
|
||||
RuleMatrix = 14,
|
||||
RuleVector_expr = 15,
|
||||
RuleFunction_value_expr = 16,
|
||||
RuleFunction_call = 17,
|
||||
RuleDql_statement = 18,
|
||||
RuleSelect_statement = 19,
|
||||
RuleSelected_elements = 20,
|
||||
RuleSelected_element = 21,
|
||||
RuleFrom_clause = 22,
|
||||
RuleOrder_by_clause = 23,
|
||||
RuleOrder_by_element = 24,
|
||||
RuleLimit_clause = 25,
|
||||
RuleTableview_name = 26,
|
||||
RuleField_name = 27,
|
||||
RuleTable_alias = 28,
|
||||
RuleField_alias = 29,
|
||||
RuleNumeric = 30,
|
||||
RuleInt_value = 31,
|
||||
RuleFloat_value = 32,
|
||||
RuleQuoted_string = 33,
|
||||
RuleBool_value = 34,
|
||||
RuleIdentifier = 35,
|
||||
RuleNe_op = 36,
|
||||
RuleGe_op = 37,
|
||||
RuleLe_op = 38,
|
||||
RuleRegular_id = 39
|
||||
};
|
||||
|
||||
SQLParser(antlr4::TokenStream *input);
|
||||
~SQLParser();
|
||||
|
||||
virtual std::string getGrammarFileName() const override;
|
||||
virtual const antlr4::atn::ATN &getATN() const override {
|
||||
return _atn;
|
||||
};
|
||||
virtual const std::vector<std::string> &getTokenNames() const override {
|
||||
return _tokenNames;
|
||||
}; // deprecated: use vocabulary instead.
|
||||
virtual const std::vector<std::string> &getRuleNames() const override;
|
||||
virtual antlr4::dfa::Vocabulary &getVocabulary() const override;
|
||||
|
||||
|
||||
class Swallow_to_semiContext;
|
||||
class Compilation_unitContext;
|
||||
class Logic_expr_unitContext;
|
||||
class Unit_statementContext;
|
||||
class Where_clauseContext;
|
||||
class Logic_exprContext;
|
||||
class Enclosed_exprContext;
|
||||
class Relation_exprContext;
|
||||
class Rel_operContext;
|
||||
class Value_exprContext;
|
||||
class In_value_expr_listContext;
|
||||
class In_value_exprContext;
|
||||
class ConstantContext;
|
||||
class Constant_num_and_strContext;
|
||||
class MatrixContext;
|
||||
class Vector_exprContext;
|
||||
class Function_value_exprContext;
|
||||
class Function_callContext;
|
||||
class Dql_statementContext;
|
||||
class Select_statementContext;
|
||||
class Selected_elementsContext;
|
||||
class Selected_elementContext;
|
||||
class From_clauseContext;
|
||||
class Order_by_clauseContext;
|
||||
class Order_by_elementContext;
|
||||
class Limit_clauseContext;
|
||||
class Tableview_nameContext;
|
||||
class Field_nameContext;
|
||||
class Table_aliasContext;
|
||||
class Field_aliasContext;
|
||||
class NumericContext;
|
||||
class Int_valueContext;
|
||||
class Float_valueContext;
|
||||
class Quoted_stringContext;
|
||||
class Bool_valueContext;
|
||||
class IdentifierContext;
|
||||
class Ne_opContext;
|
||||
class Ge_opContext;
|
||||
class Le_opContext;
|
||||
class Regular_idContext;
|
||||
|
||||
class Swallow_to_semiContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Swallow_to_semiContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
std::vector<antlr4::tree::TerminalNode *> SEMI();
|
||||
antlr4::tree::TerminalNode *SEMI(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Swallow_to_semiContext *swallow_to_semi();
|
||||
|
||||
class Compilation_unitContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Compilation_unitContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *EOF();
|
||||
std::vector<Unit_statementContext *> unit_statement();
|
||||
Unit_statementContext *unit_statement(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> SOLIDUS();
|
||||
antlr4::tree::TerminalNode *SOLIDUS(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> SEMI();
|
||||
antlr4::tree::TerminalNode *SEMI(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Compilation_unitContext *compilation_unit();
|
||||
|
||||
class Logic_expr_unitContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Logic_expr_unitContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Logic_exprContext *logic_expr();
|
||||
antlr4::tree::TerminalNode *EOF();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Logic_expr_unitContext *logic_expr_unit();
|
||||
|
||||
class Unit_statementContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Unit_statementContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Dql_statementContext *dql_statement();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Unit_statementContext *unit_statement();
|
||||
|
||||
class Where_clauseContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Where_clauseContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *WHERE();
|
||||
Logic_exprContext *logic_expr();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Where_clauseContext *where_clause();
|
||||
|
||||
class Logic_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Logic_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Relation_exprContext *relation_expr();
|
||||
Enclosed_exprContext *enclosed_expr();
|
||||
std::vector<Logic_exprContext *> logic_expr();
|
||||
Logic_exprContext *logic_expr(size_t i);
|
||||
antlr4::tree::TerminalNode *AND();
|
||||
antlr4::tree::TerminalNode *OR();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Logic_exprContext *logic_expr();
|
||||
Logic_exprContext *logic_expr(int precedence);
|
||||
class Enclosed_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Enclosed_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *LP();
|
||||
Logic_exprContext *logic_expr();
|
||||
antlr4::tree::TerminalNode *RP();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Enclosed_exprContext *enclosed_expr();
|
||||
|
||||
class Relation_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Relation_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
Rel_operContext *rel_oper();
|
||||
Value_exprContext *value_expr();
|
||||
antlr4::tree::TerminalNode *LIKE();
|
||||
antlr4::tree::TerminalNode *IN();
|
||||
antlr4::tree::TerminalNode *LP();
|
||||
In_value_expr_listContext *in_value_expr_list();
|
||||
antlr4::tree::TerminalNode *RP();
|
||||
antlr4::tree::TerminalNode *NOT();
|
||||
antlr4::tree::TerminalNode *CONTAIN_ALL();
|
||||
antlr4::tree::TerminalNode *CONTAIN_ANY();
|
||||
antlr4::tree::TerminalNode *IS();
|
||||
antlr4::tree::TerminalNode *NULL_V();
|
||||
Function_callContext *function_call();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Relation_exprContext *relation_expr();
|
||||
|
||||
class Rel_operContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Rel_operContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *E_OP();
|
||||
Ne_opContext *ne_op();
|
||||
antlr4::tree::TerminalNode *L_OP();
|
||||
antlr4::tree::TerminalNode *G_OP();
|
||||
Le_opContext *le_op();
|
||||
Ge_opContext *ge_op();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Rel_operContext *rel_oper();
|
||||
|
||||
class Value_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Value_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
ConstantContext *constant();
|
||||
Function_callContext *function_call();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Value_exprContext *value_expr();
|
||||
|
||||
class In_value_expr_listContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
In_value_expr_listContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
std::vector<In_value_exprContext *> in_value_expr();
|
||||
In_value_exprContext *in_value_expr(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> COMMA();
|
||||
antlr4::tree::TerminalNode *COMMA(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
In_value_expr_listContext *in_value_expr_list();
|
||||
|
||||
class In_value_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
In_value_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Constant_num_and_strContext *constant_num_and_str();
|
||||
Bool_valueContext *bool_value();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
In_value_exprContext *in_value_expr();
|
||||
|
||||
class ConstantContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
ConstantContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
NumericContext *numeric();
|
||||
Quoted_stringContext *quoted_string();
|
||||
Vector_exprContext *vector_expr();
|
||||
Bool_valueContext *bool_value();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
ConstantContext *constant();
|
||||
|
||||
class Constant_num_and_strContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Constant_num_and_strContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
NumericContext *numeric();
|
||||
Quoted_stringContext *quoted_string();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Constant_num_and_strContext *constant_num_and_str();
|
||||
|
||||
class MatrixContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
MatrixContext(antlr4::ParserRuleContext *parent_ctx, size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *LMP();
|
||||
std::vector<antlr4::tree::TerminalNode *> VECTOR();
|
||||
antlr4::tree::TerminalNode *VECTOR(size_t i);
|
||||
antlr4::tree::TerminalNode *RMP();
|
||||
std::vector<antlr4::tree::TerminalNode *> COMMA();
|
||||
antlr4::tree::TerminalNode *COMMA(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
MatrixContext *matrix();
|
||||
|
||||
class Vector_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Vector_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *VECTOR();
|
||||
MatrixContext *matrix();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Vector_exprContext *vector_expr();
|
||||
|
||||
class Function_value_exprContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Function_value_exprContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Value_exprContext *value_expr();
|
||||
IdentifierContext *identifier();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Function_value_exprContext *function_value_expr();
|
||||
|
||||
class Function_callContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Function_callContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
antlr4::tree::TerminalNode *LP();
|
||||
antlr4::tree::TerminalNode *RP();
|
||||
std::vector<Function_value_exprContext *> function_value_expr();
|
||||
Function_value_exprContext *function_value_expr(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> COMMA();
|
||||
antlr4::tree::TerminalNode *COMMA(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Function_callContext *function_call();
|
||||
|
||||
class Dql_statementContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Dql_statementContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Select_statementContext *select_statement();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Dql_statementContext *dql_statement();
|
||||
|
||||
class Select_statementContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Select_statementContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *SELECT();
|
||||
Selected_elementsContext *selected_elements();
|
||||
From_clauseContext *from_clause();
|
||||
Where_clauseContext *where_clause();
|
||||
Order_by_clauseContext *order_by_clause();
|
||||
Limit_clauseContext *limit_clause();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Select_statementContext *select_statement();
|
||||
|
||||
class Selected_elementsContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Selected_elementsContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
std::vector<Selected_elementContext *> selected_element();
|
||||
Selected_elementContext *selected_element(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> COMMA();
|
||||
antlr4::tree::TerminalNode *COMMA(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Selected_elementsContext *selected_elements();
|
||||
|
||||
class Selected_elementContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Selected_elementContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *ASTERISK();
|
||||
Field_nameContext *field_name();
|
||||
antlr4::tree::TerminalNode *AS();
|
||||
Field_aliasContext *field_alias();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Selected_elementContext *selected_element();
|
||||
|
||||
class From_clauseContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
From_clauseContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *FROM();
|
||||
Tableview_nameContext *tableview_name();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
From_clauseContext *from_clause();
|
||||
|
||||
class Order_by_clauseContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Order_by_clauseContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *ORDER();
|
||||
antlr4::tree::TerminalNode *BY();
|
||||
std::vector<Order_by_elementContext *> order_by_element();
|
||||
Order_by_elementContext *order_by_element(size_t i);
|
||||
std::vector<antlr4::tree::TerminalNode *> COMMA();
|
||||
antlr4::tree::TerminalNode *COMMA(size_t i);
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Order_by_clauseContext *order_by_clause();
|
||||
|
||||
class Order_by_elementContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Order_by_elementContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Field_nameContext *field_name();
|
||||
antlr4::tree::TerminalNode *ASC();
|
||||
antlr4::tree::TerminalNode *DESC();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Order_by_elementContext *order_by_element();
|
||||
|
||||
class Limit_clauseContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Limit_clauseContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *LIMIT();
|
||||
Int_valueContext *int_value();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Limit_clauseContext *limit_clause();
|
||||
|
||||
class Tableview_nameContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Tableview_nameContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Tableview_nameContext *tableview_name();
|
||||
|
||||
class Field_nameContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Field_nameContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Field_nameContext *field_name();
|
||||
|
||||
class Table_aliasContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Table_aliasContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Table_aliasContext *table_alias();
|
||||
|
||||
class Field_aliasContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Field_aliasContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
IdentifierContext *identifier();
|
||||
antlr4::tree::TerminalNode *AS();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Field_aliasContext *field_alias();
|
||||
|
||||
class NumericContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
NumericContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Int_valueContext *int_value();
|
||||
Float_valueContext *float_value();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
NumericContext *numeric();
|
||||
|
||||
class Int_valueContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Int_valueContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *INTEGER();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Int_valueContext *int_value();
|
||||
|
||||
class Float_valueContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Float_valueContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *FLOAT();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Float_valueContext *float_value();
|
||||
|
||||
class Quoted_stringContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Quoted_stringContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *SQUOTA_STRING();
|
||||
antlr4::tree::TerminalNode *DQUOTA_STRING();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Quoted_stringContext *quoted_string();
|
||||
|
||||
class Bool_valueContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Bool_valueContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *TRUE_V();
|
||||
antlr4::tree::TerminalNode *FALSE_V();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Bool_valueContext *bool_value();
|
||||
|
||||
class IdentifierContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
IdentifierContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
Regular_idContext *regular_id();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
IdentifierContext *identifier();
|
||||
|
||||
class Ne_opContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Ne_opContext(antlr4::ParserRuleContext *parent_ctx, size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *NE_OP();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Ne_opContext *ne_op();
|
||||
|
||||
class Ge_opContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Ge_opContext(antlr4::ParserRuleContext *parent_ctx, size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *GE_OP();
|
||||
antlr4::tree::TerminalNode *G_OP();
|
||||
antlr4::tree::TerminalNode *E_OP();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Ge_opContext *ge_op();
|
||||
|
||||
class Le_opContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Le_opContext(antlr4::ParserRuleContext *parent_ctx, size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *LE_OP();
|
||||
antlr4::tree::TerminalNode *L_OP();
|
||||
antlr4::tree::TerminalNode *E_OP();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Le_opContext *le_op();
|
||||
|
||||
class Regular_idContext : public antlr4::ParserRuleContext {
|
||||
public:
|
||||
Regular_idContext(antlr4::ParserRuleContext *parent_ctx,
|
||||
size_t invoking_state);
|
||||
virtual size_t getRuleIndex() const override;
|
||||
antlr4::tree::TerminalNode *REGULAR_ID();
|
||||
antlr4::tree::TerminalNode *OR();
|
||||
antlr4::tree::TerminalNode *AND();
|
||||
antlr4::tree::TerminalNode *NOT();
|
||||
antlr4::tree::TerminalNode *IN();
|
||||
antlr4::tree::TerminalNode *BETWEEN();
|
||||
antlr4::tree::TerminalNode *LIKE();
|
||||
antlr4::tree::TerminalNode *WHERE();
|
||||
antlr4::tree::TerminalNode *SELECT();
|
||||
antlr4::tree::TerminalNode *AS();
|
||||
antlr4::tree::TerminalNode *BY();
|
||||
antlr4::tree::TerminalNode *ORDER();
|
||||
antlr4::tree::TerminalNode *ASC();
|
||||
antlr4::tree::TerminalNode *DESC();
|
||||
antlr4::tree::TerminalNode *LIMIT();
|
||||
|
||||
virtual void enterRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
virtual void exitRule(antlr4::tree::ParseTreeListener *listener) override;
|
||||
};
|
||||
|
||||
Regular_idContext *regular_id();
|
||||
|
||||
|
||||
virtual bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex,
|
||||
size_t predicateIndex) override;
|
||||
bool logic_exprSempred(Logic_exprContext * /*_localctx*/,
|
||||
size_t predicateIndex);
|
||||
|
||||
private:
|
||||
static std::vector<antlr4::dfa::DFA> _decisionToDFA;
|
||||
static antlr4::atn::PredictionContextCache _sharedContextCache;
|
||||
static std::vector<std::string> _ruleNames;
|
||||
static std::vector<std::string> _tokenNames;
|
||||
|
||||
static std::vector<std::string> _literalNames;
|
||||
static std::vector<std::string> _symbolicNames;
|
||||
static antlr4::dfa::Vocabulary _vocabulary;
|
||||
static antlr4::atn::ATN _atn;
|
||||
static std::vector<uint16_t> _serializedATN;
|
||||
|
||||
|
||||
struct Initializer {
|
||||
Initializer();
|
||||
};
|
||||
static Initializer _init;
|
||||
};
|
||||
|
||||
} // namespace antlr4
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,103 @@
|
||||
OR=1
|
||||
AND=2
|
||||
NOT=3
|
||||
IN=4
|
||||
CONTAIN_ALL=5
|
||||
CONTAIN_ANY=6
|
||||
BETWEEN=7
|
||||
LIKE=8
|
||||
WHERE=9
|
||||
SELECT=10
|
||||
FROM=11
|
||||
AS=12
|
||||
BY=13
|
||||
ORDER=14
|
||||
ASC=15
|
||||
DESC=16
|
||||
LIMIT=17
|
||||
TRUE_V=18
|
||||
FALSE_V=19
|
||||
IS=20
|
||||
NULL_V=21
|
||||
INTEGER=22
|
||||
FLOAT=23
|
||||
SQUOTA_STRING=24
|
||||
DQUOTA_STRING=25
|
||||
DOT=26
|
||||
LP=27
|
||||
RP=28
|
||||
LMP=29
|
||||
RMP=30
|
||||
ASTERISK=31
|
||||
PLUS_SIGN=32
|
||||
MINUS_SIGN=33
|
||||
COMMA=34
|
||||
SOLIDUS=35
|
||||
MOD=36
|
||||
AT_SIGN=37
|
||||
ASSIGN_OP=38
|
||||
SHARP_SIGN=39
|
||||
COLON=40
|
||||
SEMI=41
|
||||
LE_OP=42
|
||||
GE_OP=43
|
||||
NE_OP=44
|
||||
CARET_OP=45
|
||||
TILDE_OP=46
|
||||
L_OP=47
|
||||
G_OP=48
|
||||
E_OP=49
|
||||
CONCAT_OP=50
|
||||
UNDERSCORE=51
|
||||
SPACES=52
|
||||
VECTOR=53
|
||||
SINGLE_LINE_COMMENT=54
|
||||
MULTI_LINE_COMMENT=55
|
||||
REGULAR_ID=56
|
||||
'OR'=1
|
||||
'AND'=2
|
||||
'NOT'=3
|
||||
'IN'=4
|
||||
'CONTAIN_ALL'=5
|
||||
'CONTAIN_ANY'=6
|
||||
'BETWEEN'=7
|
||||
'LIKE'=8
|
||||
'WHERE'=9
|
||||
'SELECT'=10
|
||||
'FROM'=11
|
||||
'AS'=12
|
||||
'BY'=13
|
||||
'ORDER'=14
|
||||
'ASC'=15
|
||||
'DESC'=16
|
||||
'LIMIT'=17
|
||||
'TRUE'=18
|
||||
'FALSE'=19
|
||||
'IS'=20
|
||||
'NULL'=21
|
||||
'.'=26
|
||||
'('=27
|
||||
')'=28
|
||||
'['=29
|
||||
']'=30
|
||||
'*'=31
|
||||
'+'=32
|
||||
'-'=33
|
||||
','=34
|
||||
'/'=35
|
||||
'%'=36
|
||||
'@'=37
|
||||
':='=38
|
||||
'#'=39
|
||||
':'=40
|
||||
';'=41
|
||||
'<='=42
|
||||
'>='=43
|
||||
'!='=44
|
||||
'^'=45
|
||||
'~'=46
|
||||
'<'=47
|
||||
'>'=48
|
||||
'='=49
|
||||
'||'=50
|
||||
'_'=51
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
// Generated from SQLParser.g4 by ANTLR 4.8
|
||||
|
||||
|
||||
#include "SQLParserBaseListener.h"
|
||||
|
||||
|
||||
using namespace antlr4;
|
||||
@@ -0,0 +1,211 @@
|
||||
|
||||
// Generated from SQLParser.g4 by ANTLR 4.8
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include "SQLParserListener.h"
|
||||
#include "antlr4-runtime.h"
|
||||
|
||||
|
||||
namespace antlr4 {
|
||||
|
||||
/**
|
||||
* This class provides an empty implementation of SQLParserListener,
|
||||
* which can be extended to create a listener which only needs to handle a
|
||||
* subset of the available methods.
|
||||
*/
|
||||
class SQLParserBaseListener : public SQLParserListener {
|
||||
public:
|
||||
virtual void enterSwallow_to_semi(
|
||||
SQLParser::Swallow_to_semiContext * /*ctx*/) override {}
|
||||
virtual void exitSwallow_to_semi(
|
||||
SQLParser::Swallow_to_semiContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterCompilation_unit(
|
||||
SQLParser::Compilation_unitContext * /*ctx*/) override {}
|
||||
virtual void exitCompilation_unit(
|
||||
SQLParser::Compilation_unitContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterLogic_expr_unit(
|
||||
SQLParser::Logic_expr_unitContext * /*ctx*/) override {}
|
||||
virtual void exitLogic_expr_unit(
|
||||
SQLParser::Logic_expr_unitContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterUnit_statement(
|
||||
SQLParser::Unit_statementContext * /*ctx*/) override {}
|
||||
virtual void exitUnit_statement(
|
||||
SQLParser::Unit_statementContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterWhere_clause(
|
||||
SQLParser::Where_clauseContext * /*ctx*/) override {}
|
||||
virtual void exitWhere_clause(
|
||||
SQLParser::Where_clauseContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterLogic_expr(
|
||||
SQLParser::Logic_exprContext * /*ctx*/) override {}
|
||||
virtual void exitLogic_expr(SQLParser::Logic_exprContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
virtual void enterEnclosed_expr(
|
||||
SQLParser::Enclosed_exprContext * /*ctx*/) override {}
|
||||
virtual void exitEnclosed_expr(
|
||||
SQLParser::Enclosed_exprContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterRelation_expr(
|
||||
SQLParser::Relation_exprContext * /*ctx*/) override {}
|
||||
virtual void exitRelation_expr(
|
||||
SQLParser::Relation_exprContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterRel_oper(SQLParser::Rel_operContext * /*ctx*/) override {}
|
||||
virtual void exitRel_oper(SQLParser::Rel_operContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterValue_expr(
|
||||
SQLParser::Value_exprContext * /*ctx*/) override {}
|
||||
virtual void exitValue_expr(SQLParser::Value_exprContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
virtual void enterIn_value_expr_list(
|
||||
SQLParser::In_value_expr_listContext * /*ctx*/) override {}
|
||||
virtual void exitIn_value_expr_list(
|
||||
SQLParser::In_value_expr_listContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterIn_value_expr(
|
||||
SQLParser::In_value_exprContext * /*ctx*/) override {}
|
||||
virtual void exitIn_value_expr(
|
||||
SQLParser::In_value_exprContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterConstant(SQLParser::ConstantContext * /*ctx*/) override {}
|
||||
virtual void exitConstant(SQLParser::ConstantContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterConstant_num_and_str(
|
||||
SQLParser::Constant_num_and_strContext * /*ctx*/) override {}
|
||||
virtual void exitConstant_num_and_str(
|
||||
SQLParser::Constant_num_and_strContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterMatrix(SQLParser::MatrixContext * /*ctx*/) override {}
|
||||
virtual void exitMatrix(SQLParser::MatrixContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterVector_expr(
|
||||
SQLParser::Vector_exprContext * /*ctx*/) override {}
|
||||
virtual void exitVector_expr(
|
||||
SQLParser::Vector_exprContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterFunction_value_expr(
|
||||
SQLParser::Function_value_exprContext * /*ctx*/) override {}
|
||||
virtual void exitFunction_value_expr(
|
||||
SQLParser::Function_value_exprContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterFunction_call(
|
||||
SQLParser::Function_callContext * /*ctx*/) override {}
|
||||
virtual void exitFunction_call(
|
||||
SQLParser::Function_callContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterDql_statement(
|
||||
SQLParser::Dql_statementContext * /*ctx*/) override {}
|
||||
virtual void exitDql_statement(
|
||||
SQLParser::Dql_statementContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterSelect_statement(
|
||||
SQLParser::Select_statementContext * /*ctx*/) override {}
|
||||
virtual void exitSelect_statement(
|
||||
SQLParser::Select_statementContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterSelected_elements(
|
||||
SQLParser::Selected_elementsContext * /*ctx*/) override {}
|
||||
virtual void exitSelected_elements(
|
||||
SQLParser::Selected_elementsContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterSelected_element(
|
||||
SQLParser::Selected_elementContext * /*ctx*/) override {}
|
||||
virtual void exitSelected_element(
|
||||
SQLParser::Selected_elementContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterFrom_clause(
|
||||
SQLParser::From_clauseContext * /*ctx*/) override {}
|
||||
virtual void exitFrom_clause(
|
||||
SQLParser::From_clauseContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterOrder_by_clause(
|
||||
SQLParser::Order_by_clauseContext * /*ctx*/) override {}
|
||||
virtual void exitOrder_by_clause(
|
||||
SQLParser::Order_by_clauseContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterOrder_by_element(
|
||||
SQLParser::Order_by_elementContext * /*ctx*/) override {}
|
||||
virtual void exitOrder_by_element(
|
||||
SQLParser::Order_by_elementContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterLimit_clause(
|
||||
SQLParser::Limit_clauseContext * /*ctx*/) override {}
|
||||
virtual void exitLimit_clause(
|
||||
SQLParser::Limit_clauseContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterTableview_name(
|
||||
SQLParser::Tableview_nameContext * /*ctx*/) override {}
|
||||
virtual void exitTableview_name(
|
||||
SQLParser::Tableview_nameContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterField_name(
|
||||
SQLParser::Field_nameContext * /*ctx*/) override {}
|
||||
virtual void exitField_name(SQLParser::Field_nameContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
virtual void enterTable_alias(
|
||||
SQLParser::Table_aliasContext * /*ctx*/) override {}
|
||||
virtual void exitTable_alias(
|
||||
SQLParser::Table_aliasContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterField_alias(
|
||||
SQLParser::Field_aliasContext * /*ctx*/) override {}
|
||||
virtual void exitField_alias(
|
||||
SQLParser::Field_aliasContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterNumeric(SQLParser::NumericContext * /*ctx*/) override {}
|
||||
virtual void exitNumeric(SQLParser::NumericContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterInt_value(SQLParser::Int_valueContext * /*ctx*/) override {}
|
||||
virtual void exitInt_value(SQLParser::Int_valueContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterFloat_value(
|
||||
SQLParser::Float_valueContext * /*ctx*/) override {}
|
||||
virtual void exitFloat_value(
|
||||
SQLParser::Float_valueContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterQuoted_string(
|
||||
SQLParser::Quoted_stringContext * /*ctx*/) override {}
|
||||
virtual void exitQuoted_string(
|
||||
SQLParser::Quoted_stringContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterBool_value(
|
||||
SQLParser::Bool_valueContext * /*ctx*/) override {}
|
||||
virtual void exitBool_value(SQLParser::Bool_valueContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
virtual void enterIdentifier(
|
||||
SQLParser::IdentifierContext * /*ctx*/) override {}
|
||||
virtual void exitIdentifier(SQLParser::IdentifierContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
virtual void enterNe_op(SQLParser::Ne_opContext * /*ctx*/) override {}
|
||||
virtual void exitNe_op(SQLParser::Ne_opContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterGe_op(SQLParser::Ge_opContext * /*ctx*/) override {}
|
||||
virtual void exitGe_op(SQLParser::Ge_opContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterLe_op(SQLParser::Le_opContext * /*ctx*/) override {}
|
||||
virtual void exitLe_op(SQLParser::Le_opContext * /*ctx*/) override {}
|
||||
|
||||
virtual void enterRegular_id(
|
||||
SQLParser::Regular_idContext * /*ctx*/) override {}
|
||||
virtual void exitRegular_id(SQLParser::Regular_idContext * /*ctx*/) override {
|
||||
}
|
||||
|
||||
|
||||
virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override {}
|
||||
virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override {}
|
||||
virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override {}
|
||||
virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override {}
|
||||
};
|
||||
|
||||
} // namespace antlr4
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
// Generated from SQLParser.g4 by ANTLR 4.8
|
||||
|
||||
|
||||
#include "SQLParserListener.h"
|
||||
|
||||
|
||||
using namespace antlr4;
|
||||
@@ -0,0 +1,156 @@
|
||||
|
||||
// Generated from SQLParser.g4 by ANTLR 4.8
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
#include "SQLParser.h"
|
||||
#include "antlr4-runtime.h"
|
||||
|
||||
|
||||
namespace antlr4 {
|
||||
|
||||
/**
|
||||
* This interface defines an abstract listener for a parse tree produced by
|
||||
* SQLParser.
|
||||
*/
|
||||
class SQLParserListener : public antlr4::tree::ParseTreeListener {
|
||||
public:
|
||||
virtual void enterSwallow_to_semi(SQLParser::Swallow_to_semiContext *ctx) = 0;
|
||||
virtual void exitSwallow_to_semi(SQLParser::Swallow_to_semiContext *ctx) = 0;
|
||||
|
||||
virtual void enterCompilation_unit(
|
||||
SQLParser::Compilation_unitContext *ctx) = 0;
|
||||
virtual void exitCompilation_unit(
|
||||
SQLParser::Compilation_unitContext *ctx) = 0;
|
||||
|
||||
virtual void enterLogic_expr_unit(SQLParser::Logic_expr_unitContext *ctx) = 0;
|
||||
virtual void exitLogic_expr_unit(SQLParser::Logic_expr_unitContext *ctx) = 0;
|
||||
|
||||
virtual void enterUnit_statement(SQLParser::Unit_statementContext *ctx) = 0;
|
||||
virtual void exitUnit_statement(SQLParser::Unit_statementContext *ctx) = 0;
|
||||
|
||||
virtual void enterWhere_clause(SQLParser::Where_clauseContext *ctx) = 0;
|
||||
virtual void exitWhere_clause(SQLParser::Where_clauseContext *ctx) = 0;
|
||||
|
||||
virtual void enterLogic_expr(SQLParser::Logic_exprContext *ctx) = 0;
|
||||
virtual void exitLogic_expr(SQLParser::Logic_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterEnclosed_expr(SQLParser::Enclosed_exprContext *ctx) = 0;
|
||||
virtual void exitEnclosed_expr(SQLParser::Enclosed_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterRelation_expr(SQLParser::Relation_exprContext *ctx) = 0;
|
||||
virtual void exitRelation_expr(SQLParser::Relation_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterRel_oper(SQLParser::Rel_operContext *ctx) = 0;
|
||||
virtual void exitRel_oper(SQLParser::Rel_operContext *ctx) = 0;
|
||||
|
||||
virtual void enterValue_expr(SQLParser::Value_exprContext *ctx) = 0;
|
||||
virtual void exitValue_expr(SQLParser::Value_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterIn_value_expr_list(
|
||||
SQLParser::In_value_expr_listContext *ctx) = 0;
|
||||
virtual void exitIn_value_expr_list(
|
||||
SQLParser::In_value_expr_listContext *ctx) = 0;
|
||||
|
||||
virtual void enterIn_value_expr(SQLParser::In_value_exprContext *ctx) = 0;
|
||||
virtual void exitIn_value_expr(SQLParser::In_value_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterConstant(SQLParser::ConstantContext *ctx) = 0;
|
||||
virtual void exitConstant(SQLParser::ConstantContext *ctx) = 0;
|
||||
|
||||
virtual void enterConstant_num_and_str(
|
||||
SQLParser::Constant_num_and_strContext *ctx) = 0;
|
||||
virtual void exitConstant_num_and_str(
|
||||
SQLParser::Constant_num_and_strContext *ctx) = 0;
|
||||
|
||||
virtual void enterMatrix(SQLParser::MatrixContext *ctx) = 0;
|
||||
virtual void exitMatrix(SQLParser::MatrixContext *ctx) = 0;
|
||||
|
||||
virtual void enterVector_expr(SQLParser::Vector_exprContext *ctx) = 0;
|
||||
virtual void exitVector_expr(SQLParser::Vector_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterFunction_value_expr(
|
||||
SQLParser::Function_value_exprContext *ctx) = 0;
|
||||
virtual void exitFunction_value_expr(
|
||||
SQLParser::Function_value_exprContext *ctx) = 0;
|
||||
|
||||
virtual void enterFunction_call(SQLParser::Function_callContext *ctx) = 0;
|
||||
virtual void exitFunction_call(SQLParser::Function_callContext *ctx) = 0;
|
||||
|
||||
virtual void enterDql_statement(SQLParser::Dql_statementContext *ctx) = 0;
|
||||
virtual void exitDql_statement(SQLParser::Dql_statementContext *ctx) = 0;
|
||||
|
||||
virtual void enterSelect_statement(
|
||||
SQLParser::Select_statementContext *ctx) = 0;
|
||||
virtual void exitSelect_statement(
|
||||
SQLParser::Select_statementContext *ctx) = 0;
|
||||
|
||||
virtual void enterSelected_elements(
|
||||
SQLParser::Selected_elementsContext *ctx) = 0;
|
||||
virtual void exitSelected_elements(
|
||||
SQLParser::Selected_elementsContext *ctx) = 0;
|
||||
|
||||
virtual void enterSelected_element(
|
||||
SQLParser::Selected_elementContext *ctx) = 0;
|
||||
virtual void exitSelected_element(
|
||||
SQLParser::Selected_elementContext *ctx) = 0;
|
||||
|
||||
virtual void enterFrom_clause(SQLParser::From_clauseContext *ctx) = 0;
|
||||
virtual void exitFrom_clause(SQLParser::From_clauseContext *ctx) = 0;
|
||||
|
||||
virtual void enterOrder_by_clause(SQLParser::Order_by_clauseContext *ctx) = 0;
|
||||
virtual void exitOrder_by_clause(SQLParser::Order_by_clauseContext *ctx) = 0;
|
||||
|
||||
virtual void enterOrder_by_element(
|
||||
SQLParser::Order_by_elementContext *ctx) = 0;
|
||||
virtual void exitOrder_by_element(
|
||||
SQLParser::Order_by_elementContext *ctx) = 0;
|
||||
|
||||
virtual void enterLimit_clause(SQLParser::Limit_clauseContext *ctx) = 0;
|
||||
virtual void exitLimit_clause(SQLParser::Limit_clauseContext *ctx) = 0;
|
||||
|
||||
virtual void enterTableview_name(SQLParser::Tableview_nameContext *ctx) = 0;
|
||||
virtual void exitTableview_name(SQLParser::Tableview_nameContext *ctx) = 0;
|
||||
|
||||
virtual void enterField_name(SQLParser::Field_nameContext *ctx) = 0;
|
||||
virtual void exitField_name(SQLParser::Field_nameContext *ctx) = 0;
|
||||
|
||||
virtual void enterTable_alias(SQLParser::Table_aliasContext *ctx) = 0;
|
||||
virtual void exitTable_alias(SQLParser::Table_aliasContext *ctx) = 0;
|
||||
|
||||
virtual void enterField_alias(SQLParser::Field_aliasContext *ctx) = 0;
|
||||
virtual void exitField_alias(SQLParser::Field_aliasContext *ctx) = 0;
|
||||
|
||||
virtual void enterNumeric(SQLParser::NumericContext *ctx) = 0;
|
||||
virtual void exitNumeric(SQLParser::NumericContext *ctx) = 0;
|
||||
|
||||
virtual void enterInt_value(SQLParser::Int_valueContext *ctx) = 0;
|
||||
virtual void exitInt_value(SQLParser::Int_valueContext *ctx) = 0;
|
||||
|
||||
virtual void enterFloat_value(SQLParser::Float_valueContext *ctx) = 0;
|
||||
virtual void exitFloat_value(SQLParser::Float_valueContext *ctx) = 0;
|
||||
|
||||
virtual void enterQuoted_string(SQLParser::Quoted_stringContext *ctx) = 0;
|
||||
virtual void exitQuoted_string(SQLParser::Quoted_stringContext *ctx) = 0;
|
||||
|
||||
virtual void enterBool_value(SQLParser::Bool_valueContext *ctx) = 0;
|
||||
virtual void exitBool_value(SQLParser::Bool_valueContext *ctx) = 0;
|
||||
|
||||
virtual void enterIdentifier(SQLParser::IdentifierContext *ctx) = 0;
|
||||
virtual void exitIdentifier(SQLParser::IdentifierContext *ctx) = 0;
|
||||
|
||||
virtual void enterNe_op(SQLParser::Ne_opContext *ctx) = 0;
|
||||
virtual void exitNe_op(SQLParser::Ne_opContext *ctx) = 0;
|
||||
|
||||
virtual void enterGe_op(SQLParser::Ge_opContext *ctx) = 0;
|
||||
virtual void exitGe_op(SQLParser::Ge_opContext *ctx) = 0;
|
||||
|
||||
virtual void enterLe_op(SQLParser::Le_opContext *ctx) = 0;
|
||||
virtual void exitLe_op(SQLParser::Le_opContext *ctx) = 0;
|
||||
|
||||
virtual void enterRegular_id(SQLParser::Regular_idContext *ctx) = 0;
|
||||
virtual void exitRegular_id(SQLParser::Regular_idContext *ctx) = 0;
|
||||
};
|
||||
|
||||
} // namespace antlr4
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
#****************************************************************#
|
||||
# ScriptName: gen_parser.sh
|
||||
# Author: fancy.lf
|
||||
# Function: command to generate antlr sql parser code in se directory
|
||||
#***************************************************************#
|
||||
|
||||
java -jar ../../../../../thirdparty/antlr/antlr-4.8-complete.jar -Dlanguage=Cpp -package antlr4 SQLLexer.g4 SQLParser.g4 -o gen
|
||||
sed -i 's/\bu8"/"/g' gen/*.cc
|
||||
@@ -0,0 +1,89 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
template <typename NodeOp, typename Node>
|
||||
class Generic_Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Node>;
|
||||
|
||||
Generic_Node(NodeOp m_op);
|
||||
virtual ~Generic_Node() = default;
|
||||
|
||||
void set_left(Ptr m_left);
|
||||
void set_right(Ptr m_right);
|
||||
const Ptr &left() const {
|
||||
return left_;
|
||||
}
|
||||
const Ptr &right() const {
|
||||
return right_;
|
||||
}
|
||||
Node *left_node() const {
|
||||
return left_.get();
|
||||
}
|
||||
Node *right_node() const {
|
||||
return right_.get();
|
||||
}
|
||||
void set_parent(Generic_Node *m_parent);
|
||||
Generic_Node *parent();
|
||||
|
||||
virtual NodeOp op() const {
|
||||
return op_;
|
||||
}
|
||||
virtual void set_op(NodeOp value) {
|
||||
op_ = value;
|
||||
}
|
||||
virtual std::string text() const = 0;
|
||||
|
||||
protected:
|
||||
NodeOp op_;
|
||||
Ptr left_{nullptr};
|
||||
Ptr right_{nullptr};
|
||||
Generic_Node *parent_{nullptr};
|
||||
};
|
||||
|
||||
template <typename NodeOp, typename Node>
|
||||
Generic_Node<NodeOp, Node>::Generic_Node(NodeOp m_op) {
|
||||
op_ = m_op;
|
||||
}
|
||||
|
||||
template <typename NodeOp, typename Node>
|
||||
void Generic_Node<NodeOp, Node>::set_left(Ptr m_left) {
|
||||
left_ = std::move(m_left);
|
||||
if (left_ != nullptr) {
|
||||
left_->set_parent(this);
|
||||
}
|
||||
}
|
||||
template <typename NodeOp, typename Node>
|
||||
void Generic_Node<NodeOp, Node>::set_right(Ptr m_right) {
|
||||
right_ = std::move(m_right);
|
||||
if (right_ != nullptr) {
|
||||
right_->set_parent(this);
|
||||
}
|
||||
}
|
||||
template <typename NodeOp, typename Node>
|
||||
void Generic_Node<NodeOp, Node>::set_parent(Generic_Node<NodeOp, Node> *value) {
|
||||
this->parent_ = value;
|
||||
}
|
||||
template <typename NodeOp, typename Node>
|
||||
Generic_Node<NodeOp, Node> *Generic_Node<NodeOp, Node>::parent() {
|
||||
return parent_;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "db/index/common/doc.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
struct GroupBy {
|
||||
using Ptr = std::shared_ptr<GroupBy>;
|
||||
|
||||
GroupBy() = default;
|
||||
|
||||
GroupBy(std::string group_by_field, uint32_t group_topk, uint32_t group_count)
|
||||
: group_by_field(std::move(group_by_field)),
|
||||
group_topk(group_topk),
|
||||
group_count(group_count) {}
|
||||
|
||||
std::string to_string() {
|
||||
return ailego::StringHelper::Concat("field[", group_by_field, "] topk[",
|
||||
group_topk, "] count[", group_count,
|
||||
"]");
|
||||
}
|
||||
|
||||
std::string group_by_field;
|
||||
uint32_t group_topk{0};
|
||||
uint32_t group_count{0};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "util.h"
|
||||
#include <sys/time.h>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <ailego/encoding/json.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include <arrow/type.h>
|
||||
#include <arrow/type_fwd.h>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
// std::string
|
||||
// Util::trim(const std::string str, char c) {
|
||||
// std::string tmp = str.substr(str.find_first_not_of(c));
|
||||
// return tmp.substr(0, tmp.find_last_not_of(c) + 1);
|
||||
//}
|
||||
|
||||
// above implementation will trim more than one c at front or rear. This is not
|
||||
// expected.
|
||||
// below implementation remove both side only one matched char, strictly.
|
||||
// str is supposed to match on both side at same time. remove both side one byte
|
||||
// each as c = 0
|
||||
std::string Util::trim_one_both_side(const std::string &str, unsigned char c) {
|
||||
int len = str.length();
|
||||
if (len < 2) {
|
||||
return str;
|
||||
}
|
||||
|
||||
if (str.at(0) == c && str.at(len - 1) == c) {
|
||||
return str.substr(1, len - 2);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
void Util::string_replace(const std::string &src, const std::string &dst,
|
||||
std::string *str) {
|
||||
std::string::size_type pos = 0;
|
||||
std::string::size_type srclen = src.size();
|
||||
std::string::size_type dstlen = dst.size();
|
||||
|
||||
while ((pos = str->find(src, pos)) != std::string::npos) {
|
||||
str->replace(pos, srclen, dst);
|
||||
pos += dstlen;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// normalize sql for parse result after parse
|
||||
std::string Util::normalize(const std::string &sql) {
|
||||
std::string new_sql = sql;
|
||||
// rule 1. replace \" with "
|
||||
Util::string_replace("\\\"", "\"", &new_sql);
|
||||
// rule 2. replace \' with ''
|
||||
Util::string_replace("\\\'", "\'", &new_sql);
|
||||
|
||||
return new_sql;
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Schema> Util::append_field(
|
||||
const arrow::Schema &schema, const std::string &name,
|
||||
std::shared_ptr<arrow::DataType> type) {
|
||||
auto res = schema.AddField(schema.num_fields(), arrow::field(name, type));
|
||||
return res.MoveValueUnsafe();
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::DataType> Util::sparse_type() {
|
||||
return arrow::struct_(arrow::FieldVector{
|
||||
arrow::field("index", arrow::binary()),
|
||||
arrow::field("value", arrow::binary()),
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/record_batch.h>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
static const constexpr char *kFieldScore = "_zvec_score";
|
||||
static const constexpr char *kFieldVector = "_zvec_vector";
|
||||
static const constexpr char *kFieldSparseIndices = "_zvec_sindices";
|
||||
static const constexpr char *kFieldSparseValues = "_zvec_svalues";
|
||||
static const constexpr char *kFieldIsValid = "_zvec_is_valid";
|
||||
static const constexpr char *kFieldGroupId = "_zvec_group_id";
|
||||
|
||||
static const inline std::string kCheckNotFiltered = "check_not_filtered";
|
||||
static const inline std::string kFetchVector = "fetch_vector";
|
||||
static const inline std::string kFetchSparseVector = "fetch_sparse_vector";
|
||||
static const inline std::string kContainAll = "contain_all";
|
||||
static const inline std::string kContainAny = "contain_any";
|
||||
|
||||
static const inline std::string kFuncArrayLength = "array_length";
|
||||
|
||||
#define enum_to_string(x) #x
|
||||
|
||||
class Util {
|
||||
public:
|
||||
static std::string trim_one_both_side(const std::string &str,
|
||||
unsigned char c);
|
||||
static void string_replace(const std::string &strsrc,
|
||||
const std::string &strdst, std::string *str);
|
||||
static std::string normalize(const std::string &sql);
|
||||
|
||||
static std::shared_ptr<arrow::Schema> append_field(
|
||||
const arrow::Schema &schema, const std::string &name,
|
||||
std::shared_ptr<arrow::DataType> type);
|
||||
|
||||
static std::shared_ptr<arrow::DataType> sparse_type();
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class BaseInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<BaseInfo>;
|
||||
|
||||
BaseInfo(const std::string &value) {
|
||||
table_name_ = value;
|
||||
}
|
||||
|
||||
virtual ~BaseInfo() {}
|
||||
|
||||
BaseInfo(const BaseInfo &info) {
|
||||
table_name_ = info.table_name_;
|
||||
}
|
||||
|
||||
BaseInfo &operator=(const BaseInfo &info) {
|
||||
table_name_ = info.table_name_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::string table_name() {
|
||||
return table_name_;
|
||||
}
|
||||
|
||||
bool validate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string &err_msg() {
|
||||
return err_msg_;
|
||||
}
|
||||
|
||||
void set_err_msg(const std::string &value) {
|
||||
err_msg_ = value;
|
||||
}
|
||||
|
||||
virtual std::string to_string() = 0;
|
||||
|
||||
private:
|
||||
std::string table_name_{""};
|
||||
std::string err_msg_{""};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,88 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
#include "CharStream.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
using namespace antlr4;
|
||||
|
||||
class CaseChangingCharStream : public CharStream {
|
||||
public:
|
||||
// Constructs a new CaseChangingCharStream wrapping the given {@link
|
||||
// CharStream} forcing all characters to upper_ case or lower case.
|
||||
// @param stream_ The stream_ to wrap.
|
||||
// @param upper_ If true force each symbol to upper_ case, otherwise force to
|
||||
// lower.
|
||||
CaseChangingCharStream(CharStream *m_stream, bool m_upper) {
|
||||
stream_ = m_stream;
|
||||
upper_ = m_upper;
|
||||
}
|
||||
|
||||
std::string getText(const misc::Interval &interval) {
|
||||
return stream_->getText(interval);
|
||||
}
|
||||
|
||||
void consume() {
|
||||
stream_->consume();
|
||||
}
|
||||
|
||||
size_t LA(ssize_t i) {
|
||||
size_t c = stream_->LA(i);
|
||||
if (c <= 0) {
|
||||
return c;
|
||||
}
|
||||
if (upper_) {
|
||||
return toupper((int)c);
|
||||
}
|
||||
return tolower((int)c);
|
||||
}
|
||||
|
||||
ssize_t mark() {
|
||||
return stream_->mark();
|
||||
}
|
||||
|
||||
void release(ssize_t marker) {
|
||||
stream_->release(marker);
|
||||
}
|
||||
|
||||
size_t index() {
|
||||
return stream_->index();
|
||||
}
|
||||
|
||||
void seek(size_t m_index) {
|
||||
stream_->seek(m_index);
|
||||
}
|
||||
|
||||
size_t size() {
|
||||
return stream_->size();
|
||||
}
|
||||
|
||||
std::string getSourceName() const {
|
||||
return stream_->getSourceName();
|
||||
}
|
||||
|
||||
std::string toString() const {
|
||||
return stream_->toString();
|
||||
}
|
||||
|
||||
private:
|
||||
CharStream *stream_;
|
||||
bool upper_ = true;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "BaseErrorListener.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
using namespace antlr4;
|
||||
|
||||
#define UNUSED(x) (void)x
|
||||
|
||||
class ErrorVerboseListener : BaseErrorListener {
|
||||
public:
|
||||
ErrorVerboseListener() {}
|
||||
~ErrorVerboseListener() {}
|
||||
|
||||
void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line,
|
||||
size_t charPositionInLine, const std::string &msg,
|
||||
std::exception_ptr e) {
|
||||
UNUSED(recognizer);
|
||||
UNUSED(offendingSymbol);
|
||||
UNUSED(e);
|
||||
|
||||
err_msg_ = std::to_string(line) + " " + std::to_string(charPositionInLine) +
|
||||
" " + msg;
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string &err_msg() {
|
||||
return err_msg_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string err_msg_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,249 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "node.h"
|
||||
#include <assert.h>
|
||||
#include <sstream>
|
||||
#include "db/sqlengine/common/util.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
Node::Node() : Generic_Node(NodeOp::T_NONE) {}
|
||||
|
||||
Node::Node(NodeOp m_op) : Generic_Node(m_op) {
|
||||
set_op(m_op);
|
||||
}
|
||||
|
||||
void Node::set_op(NodeOp value) {
|
||||
Generic_Node<NodeOp, Node>::set_op(value);
|
||||
set_type_by_op();
|
||||
}
|
||||
|
||||
std::string Node::op_name() const {
|
||||
return type_to_str(op_);
|
||||
}
|
||||
|
||||
Node::NodeType Node::type() {
|
||||
return type_;
|
||||
}
|
||||
|
||||
void Node::set_type_by_op() {
|
||||
NodeType node_type = NodeType::NO_TYPE;
|
||||
switch (op()) {
|
||||
case NodeOp::T_AND:
|
||||
case NodeOp::T_OR:
|
||||
node_type = NodeType::LOGIC_EXPR;
|
||||
break;
|
||||
|
||||
case NodeOp::T_EQ:
|
||||
case NodeOp::T_NE:
|
||||
case NodeOp::T_GT:
|
||||
case NodeOp::T_GE:
|
||||
case NodeOp::T_LT:
|
||||
case NodeOp::T_LE:
|
||||
case NodeOp::T_LIKE:
|
||||
case NodeOp::T_IN:
|
||||
case NodeOp::T_CONTAIN_ALL:
|
||||
case NodeOp::T_CONTAIN_ANY:
|
||||
case NodeOp::T_IS_NULL:
|
||||
case NodeOp::T_IS_NOT_NULL:
|
||||
node_type = NodeType::REL_EXPR;
|
||||
break;
|
||||
|
||||
case NodeOp::T_PLUS:
|
||||
case NodeOp::T_MINUS:
|
||||
case NodeOp::T_MUL:
|
||||
case NodeOp::T_DIV:
|
||||
node_type = NodeType::ARITH_EXPR;
|
||||
break;
|
||||
|
||||
case NodeOp::T_FUNCTION_CALL:
|
||||
node_type = NodeType::FUNC;
|
||||
break;
|
||||
|
||||
case NodeOp::T_RANGE_VALUE:
|
||||
case NodeOp::T_LIST_VALUE:
|
||||
case NodeOp::T_VECTOR_MATRIX_VALUE:
|
||||
case NodeOp::T_INT_VALUE:
|
||||
case NodeOp::T_FLOAT_VALUE:
|
||||
case NodeOp::T_STRING_VALUE:
|
||||
case NodeOp::T_BOOL_VALUE:
|
||||
case NodeOp::T_NULL_VALUE:
|
||||
node_type = NodeType::CONST;
|
||||
break;
|
||||
case NodeOp::T_ID:
|
||||
node_type = NodeType::ID;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
type_ = node_type;
|
||||
}
|
||||
|
||||
std::string Node::text() const {
|
||||
std::stringstream stream;
|
||||
switch (type_) {
|
||||
case NodeType::LOGIC_EXPR:
|
||||
stream << "(" << left()->text() << ") " << op_name() << " ("
|
||||
<< right()->text() << ")";
|
||||
break;
|
||||
case NodeType::REL_EXPR:
|
||||
stream << left()->text() << op_name() << right()->text();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::string Node::to_string() {
|
||||
return text();
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
RangeNode::RangeNode() : Node(NodeOp::T_RANGE_VALUE) {}
|
||||
|
||||
RangeNode::RangeNode(bool m_min_equal, bool m_max_equal) {
|
||||
set_op(NodeOp::T_RANGE_VALUE);
|
||||
min_equal_ = m_min_equal;
|
||||
max_equal_ = m_max_equal;
|
||||
}
|
||||
|
||||
void RangeNode::set_min_equal(bool value) {
|
||||
min_equal_ = value;
|
||||
}
|
||||
|
||||
void RangeNode::set_max_equal(bool value) {
|
||||
max_equal_ = value;
|
||||
}
|
||||
|
||||
bool RangeNode::min_equal() {
|
||||
return min_equal_;
|
||||
}
|
||||
bool RangeNode::max_equal() {
|
||||
return max_equal_;
|
||||
}
|
||||
|
||||
std::string RangeNode::text() const {
|
||||
return (min_equal_ ? "[" : "(") + left()->text() + "~" + right()->text() +
|
||||
(max_equal_ ? "]" : ")");
|
||||
}
|
||||
|
||||
void RangeNode::set_child_op(NodeOp value) {
|
||||
child_op_ = value;
|
||||
}
|
||||
|
||||
NodeOp RangeNode::child_op() {
|
||||
return child_op_;
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
ConstantNode::ConstantNode(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
|
||||
void ConstantNode::set_value(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
const std::string &ConstantNode::value() {
|
||||
return value_;
|
||||
}
|
||||
|
||||
std::string ConstantNode::text() const {
|
||||
return value_;
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
IDNode::IDNode(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
set_op(NodeOp::T_ID);
|
||||
}
|
||||
|
||||
void IDNode::set_value(const std::string &m_value) {
|
||||
value_ = m_value;
|
||||
}
|
||||
const std::string &IDNode::value() {
|
||||
return value_;
|
||||
}
|
||||
|
||||
std::string IDNode::text() const {
|
||||
return value_;
|
||||
}
|
||||
|
||||
//========================================================================
|
||||
|
||||
FuncNode::FuncNode() : Node(NodeOp::T_FUNCTION_CALL) {}
|
||||
|
||||
void FuncNode::set_func_name_node(Node::Ptr func_name_node) {
|
||||
func_name_node_ = std::move(func_name_node);
|
||||
}
|
||||
|
||||
const Node::Ptr &FuncNode::get_func_name_node() {
|
||||
return func_name_node_;
|
||||
}
|
||||
|
||||
void FuncNode::add_argument(Node::Ptr argument_node) {
|
||||
arguments_.emplace_back(std::move(argument_node));
|
||||
}
|
||||
|
||||
const std::vector<Node::Ptr> &FuncNode::arguments() {
|
||||
return arguments_;
|
||||
}
|
||||
|
||||
std::string FuncNode::text() const {
|
||||
std::stringstream stream;
|
||||
stream << func_name_node_->text();
|
||||
stream << "(";
|
||||
|
||||
int i = 0;
|
||||
for (auto argument : arguments_) {
|
||||
if (i > 0) {
|
||||
stream << ", ";
|
||||
}
|
||||
stream << argument->text();
|
||||
i++;
|
||||
}
|
||||
stream << ")";
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
|
||||
//========================================================================
|
||||
|
||||
std::string InValueExprListNode::text() const {
|
||||
std::stringstream stream;
|
||||
if (exclude_) {
|
||||
stream << "NOT ";
|
||||
}
|
||||
|
||||
stream << "(";
|
||||
|
||||
int i = 0;
|
||||
for (auto in_value_expr : in_value_expr_list_) {
|
||||
if (i > 0) {
|
||||
stream << ", ";
|
||||
}
|
||||
stream << in_value_expr->text();
|
||||
i++;
|
||||
}
|
||||
stream << ")";
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,279 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "db/index/common/query_params.h"
|
||||
#include "db/sqlengine/common/generic_node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
enum class NodeOp {
|
||||
T_NONE,
|
||||
T_NOT,
|
||||
T_AND,
|
||||
T_OR,
|
||||
T_EQ,
|
||||
T_NE,
|
||||
T_GT,
|
||||
T_GE,
|
||||
T_LT,
|
||||
T_LE,
|
||||
T_BETWEEN,
|
||||
T_LIKE,
|
||||
T_IN,
|
||||
T_CONTAIN_ALL,
|
||||
T_CONTAIN_ANY,
|
||||
T_IS_NULL,
|
||||
T_IS_NOT_NULL,
|
||||
T_PLUS,
|
||||
T_MINUS,
|
||||
T_MUL,
|
||||
T_DIV,
|
||||
T_FUNCTION_CALL,
|
||||
T_RANGE_VALUE,
|
||||
T_LIST_VALUE,
|
||||
T_VECTOR_MATRIX_VALUE,
|
||||
T_INT_VALUE,
|
||||
T_FLOAT_VALUE,
|
||||
T_STRING_VALUE,
|
||||
T_NULL_VALUE,
|
||||
T_ID,
|
||||
T_BOOL_VALUE
|
||||
};
|
||||
|
||||
class Node : public Generic_Node<NodeOp, Node> {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Node>;
|
||||
|
||||
static inline std::string type_to_str(NodeOp c) {
|
||||
static std::string names[] = {"NONE",
|
||||
"!",
|
||||
"and",
|
||||
"or",
|
||||
"=",
|
||||
"!=",
|
||||
">",
|
||||
">=",
|
||||
"<",
|
||||
"<=",
|
||||
"BETWEEN",
|
||||
" LIKE ",
|
||||
" IN ",
|
||||
" CONTAIN_ALL ",
|
||||
" CONTAIN_ANY ",
|
||||
"IS_NULL",
|
||||
"IS_NOT_NULL",
|
||||
"+",
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"FUNCTION_CALL",
|
||||
"RANGE_VALUE",
|
||||
"LIST_VALUE",
|
||||
"VECTOR_MATRIX_VALUE",
|
||||
"VECTOR_FEATURES_VALUE",
|
||||
"INT_VALUE",
|
||||
"FLOAT_VALUE",
|
||||
"STRING_VALUE",
|
||||
"NULL_VALUE",
|
||||
"ID",
|
||||
"BOOL_VALUE"};
|
||||
|
||||
return names[static_cast<int>(c)];
|
||||
}
|
||||
|
||||
enum class NodeType {
|
||||
NO_TYPE,
|
||||
LOGIC_EXPR,
|
||||
REL_EXPR,
|
||||
ENCLOSED_ARITH_EXPR,
|
||||
ARITH_EXPR,
|
||||
FUNC,
|
||||
CONST,
|
||||
ID
|
||||
};
|
||||
|
||||
public:
|
||||
Node();
|
||||
Node(NodeOp op);
|
||||
~Node() override = default;
|
||||
|
||||
void set_op(NodeOp op) override;
|
||||
std::string op_name() const;
|
||||
|
||||
NodeType type();
|
||||
|
||||
virtual std::string text() const override;
|
||||
std::string to_string();
|
||||
|
||||
private:
|
||||
void set_type_by_op();
|
||||
|
||||
private:
|
||||
static const std::string node_op_names[];
|
||||
|
||||
private:
|
||||
NodeType type_{NodeType::NO_TYPE};
|
||||
};
|
||||
|
||||
class RangeNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<RangeNode>;
|
||||
|
||||
RangeNode();
|
||||
RangeNode(bool m_min_equal, bool m_max_equal);
|
||||
virtual ~RangeNode() = default;
|
||||
|
||||
void set_min_equal(bool value);
|
||||
void set_max_equal(bool value);
|
||||
|
||||
bool min_equal();
|
||||
bool max_equal();
|
||||
|
||||
std::string text() const override;
|
||||
void set_child_op(NodeOp value);
|
||||
NodeOp child_op();
|
||||
|
||||
private:
|
||||
bool min_equal_{false}, max_equal_{false};
|
||||
NodeOp child_op_{NodeOp::T_NONE};
|
||||
};
|
||||
|
||||
class VectorMatrixNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<VectorMatrixNode>;
|
||||
|
||||
VectorMatrixNode(std::string matrix, std::string sparse_indices,
|
||||
std::string sparse_values, QueryParams::Ptr query_params)
|
||||
: matrix_(std::move(matrix)),
|
||||
sparse_indices_(std::move(sparse_indices)),
|
||||
sparse_values_(std::move(sparse_values)),
|
||||
query_params_(std::move(query_params)) {
|
||||
set_op(NodeOp::T_VECTOR_MATRIX_VALUE);
|
||||
}
|
||||
|
||||
const std::string &matrix() const {
|
||||
return matrix_;
|
||||
}
|
||||
|
||||
const std::string &sparse_indices() const {
|
||||
return sparse_indices_;
|
||||
}
|
||||
|
||||
const std::string &sparse_values() const {
|
||||
return sparse_values_;
|
||||
}
|
||||
|
||||
const QueryParams::Ptr &query_params() const {
|
||||
return query_params_;
|
||||
}
|
||||
|
||||
std::string text() const override {
|
||||
// do not distinguish between matrix and vector
|
||||
static std::string txt = "[...]";
|
||||
return txt;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string matrix_;
|
||||
std::string sparse_indices_;
|
||||
std::string sparse_values_;
|
||||
QueryParams::Ptr query_params_;
|
||||
};
|
||||
|
||||
class ConstantNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<ConstantNode>;
|
||||
|
||||
ConstantNode(const std::string &m_value);
|
||||
|
||||
void set_value(const std::string &m_value);
|
||||
const std::string &value();
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
private:
|
||||
std::string value_{""};
|
||||
};
|
||||
|
||||
class IDNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<IDNode>;
|
||||
|
||||
IDNode(const std::string &m_value);
|
||||
|
||||
void set_value(const std::string &m_value);
|
||||
const std::string &value();
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
private:
|
||||
std::string value_{""};
|
||||
};
|
||||
|
||||
class FuncNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<FuncNode>;
|
||||
|
||||
FuncNode();
|
||||
virtual ~FuncNode() = default;
|
||||
|
||||
void set_func_name_node(Node::Ptr func_name_node);
|
||||
const Node::Ptr &get_func_name_node();
|
||||
|
||||
void add_argument(Node::Ptr argument_node);
|
||||
const std::vector<Node::Ptr> &arguments();
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
private:
|
||||
Node::Ptr func_name_node_{nullptr};
|
||||
std::vector<Node::Ptr> arguments_{};
|
||||
};
|
||||
|
||||
class InValueExprListNode : public Node {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<InValueExprListNode>;
|
||||
|
||||
InValueExprListNode() : Node(NodeOp::T_LIST_VALUE) {}
|
||||
|
||||
void add_in_value_expr(Node::Ptr in_value_expr) {
|
||||
in_value_expr_list_.emplace_back(std::move(in_value_expr));
|
||||
}
|
||||
|
||||
const std::vector<Node::Ptr> &in_value_expr_list() {
|
||||
return in_value_expr_list_;
|
||||
}
|
||||
|
||||
bool exclude() {
|
||||
return exclude_;
|
||||
}
|
||||
|
||||
void set_exclude(bool val) {
|
||||
exclude_ = val;
|
||||
}
|
||||
|
||||
std::string text() const override;
|
||||
|
||||
private:
|
||||
std::vector<Node::Ptr> in_value_expr_list_{};
|
||||
bool exclude_{false};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class OrderByElemInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<OrderByElemInfo>;
|
||||
|
||||
OrderByElemInfo() = default;
|
||||
|
||||
const std::string &field_name() {
|
||||
return field_name_;
|
||||
}
|
||||
|
||||
void set_field_name(const std::string &value) {
|
||||
field_name_ = value;
|
||||
}
|
||||
|
||||
void set_desc() {
|
||||
desc_ = true;
|
||||
}
|
||||
|
||||
bool is_desc() {
|
||||
return desc_;
|
||||
}
|
||||
|
||||
std::string to_string() {
|
||||
std::string str = field_name_ + " " + (desc_ ? "DESC" : "ASC");
|
||||
return str;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string field_name_{""};
|
||||
bool desc_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_parser.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
SQLInfo::Ptr QueryParser::parse(const std::string &query) {
|
||||
ZVecSQLParser se_sql_parser_;
|
||||
|
||||
SQLInfo::Ptr sql_info = se_sql_parser_.parse(query);
|
||||
if (sql_info == NULL) {
|
||||
err_msg_ = se_sql_parser_.err_msg();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return sql_info;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "sql_info.h"
|
||||
#include "zvec_sql_parser.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class QueryParser {
|
||||
public:
|
||||
SQLInfo::Ptr parse(const std::string &query);
|
||||
|
||||
const std::string &err_msg() {
|
||||
return err_msg_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string err_msg_{""};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,202 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "select_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
SelectInfo::SelectInfo(const std::string &m_table_name)
|
||||
: BaseInfo(m_table_name) {}
|
||||
|
||||
SelectInfo::~SelectInfo() {}
|
||||
|
||||
SelectInfo::SelectInfo(const SelectInfo &info) : BaseInfo(info) {
|
||||
if (info.selected_elems_.empty() == false) {
|
||||
for (auto iter = info.selected_elems_.begin();
|
||||
iter != info.selected_elems_.end(); iter++) {
|
||||
add_selected_elem(std::make_shared<SelectedElemInfo>(*(*iter)));
|
||||
}
|
||||
}
|
||||
|
||||
if (info.orderby_elems_.empty() == false) {
|
||||
for (auto iter = info.orderby_elems_.begin();
|
||||
iter != info.orderby_elems_.end(); iter++) {
|
||||
add_order_by_elem(std::make_shared<OrderByElemInfo>(*(*iter)));
|
||||
}
|
||||
}
|
||||
|
||||
search_cond_ = copy_node(info.search_cond_);
|
||||
|
||||
limit_ = info.limit_;
|
||||
}
|
||||
|
||||
SelectInfo &SelectInfo::operator=(const SelectInfo &info) {
|
||||
if (info.selected_elems_.empty() == false) {
|
||||
for (auto iter = info.selected_elems_.begin();
|
||||
iter != info.selected_elems_.end(); iter++) {
|
||||
add_selected_elem(std::make_shared<SelectedElemInfo>(*(*iter)));
|
||||
}
|
||||
}
|
||||
|
||||
if (info.orderby_elems_.empty() == false) {
|
||||
for (auto iter = info.orderby_elems_.begin();
|
||||
iter != info.orderby_elems_.end(); iter++) {
|
||||
add_order_by_elem(std::make_shared<OrderByElemInfo>(*(*iter)));
|
||||
}
|
||||
}
|
||||
|
||||
search_cond_ = copy_node(info.search_cond_);
|
||||
|
||||
limit_ = info.limit_;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
Node::Ptr SelectInfo::copy_node(const Node::Ptr &node) {
|
||||
Node::Ptr new_node = nullptr;
|
||||
|
||||
if (node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (node->op() == NodeOp::T_INT_VALUE ||
|
||||
node->op() == NodeOp::T_FLOAT_VALUE ||
|
||||
node->op() == NodeOp::T_STRING_VALUE ||
|
||||
node->op() == NodeOp::T_NULL_VALUE ||
|
||||
node->op() == NodeOp::T_BOOL_VALUE) {
|
||||
ConstantNode::Ptr constant_node =
|
||||
std::dynamic_pointer_cast<ConstantNode>(node);
|
||||
new_node = std::make_shared<ConstantNode>(constant_node->value());
|
||||
} else if (node->op() == NodeOp::T_ID) {
|
||||
IDNode::Ptr id_node = std::dynamic_pointer_cast<IDNode>(node);
|
||||
new_node = std::make_shared<IDNode>(id_node->value());
|
||||
} else if (node->op() == NodeOp::T_VECTOR_MATRIX_VALUE) {
|
||||
VectorMatrixNode::Ptr vector_node =
|
||||
std::dynamic_pointer_cast<VectorMatrixNode>(node);
|
||||
new_node = std::make_shared<VectorMatrixNode>(
|
||||
vector_node->matrix(), vector_node->sparse_indices(),
|
||||
vector_node->sparse_values(), vector_node->query_params());
|
||||
} else if (node->op() == NodeOp::T_FUNCTION_CALL) {
|
||||
FuncNode::Ptr func_node = std::dynamic_pointer_cast<FuncNode>(node);
|
||||
FuncNode::Ptr new_func_node = std::make_shared<FuncNode>();
|
||||
new_func_node->set_func_name_node(
|
||||
copy_node(func_node->get_func_name_node()));
|
||||
for (auto argument : func_node->arguments()) {
|
||||
new_func_node->add_argument(copy_node(argument));
|
||||
}
|
||||
new_node = std::move(new_func_node);
|
||||
} else { /* others are normal Node */
|
||||
new_node = std::make_shared<Node>();
|
||||
}
|
||||
|
||||
|
||||
// copy nodeOp
|
||||
new_node->set_op(node->op());
|
||||
|
||||
// copy left & right
|
||||
if (node->left() != nullptr) {
|
||||
new_node->set_left(copy_node(node->left()));
|
||||
}
|
||||
if (node->right() != nullptr) {
|
||||
new_node->set_right(copy_node(node->right()));
|
||||
}
|
||||
|
||||
return new_node;
|
||||
}
|
||||
|
||||
void SelectInfo::add_selected_elem(SelectedElemInfo::Ptr selected_elem_info) {
|
||||
selected_elems_.push_back(std::move(selected_elem_info));
|
||||
}
|
||||
|
||||
void SelectInfo::add_order_by_elem(OrderByElemInfo::Ptr orderby_elem_info) {
|
||||
orderby_elems_.push_back(std::move(orderby_elem_info));
|
||||
}
|
||||
|
||||
void SelectInfo::set_limit(int value) {
|
||||
limit_ = value;
|
||||
}
|
||||
|
||||
void SelectInfo::set_search_cond(Node::Ptr cond) {
|
||||
search_cond_ = std::move(cond);
|
||||
}
|
||||
|
||||
const std::vector<SelectedElemInfo::Ptr> &SelectInfo::selected_elems() {
|
||||
return selected_elems_;
|
||||
}
|
||||
const std::vector<OrderByElemInfo::Ptr> &SelectInfo::orderby_elems() {
|
||||
return orderby_elems_;
|
||||
}
|
||||
|
||||
int SelectInfo::limit() {
|
||||
return limit_;
|
||||
}
|
||||
|
||||
const Node::Ptr &SelectInfo::search_cond() const {
|
||||
return search_cond_;
|
||||
}
|
||||
|
||||
Node::Ptr &SelectInfo::mutable_search_cond() {
|
||||
return search_cond_;
|
||||
}
|
||||
|
||||
std::string SelectInfo::to_string() {
|
||||
std::string str;
|
||||
|
||||
str += "table: " + table_name();
|
||||
str += "\n";
|
||||
|
||||
if (selected_elems_.empty() == false) {
|
||||
str += "SelectedElems: ";
|
||||
for (auto iter = selected_elems_.begin(); iter != selected_elems_.end();
|
||||
iter++) {
|
||||
if (iter != selected_elems_.begin()) {
|
||||
str += ", ";
|
||||
}
|
||||
str += (*iter)->to_string();
|
||||
}
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (include_vector_) {
|
||||
str += "Include Vector: true";
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (search_cond_ != nullptr) {
|
||||
str += "Search Condition: ";
|
||||
str += search_cond_->text();
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (orderby_elems_.empty() == false) {
|
||||
str += "Orderby Elems: ";
|
||||
for (auto iter = orderby_elems_.begin(); iter != orderby_elems_.end();
|
||||
iter++) {
|
||||
if (iter != orderby_elems_.begin()) {
|
||||
str += ", ";
|
||||
}
|
||||
str += (*iter)->to_string();
|
||||
}
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
if (limit_ != -1) {
|
||||
str += "limit: " + std::to_string(limit_) + " ";
|
||||
str += "\n";
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "db/sqlengine/common/group_by.h"
|
||||
#include "base_info.h"
|
||||
#include "node.h"
|
||||
#include "orderby_elem_info.h"
|
||||
#include "selected_elem_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SelectInfo : public BaseInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SelectInfo>;
|
||||
|
||||
SelectInfo(const std::string &m_table_name);
|
||||
~SelectInfo();
|
||||
|
||||
SelectInfo(const SelectInfo &info);
|
||||
SelectInfo &operator=(const SelectInfo &info);
|
||||
|
||||
const std::vector<SelectedElemInfo::Ptr> &selected_elems();
|
||||
const std::vector<OrderByElemInfo::Ptr> &orderby_elems();
|
||||
int limit();
|
||||
const Node::Ptr &search_cond() const;
|
||||
Node::Ptr &mutable_search_cond();
|
||||
|
||||
void add_selected_elem(SelectedElemInfo::Ptr selected_elem_info);
|
||||
void add_order_by_elem(OrderByElemInfo::Ptr orderby_elem_info);
|
||||
void set_limit(int value);
|
||||
void set_search_cond(Node::Ptr cond);
|
||||
|
||||
void set_include_vector(bool value) {
|
||||
include_vector_ = value;
|
||||
}
|
||||
|
||||
bool include_vector() {
|
||||
return include_vector_;
|
||||
}
|
||||
|
||||
void set_include_doc_id(bool value) {
|
||||
include_doc_id_ = value;
|
||||
}
|
||||
|
||||
bool is_include_doc_id() {
|
||||
return include_doc_id_;
|
||||
}
|
||||
|
||||
void set_group_by(GroupBy::Ptr group_by) {
|
||||
group_by_ = std::move(group_by);
|
||||
}
|
||||
const GroupBy::Ptr &group_by() const {
|
||||
return group_by_;
|
||||
}
|
||||
|
||||
std::string to_string();
|
||||
|
||||
private:
|
||||
Node::Ptr copy_node(const Node::Ptr &node);
|
||||
|
||||
private:
|
||||
std::vector<SelectedElemInfo::Ptr> selected_elems_{};
|
||||
std::vector<OrderByElemInfo::Ptr> orderby_elems_{};
|
||||
Node::Ptr search_cond_{nullptr};
|
||||
GroupBy::Ptr group_by_{};
|
||||
int limit_{-1};
|
||||
bool include_vector_{false};
|
||||
bool include_doc_id_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "selected_elem_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
std::string SelectedElemInfo::to_string() const {
|
||||
std::string str = "";
|
||||
if (is_asterisk()) {
|
||||
str += "*";
|
||||
} else if (is_func_call()) {
|
||||
if (is_func_param_asterisk()) {
|
||||
str += func_name_ + "(*)";
|
||||
} else {
|
||||
str += func_name_ + "(" + func_param_ + ")";
|
||||
}
|
||||
} else {
|
||||
str = field_name_;
|
||||
if (!alias().empty()) {
|
||||
str += " as " + alias();
|
||||
}
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,104 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SelectedElemInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SelectedElemInfo>;
|
||||
|
||||
void set_asterisk(const bool value) {
|
||||
asterisk_ = value;
|
||||
}
|
||||
|
||||
bool is_asterisk() const {
|
||||
return asterisk_;
|
||||
}
|
||||
|
||||
void set_empty(const bool value) {
|
||||
empty_ = value;
|
||||
}
|
||||
|
||||
bool is_empty() const {
|
||||
return empty_;
|
||||
}
|
||||
|
||||
void set_field_name(const std::string &value) {
|
||||
field_name_ = value;
|
||||
}
|
||||
|
||||
const std::string &field_name() const {
|
||||
return field_name_;
|
||||
}
|
||||
|
||||
void set_alias(const std::string &value) {
|
||||
alias_ = value;
|
||||
}
|
||||
|
||||
const std::string &alias() const {
|
||||
return alias_;
|
||||
}
|
||||
|
||||
const std::string &func_name() const {
|
||||
return func_name_;
|
||||
}
|
||||
|
||||
void set_func_name(const std::string &value) {
|
||||
func_name_ = value;
|
||||
if (!value.empty()) {
|
||||
func_call_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
const std::string &func_param() const {
|
||||
return func_param_;
|
||||
}
|
||||
|
||||
void set_func_param(const std::string &value) {
|
||||
func_param_ = value;
|
||||
}
|
||||
|
||||
bool is_func_call() const {
|
||||
return func_call_;
|
||||
}
|
||||
|
||||
void set_func_param_asterisk(bool value) {
|
||||
func_param_asterisk_ = value;
|
||||
}
|
||||
bool is_func_param_asterisk() const {
|
||||
return func_param_asterisk_;
|
||||
}
|
||||
|
||||
std::string to_string() const;
|
||||
|
||||
private:
|
||||
bool asterisk_{false};
|
||||
bool empty_{false};
|
||||
|
||||
std::string field_name_{""};
|
||||
std::string alias_{""};
|
||||
|
||||
std::string func_name_{""};
|
||||
bool func_call_{false};
|
||||
std::string func_param_{""};
|
||||
bool func_param_asterisk_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "sql_info.h"
|
||||
#include <memory>
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "select_info.h"
|
||||
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
SQLInfo::SQLInfo(SQLType m_type, BaseInfo::Ptr m_base_info) {
|
||||
type_ = m_type;
|
||||
base_info_ = m_base_info;
|
||||
}
|
||||
|
||||
SQLInfo::~SQLInfo() {}
|
||||
|
||||
SQLInfo::SQLInfo(const SQLInfo &info) {
|
||||
type_ = info.type_;
|
||||
if (type_ == SQLType::SELECT) {
|
||||
SelectInfo::Ptr select_info = std::make_shared<SelectInfo>(
|
||||
*(std::dynamic_pointer_cast<SelectInfo>(info.base_info_)));
|
||||
base_info_ = select_info;
|
||||
} else {
|
||||
base_info_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
SQLInfo &SQLInfo::operator=(const SQLInfo &info) {
|
||||
type_ = info.type_;
|
||||
if (type_ == SQLType::SELECT) {
|
||||
SelectInfo::Ptr select_info = std::make_shared<SelectInfo>(
|
||||
*(std::dynamic_pointer_cast<SelectInfo>(info.base_info_)));
|
||||
base_info_ = select_info;
|
||||
} else {
|
||||
base_info_ = nullptr;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void SQLInfo::set_base_info(BaseInfo::Ptr value) {
|
||||
base_info_ = std::move(value);
|
||||
}
|
||||
|
||||
const BaseInfo::Ptr &SQLInfo::base_info() const {
|
||||
return base_info_;
|
||||
}
|
||||
|
||||
void SQLInfo::set_type(SQLType value) {
|
||||
type_ = value;
|
||||
}
|
||||
|
||||
SQLInfo::SQLType SQLInfo::type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
std::string SQLInfo::type_name() const {
|
||||
return type_to_str(type_);
|
||||
}
|
||||
|
||||
std::string SQLInfo::to_string() {
|
||||
std::string str = "SQL Info: {\n";
|
||||
str += "Type: " + type_name();
|
||||
str += "\n";
|
||||
str += "Info:";
|
||||
str += "\n";
|
||||
str += base_info_->to_string();
|
||||
str += "}";
|
||||
return str;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,65 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include "base_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SQLInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SQLInfo>;
|
||||
|
||||
enum class SQLType {
|
||||
NONE,
|
||||
INSERT,
|
||||
UPSERT,
|
||||
UPDATE,
|
||||
DELETE,
|
||||
CREATE,
|
||||
DROP,
|
||||
SELECT,
|
||||
SHOW_TABLES
|
||||
};
|
||||
static inline std::string type_to_str(SQLType c) {
|
||||
static std::string names[] = {"NONE", "INSERT", "UPSERT",
|
||||
"UPDATE", "DELETE", "CREATE",
|
||||
"DROP", "SELECT", "SHOW_TABLES"};
|
||||
return names[static_cast<int>(c)];
|
||||
}
|
||||
|
||||
public:
|
||||
SQLInfo(SQLType type, BaseInfo::Ptr m_base_info);
|
||||
~SQLInfo();
|
||||
|
||||
SQLInfo(const SQLInfo &info);
|
||||
SQLInfo &operator=(const SQLInfo &info);
|
||||
|
||||
void set_base_info(BaseInfo::Ptr value);
|
||||
void set_type(SQLType value);
|
||||
|
||||
SQLType type() const;
|
||||
std::string type_name() const;
|
||||
const BaseInfo::Ptr &base_info() const;
|
||||
|
||||
std::string to_string();
|
||||
|
||||
private:
|
||||
SQLType type_{SQLType::NONE};
|
||||
BaseInfo::Ptr base_info_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,112 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "sql_info_helper.h"
|
||||
#include <stdint.h>
|
||||
#include <memory>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/sqlengine/common/group_by.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/parser/node.h"
|
||||
#include "select_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
using namespace zvec;
|
||||
|
||||
Node::Ptr handle_vector(const VectorQuery &request, std::string * /*err_msg*/) {
|
||||
Node::Ptr rel_exp = std::make_shared<Node>(NodeOp::T_EQ);
|
||||
rel_exp->set_left(std::make_shared<IDNode>(request.field_name_));
|
||||
rel_exp->set_right(std::make_shared<VectorMatrixNode>(
|
||||
request.query_vector_, request.query_sparse_indices_,
|
||||
request.query_sparse_values_, request.query_params_));
|
||||
return rel_exp;
|
||||
}
|
||||
|
||||
void handle_query_field(const VectorQuery *query, SelectInfo *selected_info) {
|
||||
if (!query->output_fields_.has_value()) {
|
||||
SelectedElemInfo::Ptr selected_elem_info =
|
||||
std::make_shared<SelectedElemInfo>();
|
||||
selected_elem_info->set_asterisk(true);
|
||||
selected_info->add_selected_elem(std::move(selected_elem_info));
|
||||
} else if (query->output_fields_->empty()) {
|
||||
// select no field if output_fields is specified with empty vector
|
||||
SelectedElemInfo::Ptr selected_elem_info =
|
||||
std::make_shared<SelectedElemInfo>();
|
||||
selected_elem_info->set_empty(true);
|
||||
selected_info->add_selected_elem(std::move(selected_elem_info));
|
||||
} else {
|
||||
for (const auto &field : *query->output_fields_) {
|
||||
SelectedElemInfo::Ptr selected_elem_info =
|
||||
std::make_shared<SelectedElemInfo>();
|
||||
if (field == "*") {
|
||||
selected_elem_info->set_asterisk(true);
|
||||
} else {
|
||||
selected_elem_info->set_field_name(field);
|
||||
}
|
||||
selected_info->add_selected_elem(std::move(selected_elem_info));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool SQLInfoHelper::MessageToSQLInfo(const VectorQuery *query,
|
||||
Node::Ptr filter_node,
|
||||
std::shared_ptr<GroupBy> group_by,
|
||||
sqlengine::SQLInfo::Ptr *sql_info,
|
||||
std::string *err_msg) {
|
||||
Node::Ptr index_params_node_ptr = nullptr;
|
||||
if (!query->query_vector_.empty() || !query->query_sparse_indices_.empty()) {
|
||||
index_params_node_ptr = handle_vector(*query, err_msg);
|
||||
if (index_params_node_ptr == nullptr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Node::Ptr cond_expr = nullptr;
|
||||
if (index_params_node_ptr && filter_node) {
|
||||
cond_expr = std::make_shared<Node>(NodeOp::T_AND);
|
||||
cond_expr->set_left(index_params_node_ptr);
|
||||
cond_expr->set_right(filter_node);
|
||||
} else if (index_params_node_ptr) {
|
||||
cond_expr = index_params_node_ptr;
|
||||
} else if (filter_node) {
|
||||
cond_expr = filter_node;
|
||||
}
|
||||
|
||||
SelectInfo::Ptr select_info = std::make_shared<SelectInfo>("");
|
||||
handle_query_field(query, select_info.get());
|
||||
select_info->set_search_cond(cond_expr);
|
||||
|
||||
uint32_t topk = query->topk_;
|
||||
select_info->set_limit(topk);
|
||||
select_info->set_include_vector(query->include_vector_);
|
||||
select_info->set_include_doc_id(query->include_doc_id_);
|
||||
|
||||
select_info->set_group_by(std::move(group_by));
|
||||
//
|
||||
// for (int i = 0; i < query->order_by_fields_size(); ++i) {
|
||||
// auto orderby_elem_info = std::make_shared<OrderByElemInfo>();
|
||||
// orderby_elem_info->set_field_name(query->order_by_fields(i).field());
|
||||
// if (query->order_by_fields(i).desc()) {
|
||||
// orderby_elem_info->set_desc();
|
||||
// }
|
||||
// select_info->add_order_by_elem(std::move(orderby_elem_info));
|
||||
// }
|
||||
|
||||
*sql_info = std::make_shared<SQLInfo>(SQLInfo::SQLType::SELECT, select_info);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/sqlengine/common/group_by.h"
|
||||
#include "db/sqlengine/parser/node.h"
|
||||
#include "db/sqlengine/parser/sql_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SQLInfoHelper {
|
||||
public:
|
||||
//! Perform QueryRequest to sql info conversion:
|
||||
static bool MessageToSQLInfo(const VectorQuery *query, Node::Ptr filter_node,
|
||||
std::shared_ptr<GroupBy> group_by,
|
||||
sqlengine::SQLInfo::Ptr *sql_info,
|
||||
std::string *err_msg);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,234 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "zvec_cached_sql_parser.h"
|
||||
#include <exception>
|
||||
#include <typeinfo>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "atn/ParserATNSimulator.h"
|
||||
#include "db/sqlengine/antlr/gen/SQLLexer.h"
|
||||
#include "db/sqlengine/antlr/gen/SQLParser.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "case_changing_charstream.h"
|
||||
#include "error_verbose_listener.h"
|
||||
#include "node.h"
|
||||
#include "select_info.h"
|
||||
#include "selected_elem_info.h"
|
||||
|
||||
using namespace antlr4;
|
||||
using namespace tree;
|
||||
using namespace atn;
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
std::unordered_map<std::string, SQLInfo::Ptr>
|
||||
ZVecCachedSQLParser::sql_info_map_{};
|
||||
std::unordered_map<std::string, Node::Ptr> ZVecCachedSQLParser::filter_map_;
|
||||
uint32_t ZVecCachedSQLParser::Hit{0};
|
||||
uint32_t ZVecCachedSQLParser::Miss{0};
|
||||
|
||||
ZVecCachedSQLParser::ZVecCachedSQLParser(uint32_t cache_count)
|
||||
: cache_count_(cache_count) {}
|
||||
|
||||
ZVecCachedSQLParser::~ZVecCachedSQLParser() {}
|
||||
|
||||
SQLInfo::Ptr ZVecCachedSQLParser::parse(const std::string &query,
|
||||
bool need_formatted_tree) {
|
||||
std::string query_cache_key{""};
|
||||
SQLInfo::Ptr cached_sql_info = get_from_cache(query, &query_cache_key);
|
||||
if (cached_sql_info != nullptr) {
|
||||
return cached_sql_info;
|
||||
}
|
||||
|
||||
SQLInfo::Ptr new_sql_info = real_parser_.parse(query, need_formatted_tree);
|
||||
if (new_sql_info == nullptr) {
|
||||
// no need to cache parse failed sql. just return.
|
||||
err_msg_ = real_parser_.err_msg();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
put_into_cache(query_cache_key, new_sql_info);
|
||||
|
||||
return new_sql_info;
|
||||
}
|
||||
|
||||
void ZVecCachedSQLParser::put_into_cache(const std::string &query_cache_key,
|
||||
const SQLInfo::Ptr &new_sql_info) {
|
||||
{
|
||||
std::unique_lock guard(shared_mutex_);
|
||||
if (sql_info_map_.size() >= cache_count_) {
|
||||
// if full, clear to refresh new sql
|
||||
sql_info_map_.clear();
|
||||
Hit = Miss = 0;
|
||||
}
|
||||
sql_info_map_.emplace(query_cache_key, new_sql_info);
|
||||
}
|
||||
|
||||
LOG_DEBUG("cache emplaced. [%s] [%s] ", query_cache_key.c_str(),
|
||||
new_sql_info->to_string().c_str());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
SQLInfo::Ptr ZVecCachedSQLParser::get_from_cache(const std::string &query,
|
||||
std::string *query_cache_key) {
|
||||
// find [ and ], must only one occurrence.
|
||||
std::string::size_type left_pos, right_pos;
|
||||
left_pos = query.find("[");
|
||||
if (left_pos == query.npos) {
|
||||
return nullptr;
|
||||
}
|
||||
// find from left_pos+1
|
||||
right_pos = query.rfind("]");
|
||||
if (right_pos == query.npos) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ok, let's find it.
|
||||
*query_cache_key = query.substr(0, left_pos);
|
||||
query_cache_key->append(query.begin() + right_pos + 1, query.end());
|
||||
std::string vector_text = query.substr(left_pos, right_pos - left_pos + 1);
|
||||
|
||||
SQLInfo::Ptr cached_sql_info = nullptr;
|
||||
SQLInfo::Ptr copied_sql_info = nullptr;
|
||||
{ // lock only in this block. after sql_info is copied, just unlock.
|
||||
std::shared_lock guard(shared_mutex_);
|
||||
auto iter = sql_info_map_.find(*query_cache_key);
|
||||
if (iter == sql_info_map_.end()) {
|
||||
++Miss;
|
||||
LOG_DEBUG("cache miss. key: [%s]", query_cache_key->c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
cached_sql_info = iter->second;
|
||||
// copy cached_sql_info
|
||||
copied_sql_info = std::make_shared<SQLInfo>(*cached_sql_info);
|
||||
}
|
||||
|
||||
// parse vector part
|
||||
Node::Ptr vector_node = parse_vector_text(&vector_text);
|
||||
if (vector_node == nullptr) {
|
||||
LOG_DEBUG("wrong vector format: [%s]", vector_text.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
// replace vector in copied_sql_info
|
||||
if (replace_vector_node(copied_sql_info, vector_node) != 0) {
|
||||
LOG_WARN("replace_vector_node failed. [%s][%s]", query.c_str(),
|
||||
vector_text.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
++Hit;
|
||||
LOG_DEBUG("cache hit. key: [%s] sql_info: [%s]", query_cache_key->c_str(),
|
||||
copied_sql_info->to_string().c_str());
|
||||
return copied_sql_info;
|
||||
}
|
||||
|
||||
int ZVecCachedSQLParser::replace_vector_node(SQLInfo::Ptr cached_sql_info,
|
||||
Node::Ptr vector_node) {
|
||||
SelectInfo::Ptr cached_select_info =
|
||||
std::dynamic_pointer_cast<SelectInfo>(cached_sql_info->base_info());
|
||||
if (cached_select_info == nullptr) {
|
||||
LOG_WARN("wrong select_info in cache. [%s]",
|
||||
cached_sql_info->to_string().c_str());
|
||||
return -1;
|
||||
}
|
||||
|
||||
Node::Ptr search_cond = cached_select_info->mutable_search_cond();
|
||||
if (search_cond == nullptr) {
|
||||
LOG_WARN("wrong search_cond in cache. [%s]",
|
||||
cached_sql_info->to_string().c_str());
|
||||
return -1;
|
||||
}
|
||||
|
||||
replace_flag_ = false;
|
||||
if (traverse_to_replace(search_cond, vector_node) != 0 ||
|
||||
replace_flag_ == false) {
|
||||
LOG_WARN("replace search_cond in cache failed. [%s]",
|
||||
cached_sql_info->to_string().c_str());
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ZVecCachedSQLParser::traverse_to_replace(Node::Ptr ptr,
|
||||
Node::Ptr vector_node) {
|
||||
if (ptr->op() == NodeOp::T_VECTOR_MATRIX_VALUE) {
|
||||
Node *parent = dynamic_cast<Node *>(ptr->parent());
|
||||
if (parent == nullptr) {
|
||||
LOG_WARN("wrong parent node in cache. [%s]", ptr->to_string().c_str());
|
||||
return -1;
|
||||
}
|
||||
if (parent->left() == ptr) {
|
||||
parent->set_left(vector_node);
|
||||
replace_flag_ = true;
|
||||
} else if (parent->right() == ptr) {
|
||||
parent->set_right(vector_node);
|
||||
replace_flag_ = true;
|
||||
} else {
|
||||
LOG_WARN("wrong node in cache. [%s]", ptr->to_string().c_str());
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (ptr->left() != nullptr) {
|
||||
if (traverse_to_replace(ptr->left(), vector_node) < 0) {
|
||||
return -1;
|
||||
}
|
||||
if (replace_flag_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (ptr->right() != nullptr) {
|
||||
if (traverse_to_replace(ptr->right(), vector_node) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (replace_flag_) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecCachedSQLParser::parse_filter(const std::string &filter,
|
||||
bool need_formatted_tree) {
|
||||
{
|
||||
std::shared_lock guard(shared_mutex_);
|
||||
auto iter = filter_map_.find(filter);
|
||||
if (iter != filter_map_.end()) {
|
||||
++Hit;
|
||||
return iter->second;
|
||||
}
|
||||
++Miss;
|
||||
}
|
||||
auto node = real_parser_.parse_filter(filter, need_formatted_tree);
|
||||
err_msg_ = real_parser_.err_msg();
|
||||
formatted_tree_ = real_parser_.formatted_tree();
|
||||
if (node != nullptr) {
|
||||
std::unique_lock guard(shared_mutex_);
|
||||
if (filter_map_.size() >= cache_count_) {
|
||||
// clear cache if full
|
||||
filter_map_.clear();
|
||||
Hit = Miss = 0;
|
||||
}
|
||||
filter_map_.emplace(filter, node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shared_mutex>
|
||||
#include <unordered_map>
|
||||
#include "select_info.h"
|
||||
#include "zvec_sql_parser.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class ZVecCachedSQLParser : public ZVecParser {
|
||||
public:
|
||||
ZVecCachedSQLParser(uint32_t cache_count);
|
||||
~ZVecCachedSQLParser();
|
||||
|
||||
SQLInfo::Ptr parse(const std::string &query,
|
||||
bool need_formatted_tree = false) override;
|
||||
|
||||
Node::Ptr parse_filter(const std::string &filter,
|
||||
bool need_formatted_tree = false) override;
|
||||
|
||||
private:
|
||||
void put_into_cache(const std::string &query_cache_key,
|
||||
const SQLInfo::Ptr &sql_info);
|
||||
SQLInfo::Ptr get_from_cache(const std::string &query,
|
||||
std::string *query_cache_key);
|
||||
|
||||
int replace_vector_node(SQLInfo::Ptr cached_sql_info, Node::Ptr vector_node);
|
||||
int traverse_to_replace(Node::Ptr ptr, Node::Ptr vector_node);
|
||||
|
||||
private:
|
||||
static std::unordered_map<std::string, SQLInfo::Ptr> sql_info_map_;
|
||||
static std::unordered_map<std::string, Node::Ptr> filter_map_;
|
||||
static uint32_t Hit;
|
||||
static uint32_t Miss;
|
||||
inline static std::shared_mutex shared_mutex_;
|
||||
|
||||
private:
|
||||
bool replace_flag_{false};
|
||||
ZVecSQLParser real_parser_;
|
||||
uint32_t cache_count_{0};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,155 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "zvec_parser.h"
|
||||
#include <float.h>
|
||||
#include <stdint.h>
|
||||
#include <exception>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <typeinfo>
|
||||
#include <ailego/encoding/json.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/utility/string_helper.h>
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "tree/ParseTree.h"
|
||||
#include "zvec_cached_sql_parser.h"
|
||||
#include "zvec_sql_parser.h"
|
||||
|
||||
using namespace antlr4;
|
||||
using namespace tree;
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
const std::string &ZVecParser::err_msg() {
|
||||
return err_msg_;
|
||||
}
|
||||
|
||||
std::string ZVecParser::trim(std::string &value) {
|
||||
value = Util::trim_one_both_side(value, '\'');
|
||||
value = Util::trim_one_both_side(value, '\"');
|
||||
// Util::string_replace(value, "\\", "");
|
||||
return value;
|
||||
}
|
||||
|
||||
const std::string &ZVecParser::formatted_tree() {
|
||||
return formatted_tree_;
|
||||
}
|
||||
|
||||
std::string ZVecParser::to_formatted_string_tree(void *tree, void *parser) {
|
||||
if (tree == NULL || parser == NULL) {
|
||||
return "";
|
||||
}
|
||||
|
||||
ParseTree *parse_tree = reinterpret_cast<ParseTree *>(tree);
|
||||
ZVecParser *se_parser = reinterpret_cast<ZVecParser *>(parser);
|
||||
|
||||
std::string tree_text = parse_tree->toStringTree(se_parser);
|
||||
|
||||
int pos = 0, pos1 = 0, pos2 = 0, start = 0;
|
||||
int i = 0, num = 0;
|
||||
const std::string DELIMITER = " ";
|
||||
const std::string LINE = "\n";
|
||||
int lastPos1 = 0;
|
||||
|
||||
std::string out;
|
||||
|
||||
while (true) {
|
||||
std::string formatted = "";
|
||||
|
||||
pos1 = (int)tree_text.find_first_of('(', start);
|
||||
pos2 = (int)tree_text.find_first_of(')', start);
|
||||
|
||||
if (pos1 == 0) {
|
||||
start = pos + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (pos1 < 0 && pos2 < 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (pos1 >= 0 && pos1 < pos2) {
|
||||
if (lastPos1 == 1) {
|
||||
formatted += "(";
|
||||
}
|
||||
pos = pos1;
|
||||
formatted += tree_text.substr(start, (size_t)pos1 - start);
|
||||
num++;
|
||||
} else {
|
||||
if (lastPos1 == 1) {
|
||||
formatted += "(";
|
||||
}
|
||||
pos = pos2;
|
||||
formatted += tree_text.substr(start, (size_t)pos2 - start) + ")";
|
||||
num--;
|
||||
}
|
||||
|
||||
formatted += LINE;
|
||||
for (i = 0; i < num; i++) {
|
||||
formatted += DELIMITER;
|
||||
}
|
||||
|
||||
start = pos + 1;
|
||||
|
||||
if (pos == pos1) {
|
||||
lastPos1 = 1;
|
||||
} else {
|
||||
lastPos1 = 0;
|
||||
}
|
||||
|
||||
out += formatted;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
void ZVecParser::save_to_file(const std::string &file_name,
|
||||
const std::string &formatted) {
|
||||
std::ofstream outfile(file_name);
|
||||
outfile << formatted;
|
||||
outfile << std::endl;
|
||||
outfile.close();
|
||||
}
|
||||
|
||||
ZVecParser::Ptr ZVecParser::create() {
|
||||
// TODO: support config
|
||||
// auto &config = zvec::Config::Instance();
|
||||
// int32_t cache_count = config.get_sql_info_cache_count();
|
||||
return create(100);
|
||||
}
|
||||
|
||||
ZVecParser::Ptr ZVecParser::create(int cache_count) {
|
||||
// if not config, or if config between 0 and 100, upround to 100
|
||||
if (cache_count >= 0 && cache_count < DEFAULT_CACHE_COUNT) {
|
||||
cache_count = DEFAULT_CACHE_COUNT;
|
||||
}
|
||||
|
||||
if (cache_count > 0) {
|
||||
LOG_DEBUG("ZVecCachedSQLParser enabled. effective cache_count %d",
|
||||
cache_count);
|
||||
return std::make_shared<ZVecCachedSQLParser>(cache_count);
|
||||
} else {
|
||||
LOG_DEBUG("ZVecCachedSQLParser disabled.");
|
||||
return std::make_shared<ZVecSQLParser>();
|
||||
}
|
||||
}
|
||||
|
||||
Node::Ptr ZVecParser::parse_vector_text(std::string *vector_text) {
|
||||
return std::make_shared<VectorMatrixNode>(std::move(*vector_text), "", "",
|
||||
nullptr);
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,60 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "node.h"
|
||||
#include "sql_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
using VoidPtr = void *;
|
||||
|
||||
class ZVecParser {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<ZVecParser>;
|
||||
|
||||
ZVecParser() = default;
|
||||
virtual ~ZVecParser() {};
|
||||
|
||||
virtual SQLInfo::Ptr parse(const std::string &query,
|
||||
bool formatted_tree = false) = 0;
|
||||
|
||||
virtual Node::Ptr parse_filter(const std::string &filter,
|
||||
bool need_formatted_tree = false) = 0;
|
||||
|
||||
|
||||
protected:
|
||||
std::string trim(std::string &value);
|
||||
virtual std::string to_formatted_string_tree(void *tree, void *parser);
|
||||
virtual void save_to_file(const std::string &file_name,
|
||||
const std::string &formatted);
|
||||
|
||||
public:
|
||||
virtual const std::string &err_msg();
|
||||
virtual const std::string &formatted_tree();
|
||||
|
||||
Node::Ptr parse_vector_text(std::string *vector_text);
|
||||
|
||||
public:
|
||||
static ZVecParser::Ptr create();
|
||||
static ZVecParser::Ptr create(int cache_count);
|
||||
const static int32_t DEFAULT_CACHE_COUNT{100};
|
||||
|
||||
protected:
|
||||
std::string err_msg_{""};
|
||||
std::string formatted_tree_{""};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,566 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "zvec_sql_parser.h"
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "atn/ParserATNSimulator.h"
|
||||
#include "db/sqlengine/antlr/gen/SQLLexer.h"
|
||||
#include "db/sqlengine/antlr/gen/SQLParser.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "case_changing_charstream.h"
|
||||
#include "error_verbose_listener.h"
|
||||
#include "node.h"
|
||||
#include "select_info.h"
|
||||
#include "selected_elem_info.h"
|
||||
|
||||
using namespace antlr4;
|
||||
using namespace tree;
|
||||
using namespace atn;
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
SQLInfo::Ptr ZVecSQLParser::parse(const std::string &query,
|
||||
bool need_formatted_tree) {
|
||||
try {
|
||||
ANTLRInputStream input(query);
|
||||
CaseChangingCharStream in(&input, true);
|
||||
|
||||
SQLLexer lexer(&in);
|
||||
|
||||
CommonTokenStream tokens(&lexer);
|
||||
|
||||
SQLParser parser(&tokens);
|
||||
|
||||
// remove and add new error listeners
|
||||
ErrorVerboseListener lexer_error_listener;
|
||||
lexer.removeErrorListeners(); // remove all error listeners
|
||||
lexer.addErrorListener((ANTLRErrorListener *)&lexer_error_listener); // add
|
||||
ErrorVerboseListener parser_error_listener;
|
||||
parser.removeErrorListeners(); // remove all error listeners
|
||||
parser.addErrorListener(
|
||||
(ANTLRErrorListener *)&parser_error_listener); // add
|
||||
|
||||
// int64_t curtime = Util::cur_micro_second_time();
|
||||
ParseTree *tree = parser.compilation_unit();
|
||||
|
||||
if (lexer.getNumberOfSyntaxErrors() > 0 ||
|
||||
parser.getNumberOfSyntaxErrors() > 0) {
|
||||
LOG_INFO("SLL failed. using LL");
|
||||
tokens.reset();
|
||||
parser.reset();
|
||||
parser.getInterpreter<ParserATNSimulator>()->setPredictionMode(
|
||||
PredictionMode::LL);
|
||||
tree = parser.compilation_unit();
|
||||
}
|
||||
|
||||
// int64_t duration = Util::cur_micro_second_time() - curtime;
|
||||
// printf("parsing time %ld\n", duration);
|
||||
// LOG_DEBUG("antlr parsing time: [%ld]", duration);
|
||||
|
||||
if (lexer.getNumberOfSyntaxErrors() > 0) {
|
||||
err_msg_ = "lexer error [" + lexer_error_listener.err_msg() + "]";
|
||||
return nullptr;
|
||||
}
|
||||
if (parser.getNumberOfSyntaxErrors() > 0) {
|
||||
err_msg_ = "syntax error [" + parser_error_listener.err_msg() + "]";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (need_formatted_tree) {
|
||||
formatted_tree_ = to_formatted_string_tree(tree, &parser);
|
||||
}
|
||||
|
||||
SQLInfo::Ptr sqlInfo = sql_info(tree);
|
||||
return sqlInfo;
|
||||
} catch (std::exception &e) {
|
||||
err_msg_ = "parse error [" + std::string(e.what()) + "]";
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
SQLInfo::Ptr ZVecSQLParser::sql_info(VoidPtr tree) {
|
||||
ParseTree *parseTree = reinterpret_cast<ParseTree *>(tree);
|
||||
SQLParser::Compilation_unitContext *compilation_unit_node =
|
||||
(SQLParser::Compilation_unitContext *)parseTree;
|
||||
SQLParser::Unit_statementContext *unit_statement_node =
|
||||
(SQLParser::Unit_statementContext *)compilation_unit_node->children[0];
|
||||
|
||||
SQLInfo::SQLType sqlType = sql_type(unit_statement_node);
|
||||
if (sqlType == SQLInfo::SQLType::NONE) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BaseInfo::Ptr baseInfo = nullptr;
|
||||
switch (sqlType) {
|
||||
case SQLInfo::SQLType::SELECT:
|
||||
baseInfo =
|
||||
select_info(unit_statement_node->dql_statement()->select_statement());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (baseInfo == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (baseInfo->validate() == false) {
|
||||
err_msg_ = baseInfo->err_msg();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
SQLInfo::Ptr sqlInfo = std::make_shared<SQLInfo>(sqlType, baseInfo);
|
||||
return sqlInfo;
|
||||
}
|
||||
|
||||
SQLInfo::SQLType ZVecSQLParser::sql_type(VoidPtr node) {
|
||||
SQLParser::Unit_statementContext *unit_statement_node =
|
||||
reinterpret_cast<SQLParser::Unit_statementContext *>(node);
|
||||
|
||||
SQLParser::Dql_statementContext *dql_statement_node =
|
||||
(SQLParser::Dql_statementContext *)unit_statement_node->dql_statement();
|
||||
|
||||
if (dql_statement_node != nullptr) {
|
||||
if (dql_statement_node->select_statement() != nullptr) {
|
||||
return SQLInfo::SQLType::SELECT;
|
||||
}
|
||||
}
|
||||
|
||||
return SQLInfo::SQLType::NONE;
|
||||
}
|
||||
|
||||
SelectInfo::Ptr ZVecSQLParser::select_info(VoidPtr node) {
|
||||
SQLParser::Select_statementContext *select_statement_node =
|
||||
reinterpret_cast<SQLParser::Select_statementContext *>(node);
|
||||
|
||||
SQLParser::Selected_elementsContext *selected_elements_node =
|
||||
select_statement_node->selected_elements();
|
||||
SQLParser::From_clauseContext *from_clause_node =
|
||||
select_statement_node->from_clause();
|
||||
SQLParser::Where_clauseContext *where_node =
|
||||
select_statement_node->where_clause();
|
||||
SQLParser::Order_by_clauseContext *order_by_node =
|
||||
select_statement_node->order_by_clause();
|
||||
SQLParser::Limit_clauseContext *limit_node =
|
||||
select_statement_node->limit_clause();
|
||||
|
||||
std::string table_name = "";
|
||||
|
||||
if (from_clause_node->tableview_name() != nullptr) {
|
||||
table_name = from_clause_node->tableview_name()->getText();
|
||||
}
|
||||
SelectInfo::Ptr selectInfo = std::make_shared<SelectInfo>(table_name);
|
||||
|
||||
for (auto selected_element_node :
|
||||
selected_elements_node->selected_element()) {
|
||||
SelectedElemInfo::Ptr selected_elem_info =
|
||||
std::make_shared<SelectedElemInfo>();
|
||||
|
||||
if (selected_element_node->field_name() != nullptr) {
|
||||
selected_elem_info->set_field_name(
|
||||
selected_element_node->field_name()->getText());
|
||||
if (selected_element_node->field_alias() != nullptr) {
|
||||
selected_elem_info->set_alias(
|
||||
selected_element_node->field_alias()->getText());
|
||||
}
|
||||
} else if (selected_element_node->ASTERISK()) {
|
||||
selected_elem_info->set_asterisk(true);
|
||||
}
|
||||
|
||||
selectInfo->add_selected_elem(std::move(selected_elem_info));
|
||||
}
|
||||
|
||||
if (where_node) {
|
||||
Node::Ptr cond = handle_logic_expr_node(where_node->logic_expr());
|
||||
if (cond == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
selectInfo->set_search_cond(std::move(cond));
|
||||
}
|
||||
|
||||
if (order_by_node != nullptr) {
|
||||
for (auto order_by_element : order_by_node->order_by_element()) {
|
||||
auto orderby_elem_info = std::make_shared<OrderByElemInfo>();
|
||||
orderby_elem_info->set_field_name(
|
||||
order_by_element->field_name()->getText());
|
||||
if (order_by_element->DESC()) {
|
||||
orderby_elem_info->set_desc();
|
||||
}
|
||||
selectInfo->add_order_by_elem(std::move(orderby_elem_info));
|
||||
}
|
||||
}
|
||||
|
||||
if (limit_node != nullptr) {
|
||||
selectInfo->set_limit(std::stoi(limit_node->int_value()->getText()));
|
||||
}
|
||||
|
||||
return selectInfo;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_logic_expr_node(VoidPtr node) {
|
||||
SQLParser::Logic_exprContext *logicExprNode =
|
||||
reinterpret_cast<SQLParser::Logic_exprContext *>(node);
|
||||
const std::vector<SQLParser::Logic_exprContext *> &logicExprChildNodes =
|
||||
logicExprNode->logic_expr();
|
||||
|
||||
if (logicExprNode->OR() != nullptr) {
|
||||
Node::Ptr orExpr = std::make_shared<Node>(NodeOp::T_OR);
|
||||
orExpr->set_left(handle_logic_expr_node(logicExprChildNodes[0]));
|
||||
orExpr->set_right(handle_logic_expr_node(logicExprChildNodes[1]));
|
||||
return orExpr;
|
||||
} else if (logicExprNode->AND() != nullptr) {
|
||||
Node::Ptr andExpr = std::make_shared<Node>(NodeOp::T_AND);
|
||||
andExpr->set_left(handle_logic_expr_node(logicExprChildNodes[0]));
|
||||
andExpr->set_right(handle_logic_expr_node(logicExprChildNodes[1]));
|
||||
return andExpr;
|
||||
} else if (logicExprNode->enclosed_expr() != nullptr) {
|
||||
// enclosed_expr is represented by sub-tree structure
|
||||
return handle_logic_expr_node(logicExprNode->enclosed_expr()->logic_expr());
|
||||
} else if (logicExprNode->relation_expr() != nullptr) {
|
||||
return handle_rel_expr_node(logicExprNode->relation_expr());
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_rel_expr_left_node(VoidPtr node) {
|
||||
SQLParser::Relation_exprContext *relationExprNode =
|
||||
reinterpret_cast<SQLParser::Relation_exprContext *>(node);
|
||||
// either identifier or function call
|
||||
if (relationExprNode->identifier() != nullptr) {
|
||||
return handle_id_node(relationExprNode->identifier());
|
||||
} else if (relationExprNode->function_call() != nullptr) {
|
||||
return handle_function_call_node(relationExprNode->function_call());
|
||||
}
|
||||
|
||||
err_msg_ = "Parse failed. Unexpected rel expr left node." +
|
||||
relationExprNode->getText();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_rel_expr_node(VoidPtr node) {
|
||||
SQLParser::Relation_exprContext *relationExprNode =
|
||||
reinterpret_cast<SQLParser::Relation_exprContext *>(node);
|
||||
if (relationExprNode->rel_oper() != nullptr) {
|
||||
SQLParser::Rel_operContext *op = relationExprNode->rel_oper();
|
||||
NodeOp nodeOp = NodeOp::T_NONE;
|
||||
if (op->E_OP()) {
|
||||
nodeOp = NodeOp::T_EQ;
|
||||
} else if (op->ne_op()) {
|
||||
nodeOp = NodeOp::T_NE;
|
||||
} else if (op->L_OP()) {
|
||||
nodeOp = NodeOp::T_LT;
|
||||
} else if (op->G_OP()) {
|
||||
nodeOp = NodeOp::T_GT;
|
||||
} else if (op->le_op()) {
|
||||
nodeOp = NodeOp::T_LE;
|
||||
} else if (op->ge_op()) {
|
||||
nodeOp = NodeOp::T_GE;
|
||||
}
|
||||
Node::Ptr relationalExpr = std::make_shared<Node>(nodeOp);
|
||||
relationalExpr->set_left(handle_rel_expr_left_node(relationExprNode));
|
||||
Node::Ptr value_node =
|
||||
handle_value_expr_node(relationExprNode->value_expr());
|
||||
if (value_node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
relationalExpr->set_right(std::move(value_node));
|
||||
return relationalExpr;
|
||||
} else if (relationExprNode->LIKE() != nullptr) {
|
||||
NodeOp nodeOp = NodeOp::T_LIKE;
|
||||
Node::Ptr relationalExpr = std::make_shared<Node>(nodeOp);
|
||||
relationalExpr->set_left(handle_rel_expr_left_node(relationExprNode));
|
||||
Node::Ptr value_node =
|
||||
handle_value_expr_node(relationExprNode->value_expr());
|
||||
if (value_node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
relationalExpr->set_right(std::move(value_node));
|
||||
return relationalExpr;
|
||||
} else if (relationExprNode->IN() != nullptr ||
|
||||
relationExprNode->CONTAIN_ALL() != nullptr ||
|
||||
relationExprNode->CONTAIN_ANY() != nullptr) {
|
||||
NodeOp nodeOp = NodeOp::T_NONE;
|
||||
|
||||
if (relationExprNode->CONTAIN_ALL() != nullptr) {
|
||||
nodeOp = NodeOp::T_CONTAIN_ALL;
|
||||
} else if (relationExprNode->CONTAIN_ANY() != nullptr) {
|
||||
nodeOp = NodeOp::T_CONTAIN_ANY;
|
||||
} else {
|
||||
// relationExprNode->IN() != nullptr
|
||||
nodeOp = NodeOp::T_IN;
|
||||
}
|
||||
|
||||
Node::Ptr relationalExpr = std::make_shared<Node>(nodeOp);
|
||||
relationalExpr->set_left(handle_rel_expr_left_node(relationExprNode));
|
||||
Node::Ptr in_value_expr_list_node =
|
||||
handle_in_value_expr_list_node(relationExprNode->in_value_expr_list(),
|
||||
relationExprNode->NOT() != nullptr);
|
||||
if (in_value_expr_list_node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
relationalExpr->set_right(std::move(in_value_expr_list_node));
|
||||
return relationalExpr;
|
||||
} else if (relationExprNode->NULL_V() != nullptr) {
|
||||
NodeOp nodeOp = NodeOp::T_IS_NULL;
|
||||
if (relationExprNode->NOT() != nullptr) {
|
||||
nodeOp = NodeOp::T_IS_NOT_NULL;
|
||||
}
|
||||
auto null_node = std::make_shared<Node>(nodeOp);
|
||||
null_node->set_left(handle_rel_expr_left_node(relationExprNode));
|
||||
auto right = std::make_shared<ConstantNode>("");
|
||||
right->set_op(NodeOp::T_NULL_VALUE);
|
||||
null_node->set_right(std::move(right));
|
||||
return null_node;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_value_expr_node(VoidPtr node) {
|
||||
SQLParser::Value_exprContext *valueExprNode =
|
||||
reinterpret_cast<SQLParser::Value_exprContext *>(node);
|
||||
|
||||
if (valueExprNode->constant() != nullptr) {
|
||||
return handle_const_node(valueExprNode->constant());
|
||||
} else if (valueExprNode->function_call() != nullptr) {
|
||||
return handle_function_call_node(valueExprNode->function_call());
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_function_value_expr_node(VoidPtr node) {
|
||||
SQLParser::Function_value_exprContext *valueExprNode =
|
||||
reinterpret_cast<SQLParser::Function_value_exprContext *>(node);
|
||||
|
||||
if (valueExprNode->value_expr() != nullptr) {
|
||||
return handle_value_expr_node(valueExprNode->value_expr());
|
||||
} else if (valueExprNode->identifier() != nullptr) {
|
||||
return handle_id_node(valueExprNode->identifier());
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_in_value_expr_node(VoidPtr node) {
|
||||
SQLParser::In_value_exprContext *inValueExprNode =
|
||||
reinterpret_cast<SQLParser::In_value_exprContext *>(node);
|
||||
|
||||
if (inValueExprNode->constant_num_and_str() != nullptr) {
|
||||
return handle_const_num_and_str_node(
|
||||
inValueExprNode->constant_num_and_str());
|
||||
} else if (inValueExprNode->bool_value() != nullptr) {
|
||||
return handle_bool_value_node(inValueExprNode->bool_value());
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_bool_value_node(
|
||||
antlr4::SQLParser::Bool_valueContext *node) {
|
||||
// normalize bool value
|
||||
auto value = node->TRUE_V() ? "true" : "false";
|
||||
auto constExpr = std::make_shared<ConstantNode>(value);
|
||||
constExpr->set_op(NodeOp::T_BOOL_VALUE);
|
||||
return constExpr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_in_value_expr_list_node(VoidPtr node,
|
||||
bool exclude) {
|
||||
SQLParser::In_value_expr_listContext *inValueExprListContext =
|
||||
reinterpret_cast<SQLParser::In_value_expr_listContext *>(node);
|
||||
|
||||
InValueExprListNode::Ptr in_value_expr_list_node =
|
||||
std::make_shared<InValueExprListNode>();
|
||||
in_value_expr_list_node->set_exclude(exclude);
|
||||
if (!inValueExprListContext) {
|
||||
return in_value_expr_list_node;
|
||||
}
|
||||
|
||||
auto in_value_expr_list = inValueExprListContext->in_value_expr();
|
||||
for (auto in_value_expr : in_value_expr_list) {
|
||||
Node::Ptr in_value_node = handle_in_value_expr_node(in_value_expr);
|
||||
if (in_value_node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
in_value_expr_list_node->add_in_value_expr(std::move(in_value_node));
|
||||
}
|
||||
|
||||
return in_value_expr_list_node;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_function_call_node(VoidPtr node) {
|
||||
SQLParser::Function_callContext *function_call_node =
|
||||
reinterpret_cast<SQLParser::Function_callContext *>(node);
|
||||
|
||||
FuncNode::Ptr func_node_ptr = std::make_shared<FuncNode>();
|
||||
|
||||
func_node_ptr->set_func_name_node(
|
||||
handle_id_node(function_call_node->identifier()));
|
||||
auto value_expr_list = function_call_node->function_value_expr();
|
||||
for (auto value_expr : value_expr_list) {
|
||||
Node::Ptr value_node = handle_function_value_expr_node(value_expr);
|
||||
if (value_node == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
func_node_ptr->add_argument(std::move(value_node));
|
||||
}
|
||||
|
||||
return func_node_ptr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_const_node(VoidPtr node) {
|
||||
Node::Ptr constExpr = nullptr;
|
||||
SQLParser::ConstantContext *constantNode =
|
||||
reinterpret_cast<SQLParser::ConstantContext *>(node);
|
||||
if (constantNode->numeric()) {
|
||||
constExpr =
|
||||
std::make_shared<ConstantNode>(constantNode->numeric()->getText());
|
||||
if (constantNode->numeric()->int_value()) {
|
||||
constExpr->set_op(NodeOp::T_INT_VALUE);
|
||||
} else if (constantNode->numeric()->float_value()) {
|
||||
constExpr->set_op(NodeOp::T_FLOAT_VALUE);
|
||||
}
|
||||
} else if (constantNode->quoted_string()) {
|
||||
std::string value = constantNode->quoted_string()->getText();
|
||||
value = trim(value);
|
||||
value = Util::normalize(value);
|
||||
constExpr = std::make_shared<ConstantNode>(value);
|
||||
constExpr->set_op(NodeOp::T_STRING_VALUE);
|
||||
} else if (constantNode->vector_expr()) {
|
||||
constExpr = handle_vector_expr_node(constantNode->vector_expr());
|
||||
if (constExpr == nullptr) {
|
||||
err_msg_ = "Parse failed. vector format error." +
|
||||
constantNode->vector_expr()->getText();
|
||||
LOG_ERROR("Parse failed. vector format error. [%s]",
|
||||
constantNode->vector_expr()->getText().c_str());
|
||||
return nullptr;
|
||||
}
|
||||
} else if (constantNode->bool_value()) {
|
||||
constExpr = handle_bool_value_node(constantNode->bool_value());
|
||||
}
|
||||
|
||||
return constExpr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_const_num_and_str_node(VoidPtr node) {
|
||||
Node::Ptr constExpr = nullptr;
|
||||
SQLParser::Constant_num_and_strContext *constant_num_and_str_Node =
|
||||
reinterpret_cast<SQLParser::Constant_num_and_strContext *>(node);
|
||||
if (constant_num_and_str_Node->numeric()) {
|
||||
constExpr = std::make_shared<ConstantNode>(
|
||||
constant_num_and_str_Node->numeric()->getText());
|
||||
if (constant_num_and_str_Node->numeric()->int_value()) {
|
||||
constExpr->set_op(NodeOp::T_INT_VALUE);
|
||||
} else if (constant_num_and_str_Node->numeric()->float_value()) {
|
||||
constExpr->set_op(NodeOp::T_FLOAT_VALUE);
|
||||
}
|
||||
} else if (constant_num_and_str_Node->quoted_string()) {
|
||||
std::string value = constant_num_and_str_Node->quoted_string()->getText();
|
||||
value = trim(value);
|
||||
value = Util::normalize(value);
|
||||
constExpr = std::make_shared<ConstantNode>(value);
|
||||
constExpr->set_op(NodeOp::T_STRING_VALUE);
|
||||
}
|
||||
|
||||
return constExpr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_vector_expr_node(VoidPtr node) {
|
||||
SQLParser::Vector_exprContext *vector_ExprNode =
|
||||
reinterpret_cast<SQLParser::Vector_exprContext *>(node);
|
||||
|
||||
std::string vector_text = vector_ExprNode->getText();
|
||||
return parse_vector_text(&vector_text);
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::handle_id_node(VoidPtr node) {
|
||||
SQLParser::IdentifierContext *identifierNode =
|
||||
reinterpret_cast<SQLParser::IdentifierContext *>(node);
|
||||
|
||||
Node::Ptr identifierExpr =
|
||||
std::make_shared<IDNode>(identifierNode->getText());
|
||||
identifierExpr->set_op(NodeOp::T_ID);
|
||||
return identifierExpr;
|
||||
}
|
||||
|
||||
Node::Ptr ZVecSQLParser::parse_filter(const std::string &filter,
|
||||
bool need_formatted_tree) {
|
||||
try {
|
||||
ANTLRInputStream input(filter);
|
||||
CaseChangingCharStream in(&input, true);
|
||||
|
||||
SQLLexer lexer(&in);
|
||||
|
||||
CommonTokenStream tokens(&lexer);
|
||||
|
||||
SQLParser parser(&tokens);
|
||||
|
||||
// remove and add new error listeners
|
||||
ErrorVerboseListener lexer_error_listener;
|
||||
lexer.removeErrorListeners(); // remove all error listeners
|
||||
lexer.addErrorListener((ANTLRErrorListener *)&lexer_error_listener); // add
|
||||
ErrorVerboseListener parser_error_listener;
|
||||
parser.removeErrorListeners(); // remove all error listeners
|
||||
parser.addErrorListener(
|
||||
(ANTLRErrorListener *)&parser_error_listener); // add
|
||||
|
||||
// int64_t curtime = Util::cur_micro_second_time();
|
||||
ParseTree *tree = parser.logic_expr_unit();
|
||||
|
||||
if (lexer.getNumberOfSyntaxErrors() > 0 ||
|
||||
parser.getNumberOfSyntaxErrors() > 0) {
|
||||
LOG_INFO("SLL failed. using LL");
|
||||
tokens.reset();
|
||||
parser.reset();
|
||||
parser.getInterpreter<ParserATNSimulator>()->setPredictionMode(
|
||||
PredictionMode::LL);
|
||||
tree = parser.logic_expr_unit();
|
||||
}
|
||||
|
||||
// int64_t duration = Util::cur_micro_second_time() - curtime;
|
||||
// printf("parsing time %ld\n", duration);
|
||||
// LOG_DEBUG("antlr parsing time: [%ld]", duration);
|
||||
|
||||
if (lexer.getNumberOfSyntaxErrors() > 0) {
|
||||
err_msg_ = "lexer error [" + lexer_error_listener.err_msg() + "]";
|
||||
return nullptr;
|
||||
}
|
||||
if (parser.getNumberOfSyntaxErrors() > 0) {
|
||||
err_msg_ = "syntax error [" + parser_error_listener.err_msg() + "]";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (need_formatted_tree) {
|
||||
formatted_tree_ = to_formatted_string_tree(tree, &parser);
|
||||
}
|
||||
auto *logic_expr_tree =
|
||||
dynamic_cast<SQLParser::Logic_expr_unitContext *>(tree);
|
||||
if (logic_expr_tree == nullptr ||
|
||||
logic_expr_tree->logic_expr() == nullptr) {
|
||||
err_msg_ = "parse error [null tree]";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return handle_logic_expr_node(logic_expr_tree->logic_expr());
|
||||
} catch (const std::exception &e) {
|
||||
err_msg_ = "parse error [" + std::string(e.what()) + "]";
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "db/sqlengine/antlr/gen/SQLParser.h"
|
||||
#include "select_info.h"
|
||||
#include "zvec_parser.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class ZVecSQLParser : public ZVecParser {
|
||||
public:
|
||||
ZVecSQLParser() = default;
|
||||
|
||||
SQLInfo::Ptr parse(const std::string &query,
|
||||
bool need_formatted_tree = false) override;
|
||||
|
||||
Node::Ptr parse_filter(const std::string &filter,
|
||||
bool need_formatted_tree = false) override;
|
||||
|
||||
private:
|
||||
SQLInfo::Ptr sql_info(VoidPtr tree);
|
||||
|
||||
SQLInfo::SQLType sql_type(VoidPtr node);
|
||||
SelectInfo::Ptr select_info(VoidPtr node);
|
||||
|
||||
Node::Ptr handle_logic_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_rel_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_rel_expr_left_node(VoidPtr node);
|
||||
Node::Ptr handle_value_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_function_value_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_in_value_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_in_value_expr_list_node(VoidPtr node, bool exclude);
|
||||
Node::Ptr handle_id_node(VoidPtr node);
|
||||
Node::Ptr handle_const_node(VoidPtr node);
|
||||
Node::Ptr handle_const_num_and_str_node(VoidPtr node);
|
||||
Node::Ptr handle_bool_value_node(antlr4::SQLParser::Bool_valueContext *node);
|
||||
Node::Ptr handle_vector_expr_node(VoidPtr node);
|
||||
Node::Ptr handle_function_call_node(VoidPtr node);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,166 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/planner/doc_filter.h"
|
||||
#include <optional>
|
||||
#include <arrow/acero/exec_plan.h>
|
||||
#include <arrow/table.h>
|
||||
#include "ailego/logger/logger.h"
|
||||
#include "db/common/config.h"
|
||||
#include "db/sqlengine/planner/invert_search.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
Status DocFilter::compute_filter() {
|
||||
if (invert_cond_) {
|
||||
InvertSearch search(segment_.get());
|
||||
auto invert_res = search.exec_invert_cond_tree(invert_cond_.get());
|
||||
if (!invert_res) {
|
||||
return Status::InternalError("Execute invert search failed: ",
|
||||
invert_res.error().message());
|
||||
}
|
||||
invert_result_ = invert_res.value();
|
||||
invert_filter_ = invert_result_->make_filter();
|
||||
}
|
||||
|
||||
if (forward_plan_) {
|
||||
auto forward_result = arrow::acero::DeclarationToTable(*forward_plan_);
|
||||
if (!forward_result.ok()) {
|
||||
return Status::InternalError("Execute filter bitmap failed: ",
|
||||
forward_result.status().ToString());
|
||||
}
|
||||
// has only one column with boolean type
|
||||
auto &forward_table = forward_result.ValueUnsafe();
|
||||
if (forward_table->num_columns() != 1 ||
|
||||
forward_table->column(0)->type() != arrow::boolean()) {
|
||||
return Status::InternalError("Filter bitmap is not boolean type");
|
||||
}
|
||||
forward_bitmap_ = forward_table->column(0);
|
||||
}
|
||||
|
||||
if (forward_filter_expr_) {
|
||||
// get schema to bind to Expression
|
||||
auto table = segment_->fetch(query_info_->get_forward_filter_field_names(),
|
||||
std::vector<int>{});
|
||||
if (!table) {
|
||||
return Status::InternalError("Fetch forward failed");
|
||||
}
|
||||
auto bind_res = forward_filter_expr_->Bind(*table->schema());
|
||||
if (!bind_res.ok()) {
|
||||
return Status::InternalError("Bind forward filter expression failed",
|
||||
bind_res.status().ToString());
|
||||
}
|
||||
*forward_filter_expr_ = bind_res.MoveValueUnsafe();
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
bool DocFilter::empty() const {
|
||||
return !(delete_filter_ || invert_filter_ || forward_plan_ ||
|
||||
forward_filter_expr_);
|
||||
}
|
||||
|
||||
bool DocFilter::is_filtered(uint64_t id) const {
|
||||
if (delete_filter_ && delete_filter_->is_filtered(id)) {
|
||||
return true;
|
||||
}
|
||||
if (invert_filter_ && invert_filter_->is_filtered(id)) {
|
||||
return true;
|
||||
}
|
||||
auto forward_bit = get_forward_bit(id);
|
||||
if (!forward_bit) {
|
||||
return false;
|
||||
}
|
||||
// revert to return false if forward filter is matched
|
||||
return !forward_bit.value();
|
||||
}
|
||||
|
||||
std::optional<bool> DocFilter::get_forward_bit(uint64_t id) const {
|
||||
if (forward_filter_expr_) {
|
||||
return is_matched_by_forward_filter(id);
|
||||
}
|
||||
if (!forward_bitmap_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
uint64_t rows_seen = 0;
|
||||
for (int c = 0; c < forward_bitmap_->num_chunks(); c++) {
|
||||
const auto &arr = forward_bitmap_->chunk(c);
|
||||
if (id < rows_seen + arr->length()) {
|
||||
auto *bool_array = static_cast<arrow::BooleanArray *>(arr.get());
|
||||
return (*bool_array)[id - rows_seen];
|
||||
}
|
||||
rows_seen += arr->length();
|
||||
}
|
||||
LOG_ERROR("ID is out or range: id[%zu] count[%zu]", (size_t)id,
|
||||
(size_t)rows_seen);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::vector<uint64_t>> DocFilter::get_bf_by_keys_and_update() {
|
||||
auto meta = segment_->meta();
|
||||
if (!meta) {
|
||||
return std::nullopt;
|
||||
}
|
||||
// TODO: support forward
|
||||
if (!invert_result_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
size_t doc_count = meta->doc_count();
|
||||
float brute_force_by_keys_ratio =
|
||||
GlobalConfig::Instance().brute_force_by_keys_ratio();
|
||||
uint64_t bf_by_keys_threshold = meta->doc_count() * brute_force_by_keys_ratio;
|
||||
|
||||
// decide to use brute force by keys or not
|
||||
if (size_t match_count = invert_result_->count();
|
||||
match_count <= bf_by_keys_threshold) {
|
||||
std::vector<uint32_t> ids;
|
||||
invert_result_->extract_ids(&ids);
|
||||
invert_filter_.reset();
|
||||
invert_result_.reset();
|
||||
LOG_INFO("Use brute force by keys, doc_count[%zu] invert_result_count[%zu]",
|
||||
doc_count, match_count);
|
||||
return std::vector<uint64_t>(ids.begin(), ids.end());
|
||||
} else {
|
||||
LOG_DEBUG(
|
||||
"Not use brute force by keys, doc_count[%zu] invert_result_count[%zu]",
|
||||
doc_count, match_count);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<bool> DocFilter::is_matched_by_forward_filter(uint64_t id) const {
|
||||
auto exec_batch =
|
||||
segment_->fetch(query_info_->get_forward_filter_field_names(), id);
|
||||
if (!exec_batch) {
|
||||
LOG_ERROR("Fetch forward failed, id[%zu]", (size_t)id);
|
||||
return std::nullopt;
|
||||
}
|
||||
auto maybe_result = arrow::compute::ExecuteScalarExpression(
|
||||
*forward_filter_expr_, *exec_batch);
|
||||
if (!maybe_result.ok()) {
|
||||
LOG_ERROR("Execute scalar expression failed, id[%zu] err[%s]", (size_t)id,
|
||||
maybe_result.status().ToString().c_str());
|
||||
return std::nullopt;
|
||||
}
|
||||
arrow::Datum datum = maybe_result.MoveValueUnsafe();
|
||||
if (datum.is_scalar()) {
|
||||
return datum.scalar_as<arrow::BooleanScalar>().value;
|
||||
}
|
||||
LOG_ERROR("Datum is not scalar, id[%zu] type[%s]", (size_t)id,
|
||||
datum.type()->ToString().c_str());
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,71 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/chunked_array.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/column/inverted_column/inverted_search_result.h"
|
||||
#include "db/index/common/index_filter.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
#include "db/sqlengine/analyzer/query_node.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class DocFilter : public IndexFilter {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<DocFilter>;
|
||||
|
||||
DocFilter(Segment::Ptr segment, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::acero::Declaration> forward_plan,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter)
|
||||
: segment_(std::move(segment)),
|
||||
query_info_(std::move(query_info)),
|
||||
delete_filter_(segment_->get_filter()),
|
||||
invert_cond_(query_info_->invert_cond()),
|
||||
forward_plan_(std::move(forward_plan)),
|
||||
forward_filter_expr_(std::move(forward_filter)) {}
|
||||
|
||||
Status compute_filter();
|
||||
|
||||
bool is_filtered(uint64_t id) const override;
|
||||
|
||||
//! get brute force by keys and clear `invert_filter_` if suitable
|
||||
std::optional<std::vector<uint64_t>> get_bf_by_keys_and_update();
|
||||
|
||||
bool empty() const;
|
||||
|
||||
private:
|
||||
std::optional<bool> get_forward_bit(uint64_t id) const;
|
||||
std::optional<bool> is_matched_by_forward_filter(uint64_t id) const;
|
||||
|
||||
private:
|
||||
Segment::Ptr segment_;
|
||||
QueryInfo::Ptr query_info_;
|
||||
IndexFilter::Ptr delete_filter_;
|
||||
QueryNode::Ptr invert_cond_;
|
||||
// either forward_plan_ or forward_expr_ is set
|
||||
std::unique_ptr<arrow::acero::Declaration> forward_plan_;
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter_expr_;
|
||||
|
||||
InvertedSearchResult::Ptr invert_result_;
|
||||
IndexFilter::Ptr invert_filter_{nullptr};
|
||||
|
||||
std::shared_ptr<arrow::ChunkedArray> forward_bitmap_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/planner/invert_recall_node.h"
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/api.h>
|
||||
#include "db/sqlengine/planner/invert_search.h"
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> InvertRecallNode::gen() {
|
||||
auto state_ptr = std::make_shared<State>();
|
||||
return [self = shared_from_this(), state_ptr = std::move(state_ptr)]()
|
||||
-> arrow::Future<std::optional<cp::ExecBatch>> {
|
||||
auto &state = *state_ptr;
|
||||
|
||||
if (!state.iter_) {
|
||||
auto invert_ret = self->prepare();
|
||||
if (!invert_ret) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("prepare invert failed:",
|
||||
invert_ret.error().c_str()));
|
||||
}
|
||||
state.invert_result_ = invert_ret.value();
|
||||
state.iter_ = state.invert_result_->create_iterator();
|
||||
}
|
||||
|
||||
if (!state.iter_->valid()) {
|
||||
// return nullopt to indicate end
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::nullopt);
|
||||
}
|
||||
|
||||
// collect a batch
|
||||
std::vector<int> indices;
|
||||
indices.reserve(self->batch_size_);
|
||||
for (int i = 0; state.iter_->valid() && i < self->batch_size_;
|
||||
state.iter_->next()) {
|
||||
if (self->seg_filter_ &&
|
||||
self->seg_filter_->is_filtered(state.iter_->doc_id())) {
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
indices.push_back(state.iter_->doc_id());
|
||||
}
|
||||
if (indices.empty()) {
|
||||
// return nullopt to indicate end
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::nullopt);
|
||||
}
|
||||
|
||||
auto table = self->segment_->fetch(self->fetched_columns_, indices);
|
||||
if (!table) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::UnknownError("fetch table failed"));
|
||||
}
|
||||
auto batch = table->CombineChunksToBatch();
|
||||
if (!batch.ok()) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("combine chunks to batch failed:",
|
||||
batch.status().ToString()));
|
||||
}
|
||||
cp::ExecBatch exec_batch(*batch.ValueUnsafe());
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::move(exec_batch));
|
||||
};
|
||||
}
|
||||
|
||||
Result<InvertedSearchResult::Ptr> InvertRecallNode::prepare() {
|
||||
InvertSearch search(segment_.get());
|
||||
return search.exec_invert_cond_tree(query_info_->invert_cond().get());
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/api.h>
|
||||
#include "db/index/column/common/index_results.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class InvertRecallNode : public std::enable_shared_from_this<InvertRecallNode> {
|
||||
public:
|
||||
InvertRecallNode(Segment::Ptr segment, QueryInfo::Ptr query_info,
|
||||
int batch_size)
|
||||
: segment_(std::move(segment)),
|
||||
query_info_(std::move(query_info)),
|
||||
// need fetch for forward filter, order by
|
||||
fetched_columns_(query_info_->get_all_fetched_scalar_field_names()),
|
||||
seg_filter_(segment_->get_filter()),
|
||||
batch_size_(batch_size) {
|
||||
auto table = segment_->fetch(fetched_columns_, std::vector<int>{});
|
||||
schema_ = table->schema();
|
||||
}
|
||||
|
||||
//! get schema
|
||||
std::shared_ptr<arrow::Schema> schema() const {
|
||||
return schema_;
|
||||
}
|
||||
|
||||
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> gen();
|
||||
|
||||
private:
|
||||
Result<InvertedSearchResult::Ptr> prepare();
|
||||
|
||||
private:
|
||||
struct State {
|
||||
InvertedSearchResult::Ptr invert_result_;
|
||||
IndexResults::IteratorUPtr iter_;
|
||||
};
|
||||
|
||||
Segment::Ptr segment_;
|
||||
QueryInfo::Ptr query_info_;
|
||||
const std::vector<std::string> &fetched_columns_;
|
||||
IndexFilter::Ptr seg_filter_;
|
||||
int batch_size_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,177 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "invert_search.h"
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "analyzer/query_node.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
const std::unordered_map<QueryNodeOp, CompareOp> kOpMap_ = {
|
||||
{QueryNodeOp::Q_EQ, CompareOp::EQ},
|
||||
{QueryNodeOp::Q_NE, CompareOp::NE},
|
||||
{QueryNodeOp::Q_LT, CompareOp::LT},
|
||||
{QueryNodeOp::Q_LE, CompareOp::LE},
|
||||
{QueryNodeOp::Q_GT, CompareOp::GT},
|
||||
{QueryNodeOp::Q_GE, CompareOp::GE},
|
||||
{QueryNodeOp::Q_LIKE, CompareOp::LIKE},
|
||||
{QueryNodeOp::Q_IN, CompareOp::CONTAIN_ANY},
|
||||
{QueryNodeOp::Q_CONTAIN_ALL, CompareOp::CONTAIN_ALL},
|
||||
{QueryNodeOp::Q_CONTAIN_ANY, CompareOp::CONTAIN_ANY},
|
||||
{QueryNodeOp::Q_IS_NULL, CompareOp::IS_NULL},
|
||||
{QueryNodeOp::Q_IS_NOT_NULL, CompareOp::IS_NOT_NULL},
|
||||
};
|
||||
|
||||
Result<InvertedSearchResult::Ptr> InvertSearch::exec_invert_cond_tree(
|
||||
const QueryNode *query_node) {
|
||||
if (query_node->type() == QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
if (query_node->left() != nullptr) {
|
||||
auto left_res = exec_invert_cond_tree(query_node->left_node());
|
||||
if (!left_res) {
|
||||
return left_res;
|
||||
}
|
||||
if (query_node->right() == nullptr) {
|
||||
return left_res;
|
||||
} else {
|
||||
auto right_res = exec_invert_cond_tree(query_node->right_node());
|
||||
if (!right_res) {
|
||||
return right_res;
|
||||
}
|
||||
query_node->op() == QueryNodeOp::Q_AND
|
||||
? left_res.value()->AND(*right_res.value())
|
||||
: left_res.value()->OR(*right_res.value());
|
||||
return left_res;
|
||||
}
|
||||
}
|
||||
if (query_node->right() != nullptr) {
|
||||
return exec_invert_cond_tree(query_node->right_node());
|
||||
}
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"exec_invert_cond_tree, logic expr has no left or right node."));
|
||||
}
|
||||
|
||||
if (query_node->type() == QueryNode::QueryNodeType::REL_EXPR) {
|
||||
return exec_invert_cond_node(query_node);
|
||||
}
|
||||
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"exec_invert_cond_tree unexpected type:", query_node->op_name()));
|
||||
}
|
||||
|
||||
CompareOp InvertSearch::query_nodeop2search_op(QueryNodeOp op) {
|
||||
auto iter = kOpMap_.find(op);
|
||||
if (iter == kOpMap_.end()) {
|
||||
return CompareOp::NONE;
|
||||
}
|
||||
return iter->second;
|
||||
}
|
||||
|
||||
Result<InvertedSearchResult::Ptr> InvertSearch::exec_invert_cond_node(
|
||||
const QueryNode *invert_cond) {
|
||||
auto term_node = invert_cond->right();
|
||||
|
||||
// get search oper
|
||||
CompareOp oper = query_nodeop2search_op(invert_cond->op());
|
||||
if (oper == CompareOp::NONE) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"do_invert_scan, get search operator failed. op:",
|
||||
invert_cond->op_name()));
|
||||
}
|
||||
|
||||
bool is_array_length = false;
|
||||
auto *left_node = invert_cond->left_node();
|
||||
std::string invert_field_name;
|
||||
if (left_node->op() == QueryNodeOp::Q_ID) {
|
||||
invert_field_name = left_node->text();
|
||||
} else if (left_node->op() == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
const QueryFuncNode *func_node =
|
||||
dynamic_cast<const QueryFuncNode *>(left_node);
|
||||
const auto &func_name = func_node->get_func_name();
|
||||
const auto &arguments = func_node->arguments();
|
||||
if (func_name == kFuncArrayLength) {
|
||||
invert_field_name = arguments[0]->text();
|
||||
is_array_length = true;
|
||||
} else {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"do_invert_scan, unsupported function call. func:",
|
||||
func_name.c_str()));
|
||||
}
|
||||
} else {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"do_invert_scan, unsupported left node. op:", left_node->op_name()));
|
||||
}
|
||||
|
||||
// get field reader
|
||||
auto invert_reader = segment_->get_scalar_indexer(invert_field_name);
|
||||
if (invert_reader == nullptr) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"do_invert_scan, get invert column reader failed. field:",
|
||||
invert_field_name.c_str()));
|
||||
}
|
||||
|
||||
if (oper == CompareOp::IS_NULL) {
|
||||
auto invert_res = invert_reader->search_null();
|
||||
if (!invert_res) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("invert column reader search null failed."));
|
||||
}
|
||||
return invert_res;
|
||||
} else if (oper == CompareOp::IS_NOT_NULL) {
|
||||
auto invert_res = invert_reader->search_non_null();
|
||||
if (!invert_res) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"invert column reader search not null failed."));
|
||||
}
|
||||
return invert_res;
|
||||
} else if (oper == CompareOp::CONTAIN_ALL || oper == CompareOp::CONTAIN_ANY) {
|
||||
// NOTE: IN is handled as CONTAIN_ANY
|
||||
QueryListNode::Ptr list_node =
|
||||
std::dynamic_pointer_cast<QueryListNode>(term_node);
|
||||
if (list_node->exclude()) {
|
||||
oper = oper == CompareOp::CONTAIN_ALL ? CompareOp::NOT_CONTAIN_ALL
|
||||
: CompareOp::NOT_CONTAIN_ANY;
|
||||
}
|
||||
auto invert_res =
|
||||
invert_reader->multi_search(list_node->to_value_list(), oper);
|
||||
if (!invert_res) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"invert column reader multi_search failed. op:", int(oper)));
|
||||
}
|
||||
return invert_res;
|
||||
} else if (!is_array_length) {
|
||||
auto invert_term = term_node->text();
|
||||
auto invert_res = invert_reader->search(invert_term, oper);
|
||||
if (!invert_res) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"invert column reader search failed. term:", invert_term.c_str(),
|
||||
" op:", invert_cond->op_name().c_str()));
|
||||
}
|
||||
return invert_res;
|
||||
} else {
|
||||
auto invert_term = term_node->text();
|
||||
uint32_t len = *(reinterpret_cast<const uint32_t *>(invert_term.data()));
|
||||
auto invert_res = invert_reader->search_array_len(len, oper);
|
||||
if (!invert_res) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"invert column reader search failed. term:", invert_term.c_str(),
|
||||
" op:", invert_cond->op_name().c_str()));
|
||||
}
|
||||
return invert_res;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include "analyzer/query_node.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class InvertSearch {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<InvertSearch>;
|
||||
|
||||
InvertSearch(zvec::Segment *segment) : segment_(segment) {}
|
||||
|
||||
Result<InvertedSearchResult::Ptr> exec_invert_cond_tree(
|
||||
const QueryNode *invert_cond);
|
||||
|
||||
static CompareOp query_nodeop2search_op(QueryNodeOp op);
|
||||
|
||||
private:
|
||||
Result<InvertedSearchResult::Ptr> exec_invert_cond_node(
|
||||
const QueryNode *invert_cond);
|
||||
|
||||
private:
|
||||
zvec::Segment *segment_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#include "db/sqlengine/planner/op_register.h"
|
||||
#include <arrow/status.h>
|
||||
#include "db/sqlengine/planner/ops/check_not_filtered_op.h"
|
||||
#include "db/sqlengine/planner/ops/contain_op.h"
|
||||
#include "db/sqlengine/planner/ops/fetch_vector_op.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
arrow::Status OpRegister::register_ops() {
|
||||
ARROW_RETURN_NOT_OK(CheckNotFilteredOp::register_op());
|
||||
ARROW_RETURN_NOT_OK(FetchVectorOp::register_op());
|
||||
ARROW_RETURN_NOT_OK(ContainOp::register_op());
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,26 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <arrow/status.h>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class OpRegister {
|
||||
public:
|
||||
static arrow::Status register_ops();
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#include "db/sqlengine/planner/ops/check_not_filtered_op.h"
|
||||
#include <arrow/type_fwd.h>
|
||||
#include "db/sqlengine/common/util.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
arrow::Status CheckNotFilteredOp::CheckNotFilteredFunction(
|
||||
cp::KernelContext *ctx, const cp::ExecSpan &batch, cp::ExecResult *out) {
|
||||
CheckNotFilteredState *state =
|
||||
static_cast<CheckNotFilteredState *>(ctx->state());
|
||||
auto *filter = state->args.filter.get();
|
||||
if (filter == nullptr) {
|
||||
return arrow::Status::ExecutionError("filter is null");
|
||||
}
|
||||
|
||||
auto row_span = batch[0].array.GetSpan<uint64_t>(1, batch.length);
|
||||
std::shared_ptr<arrow::BooleanBuilder> builder =
|
||||
std::make_shared<arrow::BooleanBuilder>(ctx->memory_pool());
|
||||
ARROW_RETURN_NOT_OK(builder->Reserve(batch.length));
|
||||
for (int i = 0; i < batch.length; i++) {
|
||||
builder->UnsafeAppend(!filter->is_filtered(row_span[i]));
|
||||
}
|
||||
std::shared_ptr<arrow::Array> result_array;
|
||||
ARROW_RETURN_NOT_OK(builder->Finish(&result_array));
|
||||
|
||||
out->value = std::move(result_array->data());
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
CheckNotFilteredOp::InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args) {
|
||||
auto func_options =
|
||||
static_cast<const CheckNotFilteredOp::Options *>(args.options);
|
||||
return std::make_unique<CheckNotFilteredOp::CheckNotFilteredState>(
|
||||
func_options ? func_options : nullptr);
|
||||
}
|
||||
|
||||
|
||||
arrow::Status CheckNotFilteredOp::register_op() {
|
||||
static Options options = Options::Defaults();
|
||||
auto func = std::make_shared<cp::ScalarFunction>(
|
||||
kCheckNotFiltered, cp::Arity::Unary(), func_doc, &options, false);
|
||||
cp::ScalarKernel kernel({arrow::uint64()}, arrow::boolean(),
|
||||
CheckNotFilteredFunction, InitExprValue);
|
||||
|
||||
kernel.mem_allocation = cp::MemAllocation::NO_PREALLOCATE;
|
||||
kernel.null_handling = cp::NullHandling::COMPUTED_NO_PREALLOCATE;
|
||||
|
||||
ARROW_RETURN_NOT_OK(func->AddKernel(std::move(kernel)));
|
||||
|
||||
auto registry = cp::GetFunctionRegistry();
|
||||
ARROW_RETURN_NOT_OK(registry->AddFunction(std::move(func)));
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,114 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include "db/index/common/index_filter.h"
|
||||
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
class CheckNotFilteredOp {
|
||||
public:
|
||||
class CheckNotFilteredOptionsType
|
||||
: public arrow::compute::FunctionOptionsType {
|
||||
public:
|
||||
static const arrow::compute::FunctionOptionsType *GetInstance() {
|
||||
static std::unique_ptr<arrow::compute::FunctionOptionsType> instance(
|
||||
new CheckNotFilteredOptionsType());
|
||||
return instance.get();
|
||||
}
|
||||
|
||||
const char *type_name() const override {
|
||||
return "CheckNotFiltered";
|
||||
}
|
||||
|
||||
std::string Stringify(
|
||||
const arrow::compute::FunctionOptions & /*options*/) const override {
|
||||
return type_name();
|
||||
}
|
||||
|
||||
bool Compare(const arrow::compute::FunctionOptions &options,
|
||||
const arrow::compute::FunctionOptions &other) const override {
|
||||
const auto &lop = static_cast<const Options &>(options);
|
||||
const auto &rop = static_cast<const Options &>(other);
|
||||
return lop.args.filter == rop.args.filter;
|
||||
}
|
||||
|
||||
std::unique_ptr<arrow::compute::FunctionOptions> Copy(
|
||||
const arrow::compute::FunctionOptions &options) const override {
|
||||
const auto &opts = static_cast<const Options &>(options);
|
||||
return std::make_unique<Options>(opts.args.filter);
|
||||
}
|
||||
};
|
||||
|
||||
struct Args {
|
||||
IndexFilter::Ptr filter;
|
||||
};
|
||||
|
||||
class Options : public cp::FunctionOptions {
|
||||
public:
|
||||
Options() : Options(nullptr) {}
|
||||
|
||||
Options(IndexFilter::Ptr filter)
|
||||
: cp::FunctionOptions(CheckNotFilteredOptionsType::GetInstance()),
|
||||
args{std::move(filter)} {}
|
||||
|
||||
static inline constexpr char const kTypeName[] =
|
||||
"CheckNotFilteredFunctionOptions";
|
||||
|
||||
static Options Defaults() {
|
||||
return Options();
|
||||
}
|
||||
|
||||
Args get_args() const {
|
||||
return args;
|
||||
}
|
||||
|
||||
Args args;
|
||||
};
|
||||
|
||||
struct CheckNotFilteredState : public arrow::compute::KernelState {
|
||||
Args args;
|
||||
|
||||
explicit CheckNotFilteredState(const Options *o) {
|
||||
if (o) {
|
||||
args = o->get_args();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
static arrow::Status CheckNotFilteredFunction(cp::KernelContext *ctx,
|
||||
const cp::ExecSpan &batch,
|
||||
cp::ExecResult *out);
|
||||
|
||||
static inline const cp::FunctionDoc func_doc{
|
||||
"check if the segment row id is not filtered",
|
||||
"returns not_filtered(x)",
|
||||
{"segment_row_id"},
|
||||
"Options"};
|
||||
|
||||
static arrow::Status register_op();
|
||||
|
||||
static arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,220 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#include "db/sqlengine/planner/ops/contain_op.h"
|
||||
#include <memory>
|
||||
#include <arrow/api.h>
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
enum class ContainType { kContainAll, kContainAny };
|
||||
template <typename ArrowArrayType, ContainType contain_type>
|
||||
bool match_value(const arrow::Array *value_array, int64_t offset,
|
||||
int64_t length, const arrow::Array *value_set_array) {
|
||||
auto *value_typed_arr = static_cast<const ArrowArrayType *>(value_array);
|
||||
auto *value_set_typed_arr =
|
||||
static_cast<const ArrowArrayType *>(value_set_array);
|
||||
if (contain_type == ContainType::kContainAll) {
|
||||
for (int j = 0; j < value_set_typed_arr->length(); ++j) {
|
||||
bool contain = false;
|
||||
for (int i = 0; i < length; ++i) {
|
||||
if constexpr (std::is_same_v<ArrowArrayType, arrow::StringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeStringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::BinaryArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeBinaryArray>) {
|
||||
if (value_typed_arr->GetView(offset + i) ==
|
||||
value_set_typed_arr->GetView(j)) {
|
||||
contain = true;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (value_typed_arr->Value(offset + i) ==
|
||||
value_set_typed_arr->Value(j)) {
|
||||
contain = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!contain) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} else { // contain_type == kContainAny
|
||||
for (int j = 0; j < value_set_typed_arr->length(); ++j) {
|
||||
for (int i = 0; i < length; ++i) {
|
||||
if constexpr (std::is_same_v<ArrowArrayType, arrow::StringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeStringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::BinaryArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeBinaryArray>) {
|
||||
if (value_typed_arr->GetView(offset + i) ==
|
||||
value_set_typed_arr->GetView(j)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (value_typed_arr->Value(offset + i) ==
|
||||
value_set_typed_arr->Value(j)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
template <ContainType contain_type>
|
||||
arrow::Status ContainFunction(cp::KernelContext *ctx, const cp::ExecSpan &batch,
|
||||
cp::ExecResult *out) {
|
||||
auto *state = static_cast<ContainOp::ContainState *>(ctx->state());
|
||||
const auto &value_set = state->args.value_set;
|
||||
if (value_set == nullptr) {
|
||||
return arrow::Status::ExecutionError("value_set is null");
|
||||
}
|
||||
|
||||
const auto &input_array = batch[0].array;
|
||||
if (batch[0].type()->id() != arrow::Type::LIST) {
|
||||
return arrow::Status::ExecutionError("batch type is not list");
|
||||
}
|
||||
if (!input_array.type->field(0)->type()->Equals(value_set->type())) {
|
||||
return arrow::Status::ExecutionError(
|
||||
"value_set type is not equal to batch type");
|
||||
}
|
||||
auto list_array =
|
||||
std::dynamic_pointer_cast<arrow::ListArray>(input_array.ToArray());
|
||||
|
||||
std::shared_ptr<arrow::BooleanBuilder> builder =
|
||||
std::make_shared<arrow::BooleanBuilder>(ctx->memory_pool());
|
||||
ARROW_RETURN_NOT_OK(builder->Reserve(batch.length));
|
||||
const auto &list_value_array = list_array->values();
|
||||
for (int i = 0; i < batch.length; i++) {
|
||||
// a whole list may be null for a doc
|
||||
if (list_array->IsNull(i)) {
|
||||
ARROW_RETURN_NOT_OK(builder->AppendNull());
|
||||
continue;
|
||||
}
|
||||
auto length = list_array->value_length(i);
|
||||
auto offset = list_array->value_offset(i);
|
||||
bool match = false;
|
||||
switch (state->args.data_type) {
|
||||
case DataType::ARRAY_INT32:
|
||||
match = match_value<arrow::Int32Array, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_UINT32:
|
||||
match = match_value<arrow::UInt32Array, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_INT64:
|
||||
match = match_value<arrow::Int64Array, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_UINT64:
|
||||
match = match_value<arrow::UInt64Array, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_FLOAT:
|
||||
match = match_value<arrow::FloatArray, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
match = match_value<arrow::DoubleArray, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_STRING:
|
||||
match = match_value<arrow::StringArray, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
case DataType::ARRAY_BOOL:
|
||||
match = match_value<arrow::BooleanArray, contain_type>(
|
||||
list_value_array.get(), offset, length, value_set.get());
|
||||
break;
|
||||
|
||||
default:
|
||||
return arrow::Status::ExecutionError("unsupported data type");
|
||||
}
|
||||
ARROW_RETURN_NOT_OK(builder->Append(match));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> result_array;
|
||||
ARROW_RETURN_NOT_OK(builder->Finish(&result_array));
|
||||
|
||||
out->value = std::move(result_array->data());
|
||||
// out->array_data()->type = batch[0].type()->GetShared::Ptr();
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
ContainOp::InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args) {
|
||||
auto func_options = static_cast<const ContainOp::Options *>(args.options);
|
||||
return std::make_unique<ContainOp::ContainState>(func_options ? func_options
|
||||
: nullptr);
|
||||
}
|
||||
|
||||
|
||||
arrow::Status ContainOp::register_op() {
|
||||
static Options options = Options::Defaults();
|
||||
|
||||
{
|
||||
auto func = std::make_shared<cp::ScalarFunction>(
|
||||
kContainAll, cp::Arity::Unary(), func_doc, &options, false);
|
||||
for (const auto &type :
|
||||
{arrow::int32(), arrow::uint32(), arrow::int64(), arrow::uint64(),
|
||||
arrow::float32(), arrow::float64(), arrow::utf8(),
|
||||
arrow::boolean()}) {
|
||||
cp::ScalarKernel kernel({arrow::list(type)}, arrow::boolean(),
|
||||
ContainFunction<ContainType::kContainAll>,
|
||||
InitExprValue);
|
||||
kernel.mem_allocation = cp::MemAllocation::NO_PREALLOCATE;
|
||||
kernel.null_handling = cp::NullHandling::INTERSECTION;
|
||||
ARROW_RETURN_NOT_OK(func->AddKernel(std::move(kernel)));
|
||||
}
|
||||
|
||||
auto registry = cp::GetFunctionRegistry();
|
||||
ARROW_RETURN_NOT_OK(registry->AddFunction(std::move(func)));
|
||||
}
|
||||
|
||||
{
|
||||
auto func = std::make_shared<cp::ScalarFunction>(
|
||||
kContainAny, cp::Arity::Unary(), func_doc, &options, false);
|
||||
for (const auto &type :
|
||||
{arrow::int32(), arrow::uint32(), arrow::int64(), arrow::uint64(),
|
||||
arrow::float32(), arrow::float64(), arrow::utf8(),
|
||||
arrow::boolean()}) {
|
||||
cp::ScalarKernel kernel({arrow::list(type)}, arrow::boolean(),
|
||||
ContainFunction<ContainType::kContainAny>,
|
||||
InitExprValue);
|
||||
kernel.mem_allocation = cp::MemAllocation::NO_PREALLOCATE;
|
||||
kernel.null_handling = cp::NullHandling::INTERSECTION;
|
||||
ARROW_RETURN_NOT_OK(func->AddKernel(std::move(kernel)));
|
||||
}
|
||||
|
||||
auto registry = cp::GetFunctionRegistry();
|
||||
ARROW_RETURN_NOT_OK(registry->AddFunction(std::move(func)));
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,122 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include "db/index/common/type.h"
|
||||
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
class ContainOp {
|
||||
public:
|
||||
class ContainOptionsType : public arrow::compute::FunctionOptionsType {
|
||||
public:
|
||||
static const arrow::compute::FunctionOptionsType *GetInstance() {
|
||||
static std::unique_ptr<arrow::compute::FunctionOptionsType> instance(
|
||||
new ContainOptionsType());
|
||||
return instance.get();
|
||||
}
|
||||
|
||||
const char *type_name() const override {
|
||||
return "Contain";
|
||||
}
|
||||
|
||||
std::string Stringify(
|
||||
const arrow::compute::FunctionOptions & /*options*/) const override {
|
||||
return type_name();
|
||||
}
|
||||
|
||||
bool Compare(const arrow::compute::FunctionOptions &options,
|
||||
const arrow::compute::FunctionOptions &other) const override {
|
||||
const auto &lop = static_cast<const Options &>(options);
|
||||
const auto &rop = static_cast<const Options &>(other);
|
||||
if (lop.args.data_type != rop.args.data_type) {
|
||||
return false;
|
||||
}
|
||||
auto *left_value = lop.args.value_set.get();
|
||||
auto *right_value = rop.args.value_set.get();
|
||||
if (left_value && right_value) {
|
||||
return left_value->Equals(*right_value);
|
||||
} else if (!left_value && !right_value) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<arrow::compute::FunctionOptions> Copy(
|
||||
const arrow::compute::FunctionOptions &options) const override {
|
||||
const auto &opts = static_cast<const Options &>(options);
|
||||
return std::make_unique<Options>(opts.args);
|
||||
}
|
||||
};
|
||||
|
||||
struct Args {
|
||||
std::shared_ptr<arrow::Array> value_set;
|
||||
DataType data_type;
|
||||
};
|
||||
|
||||
class Options : public cp::FunctionOptions {
|
||||
public:
|
||||
Options() : Options(Args{}) {}
|
||||
|
||||
Options(Args args)
|
||||
: cp::FunctionOptions(ContainOptionsType::GetInstance()),
|
||||
args(std::move(args)) {}
|
||||
|
||||
static inline constexpr char const kTypeName[] = "ContainFunctionOptions";
|
||||
|
||||
static Options Defaults() {
|
||||
return Options();
|
||||
}
|
||||
|
||||
Args get_args() const {
|
||||
return args;
|
||||
}
|
||||
|
||||
Args args;
|
||||
};
|
||||
|
||||
struct ContainState : public arrow::compute::KernelState {
|
||||
Args args;
|
||||
|
||||
explicit ContainState(const Options *o) {
|
||||
if (o) {
|
||||
args = o->get_args();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
static inline const cp::FunctionDoc func_doc{
|
||||
"check if contain_all/any",
|
||||
"returns contain_all/any(x)",
|
||||
{"value_set"},
|
||||
"Options",
|
||||
};
|
||||
|
||||
static arrow::Status register_op();
|
||||
|
||||
static arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,206 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#include "db/sqlengine/planner/ops/fetch_vector_op.h"
|
||||
#include <arrow/status.h>
|
||||
#include "db/index/column/vector_column/combined_vector_column_indexer.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
#define CHECK_ARROW_STATUS(msg, status) \
|
||||
if (!status.ok()) { \
|
||||
return tl::make_unexpected(Status::InternalError(msg, status.ToString())); \
|
||||
}
|
||||
|
||||
template <typename Iter>
|
||||
Result<std::shared_ptr<arrow::Array>> fetch_dense_vector_helper(
|
||||
const CombinedVectorColumnIndexer *indexer, Iter begin, Iter end) {
|
||||
size_t count = std::distance(begin, end);
|
||||
arrow::BinaryBuilder vector_builder;
|
||||
CHECK_ARROW_STATUS("Reserve vector builder failed:",
|
||||
vector_builder.Reserve(count));
|
||||
for (Iter i = begin; i != end; ++i) {
|
||||
auto vector_res = indexer->Fetch(*i);
|
||||
if (!vector_res) {
|
||||
return tl::make_unexpected(vector_res.error());
|
||||
}
|
||||
const auto &data = std::get<vector_column_params::DenseVectorBuffer>(
|
||||
vector_res.value().vector_buffer)
|
||||
.data;
|
||||
if (data.empty()) {
|
||||
CHECK_ARROW_STATUS("Append null failed:", vector_builder.AppendNull());
|
||||
} else {
|
||||
CHECK_ARROW_STATUS("Append vector failed:", vector_builder.Append(data));
|
||||
}
|
||||
}
|
||||
auto vector_array_ret = vector_builder.Finish();
|
||||
if (!vector_array_ret.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"finish vector builder failed:", vector_array_ret.status().ToString()));
|
||||
}
|
||||
return vector_array_ret.MoveValueUnsafe();
|
||||
}
|
||||
|
||||
Result<std::shared_ptr<arrow::Array>> FetchVectorOp::fetch_dense_vector(
|
||||
const Segment &segment, const std::string &vector_name,
|
||||
const std::vector<int> &rows) {
|
||||
auto indexer = segment.get_combined_vector_indexer(vector_name);
|
||||
if (!indexer) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("vector index not found:", vector_name));
|
||||
}
|
||||
return fetch_dense_vector_helper(indexer.get(), rows.begin(), rows.end());
|
||||
}
|
||||
|
||||
|
||||
template <typename Iter>
|
||||
Result<std::shared_ptr<arrow::Array>> fetch_sparse_vector_helper(
|
||||
const CombinedVectorColumnIndexer *indexer, Iter begin, Iter end) {
|
||||
size_t count = std::distance(begin, end);
|
||||
std::unique_ptr<arrow::StructBuilder> sparse_builder;
|
||||
arrow::BinaryBuilder *sparse_index_builder = nullptr;
|
||||
arrow::BinaryBuilder *sparse_value_builder = nullptr;
|
||||
auto array_builder = arrow::MakeBuilder(Util::sparse_type());
|
||||
if (!array_builder.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"make builder failed:", array_builder.status().ToString()));
|
||||
}
|
||||
sparse_builder.reset(dynamic_cast<arrow::StructBuilder *>(
|
||||
array_builder.ValueUnsafe().release()));
|
||||
sparse_index_builder =
|
||||
dynamic_cast<arrow::BinaryBuilder *>(sparse_builder->field_builder(0));
|
||||
sparse_value_builder =
|
||||
dynamic_cast<arrow::BinaryBuilder *>(sparse_builder->field_builder(1));
|
||||
|
||||
CHECK_ARROW_STATUS("Reserve failed:", sparse_builder->Reserve(count));
|
||||
CHECK_ARROW_STATUS("Reserve failed:", sparse_index_builder->Reserve(count));
|
||||
CHECK_ARROW_STATUS("Reserve failed:", sparse_value_builder->Reserve(count));
|
||||
for (auto i = begin; i != end; i++) {
|
||||
auto vector_res = indexer->Fetch(*i);
|
||||
if (!vector_res) {
|
||||
return tl::make_unexpected(vector_res.error());
|
||||
}
|
||||
const auto &data = std::get<vector_column_params::SparseVectorBuffer>(
|
||||
vector_res.value().vector_buffer);
|
||||
if (data.indices.empty()) {
|
||||
// will auto append to sub builder
|
||||
CHECK_ARROW_STATUS("Append failed", sparse_builder->AppendNull());
|
||||
} else {
|
||||
CHECK_ARROW_STATUS("Append failed", sparse_builder->Append(true));
|
||||
CHECK_ARROW_STATUS("Append failed",
|
||||
sparse_index_builder->Append(data.indices));
|
||||
CHECK_ARROW_STATUS("Append failed",
|
||||
sparse_value_builder->Append(data.values));
|
||||
}
|
||||
}
|
||||
|
||||
auto vector_array_ret = sparse_builder->Finish();
|
||||
if (!vector_array_ret.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"finish vector builder failed:", vector_array_ret.status().ToString()));
|
||||
}
|
||||
return vector_array_ret.MoveValueUnsafe();
|
||||
}
|
||||
|
||||
Result<std::shared_ptr<arrow::Array>> FetchVectorOp::fetch_sparse_vector(
|
||||
const Segment &segment, const std::string &vector_name,
|
||||
const std::vector<int> &rows) {
|
||||
auto indexer = segment.get_combined_vector_indexer(vector_name);
|
||||
if (!indexer) {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("vector index not found:", vector_name));
|
||||
}
|
||||
return fetch_sparse_vector_helper(indexer.get(), rows.begin(), rows.end());
|
||||
}
|
||||
|
||||
std::unique_ptr<cp::FunctionOptions> FetchVectorOp::FunctionOptionsType::Copy(
|
||||
const cp::FunctionOptions &) const {
|
||||
return std::make_unique<FetchVectorFunctionOptions>();
|
||||
}
|
||||
|
||||
arrow::Status FetchVectorOp::FetchVectorFunction(cp::KernelContext *ctx,
|
||||
const cp::ExecSpan &batch,
|
||||
cp::ExecResult *out) {
|
||||
FetchVectorState *state = static_cast<FetchVectorState *>(ctx->state());
|
||||
if (state->args.indexer == nullptr) {
|
||||
return arrow::Status::ExecutionError("indexer is null");
|
||||
}
|
||||
|
||||
auto row_span = batch[0].array.GetSpan<uint64_t>(1, batch.length);
|
||||
Result<std::shared_ptr<arrow::Array>> res;
|
||||
if (state->args.is_dense) {
|
||||
res = fetch_dense_vector_helper(state->args.indexer.get(), row_span.begin(),
|
||||
row_span.end());
|
||||
} else {
|
||||
res = fetch_sparse_vector_helper(state->args.indexer.get(),
|
||||
row_span.begin(), row_span.end());
|
||||
}
|
||||
if (!res) {
|
||||
return arrow::Status::ExecutionError("fetch vector failed:",
|
||||
res.error().c_str());
|
||||
}
|
||||
|
||||
out->value = std::move(res.value()->data());
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
FetchVectorOp::InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args) {
|
||||
auto func_options = static_cast<const FetchVectorOp::Options *>(args.options);
|
||||
return std::make_unique<FetchVectorOp::FetchVectorState>(
|
||||
func_options ? func_options : nullptr);
|
||||
}
|
||||
|
||||
|
||||
arrow::Status FetchVectorOp::register_op() {
|
||||
static Options options = Options::Defaults();
|
||||
{
|
||||
const std::string name = "fetch_vector";
|
||||
auto func = std::make_shared<cp::ScalarFunction>(name, cp::Arity::Unary(),
|
||||
func_doc, &options, false);
|
||||
cp::ScalarKernel kernel({arrow::uint64()}, arrow::binary(),
|
||||
FetchVectorFunction, InitExprValue);
|
||||
|
||||
kernel.mem_allocation = cp::MemAllocation::NO_PREALLOCATE;
|
||||
kernel.null_handling = cp::NullHandling::COMPUTED_NO_PREALLOCATE;
|
||||
|
||||
ARROW_RETURN_NOT_OK(func->AddKernel(std::move(kernel)));
|
||||
|
||||
auto registry = cp::GetFunctionRegistry();
|
||||
ARROW_RETURN_NOT_OK(registry->AddFunction(std::move(func)));
|
||||
}
|
||||
|
||||
{
|
||||
const std::string name = "fetch_sparse_vector";
|
||||
auto func = std::make_shared<cp::ScalarFunction>(name, cp::Arity::Unary(),
|
||||
func_doc, &options, false);
|
||||
cp::ScalarKernel kernel({arrow::uint64()}, Util::sparse_type(),
|
||||
FetchVectorFunction, InitExprValue);
|
||||
|
||||
kernel.mem_allocation = cp::MemAllocation::NO_PREALLOCATE;
|
||||
kernel.null_handling = cp::NullHandling::COMPUTED_NO_PREALLOCATE;
|
||||
|
||||
ARROW_RETURN_NOT_OK(func->AddKernel(std::move(kernel)));
|
||||
|
||||
auto registry = cp::GetFunctionRegistry();
|
||||
ARROW_RETURN_NOT_OK(registry->AddFunction(std::move(func)));
|
||||
}
|
||||
|
||||
return arrow::Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,183 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <arrow/api.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/column/vector_column/combined_vector_column_indexer.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
template <typename OptionsType>
|
||||
struct OptionsWrapper : public cp::KernelState {
|
||||
explicit OptionsWrapper(OptionsType options) : options(std::move(options)) {}
|
||||
|
||||
static arrow::Result<std::unique_ptr<KernelState>> Init(
|
||||
cp::KernelContext * /*ctx*/, const cp::KernelInitArgs &args) {
|
||||
if (auto options = static_cast<const OptionsType *>(args.options)) {
|
||||
return std::make_unique<OptionsWrapper>(*options);
|
||||
}
|
||||
|
||||
return arrow::Status::Invalid(
|
||||
"Attempted to initialize KernelState from null FunctionOptions");
|
||||
}
|
||||
|
||||
static const OptionsType &Get(const KernelState &state) {
|
||||
return ::arrow::internal::checked_cast<const OptionsWrapper &>(state)
|
||||
.options;
|
||||
}
|
||||
|
||||
static const OptionsType &Get(cp::KernelContext *ctx) {
|
||||
return Get(*ctx->state());
|
||||
}
|
||||
|
||||
OptionsType options;
|
||||
};
|
||||
|
||||
class FetchVectorOp {
|
||||
public:
|
||||
static Result<std::shared_ptr<arrow::Array>> fetch_dense_vector(
|
||||
const Segment &segment, const std::string &vector_name,
|
||||
const std::vector<int> &rows);
|
||||
|
||||
static Result<std::shared_ptr<arrow::Array>> fetch_sparse_vector(
|
||||
const Segment &segment, const std::string &vector_name,
|
||||
const std::vector<int> &rows);
|
||||
|
||||
static arrow::Status register_op();
|
||||
|
||||
class FunctionOptionsType : public cp::FunctionOptionsType {
|
||||
const char *type_name() const override {
|
||||
return "FetchVectorFunctionOptionsType";
|
||||
}
|
||||
|
||||
std::string Stringify(const cp::FunctionOptions &) const override {
|
||||
return "FetchVectorFunctionOptionsType";
|
||||
}
|
||||
|
||||
bool Compare(const cp::FunctionOptions &,
|
||||
const cp::FunctionOptions &) const override {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::unique_ptr<cp::FunctionOptions> Copy(
|
||||
const cp::FunctionOptions &) const override;
|
||||
// optional: support for serialization
|
||||
// Result<std::shared_ptr<Buffer>> Serialize(const FunctionOptions&) const
|
||||
// override; Result<std::unique_ptr<FunctionOptions>> Deserialize(const
|
||||
// Buffer&) const override;
|
||||
};
|
||||
|
||||
static cp::FunctionOptionsType *GetFetchVectorFunctionOptionsType() {
|
||||
static FunctionOptionsType options_type;
|
||||
return &options_type;
|
||||
}
|
||||
|
||||
class FetchVectorFunctionOptions : public cp::FunctionOptions {
|
||||
public:
|
||||
FetchVectorFunctionOptions()
|
||||
: cp::FunctionOptions(GetFetchVectorFunctionOptionsType()) {}
|
||||
};
|
||||
|
||||
class FetchVectorOptionsType : public arrow::compute::FunctionOptionsType {
|
||||
public:
|
||||
static const arrow::compute::FunctionOptionsType *GetInstance() {
|
||||
static std::unique_ptr<arrow::compute::FunctionOptionsType> instance(
|
||||
new FetchVectorOptionsType());
|
||||
return instance.get();
|
||||
}
|
||||
|
||||
const char *type_name() const override {
|
||||
return "FetchVector";
|
||||
}
|
||||
|
||||
std::string Stringify(
|
||||
const arrow::compute::FunctionOptions & /*options*/) const override {
|
||||
return type_name();
|
||||
}
|
||||
|
||||
bool Compare(const arrow::compute::FunctionOptions &options,
|
||||
const arrow::compute::FunctionOptions &other) const override {
|
||||
const auto &lop = static_cast<const Options &>(options);
|
||||
const auto &rop = static_cast<const Options &>(other);
|
||||
return lop.args.is_dense == rop.args.is_dense &&
|
||||
lop.args.indexer == rop.args.indexer;
|
||||
}
|
||||
|
||||
std::unique_ptr<arrow::compute::FunctionOptions> Copy(
|
||||
const arrow::compute::FunctionOptions &options) const override {
|
||||
const auto &opts = static_cast<const Options &>(options);
|
||||
return std::make_unique<Options>(opts.args.indexer, opts.args.is_dense);
|
||||
}
|
||||
};
|
||||
|
||||
struct Args {
|
||||
CombinedVectorColumnIndexer::Ptr indexer;
|
||||
bool is_dense{true};
|
||||
};
|
||||
|
||||
class Options : public cp::FunctionOptions {
|
||||
public:
|
||||
Options() : Options(nullptr, true) {}
|
||||
|
||||
Options(CombinedVectorColumnIndexer::Ptr indexer, bool is_dense)
|
||||
: cp::FunctionOptions(FetchVectorOptionsType::GetInstance()),
|
||||
args{indexer, is_dense} {}
|
||||
|
||||
static inline constexpr char const kTypeName[] =
|
||||
"FetchVectorFunctionOptions";
|
||||
|
||||
static Options Defaults() {
|
||||
return Options();
|
||||
}
|
||||
|
||||
Args get_args() const {
|
||||
return args;
|
||||
}
|
||||
|
||||
Args args;
|
||||
};
|
||||
|
||||
struct FetchVectorState : public arrow::compute::KernelState {
|
||||
Args args;
|
||||
|
||||
explicit FetchVectorState(const Options *o) {
|
||||
if (o) {
|
||||
args = o->get_args();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
static arrow::Status FetchVectorFunction(cp::KernelContext *ctx,
|
||||
const cp::ExecSpan &batch,
|
||||
cp::ExecResult *out);
|
||||
|
||||
static inline const cp::FunctionDoc func_doc{
|
||||
"fetch dense or sparse vector",
|
||||
"returns fetch_vector(x)",
|
||||
{"segment_row_id"},
|
||||
"Options",
|
||||
};
|
||||
|
||||
static arrow::Result<std::unique_ptr<arrow::compute::KernelState>>
|
||||
InitExprValue(arrow::compute::KernelContext *,
|
||||
const arrow::compute::KernelInitArgs &args);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,293 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "optimizer.h"
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "db/common/config.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/analyzer/query_info_helper.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/planner/invert_search.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
|
||||
Optimizer::Ptr InvertCondOptimizer::CreateInvertCondOptimizer(
|
||||
CollectionSchema *collection_schema) {
|
||||
return std::make_shared<InvertCondOptimizer>(collection_schema);
|
||||
}
|
||||
|
||||
// return true if invert cond should be convert to forward cond
|
||||
bool InvertCondOptimizer::ratio_rule(Segment *segment,
|
||||
QueryRelNode *invert_cond) {
|
||||
if (invert_cond == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (invert_cond->op() == QueryNodeOp::Q_LIKE ||
|
||||
invert_cond->op() == QueryNodeOp::Q_IN ||
|
||||
invert_cond->op() == QueryNodeOp::Q_CONTAIN_ANY ||
|
||||
invert_cond->op() == QueryNodeOp::Q_CONTAIN_ALL ||
|
||||
invert_cond->op() == QueryNodeOp::Q_EQ ||
|
||||
invert_cond->op() == QueryNodeOp::Q_NE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const QueryNode::Ptr &left = invert_cond->left();
|
||||
|
||||
const std::string column_name = left->text();
|
||||
auto invert_column_reader = segment->get_scalar_indexer(column_name);
|
||||
if (invert_column_reader == nullptr) {
|
||||
LOG_ERROR("Get invert column reader failed. invert_cond [%s]",
|
||||
invert_cond->text().c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
CompareOp oper = InvertSearch::query_nodeop2search_op(invert_cond->op());
|
||||
if (oper == CompareOp::NONE) {
|
||||
LOG_ERROR("Optimizer get search operator failed. invert_cond [%s]",
|
||||
invert_cond->text().c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string invert_term = invert_cond->right()->text();
|
||||
|
||||
float invert_to_forward_scan_ratio =
|
||||
GlobalConfig::Instance().invert_to_forward_scan_ratio();
|
||||
|
||||
uint64_t total_size = 0;
|
||||
uint64_t range_size = 0;
|
||||
Status status = invert_column_reader->evaluate_ratio(
|
||||
invert_term, oper, &total_size, &range_size);
|
||||
if (!status.ok()) {
|
||||
LOG_WARN("Optimizer evaluate failed. invert_cond [%s] err[%s]",
|
||||
invert_cond->text().c_str(), status.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
float ratio = 0.0;
|
||||
if (total_size > 0) {
|
||||
ratio = (range_size * 1.0) / total_size;
|
||||
}
|
||||
|
||||
if (ratio < invert_to_forward_scan_ratio) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG_DEBUG(
|
||||
"Optimizer evaluate result reach threshold. "
|
||||
"invert_cond [%s] total_size[%zu] range_size[%zu] ratio[%f]",
|
||||
invert_cond->text().c_str(), (size_t)total_size, (size_t)range_size,
|
||||
ratio);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// return true if ratio rule return false, meaning invert cond no need to be
|
||||
// optimized by ratio rule and still keep as invert cond is
|
||||
bool InvertCondOptimizer::invert_rule(Segment *segment,
|
||||
QueryRelNode *invert_cond) {
|
||||
return !ratio_rule(segment, invert_cond);
|
||||
}
|
||||
|
||||
void InvertCondOptimizer::convert_invert_cond_to_forward(
|
||||
QueryInfo *query_info, QueryNode *invert_cond) {
|
||||
if (invert_cond == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (invert_cond->type() == QueryNode::QueryNodeType::REL_EXPR) {
|
||||
// convert invert cond to forward cond
|
||||
QueryRelNode *query_rel_node =
|
||||
reinterpret_cast<QueryRelNode *>(invert_cond);
|
||||
|
||||
const QueryNode::Ptr &left = query_rel_node->left();
|
||||
const QueryNode::Ptr &right = query_rel_node->right();
|
||||
|
||||
const std::string column_name = left->text();
|
||||
|
||||
query_rel_node->set_forward();
|
||||
|
||||
// 1. add column to forward field
|
||||
auto forward_field = collection_schema_->get_forward_field(column_name);
|
||||
DataType data_type = forward_field->element_data_type();
|
||||
// currently array invert field won't be converted to forward
|
||||
// bool is_array_type = forward_field->is_array_type();
|
||||
query_info->add_forward_filter_schema_ptr(column_name,
|
||||
std::move(forward_field));
|
||||
|
||||
// 2. Revert numeric buf to numeric text
|
||||
std::string numeric_text{""};
|
||||
if (QueryInfoHelper::data_buf_2_text(right->text(), data_type,
|
||||
&numeric_text)) {
|
||||
right->set_text(numeric_text);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
convert_invert_cond_to_forward(query_info, invert_cond->left().get());
|
||||
convert_invert_cond_to_forward(query_info, invert_cond->right().get());
|
||||
}
|
||||
|
||||
|
||||
void InvertCondOptimizer::check_node_except_subroot(QueryNode *invert_cond,
|
||||
QueryNode *invert_subroot,
|
||||
bool *rest_has_invert) {
|
||||
if (invert_cond == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
// skip subroot
|
||||
if (invert_subroot != nullptr && invert_cond == invert_subroot) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (invert_cond->type() == QueryNode::QueryNodeType::REL_EXPR) {
|
||||
QueryRelNode *query_rel_node =
|
||||
reinterpret_cast<QueryRelNode *>(invert_cond);
|
||||
if (query_rel_node->rule_result()) {
|
||||
*rest_has_invert = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
check_node_except_subroot(invert_cond->left().get(), invert_subroot,
|
||||
rest_has_invert);
|
||||
if (*rest_has_invert) {
|
||||
return;
|
||||
}
|
||||
check_node_except_subroot(invert_cond->right().get(), invert_subroot,
|
||||
rest_has_invert);
|
||||
}
|
||||
|
||||
bool InvertCondOptimizer::apply_optimize_result(QueryInfo *query_info,
|
||||
QueryNode *invert_subroot) {
|
||||
// case 1. invert subroot same as invert cond, do nothing
|
||||
if (invert_subroot == query_info->invert_cond().get()) {
|
||||
LOG_DEBUG("No need to move to forward, invert conds are all eligable. ");
|
||||
return false;
|
||||
}
|
||||
|
||||
// case 2. invert subroot is not found
|
||||
if (invert_subroot == nullptr) {
|
||||
// That invert_subroot is nullptr may means different scenarios,
|
||||
// 1. All invert conditions should be converted to forward condition
|
||||
// according to optimize rule.
|
||||
// 2. Some invert condition should be converted to forward, which result in
|
||||
// left invert conditions are not able to be invert condition any more, eg:
|
||||
// A or B B won't be invert cond after A converted to forward. We need only
|
||||
// to optimize scenario 1, and leave scenario 2 untouched. Achieve the check
|
||||
// also by check_node_except_subroot same as in case 3.
|
||||
|
||||
bool rest_has_invert = false;
|
||||
check_node_except_subroot(query_info->invert_cond().get(), nullptr,
|
||||
&rest_has_invert);
|
||||
if (rest_has_invert) {
|
||||
LOG_DEBUG(
|
||||
"invert_subroot is not found, but failed in "
|
||||
"check_node_except_subroot");
|
||||
return false;
|
||||
}
|
||||
|
||||
QueryNode::Ptr subroot_ptr = query_info->invert_cond();
|
||||
|
||||
query_info->set_invert_cond(nullptr);
|
||||
|
||||
// convert invert cond to forward cond
|
||||
convert_invert_cond_to_forward(query_info, subroot_ptr.get());
|
||||
|
||||
// move to forward cond
|
||||
if (query_info->filter_cond() == nullptr) {
|
||||
query_info->set_filter_cond(std::move(subroot_ptr));
|
||||
} else {
|
||||
QueryNode::Ptr filter_node = std::make_shared<QueryNode>();
|
||||
filter_node->set_op(QueryNodeOp::Q_AND);
|
||||
filter_node->set_left(query_info->filter_cond());
|
||||
filter_node->set_right(std::move(subroot_ptr));
|
||||
query_info->set_filter_cond(std::move(filter_node));
|
||||
}
|
||||
|
||||
LOG_DEBUG("All invert conds moved to forward cond. forward conds [%s]",
|
||||
query_info->filter_cond()->text().c_str());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// case 3. subroot is found and be part of invert cond
|
||||
LOG_DEBUG(
|
||||
"find invert_subroot in invert cond. "
|
||||
"invert cond [%s] and invert_subroot [%s]. ",
|
||||
query_info->invert_cond()->text().c_str(),
|
||||
invert_subroot->text().c_str());
|
||||
|
||||
// If other nodes outside invert subroot still be invert cond,
|
||||
// these nodes should not be convert to forward cond. Not to optimize.
|
||||
bool rest_has_invert = false;
|
||||
check_node_except_subroot(query_info->invert_cond().get(), invert_subroot,
|
||||
&rest_has_invert);
|
||||
if (rest_has_invert) {
|
||||
LOG_DEBUG("invert_subroot failed in check_node_except_subroot");
|
||||
return false;
|
||||
}
|
||||
|
||||
QueryNode::Ptr invert_subroot_ptr =
|
||||
invert_subroot->detach_from_invert_cond(query_info);
|
||||
|
||||
QueryNode::Ptr invert2forward = query_info->invert_cond();
|
||||
|
||||
// convert rest of invert cond to forward cond
|
||||
convert_invert_cond_to_forward(query_info, invert2forward.get());
|
||||
|
||||
// move to forward cond
|
||||
if (query_info->filter_cond() == nullptr) {
|
||||
query_info->set_filter_cond(std::move(invert2forward));
|
||||
} else {
|
||||
QueryNode::Ptr filter_node = std::make_shared<QueryNode>();
|
||||
filter_node->set_op(QueryNodeOp::Q_AND);
|
||||
filter_node->set_left(query_info->filter_cond());
|
||||
filter_node->set_right(std::move(invert2forward));
|
||||
query_info->set_filter_cond(std::move(filter_node));
|
||||
}
|
||||
|
||||
// set subroot as invert cond
|
||||
query_info->set_invert_cond(std::move(invert_subroot_ptr));
|
||||
|
||||
LOG_DEBUG("Optimized. forward cond [%s], invert cond [%s]. ",
|
||||
query_info->filter_cond()->text().c_str(),
|
||||
query_info->invert_cond()->text().c_str());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool InvertCondOptimizer::optimize(Segment *segment, QueryInfo *query_info) {
|
||||
auto invert_cond = query_info->invert_cond();
|
||||
// TODO: check if support optimize for mutable
|
||||
if (invert_cond == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// find invert subroot after considering ratio rule,
|
||||
// specifically, which invert cond subroot is still eligable.
|
||||
SubRootResult invert_subroot;
|
||||
std::function<bool(QueryRelNode * node)> rule = std::bind(
|
||||
&InvertCondOptimizer::invert_rule, this, segment, std::placeholders::_1);
|
||||
QueryInfoHelper::find_subroot_by_rule(invert_cond.get(), rule,
|
||||
&invert_subroot);
|
||||
|
||||
return apply_optimize_result(query_info, invert_subroot.subroot);
|
||||
;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,62 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "db/index/segment/segment.h"
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class Optimizer {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<Optimizer>;
|
||||
|
||||
virtual bool optimize(Segment *segment, QueryInfo *query_info) = 0;
|
||||
};
|
||||
|
||||
class InvertCondOptimizer : public Optimizer {
|
||||
public:
|
||||
explicit InvertCondOptimizer(CollectionSchema *collection_schema)
|
||||
: collection_schema_(collection_schema) {}
|
||||
|
||||
virtual ~InvertCondOptimizer() = default;
|
||||
|
||||
public:
|
||||
static Optimizer::Ptr CreateInvertCondOptimizer(
|
||||
CollectionSchema *collection_schema);
|
||||
|
||||
public:
|
||||
bool optimize(Segment *segment, QueryInfo *query_info) override;
|
||||
|
||||
protected:
|
||||
virtual bool invert_rule(Segment *segment, QueryRelNode *invert_cond);
|
||||
|
||||
private:
|
||||
bool ratio_rule(Segment *segment, QueryRelNode *invert_cond);
|
||||
|
||||
bool apply_optimize_result(QueryInfo *query_info, QueryNode *invert_subroot);
|
||||
|
||||
void convert_invert_cond_to_forward(QueryInfo *query_info,
|
||||
QueryNode *invert_cond);
|
||||
|
||||
void check_node_except_subroot(QueryNode *invert_cond,
|
||||
QueryNode *invert_subroot,
|
||||
bool *rest_has_invert);
|
||||
|
||||
private:
|
||||
CollectionSchema *collection_schema_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "plan_info.h"
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/api.h>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "db/common/error_code.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
Result<std::unique_ptr<arrow::RecordBatchReader>>
|
||||
PlanInfo::execute_to_reader() {
|
||||
auto res = arrow::acero::DeclarationToReader(plan_);
|
||||
if (!res.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"execute plan_info failed: ", res.status().ToString()));
|
||||
}
|
||||
return res.MoveValueUnsafe();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/acero/exec_plan.h>
|
||||
#include "db/common/status.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class PlanInfo {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<PlanInfo>;
|
||||
|
||||
PlanInfo(arrow::acero::Declaration plan,
|
||||
std::shared_ptr<arrow::Schema> schema)
|
||||
: plan_(std::move(plan)), schema_(std::move(schema)) {}
|
||||
|
||||
Result<std::unique_ptr<arrow::RecordBatchReader>> execute_to_reader();
|
||||
|
||||
std::shared_ptr<arrow::Schema> schema() const {
|
||||
return schema_;
|
||||
}
|
||||
|
||||
private:
|
||||
arrow::acero::Declaration plan_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,626 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "query_planner.h"
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/parallel/thread_pool.h>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/compute/api.h>
|
||||
#include "analyzer/query_info.h"
|
||||
#include "analyzer/query_node.h"
|
||||
#include "db/common/constants.h"
|
||||
#include "db/common/global_resource.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/planner/invert_recall_node.h"
|
||||
#include "db/sqlengine/planner/ops/check_not_filtered_op.h"
|
||||
#include "db/sqlengine/planner/ops/contain_op.h"
|
||||
#include "db/sqlengine/planner/ops/fetch_vector_op.h"
|
||||
#include "db/sqlengine/planner/segment_node.h"
|
||||
#include "db/sqlengine/planner/vector_recall_node.h"
|
||||
#include "planner/plan_info.h"
|
||||
#include "optimizer.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
namespace cp = ::arrow::compute;
|
||||
namespace ac = ::arrow::acero;
|
||||
|
||||
QueryPlanner::QueryPlanner(CollectionSchema *schema) : schema_(schema) {}
|
||||
|
||||
template <typename T>
|
||||
auto convert_node_to_value(const QueryNode::Ptr &node) {
|
||||
const std::string &str = node->text();
|
||||
T value;
|
||||
if constexpr (std::is_same_v<T, int32_t>) {
|
||||
ailego::StringHelper::ToInt32(str, &value);
|
||||
} else if constexpr (std::is_same_v<T, int64_t>) {
|
||||
ailego::StringHelper::ToInt64(str, &value);
|
||||
} else if constexpr (std::is_same_v<T, uint32_t>) {
|
||||
ailego::StringHelper::ToUint32(str, &value);
|
||||
} else if constexpr (std::is_same_v<T, uint64_t>) {
|
||||
ailego::StringHelper::ToUint64(str, &value);
|
||||
} else if constexpr (std::is_same_v<T, float>) {
|
||||
ailego::StringHelper::ToFloat(str, &value);
|
||||
} else if constexpr (std::is_same_v<T, double>) {
|
||||
ailego::StringHelper::ToDouble(str, &value);
|
||||
} else {
|
||||
static_assert(!std::is_same_v<T, T>, "Unsupported type for conversion");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
template <typename ArrowType>
|
||||
arrow::Result<std::shared_ptr<arrow::Array>> to_arrow_array(
|
||||
const std::vector<QueryNode::Ptr> &input) {
|
||||
using CType = typename ArrowType::c_type;
|
||||
typename arrow::TypeTraits<ArrowType>::BuilderType builder;
|
||||
ARROW_RETURN_NOT_OK(builder.Reserve(input.size()));
|
||||
|
||||
for (auto &s : input) {
|
||||
ARROW_RETURN_NOT_OK(builder.Append(convert_node_to_value<CType>(s)));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&array));
|
||||
return array;
|
||||
}
|
||||
|
||||
arrow::Result<std::shared_ptr<arrow::Array>> to_arrow_string_array(
|
||||
const std::vector<QueryNode::Ptr> &input) {
|
||||
arrow::StringBuilder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.Reserve(input.size()));
|
||||
|
||||
for (auto &s : input) {
|
||||
ARROW_RETURN_NOT_OK(builder.Append(s->text()));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&array));
|
||||
return array;
|
||||
}
|
||||
|
||||
arrow::Result<std::shared_ptr<arrow::Array>> to_arrow_bool_array(
|
||||
const std::vector<QueryNode::Ptr> &input) {
|
||||
arrow::BooleanBuilder builder;
|
||||
ARROW_RETURN_NOT_OK(builder.Reserve(input.size()));
|
||||
|
||||
for (auto &s : input) {
|
||||
// input is normalized to "true" or "false"
|
||||
ARROW_RETURN_NOT_OK(builder.Append(s->text() == "true"));
|
||||
}
|
||||
|
||||
std::shared_ptr<arrow::Array> array;
|
||||
ARROW_RETURN_NOT_OK(builder.Finish(&array));
|
||||
return array;
|
||||
}
|
||||
|
||||
arrow::Result<std::shared_ptr<arrow::Array>> create_array_from_list_node(
|
||||
DataType data_type, const QueryListNode *list_node) {
|
||||
auto const &value_expr_list = list_node->value_expr_list();
|
||||
switch (data_type) {
|
||||
case DataType::INT32:
|
||||
return to_arrow_array<arrow::Int32Type>(value_expr_list);
|
||||
case DataType::UINT32:
|
||||
return to_arrow_array<arrow::UInt32Type>(value_expr_list);
|
||||
case DataType::INT64:
|
||||
return to_arrow_array<arrow::Int64Type>(value_expr_list);
|
||||
case DataType::UINT64:
|
||||
return to_arrow_array<arrow::UInt64Type>(value_expr_list);
|
||||
case DataType::FLOAT:
|
||||
return to_arrow_array<arrow::FloatType>(value_expr_list);
|
||||
case DataType::DOUBLE:
|
||||
return to_arrow_array<arrow::DoubleType>(value_expr_list);
|
||||
case DataType::STRING:
|
||||
return to_arrow_string_array(value_expr_list);
|
||||
case DataType::BOOL:
|
||||
return to_arrow_bool_array(value_expr_list);
|
||||
default:
|
||||
LOG_ERROR("Unsupported data type for list node. %d", (int)data_type);
|
||||
return arrow::Status::Invalid("Unsupported data type for list node.");
|
||||
}
|
||||
}
|
||||
|
||||
Result<cp::Expression> QueryPlanner::create_filter_node(
|
||||
const QueryNode *query_node) {
|
||||
const QueryNode *left = query_node->left_node();
|
||||
const QueryNode *right = query_node->right_node();
|
||||
|
||||
arrow::Expression left_exp;
|
||||
DataType data_type;
|
||||
if (left->op() == QueryNodeOp::Q_ID) {
|
||||
left_exp = cp::field_ref(left->text());
|
||||
auto field_schema = schema_->get_forward_field(left->text());
|
||||
data_type = field_schema->data_type();
|
||||
} else if (left->op() == QueryNodeOp::Q_FUNCTION_CALL) {
|
||||
const QueryFuncNode *func_node = dynamic_cast<const QueryFuncNode *>(left);
|
||||
const auto &func_name = func_node->get_func_name_node()->text();
|
||||
const auto &arguments = func_node->arguments();
|
||||
if (func_name == kFuncArrayLength) {
|
||||
left_exp =
|
||||
cp::call("list_value_length", {cp::field_ref(arguments[0]->text())});
|
||||
// assume array_length argument is uint32
|
||||
data_type = DataType::UINT32;
|
||||
} else {
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unexpected function call", func_name));
|
||||
}
|
||||
} else {
|
||||
LOG_ERROR("Unexpected left op. expr[%s]", query_node->text().c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unexpected left op", left->text()));
|
||||
}
|
||||
|
||||
cp::Expression right_exp;
|
||||
const std::string &filter_value = right->text();
|
||||
auto op = query_node->op();
|
||||
if (op == QueryNodeOp::Q_IS_NULL) {
|
||||
return cp::is_null(std::move(left_exp));
|
||||
} else if (op == QueryNodeOp::Q_IS_NOT_NULL) {
|
||||
return cp::is_valid(std::move(left_exp));
|
||||
}
|
||||
|
||||
// TODO: check invalid filter
|
||||
if (op == QueryNodeOp::Q_IN || op == QueryNodeOp::Q_CONTAIN_ALL ||
|
||||
op == QueryNodeOp::Q_CONTAIN_ANY) {
|
||||
const QueryListNode *list_node = dynamic_cast<const QueryListNode *>(right);
|
||||
auto array_res = create_array_from_list_node(
|
||||
FieldSchema::get_element_data_type(data_type), list_node);
|
||||
if (!array_res.ok()) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"create array failed", array_res.status().ToString()));
|
||||
}
|
||||
if (op == QueryNodeOp::Q_IN) {
|
||||
auto in_filter = cp::call(
|
||||
"is_in", {std::move(left_exp)},
|
||||
std::make_shared<cp::SetLookupOptions>(array_res.MoveValueUnsafe()));
|
||||
if (list_node->exclude()) {
|
||||
return cp::not_(std::move(in_filter));
|
||||
}
|
||||
return in_filter;
|
||||
}
|
||||
auto contain_filter =
|
||||
cp::call(op == QueryNodeOp::Q_CONTAIN_ALL ? kContainAll : kContainAny,
|
||||
{std::move(left_exp)},
|
||||
std::make_shared<ContainOp::Options>(
|
||||
ContainOp::Args{array_res.MoveValueUnsafe(), data_type}));
|
||||
if (list_node->exclude()) {
|
||||
return cp::not_(std::move(contain_filter));
|
||||
}
|
||||
return contain_filter;
|
||||
}
|
||||
|
||||
switch (data_type) {
|
||||
case DataType::STRING: {
|
||||
if (op == sqlengine::QueryNodeOp::Q_LIKE) {
|
||||
return cp::call("match_like", {std::move(left_exp)},
|
||||
cp::MatchSubstringOptions(filter_value));
|
||||
} else {
|
||||
right_exp = cp::literal(filter_value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case DataType::INT32: {
|
||||
int32_t int32_value;
|
||||
ailego::StringHelper::ToInt32(filter_value, &int32_value);
|
||||
right_exp = cp::literal(int32_value);
|
||||
break;
|
||||
}
|
||||
case DataType::UINT32: {
|
||||
uint32_t uint32_value;
|
||||
ailego::StringHelper::ToUint32(filter_value, &uint32_value);
|
||||
right_exp = cp::literal(uint32_value);
|
||||
break;
|
||||
}
|
||||
case DataType::INT64: {
|
||||
int64_t int64_value;
|
||||
ailego::StringHelper::ToInt64(filter_value, &int64_value);
|
||||
right_exp = cp::literal(int64_value);
|
||||
break;
|
||||
}
|
||||
case DataType::UINT64: {
|
||||
uint64_t uint64_value;
|
||||
ailego::StringHelper::ToUint64(filter_value, &uint64_value);
|
||||
right_exp = cp::literal(uint64_value);
|
||||
break;
|
||||
}
|
||||
case DataType::FLOAT: {
|
||||
float float_value;
|
||||
ailego::StringHelper::ToFloat(filter_value, &float_value);
|
||||
right_exp = cp::literal(float_value);
|
||||
break;
|
||||
}
|
||||
case DataType::DOUBLE: {
|
||||
double double_value;
|
||||
ailego::StringHelper::ToDouble(filter_value, &double_value);
|
||||
right_exp = cp::literal(double_value);
|
||||
break;
|
||||
}
|
||||
case DataType::BOOL: {
|
||||
std::string lower_filter_value;
|
||||
lower_filter_value.resize(filter_value.size());
|
||||
bool bool_value;
|
||||
std::transform(filter_value.begin(), filter_value.end(),
|
||||
lower_filter_value.begin(), ::tolower);
|
||||
if (lower_filter_value == "true") {
|
||||
bool_value = true;
|
||||
} else if (lower_filter_value == "false") {
|
||||
bool_value = false;
|
||||
} else {
|
||||
LOG_ERROR("Unrecognized bool value: %s", filter_value.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unexpected bool value", filter_value));
|
||||
}
|
||||
right_exp = cp::literal(bool_value);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
LOG_ERROR("filter to data type is not supported.");
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"filter to data type is not supported", data_type));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (op) {
|
||||
case sqlengine::QueryNodeOp::Q_EQ:
|
||||
return cp::equal(std::move(left_exp), std::move(right_exp));
|
||||
case sqlengine::QueryNodeOp::Q_NE:
|
||||
return cp::not_equal(std::move(left_exp), std::move(right_exp));
|
||||
case sqlengine::QueryNodeOp::Q_GT:
|
||||
return cp::greater(std::move(left_exp), std::move(right_exp));
|
||||
case sqlengine::QueryNodeOp::Q_LT:
|
||||
return cp::less(std::move(left_exp), std::move(right_exp));
|
||||
case sqlengine::QueryNodeOp::Q_GE:
|
||||
return cp::greater_equal(std::move(left_exp), std::move(right_exp));
|
||||
case sqlengine::QueryNodeOp::Q_LE:
|
||||
return cp::less_equal(std::move(left_exp), std::move(right_exp));
|
||||
// NOTE: Q_LIKE already handled above
|
||||
|
||||
default:
|
||||
return tl::make_unexpected(Status::InvalidArgument("unexpected op", op));
|
||||
break;
|
||||
}
|
||||
return tl::make_unexpected(Status::InvalidArgument("unexpected op", op));
|
||||
}
|
||||
|
||||
Result<cp::Expression> QueryPlanner::parse_filter(const QueryNode *query_node) {
|
||||
if (!query_node) {
|
||||
return cp::literal(true);
|
||||
}
|
||||
if (query_node->type() == QueryNode::QueryNodeType::REL_EXPR) {
|
||||
return create_filter_node(query_node);
|
||||
}
|
||||
if (query_node->type() == QueryNode::QueryNodeType::LOGIC_EXPR) {
|
||||
auto left = parse_filter(query_node->left_node());
|
||||
if (!left) {
|
||||
return left;
|
||||
}
|
||||
auto right = parse_filter(query_node->right_node());
|
||||
if (!right) {
|
||||
return right;
|
||||
}
|
||||
if (query_node->op() == QueryNodeOp::Q_AND) {
|
||||
return cp::and_(std::move(left.value()), std::move(right.value()));
|
||||
} else if (query_node->op() == QueryNodeOp::Q_OR) {
|
||||
return cp::or_(std::move(left.value()), std::move(right.value()));
|
||||
}
|
||||
}
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("unexpected ", query_node->text()));
|
||||
}
|
||||
|
||||
|
||||
Result<PlanInfo::Ptr> QueryPlanner::make_plan(
|
||||
const std::vector<Segment::Ptr> &segments, const std::string &trace_id,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos) {
|
||||
// make logic plan from query_info
|
||||
// PlanInfo::Ptr logical_plan = make_logical_plan(query_info);
|
||||
|
||||
// do logic optimization here
|
||||
|
||||
// as we don't have logic optimization in a period of time,
|
||||
// simply make physical plan directly from query info
|
||||
return make_physical_plan(segments, trace_id, query_infos);
|
||||
}
|
||||
|
||||
Result<PlanInfo::Ptr> QueryPlanner::make_physical_plan(
|
||||
const std::vector<Segment::Ptr> &segments, const std::string & /*trace_id*/,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos) {
|
||||
const std::string &table_name = schema_->name();
|
||||
if (segments.empty()) {
|
||||
LOG_ERROR("Segment not found [%s]", table_name.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("segment not found:", table_name));
|
||||
}
|
||||
|
||||
QueryInfo *query_info = (*query_infos)[0].get();
|
||||
LOG_DEBUG("Making plan for collection[%s] query_info[%s]", table_name.c_str(),
|
||||
query_info->to_string().c_str());
|
||||
int topn = query_info->query_topn();
|
||||
auto vector_cond = query_info->vector_cond_info();
|
||||
bool has_group_by = query_info->group_by() != nullptr;
|
||||
|
||||
// optimize plan by instrument query info condition, eg adjust invert cond
|
||||
Optimizer::Ptr optimizer =
|
||||
InvertCondOptimizer::CreateInvertCondOptimizer(schema_);
|
||||
int num_segments = segments.size();
|
||||
std::vector<PlanInfo::Ptr> segment_plans(segments.size());
|
||||
for (int idx = 0; idx < num_segments; ++idx) {
|
||||
auto &segment = segments[idx];
|
||||
auto &segment_query_info = (*query_infos)[idx];
|
||||
bool only_invert_before_opt =
|
||||
segment_query_info->invert_cond() != nullptr &&
|
||||
segment_query_info->filter_cond() == nullptr;
|
||||
if (optimizer) {
|
||||
// Optimize by change query info if needed.
|
||||
if (!optimizer->optimize(segment.get(), segment_query_info.get())) {
|
||||
LOG_DEBUG(
|
||||
"Not optimized. collection[%s] segment[%zu] "
|
||||
"segment_query_info[%s]",
|
||||
table_name.c_str(), (size_t)segment->id(),
|
||||
segment_query_info->to_string().c_str());
|
||||
} else {
|
||||
LOG_DEBUG(
|
||||
"Optimized. collection[%s] segment[%zu] segment_query_info[%s]",
|
||||
table_name.c_str(), (size_t)segment->id(),
|
||||
segment_query_info->to_string().c_str());
|
||||
}
|
||||
}
|
||||
bool only_forward_after_opt =
|
||||
segment_query_info->invert_cond() == nullptr &&
|
||||
segment_query_info->filter_cond() != nullptr;
|
||||
// if only invert cond before opt and only forward cond after opt,
|
||||
// single stage search should be performed as large ratio of docs match
|
||||
// with filter
|
||||
bool single_stage_search = only_invert_before_opt && only_forward_after_opt;
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter;
|
||||
if (query_info->filter_cond()) {
|
||||
auto filter = parse_filter(query_info->filter_cond().get());
|
||||
if (!filter) {
|
||||
LOG_ERROR("Parse filter failed: %s", filter.error().c_str());
|
||||
return tl::make_unexpected(filter.error());
|
||||
}
|
||||
forward_filter =
|
||||
std::make_unique<cp::Expression>(std::move(filter.value()));
|
||||
}
|
||||
|
||||
Result<PlanInfo::Ptr> seg_plan;
|
||||
if (query_info->vector_cond_info()) {
|
||||
seg_plan = vector_scan(segment, std::move(segment_query_info),
|
||||
std::move(forward_filter), single_stage_search);
|
||||
} else if (query_info->invert_cond()) {
|
||||
seg_plan = invert_scan(segment, std::move(segment_query_info),
|
||||
std::move(forward_filter));
|
||||
} else {
|
||||
seg_plan = forward_scan(segment, std::move(segment_query_info),
|
||||
std::move(forward_filter));
|
||||
}
|
||||
if (!seg_plan) {
|
||||
LOG_ERROR("Make plan failed: %s", seg_plan.error().c_str());
|
||||
return seg_plan;
|
||||
}
|
||||
if (segments.size() == 1) {
|
||||
return seg_plan;
|
||||
}
|
||||
segment_plans[idx] = std::move(seg_plan.value());
|
||||
}
|
||||
|
||||
// multi segment logic
|
||||
ailego::ThreadPool *pool = GlobalResource::Instance().query_thread_pool();
|
||||
auto recall_node =
|
||||
std::make_shared<SegmentNode>(std::move(segment_plans), pool);
|
||||
auto source_node_options =
|
||||
arrow::acero::SourceNodeOptions{recall_node->schema(), recall_node->gen(),
|
||||
arrow::compute::Ordering::Implicit()};
|
||||
ac::Declaration node{"source", source_node_options};
|
||||
|
||||
if (vector_cond) {
|
||||
node = ac::Declaration{"order_by",
|
||||
{std::move(node)},
|
||||
ac::OrderByNodeOptions{cp::Ordering{{cp::SortKey{
|
||||
kFieldScore, vector_cond->is_reverse_sort()
|
||||
? cp::SortOrder::Descending
|
||||
: cp::SortOrder::Ascending}}}}};
|
||||
}
|
||||
|
||||
// group by need to collect all docs
|
||||
if (!has_group_by) {
|
||||
node = ac::Declaration{
|
||||
"fetch", {std::move(node)}, ac::FetchNodeOptions{0, topn}};
|
||||
}
|
||||
return std::make_shared<PlanInfo>(std::move(node), recall_node->schema());
|
||||
}
|
||||
|
||||
Result<PlanInfo::Ptr> QueryPlanner::forward_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter) {
|
||||
auto reader = seg->scan(query_info->get_all_fetched_scalar_field_names());
|
||||
auto schema = reader->schema();
|
||||
ac::Declaration node{
|
||||
"record_batch_reader_source",
|
||||
ac::RecordBatchReaderSourceNodeOptions{std::move(reader)}};
|
||||
|
||||
auto seg_filter = seg->get_filter();
|
||||
if (seg_filter) {
|
||||
cp::Expression check_not_filtered =
|
||||
cp::call(kCheckNotFiltered, {cp::field_ref(LOCAL_ROW_ID)},
|
||||
std::make_shared<CheckNotFilteredOp::Options>(seg_filter));
|
||||
node =
|
||||
ac::Declaration{"filter",
|
||||
{std::move(node)},
|
||||
ac::FilterNodeOptions(std::move(check_not_filtered))};
|
||||
}
|
||||
|
||||
if (forward_filter) {
|
||||
node = ac::Declaration{"filter",
|
||||
{std::move(node)},
|
||||
ac::FilterNodeOptions(std::move(*forward_filter))};
|
||||
}
|
||||
|
||||
if (query_info->is_include_vector()) {
|
||||
std::vector<cp::Expression> expressions;
|
||||
std::vector<std::string> names =
|
||||
query_info->get_all_fetched_scalar_field_names();
|
||||
for (const auto &field_name : names) {
|
||||
expressions.emplace_back(cp::field_ref(field_name));
|
||||
}
|
||||
for (const auto &vector_field : query_info->selected_vector_fields()) {
|
||||
auto indexer = seg->get_combined_vector_indexer(vector_field.field_name);
|
||||
if (!indexer) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"vector indexer not found:", vector_field.field_name));
|
||||
}
|
||||
if (vector_field.field_schema_ptr->is_dense_vector()) {
|
||||
expressions.emplace_back(
|
||||
cp::call("fetch_vector", {cp::field_ref(LOCAL_ROW_ID)},
|
||||
std::make_shared<FetchVectorOp::Options>(indexer, true)));
|
||||
schema = Util::append_field(*schema, vector_field.field_name,
|
||||
arrow::binary());
|
||||
} else {
|
||||
expressions.emplace_back(
|
||||
cp::call("fetch_sparse_vector", {cp::field_ref(LOCAL_ROW_ID)},
|
||||
std::make_shared<FetchVectorOp::Options>(indexer, false)));
|
||||
schema = Util::append_field(*schema, vector_field.field_name,
|
||||
Util::sparse_type());
|
||||
}
|
||||
names.emplace_back(vector_field.field_name);
|
||||
}
|
||||
node = ac::Declaration{
|
||||
"project",
|
||||
{std::move(node)},
|
||||
ac::ProjectNodeOptions{std::move(expressions), std::move(names)}};
|
||||
}
|
||||
|
||||
node = ac::Declaration{"fetch",
|
||||
{std::move(node)},
|
||||
ac::FetchNodeOptions{0, query_info->query_topn()}};
|
||||
return std::make_shared<PlanInfo>(std::move(node), std::move(schema));
|
||||
}
|
||||
|
||||
Result<PlanInfo::Ptr> QueryPlanner::vector_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter,
|
||||
bool single_stage_search) {
|
||||
std::unique_ptr<ac::Declaration> forward_filter_plan;
|
||||
// if single stage search is not enabled, first run acero plan to get
|
||||
// forward bitmap, then filter during vector search. otherwise, filter
|
||||
// forward during forward search.
|
||||
if (forward_filter && !single_stage_search) {
|
||||
ac::RecordBatchReaderSourceNodeOptions source_options{
|
||||
seg->scan(query_info->get_forward_filter_field_names())};
|
||||
forward_filter_plan.reset(new ac::Declaration{ac::Declaration::Sequence({
|
||||
{"record_batch_reader_source", std::move(source_options)},
|
||||
{
|
||||
"project",
|
||||
ac::ProjectNodeOptions{{std::move(*forward_filter)},
|
||||
{kFieldIsValid}},
|
||||
},
|
||||
})});
|
||||
forward_filter.reset();
|
||||
}
|
||||
auto doc_filter = std::make_shared<DocFilter>(seg, query_info,
|
||||
std::move(forward_filter_plan),
|
||||
std::move(forward_filter));
|
||||
|
||||
int topn = query_info->query_topn();
|
||||
int batch_size = get_batch_size(*query_info, false);
|
||||
auto recall_node = std::make_shared<VectorRecallNode>(
|
||||
std::move(seg), std::move(query_info), std::move(doc_filter), batch_size,
|
||||
single_stage_search);
|
||||
|
||||
auto source_node_options =
|
||||
arrow::acero::SourceNodeOptions{recall_node->schema(), recall_node->gen(),
|
||||
arrow::compute::Ordering::Implicit()};
|
||||
ac::Declaration node{"source", source_node_options};
|
||||
// group by need to collect all docs
|
||||
if (!recall_node->query_info()->group_by()) {
|
||||
node = ac::Declaration{
|
||||
"fetch", {std::move(node)}, ac::FetchNodeOptions{0, topn}};
|
||||
}
|
||||
return std::make_shared<PlanInfo>(std::move(node), recall_node->schema());
|
||||
}
|
||||
|
||||
Result<PlanInfo::Ptr> QueryPlanner::invert_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter) {
|
||||
auto topn = query_info->query_topn();
|
||||
int batch_size = get_batch_size(*query_info, forward_filter != nullptr);
|
||||
auto recall_node =
|
||||
std::make_shared<InvertRecallNode>(seg, query_info, batch_size);
|
||||
|
||||
auto source_node_options =
|
||||
arrow::acero::SourceNodeOptions{recall_node->schema(), recall_node->gen(),
|
||||
arrow::compute::Ordering::Implicit()};
|
||||
ac::Declaration node{"source", source_node_options};
|
||||
if (forward_filter) {
|
||||
node = ac::Declaration{"filter",
|
||||
{std::move(node)},
|
||||
ac::FilterNodeOptions(std::move(*forward_filter))};
|
||||
}
|
||||
|
||||
auto schema = recall_node->schema();
|
||||
if (query_info->is_include_vector()) {
|
||||
std::vector<cp::Expression> expressions;
|
||||
std::vector<std::string> names =
|
||||
query_info->get_all_fetched_scalar_field_names();
|
||||
for (const auto &field_name : names) {
|
||||
expressions.emplace_back(cp::field_ref(field_name));
|
||||
}
|
||||
for (const auto &vector_field : query_info->selected_vector_fields()) {
|
||||
auto indexer = seg->get_combined_vector_indexer(vector_field.field_name);
|
||||
if (!indexer) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"vector indexer not found:", vector_field.field_name));
|
||||
}
|
||||
if (vector_field.field_schema_ptr->is_dense_vector()) {
|
||||
expressions.emplace_back(
|
||||
cp::call("fetch_vector", {cp::field_ref(LOCAL_ROW_ID)},
|
||||
std::make_shared<FetchVectorOp::Options>(indexer, true)));
|
||||
schema = Util::append_field(*schema, vector_field.field_name,
|
||||
arrow::binary());
|
||||
} else {
|
||||
expressions.emplace_back(
|
||||
cp::call("fetch_sparse_vector", {cp::field_ref(LOCAL_ROW_ID)},
|
||||
std::make_shared<FetchVectorOp::Options>(indexer, false)));
|
||||
schema = Util::append_field(*schema, vector_field.field_name,
|
||||
Util::sparse_type());
|
||||
}
|
||||
names.emplace_back(vector_field.field_name);
|
||||
}
|
||||
node = ac::Declaration{
|
||||
"project",
|
||||
{std::move(node)},
|
||||
ac::ProjectNodeOptions{std::move(expressions), std::move(names)}};
|
||||
}
|
||||
|
||||
node = ac::Declaration{
|
||||
"fetch", {std::move(node)}, ac::FetchNodeOptions{0, topn}};
|
||||
return std::make_shared<PlanInfo>(std::move(node), std::move(schema));
|
||||
}
|
||||
|
||||
int QueryPlanner::get_batch_size(const QueryInfo &info, bool has_later_filter) {
|
||||
if (!info.query_orderbys().empty() || has_later_filter) {
|
||||
return 32 * 1024;
|
||||
}
|
||||
return info.query_topn();
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,69 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <ailego/pattern/expected.hpp>
|
||||
#include <arrow/acero/exec_plan.h>
|
||||
#include <arrow/compute/expression.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
#include "plan_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class QueryPlanner {
|
||||
public:
|
||||
QueryPlanner(CollectionSchema *schema);
|
||||
|
||||
Result<PlanInfo::Ptr> make_plan(
|
||||
const std::vector<Segment::Ptr> &segments, const std::string &trace_id,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos);
|
||||
|
||||
|
||||
private:
|
||||
Result<PlanInfo::Ptr> make_physical_plan(
|
||||
const std::vector<Segment::Ptr> &segments, const std::string &trace_id,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos);
|
||||
|
||||
Result<PlanInfo::Ptr> make_group_by_physical_plan(
|
||||
const std::vector<Segment::Ptr> &segments, const std::string &trace_id,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos);
|
||||
|
||||
private:
|
||||
Result<cp::Expression> parse_filter(const QueryNode *node);
|
||||
|
||||
Result<cp::Expression> create_filter_node(const QueryNode *node);
|
||||
|
||||
Result<PlanInfo::Ptr> vector_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter,
|
||||
bool single_stage_search);
|
||||
Result<PlanInfo::Ptr> invert_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter);
|
||||
Result<PlanInfo::Ptr> forward_scan(
|
||||
Segment::Ptr seg, QueryInfo::Ptr query_info,
|
||||
std::unique_ptr<arrow::compute::Expression> forward_filter);
|
||||
|
||||
static int get_batch_size(const QueryInfo &info, bool has_later_filter);
|
||||
|
||||
private:
|
||||
CollectionSchema *schema_{nullptr};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/planner/segment_node.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <ailego/parallel/thread_pool.h>
|
||||
#include <arrow/record_batch.h>
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
namespace cp = arrow::compute;
|
||||
|
||||
arrow::AsyncGenerator<std::optional<arrow::compute::ExecBatch>>
|
||||
SegmentNode::gen() {
|
||||
return [self = shared_from_this()]()
|
||||
-> arrow::Future<std::optional<arrow::compute::ExecBatch>> {
|
||||
if (!self->prepared_.exchange(true)) {
|
||||
auto status = self->prepare();
|
||||
if (!status.ok()) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("prepare segment node failed:",
|
||||
status.c_str()));
|
||||
}
|
||||
}
|
||||
// process backward
|
||||
std::shared_ptr<arrow::RecordBatch> batch;
|
||||
while (!self->readers_.empty()) {
|
||||
auto &back = self->readers_.back();
|
||||
auto status = back->ReadNext(&batch);
|
||||
if (!status.ok()) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("read next batch failed:",
|
||||
status.ToString()));
|
||||
}
|
||||
if (batch == nullptr) {
|
||||
LOG_DEBUG("batch finished: %p", back.get());
|
||||
self->readers_.pop_back();
|
||||
continue;
|
||||
}
|
||||
LOG_INFO("Segment batch: %p %s", back.get(), batch->ToString().c_str());
|
||||
cp::ExecBatch exec_batch(*batch);
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::move(exec_batch));
|
||||
};
|
||||
// 返回空的optional表示结束
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::nullopt);
|
||||
};
|
||||
}
|
||||
|
||||
Status SegmentNode::prepare() {
|
||||
auto group = thread_pool_->make_group();
|
||||
|
||||
std::vector<Result<std::unique_ptr<arrow::RecordBatchReader>>> results_;
|
||||
results_.resize(segment_plans_.size());
|
||||
for (size_t i = 0; i < segment_plans_.size(); i++) {
|
||||
auto &plan = segment_plans_[i];
|
||||
group->execute([&, i]() { results_[i] = plan->execute_to_reader(); });
|
||||
}
|
||||
group->wait_finish();
|
||||
for (size_t i = 0; i < segment_plans_.size(); i++) {
|
||||
auto &result = results_[i];
|
||||
if (!result) {
|
||||
return result.error();
|
||||
}
|
||||
readers_[i] = std::move(result.value());
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <ailego/parallel/thread_pool.h>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/api.h>
|
||||
#include <arrow/util/async_generator.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/sqlengine/planner/plan_info.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SegmentNode : public std::enable_shared_from_this<SegmentNode> {
|
||||
public:
|
||||
SegmentNode(std::vector<PlanInfo::Ptr> segment_plans,
|
||||
ailego::ThreadPool *thread_pool)
|
||||
: segment_plans_(std::move(segment_plans)),
|
||||
thread_pool_(thread_pool),
|
||||
readers_(segment_plans_.size()) {}
|
||||
|
||||
//! get schema
|
||||
std::shared_ptr<arrow::Schema> schema() const {
|
||||
return segment_plans_[0]->schema();
|
||||
}
|
||||
|
||||
arrow::AsyncGenerator<std::optional<arrow::compute::ExecBatch>> gen();
|
||||
|
||||
private:
|
||||
Status prepare();
|
||||
|
||||
private:
|
||||
std::vector<PlanInfo::Ptr> segment_plans_;
|
||||
ailego::ThreadPool *thread_pool_;
|
||||
|
||||
std::vector<std::unique_ptr<arrow::RecordBatchReader>> readers_;
|
||||
std::atomic_bool prepared_{false};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,286 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/planner/vector_recall_node.h"
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <arrow/array/builder_binary.h>
|
||||
#include <arrow/result.h>
|
||||
#include <core/framework/index_meta.h>
|
||||
#include "ailego/pattern/expected.hpp"
|
||||
#include "db/index/column/vector_column/vector_column_params.h"
|
||||
#include "db/index/common/index_params.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/planner/ops/fetch_vector_op.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
VectorRecallNode::VectorRecallNode(Segment::Ptr segment,
|
||||
QueryInfo::Ptr query_info,
|
||||
DocFilter::Ptr doc_filter, int batch_size,
|
||||
bool single_stage_search)
|
||||
: segment_(std::move(segment)),
|
||||
query_info_(std::move(query_info)),
|
||||
doc_filter_(doc_filter),
|
||||
batch_size_(batch_size),
|
||||
// need fetch filter fields if single stage search, otherwise only fetch
|
||||
// selectd scalar fields, as forward filter is already performed and order
|
||||
// by only support vector score
|
||||
fetched_columns_(single_stage_search
|
||||
? query_info_->get_all_fetched_scalar_field_names()
|
||||
: query_info_->get_selected_scalar_field_names()) {
|
||||
auto table = segment_->fetch(fetched_columns_, std::vector<int>{});
|
||||
schema_ = table->schema();
|
||||
schema_ = Util::append_field(*schema_, kFieldScore, arrow::float32());
|
||||
if (query_info_->is_include_vector()) {
|
||||
for (auto &field : query_info_->selected_vector_fields()) {
|
||||
if (field.field_schema_ptr->is_dense_vector()) {
|
||||
schema_ =
|
||||
Util::append_field(*schema_, field.field_name, arrow::binary());
|
||||
} else {
|
||||
schema_ =
|
||||
Util::append_field(*schema_, field.field_name, Util::sparse_type());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (query_info_->group_by()) {
|
||||
schema_ = Util::append_field(*schema_, kFieldGroupId, arrow::utf8());
|
||||
}
|
||||
}
|
||||
|
||||
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> VectorRecallNode::gen() {
|
||||
auto state_ptr = std::make_shared<State>(shared_from_this());
|
||||
return [state_ptr = std::move(state_ptr)]() mutable
|
||||
-> arrow::Future<std::optional<cp::ExecBatch>> {
|
||||
auto &state = *state_ptr;
|
||||
if (!state.iter_) {
|
||||
auto vector_ret = state.self_->prepare();
|
||||
if (!vector_ret) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("prepare vector failed:",
|
||||
vector_ret.error().c_str()));
|
||||
}
|
||||
state.vector_result_ = vector_ret.value();
|
||||
state.iter_ = state.vector_result_->create_iterator();
|
||||
}
|
||||
|
||||
// check if there is any data
|
||||
if (!state.iter_->valid()) {
|
||||
// return empty optional to indicate end
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::nullopt);
|
||||
}
|
||||
|
||||
auto record_batch = state.collect_batch();
|
||||
if (!record_batch.ok()) {
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
arrow::Status::ExecutionError("collect batch failed:",
|
||||
record_batch.status().ToString()));
|
||||
}
|
||||
cp::ExecBatch exec_batch(*record_batch.ValueOrDie());
|
||||
return arrow::Future<std::optional<cp::ExecBatch>>::MakeFinished(
|
||||
std::move(exec_batch));
|
||||
};
|
||||
}
|
||||
|
||||
std::string decode_group_id_from_forward(const FieldSchema *schema,
|
||||
const arrow::Array &array) {
|
||||
if (array.IsNull(0)) {
|
||||
return "";
|
||||
}
|
||||
switch (schema->data_type()) {
|
||||
case DataType::INT32:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::Int32Array &>(array).Value(0));
|
||||
case DataType::UINT32:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::UInt32Array &>(array).Value(0));
|
||||
case DataType::INT64:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::Int64Array &>(array).Value(0));
|
||||
case DataType::UINT64:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::UInt64Array &>(array).Value(0));
|
||||
case DataType::STRING:
|
||||
return static_cast<const arrow::StringArray &>(array).GetString(0);
|
||||
case DataType::FLOAT:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::FloatArray &>(array).Value(0));
|
||||
case DataType::DOUBLE:
|
||||
return std::to_string(
|
||||
static_cast<const arrow::DoubleArray &>(array).Value(0));
|
||||
case DataType::BOOL:
|
||||
return static_cast<const arrow::BooleanArray &>(array).Value(0) ? "true"
|
||||
: "false";
|
||||
default:
|
||||
LOG_ERROR("Unsupported data type: %d", (int)schema->data_type());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
Result<IndexResults::Ptr> VectorRecallNode::prepare() {
|
||||
auto filter_status = doc_filter_->compute_filter();
|
||||
if (!filter_status.ok()) {
|
||||
return tl::make_unexpected(filter_status);
|
||||
}
|
||||
auto &vector_cond_ = query_info_->vector_cond_info();
|
||||
CombinedVectorColumnIndexer::Ptr vector_indexer;
|
||||
if (auto *vector_params = dynamic_cast<const VectorIndexParams *>(
|
||||
vector_cond_->vector_schema()->index_params().get());
|
||||
vector_params == nullptr ||
|
||||
vector_params->quantize_type() == QuantizeType::UNDEFINED) {
|
||||
vector_indexer = segment_->get_combined_vector_indexer(
|
||||
vector_cond_->vector_field_name());
|
||||
} else {
|
||||
vector_indexer = segment_->get_quant_combined_vector_indexer(
|
||||
vector_cond_->vector_field_name());
|
||||
}
|
||||
if (!vector_indexer) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"vector index not found:", vector_cond_->vector_field_name()));
|
||||
}
|
||||
vector_column_params::QueryParams query_params;
|
||||
query_params.topk = query_info_->query_topn();
|
||||
query_params.data_type = vector_cond_->vector_schema()->data_type();
|
||||
query_params.dimension = vector_cond_->dimension();
|
||||
query_params.query_params = vector_cond_->query_params();
|
||||
auto brute_force_keys = doc_filter_->get_bf_by_keys_and_update();
|
||||
if (brute_force_keys) {
|
||||
query_params.bf_pks.emplace_back(std::move(brute_force_keys.value()));
|
||||
}
|
||||
// set filter after brute force check
|
||||
query_params.filter = doc_filter_->empty() ? nullptr : doc_filter_.get();
|
||||
if (const auto &group_by = query_info_->group_by(); group_by) {
|
||||
auto group_fun = [this, &group_by](uint64_t row_id) -> std::string {
|
||||
auto table = segment_->fetch({group_by->group_by_field},
|
||||
std::vector<int>{(int)row_id});
|
||||
static std::string kEmpty;
|
||||
if (!table) {
|
||||
LOG_ERROR("Fetch group by field failed: field[%s] row_id[%zu]",
|
||||
group_by->group_by_field.c_str(), (size_t)row_id);
|
||||
return kEmpty;
|
||||
}
|
||||
if (table->num_rows() != 1) {
|
||||
LOG_ERROR(
|
||||
"Fetch group by field failed: field[%s] row_id[%zu] rows[%zu]",
|
||||
group_by->group_by_field.c_str(), (size_t)row_id,
|
||||
(size_t)table->num_rows());
|
||||
return kEmpty;
|
||||
}
|
||||
if (table->column(0)->chunk(0)->IsNull(0)) {
|
||||
return kEmpty;
|
||||
}
|
||||
return decode_group_id_from_forward(query_info_->group_by_schema_ptr(),
|
||||
*table->column(0)->chunk(0));
|
||||
};
|
||||
query_params.group_by =
|
||||
std::make_unique<vector_column_params::GroupByParams>(
|
||||
group_by->group_topk, group_by->group_count, std::move(group_fun));
|
||||
}
|
||||
|
||||
vector_column_params::VectorData vector_data;
|
||||
if (vector_cond_->vector_schema()->is_dense_vector()) {
|
||||
vector_data.vector =
|
||||
vector_column_params::DenseVector{vector_cond_->vector_term().data()};
|
||||
} else {
|
||||
vector_data.vector = vector_column_params::SparseVector{
|
||||
vector_cond_->sparse_count(),
|
||||
vector_cond_->vector_sparse_indices().data(),
|
||||
vector_cond_->vector_sparse_values().data()};
|
||||
}
|
||||
|
||||
auto vector_ret = vector_indexer->Search(vector_data, query_params);
|
||||
if (!vector_ret) {
|
||||
return tl::make_unexpected(vector_ret.error());
|
||||
}
|
||||
return vector_ret;
|
||||
}
|
||||
|
||||
arrow::Result<std::shared_ptr<arrow::RecordBatch>>
|
||||
VectorRecallNode::State::collect_batch() {
|
||||
// collect a batch
|
||||
std::vector<int> indices;
|
||||
indices.reserve(self_->batch_size_);
|
||||
arrow::FloatBuilder builder;
|
||||
arrow::StringBuilder group_id_builder;
|
||||
for (int i = 0; iter_->valid() && i < self_->batch_size_;
|
||||
i++, iter_->next()) {
|
||||
indices.push_back(iter_->doc_id());
|
||||
ARROW_RETURN_NOT_OK(builder.Append(iter_->score()));
|
||||
if (self_->query_info_->group_by()) {
|
||||
ARROW_RETURN_NOT_OK(group_id_builder.Append(iter_->group_id()));
|
||||
}
|
||||
}
|
||||
auto table = self_->segment_->fetch(self_->fetched_columns_, indices);
|
||||
if (!table) {
|
||||
return arrow::Status::ExecutionError("fetch table failed");
|
||||
}
|
||||
auto batch = table->CombineChunksToBatch();
|
||||
if (!batch.ok()) {
|
||||
return arrow::Status::ExecutionError("combine chunks to batch failed:",
|
||||
batch.status().ToString());
|
||||
}
|
||||
auto score_array = builder.Finish();
|
||||
if (!score_array.ok()) {
|
||||
return arrow::Status::ExecutionError("finish builder failed:",
|
||||
score_array.status().ToString());
|
||||
}
|
||||
auto record_batch = std::move(batch.ValueUnsafe());
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
record_batch,
|
||||
record_batch->AddColumn(record_batch->num_columns(), kFieldScore,
|
||||
score_array.MoveValueUnsafe()));
|
||||
|
||||
if (self_->query_info_->is_include_vector()) {
|
||||
for (auto &field : self_->query_info_->selected_vector_fields()) {
|
||||
Result<std::shared_ptr<arrow::Array>> array_res;
|
||||
if (field.field_schema_ptr->is_dense_vector()) {
|
||||
array_res = FetchVectorOp::fetch_dense_vector(
|
||||
*self_->segment_, field.field_name, indices);
|
||||
} else {
|
||||
array_res = FetchVectorOp::fetch_sparse_vector(
|
||||
*self_->segment_, field.field_name, indices);
|
||||
}
|
||||
if (!array_res) {
|
||||
return arrow::Status::ExecutionError("fetch vector failed:",
|
||||
array_res.error().c_str());
|
||||
}
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
record_batch,
|
||||
record_batch->AddColumn(record_batch->num_columns(), field.field_name,
|
||||
std::move(array_res.value())));
|
||||
}
|
||||
}
|
||||
|
||||
if (self_->query_info_->group_by()) {
|
||||
auto group_id_array = group_id_builder.Finish();
|
||||
if (!group_id_array.ok()) {
|
||||
return arrow::Status::ExecutionError("finish group id builder failed:",
|
||||
group_id_array.status().ToString());
|
||||
}
|
||||
ARROW_ASSIGN_OR_RAISE(
|
||||
record_batch,
|
||||
record_batch->AddColumn(record_batch->num_columns(), kFieldGroupId,
|
||||
group_id_array.MoveValueUnsafe()));
|
||||
}
|
||||
|
||||
LOG_DEBUG("Record batch: %s", record_batch->ToString().c_str());
|
||||
return record_batch;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <arrow/acero/api.h>
|
||||
#include <arrow/api.h>
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/column/common/index_results.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
#include "db/sqlengine/analyzer/query_info.h"
|
||||
#include "db/sqlengine/planner/doc_filter.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class VectorRecallNode : public std::enable_shared_from_this<VectorRecallNode> {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<VectorRecallNode>;
|
||||
VectorRecallNode(Segment::Ptr segment, QueryInfo::Ptr query_info,
|
||||
DocFilter::Ptr doc_filter, int batch_size,
|
||||
bool single_stage_search);
|
||||
|
||||
//! get schema
|
||||
std::shared_ptr<arrow::Schema> schema() const {
|
||||
return schema_;
|
||||
}
|
||||
|
||||
arrow::AsyncGenerator<std::optional<cp::ExecBatch>> gen();
|
||||
|
||||
const QueryInfo::Ptr &query_info() const {
|
||||
return query_info_;
|
||||
}
|
||||
|
||||
private:
|
||||
Result<IndexResults::Ptr> prepare();
|
||||
|
||||
private:
|
||||
struct State {
|
||||
State(VectorRecallNode::Ptr self) : self_(std::move(self)) {}
|
||||
|
||||
arrow::Result<std::shared_ptr<arrow::RecordBatch>> collect_batch();
|
||||
|
||||
VectorRecallNode::Ptr self_;
|
||||
IndexResults::Ptr vector_result_;
|
||||
IndexResults::IteratorUPtr iter_;
|
||||
};
|
||||
|
||||
Segment::Ptr segment_;
|
||||
QueryInfo::Ptr query_info_;
|
||||
DocFilter::Ptr doc_filter_;
|
||||
int batch_size_;
|
||||
const std::vector<std::string> &fetched_columns_;
|
||||
std::shared_ptr<arrow::Schema> schema_;
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include "db/sqlengine/sqlengine_impl.h"
|
||||
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
SQLEngine::Ptr SQLEngine::create(zvec::Profiler::Ptr profiler) {
|
||||
return std::make_shared<SQLEngineImpl>(std::move(profiler));
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "db/common/profiler.h"
|
||||
#include "db/common/status.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/segment/segment.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SQLEngine {
|
||||
public:
|
||||
using Ptr = std::shared_ptr<SQLEngine>;
|
||||
virtual ~SQLEngine();
|
||||
|
||||
virtual Result<DocPtrList> execute(
|
||||
CollectionSchema::Ptr collection, const VectorQuery &query,
|
||||
const std::vector<Segment::Ptr> &segments) = 0;
|
||||
|
||||
virtual Result<GroupResults> execute_group_by(
|
||||
CollectionSchema::Ptr collection,
|
||||
const GroupByVectorQuery &group_by_query,
|
||||
const std::vector<Segment::Ptr> &segments) = 0;
|
||||
|
||||
public:
|
||||
static SQLEngine::Ptr create(zvec::Profiler::Ptr profiler);
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,574 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#include "db/sqlengine/sqlengine_impl.h"
|
||||
#include <unordered_map>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include "db/common/constants.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/common/type.h"
|
||||
#include "db/sqlengine/analyzer/query_analyzer.h"
|
||||
#include "db/sqlengine/parser/sql_info_helper.h"
|
||||
#include "db/sqlengine/parser/zvec_parser.h"
|
||||
#include "db/sqlengine/planner/op_register.h"
|
||||
#include "db/sqlengine/planner/query_planner.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
void global_init() {
|
||||
static std::once_flag once;
|
||||
// run once
|
||||
std::call_once(once, []() {
|
||||
auto status = arrow::compute::Initialize();
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("arrow compute init failed: [%s]", status.ToString().c_str());
|
||||
abort();
|
||||
}
|
||||
status = OpRegister::register_ops();
|
||||
if (!status.ok()) {
|
||||
LOG_ERROR("arrow compute register op failed: [%s]",
|
||||
status.ToString().c_str());
|
||||
abort();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
SQLEngine::~SQLEngine() = default;
|
||||
|
||||
SQLEngineImpl::SQLEngineImpl(zvec::Profiler::Ptr profiler)
|
||||
: profiler_(std::move(profiler)) {}
|
||||
|
||||
Result<DocPtrList> SQLEngineImpl::execute(
|
||||
CollectionSchema::Ptr collection, const VectorQuery &query,
|
||||
const std::vector<Segment::Ptr> &segments) {
|
||||
if (segments.empty()) {
|
||||
return DocPtrList{};
|
||||
}
|
||||
|
||||
auto query_info = parse_request(collection, query, nullptr);
|
||||
if (!query_info) {
|
||||
return tl::make_unexpected(query_info.error());
|
||||
}
|
||||
if (query_info.value()->is_filter_unsatisfiable()) {
|
||||
LOG_WARN("filter is unsatisfiable: %s",
|
||||
query_info.value()->to_string().c_str());
|
||||
return {};
|
||||
}
|
||||
const auto &select_item_meta_ptrs =
|
||||
query_info.value()->select_item_schema_ptrs();
|
||||
std::vector<QueryInfo::Ptr> query_infos(segments.size(), query_info.value());
|
||||
auto reader = search_by_query_info(collection, segments, &query_infos);
|
||||
if (!reader) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("Execute plan failed: ", reader.error().c_str()));
|
||||
}
|
||||
return fill_result(select_item_meta_ptrs, reader.value().get());
|
||||
}
|
||||
|
||||
VectorQuery from_group_by(const GroupByVectorQuery &gq) {
|
||||
VectorQuery vq;
|
||||
vq.field_name_ = gq.field_name_;
|
||||
vq.query_vector_ = gq.query_vector_;
|
||||
vq.query_sparse_indices_ = gq.query_sparse_indices_;
|
||||
vq.query_sparse_values_ = gq.query_sparse_values_;
|
||||
vq.filter_ = gq.filter_;
|
||||
vq.include_vector_ = gq.include_vector_;
|
||||
vq.query_params_ = gq.query_params_;
|
||||
vq.output_fields_ = gq.output_fields_;
|
||||
vq.topk_ = 0;
|
||||
return vq;
|
||||
}
|
||||
|
||||
Result<GroupResults> SQLEngineImpl::execute_group_by(
|
||||
CollectionSchema::Ptr collection, const GroupByVectorQuery &group_by_query,
|
||||
const std::vector<Segment::Ptr> &segments) {
|
||||
if (segments.empty()) {
|
||||
return GroupResults{};
|
||||
}
|
||||
|
||||
VectorQuery query = from_group_by(group_by_query);
|
||||
auto query_info = parse_request(
|
||||
collection, query,
|
||||
std::make_shared<GroupBy>(group_by_query.group_by_field_name_,
|
||||
group_by_query.group_topk_,
|
||||
group_by_query.group_count_));
|
||||
if (!query_info) {
|
||||
return tl::make_unexpected(query_info.error());
|
||||
}
|
||||
if (query_info.value()->is_filter_unsatisfiable()) {
|
||||
LOG_WARN("filter is unsatisfiable: %s",
|
||||
query_info.value()->to_string().c_str());
|
||||
return {};
|
||||
}
|
||||
std::vector<QueryInfo::Ptr> query_infos(segments.size(), query_info.value());
|
||||
auto reader = search_by_query_info(collection, segments, &query_infos);
|
||||
if (!reader) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("Execute plan failed: ", reader.error().c_str()));
|
||||
}
|
||||
return fill_group_by_result(*query_info.value(), reader.value().get());
|
||||
}
|
||||
|
||||
Result<QueryInfo::Ptr> SQLEngineImpl::parse_sql_info(
|
||||
const CollectionSchema &schema, const SQLInfo::Ptr &sql_info) {
|
||||
profiler_->open_stage("analyze stage");
|
||||
QueryAnalyzer analyzer;
|
||||
auto query_info = analyzer.analyze(schema, sql_info);
|
||||
if (!query_info) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"Analyze sql info failed:", query_info.error().c_str()));
|
||||
}
|
||||
profiler_->close_stage();
|
||||
LOG_DEBUG("query_info: [%s]", query_info.value()->to_string().c_str());
|
||||
return query_info.value();
|
||||
}
|
||||
|
||||
Result<QueryInfo::Ptr> SQLEngineImpl::parse_request(
|
||||
CollectionSchema::Ptr collection, const VectorQuery &request,
|
||||
std::shared_ptr<GroupBy> group_by) {
|
||||
profiler_->open_stage("message_to_sqlinfo");
|
||||
sqlengine::SQLInfo::Ptr sql_info;
|
||||
std::string err_msg;
|
||||
Node::Ptr filter_node;
|
||||
if (!request.filter_.empty()) {
|
||||
ZVecParser::Ptr parser = ZVecParser::create();
|
||||
filter_node = parser->parse_filter(request.filter_);
|
||||
if (filter_node == nullptr) {
|
||||
LOG_ERROR("parse filter failed. reason:[%s] filter:[%s]",
|
||||
parser->err_msg().c_str(), request.filter_.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("Invalid filter:", parser->err_msg()));
|
||||
}
|
||||
}
|
||||
if (group_by) {
|
||||
auto &group = *group_by;
|
||||
if (group.group_by_field.empty() || group.group_count == 0 ||
|
||||
group.group_topk == 0) {
|
||||
return tl::make_unexpected(Status::InvalidArgument(
|
||||
"Invalid group by request: group_by", group.group_by_field,
|
||||
" group_count: ", group.group_count,
|
||||
" group_topk: ", group.group_topk));
|
||||
}
|
||||
}
|
||||
|
||||
sqlengine::SQLInfoHelper::MessageToSQLInfo(&request, std::move(filter_node),
|
||||
std::move(group_by), &sql_info,
|
||||
&err_msg);
|
||||
profiler_->close_stage();
|
||||
if (!err_msg.empty()) {
|
||||
LOG_ERROR("QueryAgent, message to sql info failed, err_msg: %s",
|
||||
err_msg.c_str());
|
||||
return tl::make_unexpected(
|
||||
Status::InvalidArgument("To sql info failed:", err_msg));
|
||||
}
|
||||
LOG_DEBUG("Sql info is %s", sql_info->to_string().c_str());
|
||||
return parse_sql_info(*collection, std::move(sql_info));
|
||||
}
|
||||
|
||||
Result<std::unique_ptr<arrow::RecordBatchReader>>
|
||||
SQLEngineImpl::search_by_query_info(
|
||||
CollectionSchema::Ptr collection, const std::vector<Segment::Ptr> &segments,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos) {
|
||||
global_init();
|
||||
|
||||
profiler_->open_stage("plan stage");
|
||||
QueryPlanner planner(collection.get());
|
||||
auto plan_info =
|
||||
planner.make_plan(segments, profiler_->trace_id(), query_infos);
|
||||
if (!plan_info) {
|
||||
LOG_ERROR("plan query_info failed: [%s]", plan_info.error().c_str());
|
||||
return tl::make_unexpected(plan_info.error());
|
||||
}
|
||||
profiler_->close_stage();
|
||||
// LOG_DEBUG("plan_info: [%s]", plan_info->to_string().c_str());
|
||||
return plan_info.value()->execute_to_reader();
|
||||
}
|
||||
|
||||
#define GET_FIELD_FROM_RECORD_BATCH(res, field_name) \
|
||||
auto res = record_batch.GetColumnByName(field_name); \
|
||||
if (!res) { \
|
||||
return Status::InternalError("Get column by name failed: ", field_name); \
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::vector<T> to_vector(const char *data, size_t size) {
|
||||
std::vector<T> vec(size);
|
||||
memcpy(vec.data(), data, size * sizeof(T));
|
||||
return vec;
|
||||
}
|
||||
|
||||
template <typename VectorType>
|
||||
Status fill_doc_sparse_vector(const arrow::StructArray *typed_arr,
|
||||
const std::string &field_name,
|
||||
DocPtrList::iterator doc_it) {
|
||||
auto *indices = (const arrow::BinaryArray *)typed_arr->field(0).get();
|
||||
auto *values = (const arrow::BinaryArray *)typed_arr->field(1).get();
|
||||
bool has_null = typed_arr->null_count() > 0;
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
if (has_null && typed_arr->IsNull(i)) {
|
||||
continue;
|
||||
}
|
||||
auto indice_data = indices->GetView(i);
|
||||
auto value_data = values->GetView(i);
|
||||
uint32_t count = indice_data.size() / sizeof(uint32_t);
|
||||
if (count != value_data.size() / sizeof(VectorType)) {
|
||||
return Status::InvalidArgument("Dimension not match:", count, " vs ",
|
||||
value_data.size() / sizeof(VectorType));
|
||||
}
|
||||
(*doc_it)->set(
|
||||
field_name,
|
||||
std::make_pair(to_vector<uint32_t>(indice_data.data(), count),
|
||||
to_vector<VectorType>(value_data.data(), count)));
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
template <typename VectorType>
|
||||
Status fill_doc_vector(const arrow::BinaryArray *typed_arr,
|
||||
const std::string &field_name, int dimension,
|
||||
DocPtrList::iterator doc_it) {
|
||||
bool no_null = typed_arr->null_count() == 0;
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
if (no_null || !typed_arr->IsNull(i)) {
|
||||
auto data = typed_arr->GetView(i);
|
||||
if ((size_t)dimension != data.size() / sizeof(VectorType)) {
|
||||
return Status::InvalidArgument("Dimension not match:", dimension,
|
||||
" vs ",
|
||||
data.size() / sizeof(VectorType));
|
||||
}
|
||||
(*doc_it)->set(field_name, std::vector<VectorType>(
|
||||
(const VectorType *)&data[0],
|
||||
(const VectorType *)&data[0] + dimension));
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
template <typename ArrowArrayType>
|
||||
Status fill_doc_field(const arrow::Array *arr, const std::string &field_name,
|
||||
DocPtrList::iterator doc_it) {
|
||||
auto *typed_arr = static_cast<const ArrowArrayType *>(arr);
|
||||
bool no_null = typed_arr->null_count() == 0;
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
if (no_null || !typed_arr->IsNull(i)) {
|
||||
if constexpr (std::is_same_v<ArrowArrayType, arrow::StringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeStringArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::BinaryArray> ||
|
||||
std::is_same_v<ArrowArrayType, arrow::LargeBinaryArray>) {
|
||||
(*doc_it)->set(field_name, typed_arr->GetString(i));
|
||||
} else {
|
||||
(*doc_it)->set(field_name, typed_arr->Value(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
template <typename ArrowArrayType, typename ElementType>
|
||||
Status fill_doc_array_field(const arrow::Array *arr,
|
||||
const std::string &field_name,
|
||||
DocPtrList::iterator doc_it) {
|
||||
const auto *list_arr = static_cast<const arrow::ListArray *>(arr);
|
||||
auto *typed_arr =
|
||||
dynamic_cast<const ArrowArrayType *>(list_arr->values().get());
|
||||
bool has_null = list_arr->null_count() > 0;
|
||||
for (int64_t i = 0; i < list_arr->length(); ++i, ++doc_it) {
|
||||
if (has_null && list_arr->IsNull(i)) {
|
||||
continue;
|
||||
}
|
||||
int64_t offset = list_arr->value_offset(i);
|
||||
int64_t length = list_arr->value_length(i);
|
||||
std::vector<ElementType> vec(length);
|
||||
for (int64_t j = 0; j < length; ++j) {
|
||||
vec[j] = typed_arr->Value(offset + j);
|
||||
}
|
||||
(*doc_it)->set(field_name, std::move(vec));
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Status fill_doc_field(const std::shared_ptr<arrow::Array> &chunk,
|
||||
const FieldSchema &field_schema,
|
||||
DocPtrList::iterator doc_it) {
|
||||
switch (field_schema.data_type()) {
|
||||
case DataType::INT32:
|
||||
return fill_doc_field<arrow::Int32Array>(chunk.get(), field_schema.name(),
|
||||
doc_it);
|
||||
case DataType::UINT32:
|
||||
return fill_doc_field<arrow::UInt32Array>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
case DataType::INT64:
|
||||
return fill_doc_field<arrow::Int64Array>(chunk.get(), field_schema.name(),
|
||||
doc_it);
|
||||
case DataType::UINT64:
|
||||
return fill_doc_field<arrow::UInt64Array>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
case DataType::FLOAT:
|
||||
return fill_doc_field<arrow::FloatArray>(chunk.get(), field_schema.name(),
|
||||
doc_it);
|
||||
case DataType::DOUBLE:
|
||||
return fill_doc_field<arrow::DoubleArray>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
case DataType::BOOL:
|
||||
return fill_doc_field<arrow::BooleanArray>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
case DataType::BINARY:
|
||||
return fill_doc_field<arrow::BinaryArray>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
|
||||
case DataType::STRING:
|
||||
return fill_doc_field<arrow::StringArray>(chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_INT32:
|
||||
return fill_doc_array_field<arrow::Int32Array, int32_t>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_INT64:
|
||||
return fill_doc_array_field<arrow::Int64Array, int64_t>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_UINT32:
|
||||
return fill_doc_array_field<arrow::UInt32Array, uint32_t>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_UINT64:
|
||||
return fill_doc_array_field<arrow::UInt64Array, uint64_t>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_FLOAT:
|
||||
return fill_doc_array_field<arrow::FloatArray, float>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_DOUBLE:
|
||||
return fill_doc_array_field<arrow::DoubleArray, double>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_STRING:
|
||||
return fill_doc_array_field<arrow::StringArray, std::string>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_BINARY:
|
||||
return fill_doc_array_field<arrow::BinaryArray, std::string>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::ARRAY_BOOL:
|
||||
return fill_doc_array_field<arrow::BooleanArray, bool>(
|
||||
chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
case DataType::VECTOR_FP32:
|
||||
return fill_doc_vector<float>((arrow::BinaryArray *)chunk.get(),
|
||||
field_schema.name(),
|
||||
field_schema.dimension(), doc_it);
|
||||
|
||||
case DataType::VECTOR_FP64:
|
||||
return fill_doc_vector<double>((arrow::BinaryArray *)chunk.get(),
|
||||
field_schema.name(),
|
||||
field_schema.dimension(), doc_it);
|
||||
case DataType::VECTOR_FP16:
|
||||
return fill_doc_vector<float16_t>((arrow::BinaryArray *)chunk.get(),
|
||||
field_schema.name(),
|
||||
field_schema.dimension(), doc_it);
|
||||
|
||||
case DataType::VECTOR_INT16:
|
||||
return fill_doc_vector<int16_t>((arrow::BinaryArray *)chunk.get(),
|
||||
field_schema.name(),
|
||||
field_schema.dimension(), doc_it);
|
||||
|
||||
case DataType::VECTOR_INT8:
|
||||
return fill_doc_vector<int8_t>((arrow::BinaryArray *)chunk.get(),
|
||||
field_schema.name(),
|
||||
field_schema.dimension(), doc_it);
|
||||
|
||||
case DataType::VECTOR_BINARY32:
|
||||
return fill_doc_vector<uint32_t>(
|
||||
(arrow::BinaryArray *)chunk.get(), field_schema.name(),
|
||||
field_schema.dimension() / sizeof(uint32_t), doc_it);
|
||||
|
||||
case DataType::VECTOR_BINARY64:
|
||||
return fill_doc_vector<uint64_t>(
|
||||
(arrow::BinaryArray *)chunk.get(), field_schema.name(),
|
||||
field_schema.dimension() / sizeof(uint64_t), doc_it);
|
||||
|
||||
case DataType::SPARSE_VECTOR_FP32:
|
||||
return fill_doc_sparse_vector<float>((arrow::StructArray *)chunk.get(),
|
||||
field_schema.name(), doc_it);
|
||||
|
||||
case DataType::SPARSE_VECTOR_FP16:
|
||||
return fill_doc_sparse_vector<float16_t>(
|
||||
(arrow::StructArray *)chunk.get(), field_schema.name(), doc_it);
|
||||
|
||||
default:
|
||||
return Status::InvalidArgument("Datatype not supported:",
|
||||
field_schema.data_type());
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
void fill_doc_id(const std::shared_ptr<arrow::Array> &doc_id_array,
|
||||
DocPtrList::iterator doc_it) {
|
||||
arrow::UInt64Array *typed_arr =
|
||||
static_cast<arrow::UInt64Array *>(doc_id_array.get());
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
// doc_id is non-null
|
||||
(*doc_it)->set_doc_id(typed_arr->Value(i));
|
||||
}
|
||||
}
|
||||
|
||||
void fill_doc_score(const std::shared_ptr<arrow::Array> &doc_id_array,
|
||||
DocPtrList::iterator doc_it) {
|
||||
arrow::FloatArray *typed_arr =
|
||||
static_cast<arrow::FloatArray *>(doc_id_array.get());
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
// doc_score is non-null
|
||||
(*doc_it)->set_score(typed_arr->Value(i));
|
||||
}
|
||||
}
|
||||
|
||||
void fill_user_id(const std::shared_ptr<arrow::Array> &user_id_array,
|
||||
DocPtrList::iterator doc_it) {
|
||||
arrow::StringArray *typed_arr =
|
||||
static_cast<arrow::StringArray *>(user_id_array.get());
|
||||
for (int64_t i = 0; i < typed_arr->length(); ++i, ++doc_it) {
|
||||
// user_id is non-null
|
||||
(*doc_it)->set_pk(typed_arr->GetString(i));
|
||||
}
|
||||
}
|
||||
|
||||
Status record_batch_to_doc_list(
|
||||
const std::vector<FieldAndSchema> &output_fields,
|
||||
const arrow::RecordBatch &record_batch, DocPtrList::iterator doc_it) {
|
||||
GET_FIELD_FROM_RECORD_BATCH(user_id_array, USER_ID);
|
||||
fill_user_id(user_id_array, doc_it);
|
||||
if (auto doc_id_array = record_batch.GetColumnByName(GLOBAL_DOC_ID);
|
||||
doc_id_array != nullptr) {
|
||||
fill_doc_id(doc_id_array, doc_it);
|
||||
}
|
||||
if (auto score_array = record_batch.GetColumnByName(kFieldScore);
|
||||
score_array != nullptr) {
|
||||
fill_doc_score(score_array, doc_it);
|
||||
}
|
||||
|
||||
for (auto &[field_name, field_schema] : output_fields) {
|
||||
GET_FIELD_FROM_RECORD_BATCH(field_array, field_name);
|
||||
if (auto status = fill_doc_field(field_array, *field_schema, doc_it);
|
||||
!status.ok()) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
if (ailego::LoggerBroker::IsLevelEnabled(ailego::Logger::LEVEL_DEBUG)) {
|
||||
for (int i = 0; i < record_batch.num_rows(); i++) {
|
||||
LOG_DEBUG("Doc: %s", (*(doc_it + i))->to_detail_string().c_str());
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
Result<DocPtrList> SQLEngineImpl::fill_result(
|
||||
const std::vector<FieldAndSchema> &output_fields,
|
||||
arrow::RecordBatchReader *reader) {
|
||||
DocPtrList docs;
|
||||
std::shared_ptr<RecordBatch> record_batch;
|
||||
while (true) {
|
||||
auto read_res = reader->ReadNext(&record_batch);
|
||||
if (!read_res.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"Read record batch failed: ", read_res.ToString()));
|
||||
}
|
||||
if (record_batch == nullptr) {
|
||||
break;
|
||||
}
|
||||
size_t cur_size = docs.size();
|
||||
docs.resize(docs.size() + record_batch->num_rows());
|
||||
for (int i = 0; i < record_batch->num_rows(); i++) {
|
||||
docs[cur_size + i] = std::make_shared<Doc>();
|
||||
}
|
||||
auto status = record_batch_to_doc_list(output_fields, *record_batch,
|
||||
docs.begin() + cur_size);
|
||||
if (!status.ok()) {
|
||||
return tl::make_unexpected(status);
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
|
||||
Result<GroupResults> SQLEngineImpl::fill_group_by_result(
|
||||
const QueryInfo &query_info, arrow::RecordBatchReader *reader) {
|
||||
const std::vector<FieldAndSchema> &output_fields =
|
||||
query_info.select_item_schema_ptrs();
|
||||
uint32_t group_count = query_info.group_by()->group_count;
|
||||
uint32_t group_topk = query_info.group_by()->group_topk;
|
||||
std::shared_ptr<RecordBatch> record_batch;
|
||||
std::unordered_map<std::string, std::vector<Doc>> group_to_docs;
|
||||
while (true) {
|
||||
auto read_res = reader->ReadNext(&record_batch);
|
||||
if (!read_res.ok()) {
|
||||
return tl::make_unexpected(Status::InternalError(
|
||||
"Read record batch failed: ", read_res.ToString()));
|
||||
}
|
||||
if (record_batch == nullptr) {
|
||||
break;
|
||||
}
|
||||
DocPtrList docs(record_batch->num_rows());
|
||||
for (int i = 0; i < record_batch->num_rows(); i++) {
|
||||
docs[i] = std::make_shared<Doc>();
|
||||
}
|
||||
auto status =
|
||||
record_batch_to_doc_list(output_fields, *record_batch, docs.begin());
|
||||
if (!status.ok()) {
|
||||
return tl::make_unexpected(status);
|
||||
}
|
||||
auto group_id_array = record_batch->GetColumnByName(kFieldGroupId);
|
||||
if (!group_id_array) {
|
||||
return tl::make_unexpected(
|
||||
Status::InternalError("Get group_id_array failed"));
|
||||
}
|
||||
arrow::StringArray *typed_arr =
|
||||
static_cast<arrow::StringArray *>(group_id_array.get());
|
||||
for (int i = 0; i < record_batch->num_rows(); i++) {
|
||||
if (!typed_arr->IsNull(i)) {
|
||||
// docs already order by score
|
||||
auto &group_docs = group_to_docs[typed_arr->GetString(i)];
|
||||
if (group_docs.size() < group_count) {
|
||||
group_docs.push_back(std::move(*docs[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GroupResults group_results;
|
||||
for (auto &kv : group_to_docs) {
|
||||
group_results.emplace_back(
|
||||
GroupResult{std::move(kv.first), std::move(kv.second)});
|
||||
}
|
||||
std::sort(group_results.begin(), group_results.end(),
|
||||
[&query_info](GroupResult &a, GroupResult &b) {
|
||||
if (query_info.vector_cond_info()->is_reverse_sort()) {
|
||||
return a.docs_[0].score() > b.docs_[0].score();
|
||||
}
|
||||
return a.docs_[0].score() < b.docs_[0].score();
|
||||
});
|
||||
if (group_results.size() > group_topk) {
|
||||
group_results.resize(group_topk);
|
||||
}
|
||||
for (auto &group_result : group_results) {
|
||||
LOG_DEBUG("Group: %s", group_result.group_by_value_.c_str());
|
||||
for (auto &doc : group_result.docs_) {
|
||||
LOG_DEBUG("\tDoc: %s", doc.to_detail_string().c_str());
|
||||
}
|
||||
}
|
||||
return group_results;
|
||||
}
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
@@ -0,0 +1,75 @@
|
||||
// Copyright 2025-present the zvec project
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory.h>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <arrow/api.h>
|
||||
#include "analyzer/query_info.h"
|
||||
#include "common/group_by.h"
|
||||
#include "db/index/common/doc.h"
|
||||
#include "db/index/common/schema.h"
|
||||
#include "db/sqlengine/common/util.h"
|
||||
#include "db/sqlengine/parser/sql_info.h"
|
||||
#include "db/sqlengine/sqlengine.h"
|
||||
|
||||
namespace zvec::sqlengine {
|
||||
|
||||
class SQLEngineImpl : public SQLEngine {
|
||||
public:
|
||||
SQLEngineImpl(zvec::Profiler::Ptr profiler);
|
||||
|
||||
//! Parse pb request
|
||||
Result<QueryInfo::Ptr> parse_request(CollectionSchema::Ptr collection,
|
||||
const VectorQuery &request,
|
||||
std::shared_ptr<GroupBy> group_by);
|
||||
|
||||
//! Perform search with given query_info, segments and index filter
|
||||
Result<std::unique_ptr<arrow::RecordBatchReader>> search_by_query_info(
|
||||
CollectionSchema::Ptr collection,
|
||||
const std::vector<Segment::Ptr> &segments,
|
||||
std::vector<sqlengine::QueryInfo::Ptr> *query_infos);
|
||||
|
||||
Result<DocPtrList> execute(
|
||||
CollectionSchema::Ptr collection, const VectorQuery &query,
|
||||
const std::vector<Segment::Ptr> &segments) override;
|
||||
|
||||
Result<GroupResults> execute_group_by(
|
||||
CollectionSchema::Ptr collection,
|
||||
const GroupByVectorQuery &group_by_query,
|
||||
const std::vector<Segment::Ptr> &segments) override;
|
||||
|
||||
const std::string &execution_time_info() {
|
||||
return execution_time_info_;
|
||||
}
|
||||
|
||||
private:
|
||||
Result<DocPtrList> fill_result(
|
||||
const std::vector<FieldAndSchema> &output_fields,
|
||||
arrow::RecordBatchReader *reader);
|
||||
|
||||
Result<QueryInfo::Ptr> parse_sql_info(const CollectionSchema &schema,
|
||||
const SQLInfo::Ptr &sql_info);
|
||||
|
||||
Result<GroupResults> fill_group_by_result(const QueryInfo &query_info,
|
||||
arrow::RecordBatchReader *reader);
|
||||
|
||||
private:
|
||||
zvec::Profiler::Ptr profiler_;
|
||||
std::string execution_time_info_{};
|
||||
};
|
||||
|
||||
} // namespace zvec::sqlengine
|
||||
Reference in New Issue
Block a user