Debian Codegraph @

lib/proc/proc_query.cpp

raw symbols SCIP
1 /*
2 Copyright (C) 2016 Brazil
3 Copyright (C) 2018-2024 Sutou Kouhei <[email protected]>
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #include "../grn_ctx.hpp"
21 #include "../grn_expr.h"
22 #include "../grn_hash.h"
23 #include "../grn_proc.h"
24 #include "../grn_selector.h"
25 #include "../grn_table_selector.h"
26
27 #include <groonga/plugin.h>
28 #include <groonga.hpp>
29
30 #ifdef GRN_WITH_APACHE_ARROW
31 # include "../grn_arrow.hpp"
32 # include <arrow/util/thread_pool.h>
33 # include <mutex>
34 # include <thread>
35 #endif
36
37 #include <vector>
38
39 static bool grn_query_min_id_skip_enable = false;
40 static int grn_query_parallel_or_n_conditions_threshold = 4;
41 static int grn_query_parallel_or_n_threads_limit = -1;
42
43 extern "C" void
44 grn_proc_query_init_from_env(void)
45 {
46 {
47 char env[GRN_ENV_BUFFER_SIZE];
48 grn_getenv("GRN_QUERY_MIN_ID_SKIP_ENABLE", env, GRN_ENV_BUFFER_SIZE);
49 if (std::string(env) == "yes") {
50 grn_query_min_id_skip_enable = true;
51 }
52 }
53
54 {
55 char env[GRN_ENV_BUFFER_SIZE];
56 grn_getenv("GRN_QUERY_PARALLEL_OR_N_CONDITIONS_THRESHOLD",
57 env,
58 GRN_ENV_BUFFER_SIZE);
59 if (env[0]) {
60 grn_query_parallel_or_n_conditions_threshold = atoi(env);
61 }
62 }
63
64 {
65 #ifdef GRN_WITH_APACHE_ARROW
66 grn_query_parallel_or_n_threads_limit =
67 std::thread::hardware_concurrency() / 3;
68 #endif
69 char env[GRN_ENV_BUFFER_SIZE];
70 grn_getenv("GRN_QUERY_PARALLEL_OR_N_THREADS_LIMIT",
71 env,
72 GRN_ENV_BUFFER_SIZE);
73 if (env[0]) {
74 grn_query_parallel_or_n_threads_limit = atoi(env);
75 }
76 }
77 }
78
79 namespace {
80 class BaseQueryExecutor {
81 protected:
82 BaseQueryExecutor(grn_ctx *ctx,
83 grn_obj *table,
84 int n_args,
85 grn_obj **args,
86 grn_obj *res,
87 grn_operator op,
88 grn_selector_data *selector_data,
89 const char *tag)
90 : ctx_(ctx),
91 table_(table),
92 n_args_(n_args),
93 args_(args),
94 res_(res),
95 op_(op),
96 selector_data_(selector_data),
97 tag_(tag),
98 match_columns_raw_(nullptr),
99 query_expander_(nullptr),
100 query_options_(nullptr),
101 default_mode_(GRN_OP_MATCH),
102 default_operator_(GRN_OP_AND),
103 flags_(GRN_EXPR_SYNTAX_QUERY),
104 flags_specified_(-1),
105 enough_filtered_ratio_(-1),
106 max_n_enough_filtered_records_(-1),
107 match_columns_(nullptr)
108 {
109 }
110
111 virtual ~BaseQueryExecutor()
112 {
113 if (query_expander_ && grn_obj_is_accessor(ctx_, query_expander_)) {
114 grn_obj_close(ctx_, query_expander_);
115 }
116 if (match_columns_) {
117 grn_obj_close(ctx_, match_columns_);
118 }
119 }
120
121 public:
122 grn_rc
123 execute()
124 {
125 if (!prepare()) {
126 return ctx_->rc;
127 }
128 if (op_ == GRN_OP_OR || grn_table_size(ctx_, res_) > 0) {
129 if (!run()) {
130 return ctx_->rc;
131 }
132 }
133 return ctx_->rc;
134 }
135
136 private:
137 virtual bool
138 prepare() = 0;
139 virtual bool
140 run() = 0;
141
142 protected:
143 grn_id
144 get_min_id()
145 {
146 if (op_ == GRN_OP_OR) {
147 return GRN_ID_NIL;
148 }
149 if (!grn_query_min_id_skip_enable) {
150 return GRN_ID_NIL;
151 }
152 if (grn_table_size(ctx_, res_) > 10000) {
153 return GRN_ID_NIL;
154 }
155 return grn_result_set_get_min_id(ctx_,
156 reinterpret_cast<grn_hash *>(res_));
157 }
158
159 float
160 get_weight_factor()
161 {
162 if (selector_data_) {
163 return grn_selector_data_get_weight_factor(ctx_, selector_data_);
164 } else {
165 return 1.0;
166 }
167 }
168
169 virtual bool
170 can_swap_result_set()
171 {
172 return selector_data_ &&
173 grn_selector_data_get_can_swap_result_set(ctx_, selector_data_);
174 }
175
176 void
177 init_table_selector(grn_ctx *ctx,
178 grn_table_selector *table_selector,
179 grn_obj *condition,
180 grn_operator op,
181 grn_id min_id)
182 {
183 grn_table_selector_init(ctx, table_selector, table_, condition, op);
184 grn_table_selector_set_min_id(ctx, table_selector, min_id);
185 grn_table_selector_set_weight_factor(ctx,
186 table_selector,
187 get_weight_factor());
188 if (enough_filtered_ratio_ >= 0) {
189 grn_table_selector_set_enough_filtered_ratio(ctx_,
190 table_selector,
191 enough_filtered_ratio_);
192 }
193 if (max_n_enough_filtered_records_ >= 0) {
194 grn_table_selector_set_max_n_enough_filtered_records(
195 ctx_,
196 table_selector,
197 max_n_enough_filtered_records_);
198 }
199 if (can_swap_result_set()) {
200 grn_table_selector_set_ensure_using_select_result(ctx_,
201 table_selector,
202 true);
203 }
204 }
205
206 bool
207 parse_match_columns_arg()
208 {
209 match_columns_raw_ = args_[0];
210 if (!grn_obj_is_text_family_bulk(ctx_, match_columns_raw_) &&
211 !grn_obj_is_vector(ctx_, match_columns_raw_)) {
212 grn::TextBulk inspected(ctx_);
213 grn_inspect(ctx_, *inspected, match_columns_raw_);
214 GRN_PLUGIN_ERROR(ctx_,
215 GRN_INVALID_ARGUMENT,
216 "%s 1st argument must be string or array: <%.*s>",
217 tag_,
218 (int)GRN_TEXT_LEN(*inspected),
219 GRN_TEXT_VALUE(*inspected));
220 return false;
221 }
222 return true;
223 }
224
225 bool
226 parse_options(grn_obj *options)
227 {
228 grn_obj *query_options_ptr = NULL;
229 #define OPTIONS \
230 "expander", GRN_PROC_OPTION_VALUE_RAW, &query_expander_, "default_mode", \
231 GRN_PROC_OPTION_VALUE_MODE, &default_mode_, "default_operator", \
232 GRN_PROC_OPTION_VALUE_OPERATOR, &default_operator_, "flags", \
233 GRN_PROC_OPTION_VALUE_EXPR_FLAGS, &flags_specified_, "options", \
234 GRN_PROC_OPTION_VALUE_RAW, &query_options_ptr, "enough_filtered_ratio", \
235 GRN_PROC_OPTION_VALUE_DOUBLE, &enough_filtered_ratio_, \
236 "max_n_enough_filtered_records", GRN_PROC_OPTION_VALUE_INT64, \
237 &max_n_enough_filtered_records_
238 if (selector_data_) {
239 grn_selector_data_parse_options(ctx_,
240 selector_data_,
241 options,
242 tag_,
243 OPTIONS,
244 NULL);
245 } else {
246 grn_proc_options_parse(ctx_, options, tag_, OPTIONS, NULL);
247 }
248 #undef OPTIONS
249 if (ctx_->rc != GRN_SUCCESS) {
250 return false;
251 }
252 if (query_expander_) {
253 if (query_expander_->header.type == GRN_PTR) {
254 query_expander_ = GRN_PTR_VALUE(query_expander_);
255 }
256 if (!(grn_obj_is_text_family_bulk(ctx_, query_expander_) ||
257 query_expander_->header.type == GRN_TABLE_HASH_KEY)) {
258 grn::TextBulk inspected(ctx_);
259 grn_inspect(ctx_, *inspected, query_expander_);
260 GRN_PLUGIN_ERROR(ctx_,
261 GRN_INVALID_ARGUMENT,
262 "%s expander must be string or table: <%.*s>",
263 tag_,
264 (int)GRN_TEXT_LEN(*inspected),
265 GRN_TEXT_VALUE(*inspected));
266 return false;
267 }
268 }
269 if (query_options_ptr) {
270 query_options_ = GRN_PTR_VALUE(query_options_ptr);
271 }
272 return true;
273 }
274
275 bool
276 prepare_flags()
277 {
278 if (flags_specified_ == static_cast<grn_expr_flags>(-1)) {
279 flags_ |= GRN_EXPR_ALLOW_PRAGMA | GRN_EXPR_ALLOW_COLUMN;
280 } else {
281 flags_ |= flags_specified_;
282 }
283 return true;
284 }
285
286 bool
287 prepare_match_columns()
288 {
289 if (grn_obj_is_text_family_bulk(ctx_, match_columns_raw_)) {
290 return prepare_match_columns_bulk();
291 } else {
292 return prepare_match_columns_vector();
293 }
294 }
295
296 bool
297 prepare_match_columns_one(const char *match_columns_string,
298 size_t match_columns_string_length,
299 grn_obj **match_columns_inout)
300 {
301 grn_obj *match_columns = *match_columns_inout;
302 if (!match_columns) {
303 grn_obj *dummy_variable;
304 GRN_EXPR_CREATE_FOR_QUERY(ctx_, table_, match_columns, dummy_variable);
305 *match_columns_inout = match_columns;
306 if (!match_columns) {
307 return false;
308 }
309 }
310
311 grn_expr_parse(ctx_,
312 match_columns,
313 match_columns_string,
314 match_columns_string_length,
315 NULL,
316 GRN_OP_MATCH,
317 GRN_OP_AND,
318 GRN_EXPR_SYNTAX_SCRIPT);
319 return ctx_->rc == GRN_SUCCESS;
320 }
321
322 virtual bool
323 prepare_match_columns_bulk()
324 {
325 if (GRN_TEXT_LEN(match_columns_raw_) == 0) {
326 return true;
327 }
328
329 return prepare_match_columns_one(GRN_TEXT_VALUE(match_columns_raw_),
330 GRN_TEXT_LEN(match_columns_raw_),
331 &match_columns_);
332 }
333
334 virtual bool
335 prepare_match_columns_vector()
336 {
337 auto n_match_columns = grn_vector_size(ctx_, match_columns_raw_);
338 if (n_match_columns == 0) {
339 return true;
340 }
341
342 uint32_t n_sub_match_columns = 0;
343 for (unsigned int i = 0; i < n_match_columns; ++i) {
344 const char *sub_match_columns_string;
345 auto sub_match_columns_string_length =
346 grn_vector_get_element(ctx_,
347 match_columns_raw_,
348 i,
349 &sub_match_columns_string,
350 NULL,
351 NULL);
352 if (sub_match_columns_string_length == 0) {
353 continue;
354 }
355 if (!prepare_match_columns_one(sub_match_columns_string,
356 sub_match_columns_string_length,
357 &match_columns_)) {
358 return false;
359 }
360 n_sub_match_columns++;
361 if (n_sub_match_columns >= 2) {
362 grn_expr_append_op(ctx_, match_columns_, GRN_OP_OR, 2);
363 }
364 }
365 return true;
366 }
367
368 bool
369 expand_query(grn_raw_string *query, grn::TextBulk &expanded_query)
370 {
371 bool valid_query_expander = true;
372 if (!query_expander_) {
373 valid_query_expander = false;
374 } else if (grn_obj_is_text_family_bulk(ctx_, query_expander_)) {
375 valid_query_expander = (GRN_TEXT_LEN(query_expander_) > 0);
376 }
377 if (!valid_query_expander) {
378 GRN_TEXT_SET(ctx_, *expanded_query, query->value, query->length);
379 return true;
380 }
381 grn_proc_syntax_expand_query(ctx_,
382 query->value,
383 query->length,
384 flags_,
385 query_expander_,
386 NULL,
387 0,
388 NULL,
389 0,
390 *expanded_query,
391 tag_);
392 return ctx_->rc == GRN_SUCCESS;
393 }
394
395 grn_obj *
396 build_condition(grn_ctx *ctx,
397 grn_obj *match_columns,
398 const char *query,
399 size_t query_length)
400 {
401 grn_obj *condition;
402 grn_obj *dummy_variable;
403 GRN_EXPR_CREATE_FOR_QUERY(ctx, table_, condition, dummy_variable);
404 if (!condition) {
405 return nullptr;
406 }
407 grn_expr_parse(ctx,
408 condition,
409 query,
410 query_length,
411 match_columns,
412 default_mode_,
413 default_operator_,
414 flags_);
415 if (ctx->rc != GRN_SUCCESS) {
416 grn_obj_close(ctx, condition);
417 return nullptr;
418 }
419 if (query_options_) {
420 grn_expr_set_query_options(ctx, condition, query_options_);
421 }
422 return condition;
423 }
424
425 bool
426 select_one(grn_ctx *ctx,
427 grn_obj *match_columns,
428 const char *query,
429 size_t query_length,
430 grn_operator op,
431 grn_id min_id,
432 grn_obj **result_set)
433 {
434 if (ctx->rc != GRN_SUCCESS) {
435 GRN_LOG(ctx,
436 GRN_LOG_DEBUG,
437 "%s[select-one] "
438 "ctx->rc != GRN_SUCCESS before build_condition(): "
439 "<%.*s>: %d: %s:%d: %s",
440 tag_,
441 static_cast<int>(query_length),
442 query,
443 ctx->rc,
444 ctx->errfile,
445 ctx->errline,
446 ctx->errbuf);
447 }
448 auto condition = build_condition(ctx, match_columns, query, query_length);
449 if (!condition) {
450 grn_rc rc = ctx->rc;
451 if (rc == GRN_SUCCESS) {
452 rc = GRN_UNKNOWN_ERROR;
453 }
454 GRN_PLUGIN_ERROR(ctx,
455 rc,
456 "%s failed to build a condition: <%.*s>",
457 tag_,
458 static_cast<int>(query_length),
459 query);
460 return false;
461 }
462 if (ctx->rc != GRN_SUCCESS) {
463 GRN_LOG(ctx,
464 GRN_LOG_DEBUG,
465 "%s[select-one] "
466 "ctx->rc != GRN_SUCCESS before init_table_selector(): "
467 "<%.*s>: %d: %s:%d: %s",
468 tag_,
469 static_cast<int>(query_length),
470 query,
471 ctx->rc,
472 ctx->errfile,
473 ctx->errline,
474 ctx->errbuf);
475 }
476 grn::UniqueObj unique_condition(ctx, condition);
477 grn_table_selector table_selector;
478 init_table_selector(ctx, &table_selector, condition, op, min_id);
479 if (ctx->rc != GRN_SUCCESS) {
480 GRN_LOG(ctx,
481 GRN_LOG_DEBUG,
482 "%s[select-one] "
483 "ctx->rc != GRN_SUCCESS before grn_table_selector_select(): "
484 "<%.*s>: %d: %s:%d: %s",
485 tag_,
486 static_cast<int>(query_length),
487 query,
488 ctx->rc,
489 ctx->errfile,
490 ctx->errline,
491 ctx->errbuf);
492 }
493 auto base_result_set = *result_set;
494 const auto have_multiple_conditions =
495 (grn_expr_get_n_logical_ops(ctx, condition) >= 1);
496 // TODO: We can avoid this when condition uses only OR for
497 // logical operations.
498 const auto need_manual_or =
499 (op == GRN_OP_OR && have_multiple_conditions && base_result_set &&
500 grn_table_size(ctx, base_result_set) > 0);
501 if (need_manual_or) {
502 // We can't use *result_set as the base_result_set with this case.
503 // If we use it for 'A || query("...", "B C")', this expression
504 // is evaluated as '(A || B) && C' not 'A || (B && C)'.
505 base_result_set = nullptr;
506 }
507 auto new_result_set =
508 grn_table_selector_select(ctx, &table_selector, base_result_set);
509 if (new_result_set) {
510 if (ctx->rc == GRN_SUCCESS) {
511 if (need_manual_or) {
512 grn_table_setoperation(ctx,
513 *result_set,
514 new_result_set,
515 *result_set,
516 op);
517 grn_obj_close(ctx, new_result_set);
518 } else {
519 *result_set = new_result_set;
520 }
521 if (can_swap_result_set()) {
522 grn_selector_data_set_result_set(ctx, selector_data_, *result_set);
523 }
524 } else {
525 if (new_result_set != *result_set) {
526 grn_obj_close(ctx, new_result_set);
527 }
528 }
529 }
530 if (ctx->rc != GRN_SUCCESS) {
531 GRN_LOG(ctx,
532 GRN_LOG_DEBUG,
533 "%s[select-one] "
534 "ctx->rc != GRN_SUCCESS before grn_table_selector_fin(): "
535 "<%.*s>: %d: %s:%d: %s",
536 tag_,
537 static_cast<int>(query_length),
538 query,
539 ctx->rc,
540 ctx->errfile,
541 ctx->errline,
542 ctx->errbuf);
543 }
544 grn_table_selector_fin(ctx, &table_selector);
545 return ctx->rc == GRN_SUCCESS;
546 }
547
548 grn_ctx *ctx_;
549 grn_obj *table_;
550 int n_args_;
551 grn_obj **args_;
552 grn_obj *res_;
553 grn_operator op_;
554 grn_selector_data *selector_data_;
555 const char *tag_;
556
557 grn_obj *match_columns_raw_;
558 grn_obj *query_expander_;
559 grn_obj *query_options_;
560 grn_operator default_mode_;
561 grn_operator default_operator_;
562 grn_expr_flags flags_;
563 grn_expr_flags flags_specified_;
564 double enough_filtered_ratio_;
565 int64_t max_n_enough_filtered_records_;
566 grn_obj *match_columns_;
567 };
568
569 class QueryExecutor : public BaseQueryExecutor {
570 public:
571 QueryExecutor(grn_ctx *ctx,
572 grn_obj *table,
573 int n_args,
574 grn_obj **args,
575 grn_obj *res,
576 grn_operator op,
577 grn_selector_data *selector_data)
578 : BaseQueryExecutor(
579 ctx, table, n_args, args, res, op, selector_data, "[query]"),
580 query_()
581 {
582 }
583
584 ~QueryExecutor() override {}
585
586 private:
587 bool
588 prepare() override
589 {
590 if (!validate_args()) {
591 return false;
592 }
593 if (!parse_match_columns_arg()) {
594 return false;
595 }
596 if (!parse_query_arg()) {
597 return false;
598 }
599 if (n_args_ == 3) {
600 grn_obj *options = args_[2];
601 switch (options->header.type) {
602 case GRN_BULK:
603 query_expander_ = options;
604 break;
605 case GRN_TABLE_HASH_KEY:
606 if (!parse_options(options)) {
607 return false;
608 }
609 break;
610 default:
611 {
612 grn::TextBulk inspected(ctx_);
613 grn_inspect(ctx_, *inspected, options);
614 GRN_PLUGIN_ERROR(ctx_,
615 GRN_INVALID_ARGUMENT,
616 "%s "
617 "3rd argument must be string "
618 "or object literal: <%.*s>",
619 tag_,
620 (int)GRN_TEXT_LEN(*inspected),
621 GRN_TEXT_VALUE(*inspected));
622 return false;
623 }
624 break;
625 }
626 }
627 if (!prepare_flags()) {
628 return false;
629 }
630 if (!prepare_match_columns()) {
631 return false;
632 }
633 return true;
634 }
635
636 bool
637 validate_args()
638 {
639 if (!(2 <= n_args_ && n_args_ <= 3)) {
640 GRN_PLUGIN_ERROR(ctx_,
641 GRN_INVALID_ARGUMENT,
642 "%s wrong number of arguments (%d for 2..3)",
643 tag_,
644 n_args_);
645 return false;
646 }
647 return true;
648 }
649
650 bool
651 parse_query_arg()
652 {
653 auto query = args_[1];
654 if (!grn_obj_is_text_family_bulk(ctx_, query)) {
655 grn::TextBulk inspected(ctx_);
656 grn_inspect(ctx_, *inspected, query);
657 GRN_PLUGIN_ERROR(ctx_,
658 GRN_INVALID_ARGUMENT,
659 "%s 2nd argument must be string: <%.*s>",
660 tag_,
661 (int)GRN_TEXT_LEN(*inspected),
662 GRN_TEXT_VALUE(*inspected));
663 return false;
664 }
665 GRN_RAW_STRING_SET(query_, query);
666 grn_raw_string_lstrip(ctx_, &query_);
667 return true;
668 }
669
670 bool
671 run() override
672 {
673 if (query_.length == 0) {
674 return true;
675 }
676
677 grn::TextBulk expanded_query(ctx_);
678 if (!expand_query(&query_, expanded_query)) {
679 return false;
680 }
681
682 return select_one(ctx_,
683 match_columns_,
684 GRN_TEXT_VALUE(*expanded_query),
685 GRN_TEXT_LEN(*expanded_query),
686 op_,
687 get_min_id(),
688 &res_);
689 }
690
691 grn_raw_string query_;
692 };
693
694 class QueryParallelOrExecutor : public BaseQueryExecutor {
695 public:
696 QueryParallelOrExecutor(grn_ctx *ctx,
697 grn_obj *table,
698 int n_args,
699 grn_obj **args,
700 grn_obj *res,
701 grn_operator op,
702 grn_selector_data *selector_data)
703 : BaseQueryExecutor(ctx,
704 table,
705 n_args,
706 args,
707 res,
708 op,
709 selector_data,
710 "[query-parallel-or]"),
711 expanded_queries_(),
712 sub_match_columns_()
713 {
714 GRN_PTR_INIT(&sub_match_columns_,
715 GRN_OBJ_VECTOR | GRN_OBJ_OWN,
716 GRN_ID_NIL);
717 }
718
719 ~QueryParallelOrExecutor() override
720 {
721 GRN_OBJ_FIN(ctx_, &sub_match_columns_);
722 }
723
724 protected:
725 bool
726 can_swap_result_set() override
727 {
728 return false;
729 }
730
731 private:
732 bool
733 prepare_match_columns_bulk() override
734 {
735 if (GRN_TEXT_LEN(match_columns_raw_) > 0) {
736 grn_obj *sub_match_columns = nullptr;
737 if (!prepare_match_columns_one(GRN_TEXT_VALUE(match_columns_raw_),
738 GRN_TEXT_LEN(match_columns_raw_),
739 &sub_match_columns)) {
740 return false;
741 }
742 GRN_PTR_PUT(ctx_, &sub_match_columns_, sub_match_columns);
743 } else {
744 GRN_PTR_PUT(ctx_, &sub_match_columns_, NULL);
745 }
746 return true;
747 }
748
749 bool
750 prepare_match_columns_vector() override
751 {
752 auto n_match_columns = grn_vector_size(ctx_, match_columns_raw_);
753 if (n_match_columns == 0) {
754 return true;
755 }
756
757 for (unsigned int i = 0; i < n_match_columns; ++i) {
758 const char *sub_match_columns_string;
759 auto sub_match_columns_string_length =
760 grn_vector_get_element(ctx_,
761 match_columns_raw_,
762 i,
763 &sub_match_columns_string,
764 NULL,
765 NULL);
766 if (sub_match_columns_string_length == 0) {
767 continue;
768 }
769 grn_obj *sub_match_columns = nullptr;
770 if (!prepare_match_columns_one(sub_match_columns_string,
771 sub_match_columns_string_length,
772 &sub_match_columns)) {
773 return false;
774 }
775 GRN_PTR_PUT(ctx_, &sub_match_columns_, sub_match_columns);
776 }
777 return true;
778 }
779
780 bool
781 prepare() override
782 {
783 if (!validate_args()) {
784 return false;
785 }
786 if (!parse_match_columns_arg()) {
787 return false;
788 }
789 auto n_queries_ = n_args_ - 1;
790 if (n_args_ > 2 &&
791 args_[n_args_ - 1]->header.type == GRN_TABLE_HASH_KEY) {
792 n_queries_--;
793 auto options = args_[n_args_ - 1];
794 if (!parse_options(options)) {
795 return false;
796 }
797 }
798 if (!prepare_flags()) {
799 return false;
800 }
801 if (!parse_query_args(args_ + 1, n_queries_)) {
802 return false;
803 }
804 if (!prepare_match_columns()) {
805 return false;
806 }
807 return true;
808 }
809
810 bool
811 validate_args()
812 {
813 if (n_args_ < 2) {
814 GRN_PLUGIN_ERROR(ctx_,
815 GRN_INVALID_ARGUMENT,
816 "%s wrong number of arguments (%d for 2..)",
817 tag_,
818 n_args_);
819 return false;
820 }
821 return true;
822 }
823
824 bool
825 parse_query_args(grn_obj **queries, int n_queries)
826 {
827 grn::TextBulk expanded_query(ctx_);
828 for (int i = 0; i < n_queries; ++i) {
829 auto query_bulk = queries[i];
830 if (!grn_obj_is_text_family_bulk(ctx_, query_bulk)) {
831 grn::TextBulk inspected(ctx_);
832 grn_inspect(ctx_, *inspected, query_bulk);
833 GRN_PLUGIN_ERROR(ctx_,
834 GRN_INVALID_ARGUMENT,
835 "%s %dth argument must be string: <%.*s>",
836 tag_,
837 static_cast<int>(queries - args_ + i),
838 static_cast<int>(GRN_TEXT_LEN(*inspected)),
839 GRN_TEXT_VALUE(*inspected));
840 return false;
841 }
842 grn_raw_string query;
843 GRN_RAW_STRING_SET(query, query_bulk);
844 grn_raw_string_lstrip(ctx_, &query);
845 if (query.length == 0) {
846 continue;
847 }
848 GRN_BULK_REWIND(*expanded_query);
849 if (!expand_query(&query, expanded_query)) {
850 return false;
851 }
852 expanded_queries_.emplace_back(GRN_TEXT_VALUE(*expanded_query),
853 GRN_TEXT_LEN(*expanded_query));
854 }
855 return true;
856 }
857
858 bool
859 run() override
860 {
861 if (expanded_queries_.empty()) {
862 return true;
863 }
864 if (!select()) {
865 return false;
866 }
867 return ctx_->rc == GRN_SUCCESS;
868 }
869
870 bool
871 select()
872 {
873 bool processed = false;
874 #ifdef GRN_WITH_APACHE_ARROW
875 int n_conditions =
876 GRN_PTR_VECTOR_SIZE(&sub_match_columns_) * expanded_queries_.size();
877 if (n_conditions >= grn_query_parallel_or_n_conditions_threshold) {
878 auto capacity = grn_query_parallel_or_n_threads_limit;
879 if (capacity < 0) {
880 capacity = ::arrow::internal::ThreadPool::DefaultCapacity();
881 }
882 auto pool = ::arrow::internal::ThreadPool::MakeEternal(capacity);
883 if (pool.ok()) {
884 if (!select_parallel(*pool)) {
885 return false;
886 }
887 processed = true;
888 }
889 }
890 #endif
891 if (!processed) {
892 if (!select_sequential()) {
893 return false;
894 }
895 }
896 return true;
897 }
898
899 #ifdef GRN_WITH_APACHE_ARROW
900 bool
901 select_parallel(std::shared_ptr<::arrow::internal::ThreadPool> pool)
902 {
903 grn_id min_id = get_min_id();
904 // merge isn't parallel. This is just used for queue.
905 auto merge_pool_result = ::arrow::internal::ThreadPool::MakeEternal(1);
906 if (!grnarrow::check(ctx_,
907 merge_pool_result,
908 "%s failed to create a thread pool for merging",
909 tag_)) {
910 return false;
911 }
912 auto merge_pool = *merge_pool_result;
913 std::mutex mutex;
914 std::vector<grn::UniqueObj> unique_sub_results;
915 auto merge = [&](grn_obj *sub_result) {
916 std::lock_guard<std::mutex> lock(mutex);
917 auto sub_ctx = grn_ctx_pull_child(ctx_);
918 grn::ChildCtxReleaser releaser(ctx_, sub_ctx);
919 if (unique_sub_results.empty()) {
920 unique_sub_results.emplace_back(ctx_, sub_result);
921 } else {
922 if (ctx_->rc == GRN_SUCCESS) {
923 grn_table_setoperation(sub_ctx,
924 unique_sub_results[0].get(),
925 sub_result,
926 unique_sub_results[0].get(),
927 GRN_OP_OR);
928 }
929 unique_sub_results.emplace_back(ctx_, sub_result);
930 }
931 return arrow::Status::OK();
932 };
933 std::vector<::arrow::Future<>> merge_futures;
934 auto select = [&](grn_obj *match_columns, const std::string &query) {
935 auto sub_ctx = grn_ctx_pull_child(ctx_);
936 grn::ChildCtxReleaser releaser(ctx_, sub_ctx);
937 grn_obj *sub_result = nullptr;
938 {
939 std::lock_guard<std::mutex> lock(mutex);
940 auto n_unique_sub_results = unique_sub_results.size();
941 if (n_unique_sub_results < 2) {
942 sub_result =
943 grn_table_create(sub_ctx,
944 nullptr,
945 0,
946 nullptr,
947 GRN_OBJ_TABLE_HASH_KEY | GRN_OBJ_WITH_SUBREC,
948 table_,
949 nullptr);
950 } else {
951 sub_result = unique_sub_results[n_unique_sub_results - 1].release();
952 unique_sub_results.pop_back();
953 clear_result_set(ctx_, sub_result);
954 }
955 }
956 if (!select_one(sub_ctx,
957 match_columns,
958 query.data(),
959 query.length(),
960 GRN_OP_OR,
961 min_id,
962 &sub_result)) {
963 std::lock_guard<std::mutex> lock(mutex);
964 GRN_PLUGIN_ERROR(ctx_,
965 GRN_UNKNOWN_ERROR,
966 "%s failed to select a query: <%s>: %u: %s:%d: %s",
967 tag_,
968 query.c_str(),
969 sub_ctx->rc,
970 sub_ctx->errfile,
971 sub_ctx->errline,
972 sub_ctx->errbuf);
973 return ::arrow::Status::OK();
974 }
975 auto merge_future = merge_pool->Submit(merge, sub_result);
976 if (!merge_future.ok()) {
977 std::lock_guard<std::mutex> lock(mutex);
978 if (!grnarrow::check(ctx_,
979 merge_future,
980 "%s failed to submit a merge job",
981 tag_)) {
982 return merge_future.status();
983 }
984 }
985 {
986 std::lock_guard<std::mutex> lock(mutex);
987 merge_futures.push_back(*merge_future);
988 }
989 return ::arrow::Status::OK();
990 };
991
992 {
993 std::vector<::arrow::Future<>> select_futures;
994 auto n_sub_match_columns = GRN_PTR_VECTOR_SIZE(&sub_match_columns_);
995 for (size_t i = 0; i < n_sub_match_columns; ++i) {
996 grn_obj *sub_match_column = GRN_PTR_VALUE_AT(&sub_match_columns_, i);
997 for (const auto &expanded_query : expanded_queries_) {
998 auto select_future =
999 pool->Submit(select, sub_match_column, expanded_query);
1000 if (!select_future.ok()) {
1001 std::lock_guard<std::mutex> lock(mutex);
1002 if (!grnarrow::check(ctx_,
1003 select_future,
1004 "%s failed to submit a select job",
1005 tag_)) {
1006 break;
1007 }
1008 }
1009 select_futures.push_back(*select_future);
1010 }
1011 if (ctx_->rc != GRN_SUCCESS) {
1012 break;
1013 }
1014 }
1015 auto status = ::arrow::Status::OK();
1016 for (auto &select_future : select_futures) {
1017 status &= select_future.status();
1018 }
1019 if (!grnarrow::check(ctx_,
1020 status,
1021 "%s failed to complete select jobs",
1022 tag_)) {
1023 return false;
1024 }
1025 for (auto &merge_future : merge_futures) {
1026 status &= merge_future.status();
1027 }
1028 if (!grnarrow::check(ctx_,
1029 status,
1030 "%s failed to complete merge jobs",
1031 tag_)) {
1032 return false;
1033 }
1034 }
1035 if (ctx_->rc == GRN_SUCCESS && !unique_sub_results.empty()) {
1036 grn_table_setoperation(ctx_,
1037 res_,
1038 unique_sub_results[0].get(),
1039 res_,
1040 op_);
1041 }
1042 return ctx_->rc == GRN_SUCCESS;
1043 }
1044 #endif
1045
1046 bool
1047 select_sequential()
1048 {
1049 grn_id min_id = get_min_id();
1050 grn::UniqueObj unique_sub_result(ctx_, nullptr);
1051 grn::UniqueObj unique_working_sub_result(ctx_, nullptr);
1052 auto n_sub_match_columns = GRN_PTR_VECTOR_SIZE(&sub_match_columns_);
1053 for (size_t i = 0; i < n_sub_match_columns; ++i) {
1054 grn_obj *sub_match_column = GRN_PTR_VALUE_AT(&sub_match_columns_, i);
1055 for (const auto &expanded_query : expanded_queries_) {
1056 auto sub_result = unique_working_sub_result.get();
1057 if (!select_one(ctx_,
1058 sub_match_column,
1059 expanded_query.data(),
1060 expanded_query.length(),
1061 GRN_OP_OR,
1062 min_id,
1063 &sub_result)) {
1064 return false;
1065 }
1066 if (!unique_sub_result.get()) {
1067 unique_sub_result.reset(sub_result);
1068 } else {
1069 grn_table_setoperation(ctx_,
1070 unique_sub_result.get(),
1071 sub_result,
1072 unique_sub_result.get(),
1073 GRN_OP_OR);
1074 if (!unique_working_sub_result.get()) {
1075 unique_working_sub_result.reset(sub_result);
1076 }
1077 clear_result_set(ctx_, unique_working_sub_result.get());
1078 }
1079 }
1080 }
1081 grn_table_setoperation(ctx_, res_, unique_sub_result.get(), res_, op_);
1082 return true;
1083 }
1084
1085 void
1086 clear_result_set(grn_ctx *ctx, grn_obj *result_set)
1087 {
1088 // This is faster than grn_hash_truncate() or grn_table_create().
1089 GRN_HASH_EACH_BEGIN(ctx,
1090 reinterpret_cast<grn_hash *>(result_set),
1091 cursor,
1092 id)
1093 {
1094 grn_hash_cursor_delete(ctx, cursor, nullptr);
1095 }
1096 GRN_HASH_EACH_END(ctx, cursor);
1097 }
1098
1099 std::vector<std::string> expanded_queries_;
1100 grn_obj sub_match_columns_;
1101 };
1102 } // namespace
1103
1104 static grn_rc
1105 run_query(grn_ctx *ctx,
1106 grn_obj *table,
1107 int n_args,
1108 grn_obj **args,
1109 grn_obj *res,
1110 grn_operator op,
1111 grn_selector_data *selector_data)
1112 {
1113 QueryExecutor executor(ctx, table, n_args, args, res, op, selector_data);
1114 return executor.execute();
1115 }
1116
1117 static grn_obj *
1118 func_query(grn_ctx *ctx, int n_args, grn_obj **args, grn_user_data *user_data)
1119 {
1120 grn_proc_selector_to_function_data data;
1121
1122 if (grn_proc_selector_to_function_data_init(ctx, &data, user_data)) {
1123 grn_rc rc;
1124 rc =
1125 run_query(ctx, data.table, n_args, args, data.records, GRN_OP_AND, NULL);
1126 if (rc == GRN_SUCCESS) {
1127 grn_proc_selector_to_function_data_selected(ctx, &data);
1128 }
1129 }
1130 grn_proc_selector_to_function_data_fin(ctx, &data);
1131
1132 return data.found;
1133 }
1134
1135 static grn_rc
1136 selector_query(grn_ctx *ctx,
1137 grn_obj *table,
1138 grn_obj *index,
1139 int n_args,
1140 grn_obj **args,
1141 grn_obj *res,
1142 grn_operator op)
1143 {
1144 return run_query(ctx,
1145 table,
1146 n_args - 1,
1147 args + 1,
1148 res,
1149 op,
1150 grn_selector_data_get(ctx));
1151 }
1152
1153 void
1154 grn_proc_init_query(grn_ctx *ctx)
1155 {
1156 grn_obj *selector_proc = grn_proc_create(ctx,
1157 "query",
1158 -1,
1159 GRN_PROC_FUNCTION,
1160 func_query,
1161 NULL,
1162 NULL,
1163 0,
1164 NULL);
1165 grn_proc_set_selector(ctx, selector_proc, selector_query);
1166 grn_proc_set_selector_operator(ctx, selector_proc, GRN_OP_NOP);
1167 }
1168
1169 static grn_rc
1170 run_query_parallel_or(grn_ctx *ctx,
1171 grn_obj *table,
1172 int n_args,
1173 grn_obj **args,
1174 grn_obj *res,
1175 grn_operator op,
1176 grn_selector_data *selector_data)
1177 {
1178 QueryParallelOrExecutor
1179 executor(ctx, table, n_args, args, res, op, selector_data);
1180 return executor.execute();
1181 }
1182
1183 static grn_obj *
1184 func_query_parallel_or(grn_ctx *ctx,
1185 int n_args,
1186 grn_obj **args,
1187 grn_user_data *user_data)
1188 {
1189 grn_proc_selector_to_function_data data;
1190
1191 if (grn_proc_selector_to_function_data_init(ctx, &data, user_data)) {
1192 grn_rc rc;
1193 rc = run_query_parallel_or(ctx,
1194 data.table,
1195 n_args,
1196 args,
1197 data.records,
1198 GRN_OP_AND,
1199 NULL);
1200 if (rc == GRN_SUCCESS) {
1201 grn_proc_selector_to_function_data_selected(ctx, &data);
1202 }
1203 }
1204 grn_proc_selector_to_function_data_fin(ctx, &data);
1205
1206 return data.found;
1207 }
1208
1209 static grn_rc
1210 selector_query_parallel_or(grn_ctx *ctx,
1211 grn_obj *table,
1212 grn_obj *index,
1213 int n_args,
1214 grn_obj **args,
1215 grn_obj *res,
1216 grn_operator op)
1217 {
1218 return run_query_parallel_or(ctx,
1219 table,
1220 n_args - 1,
1221 args + 1,
1222 res,
1223 op,
1224 grn_selector_data_get(ctx));
1225 }
1226
1227 void
1228 grn_proc_init_query_parallel_or(grn_ctx *ctx)
1229 {
1230 grn_obj *selector_proc = grn_proc_create(ctx,
1231 "query_parallel_or",
1232 -1,
1233 GRN_PROC_FUNCTION,
1234 func_query_parallel_or,
1235 NULL,
1236 NULL,
1237 0,
1238 NULL);
1239 grn_proc_set_selector(ctx, selector_proc, selector_query_parallel_or);
1240 grn_proc_set_selector_operator(ctx, selector_proc, GRN_OP_NOP);
1241 }
1242
1243 static grn_obj *
1244 command_query_expand(grn_ctx *ctx,
1245 int n_args,
1246 grn_obj **args,
1247 grn_user_data *user_data)
1248 {
1249 grn_obj *expander;
1250 const char *query;
1251 size_t query_size;
1252 const char *flags_raw;
1253 size_t flags_raw_size;
1254 grn_expr_flags flags = GRN_EXPR_SYNTAX_QUERY;
1255 const char *term_column;
1256 size_t term_column_size;
1257 const char *expanded_term_column;
1258 size_t expanded_term_column_size;
1259 grn_obj expanded_query;
1260
1261 expander = grn_plugin_proc_get_var(ctx, user_data, "expander", -1);
1262 query =
1263 grn_plugin_proc_get_var_string(ctx, user_data, "query", -1, &query_size);
1264 flags_raw = grn_plugin_proc_get_var_string(ctx,
1265 user_data,
1266 "flags",
1267 -1,
1268 &flags_raw_size);
1269 term_column = grn_plugin_proc_get_var_string(ctx,
1270 user_data,
1271 "term_column",
1272 -1,
1273 &term_column_size);
1274 expanded_term_column =
1275 grn_plugin_proc_get_var_string(ctx,
1276 user_data,
1277 "expanded_term_column",
1278 -1,
1279 &expanded_term_column_size);
1280
1281 if (flags_raw_size > 0) {
1282 grn_obj flags_bulk;
1283 GRN_TEXT_INIT(&flags_bulk, GRN_OBJ_DO_SHALLOW_COPY);
1284 GRN_TEXT_SET(ctx, &flags_bulk, flags_raw, flags_raw_size);
1285 flags |=
1286 grn_proc_expr_query_flags_parse(ctx, &flags_bulk, "[query][expand]");
1287 } else {
1288 flags |= GRN_EXPR_ALLOW_PRAGMA | GRN_EXPR_ALLOW_COLUMN;
1289 }
1290
1291 if (ctx->rc != GRN_SUCCESS) {
1292 return NULL;
1293 }
1294
1295 GRN_TEXT_INIT(&expanded_query, 0);
1296 grn_proc_syntax_expand_query(ctx,
1297 query,
1298 query_size,
1299 flags,
1300 expander,
1301 term_column,
1302 term_column_size,
1303 expanded_term_column,
1304 expanded_term_column_size,
1305 &expanded_query,
1306 "[query][expand]");
1307 if (ctx->rc == GRN_SUCCESS) {
1308 grn_ctx_output_str(ctx,
1309 GRN_TEXT_VALUE(&expanded_query),
1310 GRN_TEXT_LEN(&expanded_query));
1311 }
1312 GRN_OBJ_FIN(ctx, &expanded_query);
1313
1314 return NULL;
1315 }
1316
1317 void
1318 grn_proc_init_query_expand(grn_ctx *ctx)
1319 {
1320 grn_expr_var vars[5];
1321
1322 grn_plugin_expr_var_init(ctx, &(vars[0]), "expander", -1);
1323 grn_plugin_expr_var_init(ctx, &(vars[1]), "query", -1);
1324 grn_plugin_expr_var_init(ctx, &(vars[2]), "flags", -1);
1325 grn_plugin_expr_var_init(ctx, &(vars[3]), "term_column", -1);
1326 grn_plugin_expr_var_init(ctx, &(vars[4]), "expanded_term_column", -1);
1327 grn_plugin_command_create(ctx,
1328 "query_expand",
1329 -1,
1330 command_query_expand,
1331 5,
1332 vars);
1333 }