-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
statement_restrictions.cc
2058 lines (1796 loc) · 93.1 KB
/
statement_restrictions.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <algorithm>
#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/algorithm/cxx11/any_of.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <functional>
#include <ranges>
#include <stdexcept>
#include "cql3/expr/expression.hh"
#include "cql3/expr/evaluate.hh"
#include "cql3/expr/expr-utils.hh"
#include "query-result-reader.hh"
#include "statement_restrictions.hh"
#include "data_dictionary/data_dictionary.hh"
#include "cartesian_product.hh"
#include "cql3/cql_config.hh"
#include "cql3/constants.hh"
#include "cql3/lists.hh"
#include "cql3/selection/selection.hh"
#include "cql3/statements/request_validations.hh"
#include "types/list.hh"
#include "types/map.hh"
#include "types/set.hh"
namespace {
struct maybe_column_definition {
const column_definition* value;
};
}
template<>
struct fmt::formatter<maybe_column_definition> : fmt::formatter<std::string_view> {
template <typename FormatContext>
auto format(const maybe_column_definition& cd, FormatContext& ctx) const {
if (cd.value != nullptr) {
return fmt::format_to(ctx.out(), "{}", *cd.value);
} else {
return fmt::format_to(ctx.out(), "(null)");
}
}
};
namespace cql3 {
namespace restrictions {
static logging::logger rlogger("restrictions");
using boost::adaptors::filtered;
using boost::adaptors::transformed;
using statements::request_validations::invalid_request;
statement_restrictions::statement_restrictions(schema_ptr schema, bool allow_filtering)
: _schema(schema)
, _partition_range_is_simple(true)
{ }
template <typename Visitor>
concept visitor_with_binary_operator_context = requires (Visitor v) {
{ v.current_binary_operator } -> std::convertible_to<const expr::binary_operator*>;
};
void with_current_binary_operator(
visitor_with_binary_operator_context auto& visitor,
std::invocable<const expr::binary_operator&> auto func) {
if (!visitor.current_binary_operator) {
throw std::logic_error("Evaluation expected within binary operator");
}
func(*visitor.current_binary_operator);
}
/// Every token, or if no tokens, an EQ/IN of every single PK column.
static std::vector<expr::expression> extract_partition_range(
const expr::expression& where_clause, schema_ptr schema) {
using namespace expr;
struct extract_partition_range_visitor {
schema_ptr table_schema;
std::optional<expression> tokens;
std::unordered_map<const column_definition*, expression> single_column;
const binary_operator* current_binary_operator = nullptr;
void operator()(const conjunction& c) {
std::ranges::for_each(c.children, [this] (const expression& child) { expr::visit(*this, child); });
}
void operator()(const binary_operator& b) {
if (current_binary_operator) {
throw std::logic_error("Nested binary operators are not supported");
}
current_binary_operator = &b;
expr::visit(*this, b.lhs);
current_binary_operator = nullptr;
}
void operator()(const function_call& token_fun_call) {
if (!is_partition_token_for_schema(token_fun_call, *table_schema)) {
on_internal_error(rlogger, "extract_partition_range(function_call)");
}
with_current_binary_operator(*this, [&] (const binary_operator& b) {
if (tokens) {
tokens = make_conjunction(std::move(*tokens), b);
} else {
tokens = b;
}
});
}
void operator()(const column_value& cv) {
auto s = &cv;
with_current_binary_operator(*this, [&] (const binary_operator& b) {
if (s->col->is_partition_key() && (b.op == oper_t::EQ || b.op == oper_t::IN)) {
const auto found = single_column.find(s->col);
if (found == single_column.end()) {
single_column[s->col] = b;
} else {
found->second = make_conjunction(std::move(found->second), b);
}
}
});
}
void operator()(const tuple_constructor& s) {
// Partition key columns are not legal in tuples, so ignore tuples.
}
void operator()(const subscript& sub) {
const column_value& cval = get_subscripted_column(sub.val);
with_current_binary_operator(*this, [&] (const binary_operator& b) {
if (cval.col->is_partition_key() && (b.op == oper_t::EQ || b.op == oper_t::IN)) {
const auto found = single_column.find(cval.col);
if (found == single_column.end()) {
single_column[cval.col] = b;
} else {
found->second = make_conjunction(std::move(found->second), b);
}
}
});
}
void operator()(const constant&) {}
void operator()(const unresolved_identifier&) {
on_internal_error(rlogger, "extract_partition_range(unresolved_identifier)");
}
void operator()(const column_mutation_attribute&) {
on_internal_error(rlogger, "extract_partition_range(column_mutation_attribute)");
}
void operator()(const cast&) {
on_internal_error(rlogger, "extract_partition_range(cast)");
}
void operator()(const field_selection&) {
on_internal_error(rlogger, "extract_partition_range(field_selection)");
}
void operator()(const bind_variable&) {
on_internal_error(rlogger, "extract_partition_range(bind_variable)");
}
void operator()(const untyped_constant&) {
on_internal_error(rlogger, "extract_partition_range(untyped_constant)");
}
void operator()(const collection_constructor&) {
on_internal_error(rlogger, "extract_partition_range(collection_constructor)");
}
void operator()(const usertype_constructor&) {
on_internal_error(rlogger, "extract_partition_range(usertype_constructor)");
}
void operator()(const temporary&) {
on_internal_error(rlogger, "extract_partition_range(temporary)");
}
};
extract_partition_range_visitor v {
.table_schema = schema
};
expr::visit(v, where_clause);
if (v.tokens) {
return {std::move(*v.tokens)};
}
if (v.single_column.size() == schema->partition_key_size()) {
return boost::copy_range<std::vector<expression>>(v.single_column | boost::adaptors::map_values);
}
return {};
}
/// Extracts where_clause atoms with clustering-column LHS and copies them to a vector. These elements define the
/// boundaries of any clustering slice that can possibly meet where_clause. This vector can be calculated before
/// binding expression markers, since LHS and operator are always known.
static std::vector<expr::expression> extract_clustering_prefix_restrictions(
const expr::expression& where_clause, schema_ptr schema) {
using namespace expr;
/// Collects all clustering-column restrictions from an expression. Presumes the expression only uses
/// conjunction to combine subexpressions.
struct visitor {
schema_ptr table_schema;
std::vector<expression> multi; ///< All multi-column restrictions.
/// All single-clustering-column restrictions, grouped by column. Each value is either an atom or a
/// conjunction of atoms.
std::unordered_map<const column_definition*, expression> single;
const binary_operator* current_binary_operator = nullptr;
void operator()(const conjunction& c) {
std::ranges::for_each(c.children, [this] (const expression& child) { expr::visit(*this, child); });
}
void operator()(const binary_operator& b) {
if (current_binary_operator) {
throw std::logic_error("Nested binary operators are not supported");
}
current_binary_operator = &b;
expr::visit(*this, b.lhs);
current_binary_operator = nullptr;
}
void operator()(const tuple_constructor& tc) {
for (auto& e : tc.elements) {
if (!expr::is<column_value>(e)) {
on_internal_error(rlogger, fmt::format("extract_clustering_prefix_restrictions: tuple of non-column_value: {}", tc));
}
}
with_current_binary_operator(*this, [&] (const binary_operator& b) {
multi.push_back(b);
});
}
void operator()(const column_value& cv) {
auto s = &cv;
with_current_binary_operator(*this, [&] (const binary_operator& b) {
if (s->col->is_clustering_key()) {
const auto found = single.find(s->col);
if (found == single.end()) {
single[s->col] = b;
} else {
found->second = make_conjunction(std::move(found->second), b);
}
}
});
}
void operator()(const subscript& sub) {
const column_value& cval = get_subscripted_column(sub.val);
with_current_binary_operator(*this, [&] (const binary_operator& b) {
if (cval.col->is_clustering_key()) {
const auto found = single.find(cval.col);
if (found == single.end()) {
single[cval.col] = b;
} else {
found->second = make_conjunction(std::move(found->second), b);
}
}
});
}
void operator()(const function_call& fun_call) {
if (is_partition_token_for_schema(fun_call, *table_schema)) {
// A token cannot be a clustering prefix restriction
return;
}
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(function_call)");
}
void operator()(const constant&) {}
void operator()(const unresolved_identifier&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(unresolved_identifier)");
}
void operator()(const column_mutation_attribute&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(column_mutation_attribute)");
}
void operator()(const cast&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(cast)");
}
void operator()(const field_selection&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(field_selection)");
}
void operator()(const bind_variable&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(bind_variable)");
}
void operator()(const untyped_constant&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(untyped_constant)");
}
void operator()(const collection_constructor&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(collection_constructor)");
}
void operator()(const usertype_constructor&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(usertype_constructor)");
}
void operator()(const temporary&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(temporary)");
}
};
visitor v {
.table_schema = schema
};
expr::visit(v, where_clause);
if (!v.multi.empty()) {
return std::move(v.multi);
}
std::vector<expression> prefix;
for (const auto& col : schema->clustering_key_columns()) {
const auto found = v.single.find(&col);
if (found == v.single.end()) { // Any further restrictions are skipping the CK order.
break;
}
if (find_needs_filtering(found->second)) { // This column's restriction doesn't define a clear bound.
// TODO: if this is a conjunction of filtering and non-filtering atoms, we could split them and add the
// latter to the prefix.
break;
}
prefix.push_back(found->second);
if (has_slice(found->second)) {
break;
}
}
return prefix;
}
statement_restrictions::statement_restrictions(data_dictionary::database db,
schema_ptr schema,
statements::statement_type type,
const expr::expression& where_clause,
prepare_context& ctx,
bool selects_only_static_columns,
bool for_view,
bool allow_filtering,
check_indexes do_check_indexes)
: statement_restrictions(schema, allow_filtering)
{
_check_indexes = do_check_indexes;
for (auto&& relation_expr : boolean_factors(where_clause)) {
const expr::binary_operator* relation_binop = expr::as_if<expr::binary_operator>(&relation_expr);
if (relation_binop == nullptr) {
on_internal_error(rlogger, format("statement_restrictions: where clause has non-binop element: {}", relation_expr));
}
expr::binary_operator prepared_restriction = expr::validate_and_prepare_new_restriction(*relation_binop, db, schema, ctx);
add_restriction(prepared_restriction, schema, allow_filtering, for_view);
if (prepared_restriction.op != expr::oper_t::IS_NOT) {
_where = _where.has_value() ? make_conjunction(std::move(*_where), prepared_restriction) : prepared_restriction;
}
}
if (_where.has_value()) {
if (!has_token_restrictions()) {
_single_column_partition_key_restrictions = expr::get_single_column_restrictions_map(_partition_key_restrictions);
}
if (!expr::contains_multi_column_restriction(_clustering_columns_restrictions)) {
_single_column_clustering_key_restrictions = expr::get_single_column_restrictions_map(_clustering_columns_restrictions);
}
_single_column_nonprimary_key_restrictions = expr::get_single_column_restrictions_map(_nonprimary_key_restrictions);
_clustering_prefix_restrictions = extract_clustering_prefix_restrictions(*_where, _schema);
_partition_range_restrictions = extract_partition_range(*_where, _schema);
}
_has_multi_column = find_binop(_clustering_columns_restrictions, expr::is_multi_column);
if (_check_indexes) {
auto cf = db.find_column_family(schema);
auto& sim = cf.get_index_manager();
const expr::allow_local_index allow_local(
!has_partition_key_unrestricted_components()
&& partition_key_restrictions_is_all_eq());
_has_multi_column = find_binop(_clustering_columns_restrictions, expr::is_multi_column);
_has_queriable_ck_index = clustering_columns_restrictions_have_supporting_index(sim, allow_local)
&& !type.is_delete();
_has_queriable_pk_index = parition_key_restrictions_have_supporting_index(sim, allow_local)
&& !type.is_delete();
_has_queriable_regular_index = expr::index_supports_some_column(_nonprimary_key_restrictions, sim, allow_local)
&& !type.is_delete();
} else {
_has_queriable_ck_index = false;
_has_queriable_pk_index = false;
_has_queriable_regular_index = false;
}
// At this point, the select statement if fully constructed, but we still have a few things to validate
process_partition_key_restrictions(for_view, allow_filtering);
// Some but not all of the partition key columns have been specified;
// hence we need turn these restrictions into index expressions.
if (_uses_secondary_indexing || pk_restrictions_need_filtering()) {
_index_restrictions.push_back(_partition_key_restrictions);
}
// If the only updated/deleted columns are static, then we don't need clustering columns.
// And in fact, unless it is an INSERT, we reject if clustering columns are provided as that
// suggest something unintended. For instance, given:
// CREATE TABLE t (k int, v int, s int static, PRIMARY KEY (k, v))
// it can make sense to do:
// INSERT INTO t(k, v, s) VALUES (0, 1, 2)
// but both
// UPDATE t SET s = 3 WHERE k = 0 AND v = 1
// DELETE s FROM t WHERE k = 0 AND v = 1
// sounds like you don't really understand what your are doing.
if (selects_only_static_columns && has_clustering_columns_restriction()) {
if (type.is_update() || type.is_delete()) {
throw exceptions::invalid_request_exception(format("Invalid restrictions on clustering columns since the {} statement modifies only static columns", type));
}
if (type.is_select()) {
throw exceptions::invalid_request_exception(
"Cannot restrict clustering columns when selecting only static columns");
}
}
process_clustering_columns_restrictions(for_view, allow_filtering);
// Covers indexes on the first clustering column (among others).
if (_is_key_range && _has_queriable_ck_index && !_has_multi_column) {
_uses_secondary_indexing = true;
}
if (_uses_secondary_indexing || clustering_key_restrictions_need_filtering()) {
_index_restrictions.push_back(_clustering_columns_restrictions);
} else if (find_binop(_clustering_columns_restrictions, expr::is_on_collection)) {
fail(unimplemented::cause::INDEXES);
}
if (!expr::is_empty_restriction(_nonprimary_key_restrictions)) {
if (_has_queriable_regular_index && _partition_range_is_simple) {
_uses_secondary_indexing = true;
} else if (!allow_filtering) {
throw exceptions::invalid_request_exception("Cannot execute this query as it might involve data filtering and "
"thus may have unpredictable performance. If you want to execute "
"this query despite the performance unpredictability, use ALLOW FILTERING");
}
_index_restrictions.push_back(_nonprimary_key_restrictions);
}
if (_uses_secondary_indexing && !(for_view || allow_filtering)) {
validate_secondary_index_selections(selects_only_static_columns);
}
}
bool
statement_restrictions::clustering_key_restrictions_has_IN() const {
return find(_clustering_columns_restrictions, expr::oper_t::IN);
}
bool
statement_restrictions::clustering_key_restrictions_has_only_eq() const {
return expr::has_only_eq_binops(_clustering_columns_restrictions);
}
bool
statement_restrictions::has_token_restrictions() const {
return has_partition_token(_partition_key_restrictions, *_schema);
}
bool
statement_restrictions::key_is_in_relation() const {
return find(_partition_key_restrictions, expr::oper_t::IN);
}
const expr::expression&
statement_restrictions::get_restrictions(column_kind kind) const {
switch (kind) {
case column_kind::partition_key: return _partition_key_restrictions;
case column_kind::clustering_key: return _clustering_columns_restrictions;
default: return _nonprimary_key_restrictions;
}
}
bool
statement_restrictions::has_clustering_columns_restriction() const {
return !expr::is_empty_restriction(_clustering_columns_restrictions);
}
bool
statement_restrictions::has_non_primary_key_restriction() const {
return !expr::is_empty_restriction(_nonprimary_key_restrictions);
}
bool
statement_restrictions::ck_restrictions_need_filtering() const {
if (expr::is_empty_restriction(_clustering_columns_restrictions)) {
return false;
}
return has_partition_key_unrestricted_components()
|| clustering_key_restrictions_need_filtering()
// If token restrictions are present in an indexed query, then all other restrictions need to be filtered.
// A single token restriction can have multiple matching partition key values.
// Because of this we can't create a clustering prefix with more than token restriction.
|| (_uses_secondary_indexing && has_token_restrictions());
}
bool
statement_restrictions::is_restricted(const column_definition* cdef) const {
if (_not_null_columns.contains(cdef)) {
return true;
}
auto restricted = expr::get_sorted_column_defs(get_restrictions(cdef->kind));
return std::find(restricted.begin(), restricted.end(), cdef) != restricted.end();
}
const std::vector<expr::expression>& statement_restrictions::index_restrictions() const {
return _index_restrictions;
}
// Current score table:
// local and restrictions include full partition key: 2
// global: 1
// local and restrictions does not include full partition key: 0 (do not pick)
int statement_restrictions::score(const secondary_index::index& index) const {
if (index.metadata().local()) {
const bool allow_local = !has_partition_key_unrestricted_components() && partition_key_restrictions_is_all_eq();
return allow_local ? 2 : 0;
}
return 1;
}
std::pair<std::optional<secondary_index::index>, expr::expression> statement_restrictions::find_idx(const secondary_index::secondary_index_manager& sim) const {
std::optional<secondary_index::index> chosen_index;
int chosen_index_score = 0;
expr::expression chosen_index_restrictions;
for (const auto& index : sim.list_indexes()) {
auto cdef = _schema->get_column_definition(to_bytes(index.target_column()));
for (const expr::expression& restriction : index_restrictions()) {
if (has_partition_token(restriction, *_schema) || contains_multi_column_restriction(restriction)) {
continue;
}
expr::single_column_restrictions_map rmap = expr::get_single_column_restrictions_map(restriction);
const auto found = rmap.find(cdef);
if (found != rmap.end() && is_supported_by(found->second, index)
&& score(index) > chosen_index_score) {
chosen_index = index;
chosen_index_score = score(index);
chosen_index_restrictions = restriction;
}
}
}
return {chosen_index, chosen_index_restrictions};
}
bool statement_restrictions::has_eq_restriction_on_column(const column_definition& column) const {
if (!_where.has_value()) {
return false;
}
return expr::has_eq_restriction_on_column(column, *_where);
}
std::vector<const column_definition*> statement_restrictions::get_column_defs_for_filtering(data_dictionary::database db) const {
std::vector<const column_definition*> column_defs_for_filtering;
if (need_filtering()) {
std::optional<secondary_index::index> opt_idx;
if (_check_indexes) {
auto cf = db.find_column_family(_schema);
auto& sim = cf.get_index_manager();
opt_idx = std::get<0>(find_idx(sim));
}
auto column_uses_indexing = [&opt_idx] (const column_definition* cdef, const expr::expression* single_col_restr) {
return opt_idx && single_col_restr && is_supported_by(*single_col_restr, *opt_idx);
};
if (pk_restrictions_need_filtering()) {
for (auto&& cdef : expr::get_sorted_column_defs(_partition_key_restrictions)) {
const expr::expression* single_col_restr = nullptr;
auto it = _single_column_partition_key_restrictions.find(cdef);
if (it != _single_column_partition_key_restrictions.end()) {
if (is_single_column_restriction(it->second)) {
single_col_restr = &it->second;
}
}
if (!column_uses_indexing(cdef, single_col_restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
const bool pk_has_unrestricted_components = has_partition_key_unrestricted_components();
if (pk_has_unrestricted_components || clustering_key_restrictions_need_filtering()) {
column_id first_filtering_id = pk_has_unrestricted_components ? 0 : _schema->clustering_key_columns().begin()->id +
num_clustering_prefix_columns_that_need_not_be_filtered();
for (auto&& cdef : expr::get_sorted_column_defs(_clustering_columns_restrictions)) {
const expr::expression* single_col_restr = nullptr;
auto it = _single_column_partition_key_restrictions.find(cdef);
if (it != _single_column_partition_key_restrictions.end()) {
single_col_restr = &it->second;
}
if (cdef->id >= first_filtering_id && !column_uses_indexing(cdef, single_col_restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
for (auto&& [cdef, cur_restr] : _single_column_nonprimary_key_restrictions) {
if (!column_uses_indexing(cdef, &cur_restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
return column_defs_for_filtering;
}
void statement_restrictions::add_restriction(const expr::binary_operator& restr, schema_ptr schema, bool allow_filtering, bool for_view) {
if (restr.op == expr::oper_t::IS_NOT) {
// Handle IS NOT NULL restrictions seperately
add_is_not_restriction(restr, schema, for_view);
} else if (expr::is_multi_column(restr)) {
// Multi column restrictions are only allowed on clustering columns
add_multi_column_clustering_key_restriction(restr);
} else if (has_partition_token(restr, *_schema)) {
// Token always restricts the partition key
add_token_partition_key_restriction(restr);
} else if (expr::is_single_column_restriction(restr)) {
const column_definition* def = get_the_only_column(restr).col;
if (def->is_partition_key()) {
add_single_column_parition_key_restriction(restr, schema, allow_filtering, for_view);
} else if (def->is_clustering_key()) {
add_single_column_clustering_key_restriction(restr, schema, allow_filtering);
} else {
add_single_column_nonprimary_key_restriction(restr);
}
} else {
throw exceptions::invalid_request_exception(format("Unhandled restriction: {}", restr));
}
}
void statement_restrictions::add_is_not_restriction(const expr::binary_operator& restr, schema_ptr schema, bool for_view) {
const expr::column_value* lhs_col_def = expr::as_if<expr::column_value>(&restr.lhs);
// The "IS NOT NULL" restriction is only supported (and
// mandatory) for materialized view creation:
if (lhs_col_def == nullptr) {
throw exceptions::invalid_request_exception("IS NOT only supports single column");
}
// currently, the grammar only allows the NULL argument to be
// "IS NOT", so this assertion should not be able to fail
if (!expr::is<expr::constant>(restr.rhs) || !expr::as<expr::constant>(restr.rhs).is_null()) {
throw exceptions::invalid_request_exception("Only IS NOT NULL is supported");
}
_not_null_columns.insert(lhs_col_def->col);
if (!for_view) {
throw exceptions::invalid_request_exception(format("restriction '{}' is only supported in materialized view creation", restr));
}
}
void statement_restrictions::add_single_column_parition_key_restriction(const expr::binary_operator& restr, schema_ptr schema, bool allow_filtering, bool for_view) {
// View definition allows PK slices, because it's not a performance problem.
if (restr.op != expr::oper_t::EQ && restr.op != expr::oper_t::IN && !allow_filtering && !for_view) {
throw exceptions::invalid_request_exception(
"Only EQ and IN relation are supported on the partition key "
"(unless you use the token() function or allow filtering)");
}
if (has_token_restrictions()) {
throw exceptions::invalid_request_exception(
format("Columns \"{}\" cannot be restricted by both a normal relation and a token relation",
fmt::join(expr::get_sorted_column_defs(_partition_key_restrictions) |
boost::adaptors::transformed([](auto* p) {
return maybe_column_definition{p};
}),
", ")));
}
_partition_key_restrictions = expr::make_conjunction(_partition_key_restrictions, restr);
_partition_range_is_simple &= !find(restr, expr::oper_t::IN);
}
void statement_restrictions::add_token_partition_key_restriction(const expr::binary_operator& restr) {
if (!partition_key_restrictions_is_empty() && !has_token_restrictions()) {
throw exceptions::invalid_request_exception(
format("Columns \"{}\" cannot be restricted by both a normal relation and a token relation",
fmt::join(expr::get_sorted_column_defs(_partition_key_restrictions) |
boost::adaptors::transformed([](auto* p) {
return maybe_column_definition{p};
}),
", ")));
}
_partition_key_restrictions = expr::make_conjunction(_partition_key_restrictions, restr);
}
void statement_restrictions::add_single_column_clustering_key_restriction(const expr::binary_operator& restr, schema_ptr schema, bool allow_filtering) {
if (find_binop(_clustering_columns_restrictions, [] (const expr::binary_operator& b) {
return expr::is<expr::tuple_constructor>(b.lhs);
})) {
throw exceptions::invalid_request_exception(
"Mixing single column relations and multi column relations on clustering columns is not allowed");
}
const column_definition* new_column = expr::get_the_only_column(restr).col;
const column_definition* last_column = expr::get_last_column_def(_clustering_columns_restrictions);
if (last_column != nullptr && !allow_filtering) {
if (has_slice(_clustering_columns_restrictions) && schema->position(*new_column) > schema->position(*last_column)) {
throw exceptions::invalid_request_exception(format("Clustering column \"{}\" cannot be restricted (preceding column \"{}\" is restricted by a non-EQ relation)",
new_column->name_as_text(), last_column->name_as_text()));
}
if (schema->position(*new_column) < schema->position(*last_column)) {
if (has_slice(restr)) {
throw exceptions::invalid_request_exception(format("PRIMARY KEY column \"{}\" cannot be restricted (preceding column \"{}\" is restricted by a non-EQ relation)",
last_column->name_as_text(), new_column->name_as_text()));
}
}
}
_clustering_columns_restrictions = expr::make_conjunction(_clustering_columns_restrictions, restr);
}
void statement_restrictions::add_multi_column_clustering_key_restriction(const expr::binary_operator& restr) {
if (expr::is_empty_restriction(_clustering_columns_restrictions)) {
_clustering_columns_restrictions = restr;
return;
}
if (!find_binop(_clustering_columns_restrictions, [] (const expr::binary_operator& b) {
return expr::is<expr::tuple_constructor>(b.lhs);
})) {
throw exceptions::invalid_request_exception("Mixing single column relations and multi column relations on clustering columns is not allowed");
}
if (restr.op == expr::oper_t::EQ) {
throw exceptions::invalid_request_exception(format("{} cannot be restricted by more than one relation if it includes an Equal",
expr::get_columns_in_commons(_clustering_columns_restrictions, restr)));
} else if (restr.op == expr::oper_t::IN) {
throw exceptions::invalid_request_exception(format("{} cannot be restricted by more than one relation if it includes a IN",
expr::get_columns_in_commons(_clustering_columns_restrictions, restr)));
} else if (is_slice(restr.op)) {
if (!expr::has_slice(_clustering_columns_restrictions)) {
throw exceptions::invalid_request_exception(format("Column \"{}\" cannot be restricted by both an equality and an inequality relation",
expr::get_columns_in_commons(_clustering_columns_restrictions, restr)));
}
const expr::binary_operator* other_slice = expr::find_in_expression<expr::binary_operator>(_clustering_columns_restrictions, [](const expr::binary_operator){return true;});
if (other_slice == nullptr) {
on_internal_error(rlogger, "add_multi_column_clustering_key_restriction: _clustering_columns_restrictions is empty!");
}
// Don't allow to mix plain and SCYLLA_CLUSTERING_BOUND bounds
if (other_slice->order != restr.order) {
static auto order2str = [](auto o) { return o == expr::comparison_order::cql ? "plain" : "SCYLLA_CLUSTERING_BOUND"; };
throw exceptions::invalid_request_exception(
format("Invalid combination of restrictions ({} / {})",
order2str(other_slice->order), order2str(restr.order)));
}
// Here check that there aren't two < <= or two > and >=
auto is_greater = [](expr::oper_t op) {return op == expr::oper_t::GT || op == expr::oper_t::GTE; };
auto is_less = [](expr::oper_t op) {return op == expr::oper_t::LT || op == expr::oper_t::LTE; };
if (is_greater(restr.op) && is_greater(other_slice->op)) {
throw exceptions::invalid_request_exception(format(
"More than one restriction was found for the start bound on {}",
expr::get_columns_in_commons(restr, *other_slice)));
}
if (is_less(restr.op) && is_less(other_slice->op)) {
throw exceptions::invalid_request_exception(format(
"More than one restriction was found for the end bound on {}",
expr::get_columns_in_commons(restr, *other_slice)));
}
_clustering_columns_restrictions = expr::make_conjunction(_clustering_columns_restrictions, restr);
} else {
throw exceptions::invalid_request_exception(format("Unsupported multi-column relation: ", restr));
}
}
void statement_restrictions::add_single_column_nonprimary_key_restriction(const expr::binary_operator& restr) {
_nonprimary_key_restrictions = expr::make_conjunction(_nonprimary_key_restrictions, restr);
}
void statement_restrictions::process_partition_key_restrictions(bool for_view, bool allow_filtering) {
// If there is a queriable index, no special condition are required on the other restrictions.
// But we still need to know 2 things:
// - If we don't have a queriable index, is the query ok
// - Is it queriable without 2ndary index, which is always more efficient
// If a component of the partition key is restricted by a relation, all preceding
// components must have a EQ. Only the last partition key component can be in IN relation.
if (has_token_restrictions()) {
_is_key_range = true;
} else if (expr::is_empty_restriction(_partition_key_restrictions)) {
_is_key_range = true;
_uses_secondary_indexing = _has_queriable_pk_index;
}
if (pk_restrictions_need_filtering()) {
if (!allow_filtering && !for_view && !_has_queriable_pk_index) {
throw exceptions::invalid_request_exception("Cannot execute this query as it might involve data filtering and "
"thus may have unpredictable performance. If you want to execute "
"this query despite the performance unpredictability, use ALLOW FILTERING");
}
_is_key_range = true;
_uses_secondary_indexing = _has_queriable_pk_index;
}
}
bool statement_restrictions::has_partition_key_unrestricted_components() const {
std::vector<const column_definition*> pk_columns = expr::get_sorted_column_defs(_partition_key_restrictions);
bool all_restricted = pk_columns.size() == _schema->partition_key_size();
return !all_restricted;
}
bool statement_restrictions::partition_key_restrictions_is_empty() const {
return expr::is_empty_restriction(_partition_key_restrictions);
}
bool statement_restrictions::partition_key_restrictions_is_all_eq() const {
return expr::has_only_eq_binops(_partition_key_restrictions);
}
size_t statement_restrictions::partition_key_restrictions_size() const {
return expr::get_sorted_column_defs(_partition_key_restrictions).size();
}
bool statement_restrictions::pk_restrictions_need_filtering() const {
return !expr::is_empty_restriction(_partition_key_restrictions)
&& !has_token_restrictions()
&& (has_partition_key_unrestricted_components() || expr::has_slice_or_needs_filtering(_partition_key_restrictions));
}
size_t statement_restrictions::clustering_columns_restrictions_size() const {
return expr::get_sorted_column_defs(_clustering_columns_restrictions).size();
}
bool statement_restrictions::clustering_key_restrictions_need_filtering() const {
if (expr::contains_multi_column_restriction(_clustering_columns_restrictions)) {
return false;
}
return num_clustering_prefix_columns_that_need_not_be_filtered() < clustering_columns_restrictions_size();
}
bool statement_restrictions::has_unrestricted_clustering_columns() const {
return clustering_columns_restrictions_size() < _schema->clustering_key_size();
}
const column_definition& statement_restrictions::unrestricted_column(column_kind kind) const {
const auto& restrictions = get_restrictions(kind);
const auto sorted_cols = expr::get_sorted_column_defs(restrictions);
for (size_t i = 0, count = _schema->columns_count(kind); i < count; ++i) {
if (i >= sorted_cols.size() || sorted_cols[i]->component_index() != i) {
return _schema->column_at(kind, i);
}
}
on_internal_error(rlogger, format(
"no missing columns with kind {} found in expression {}",
to_sstring(kind), restrictions));
};
bool statement_restrictions::clustering_columns_restrictions_have_supporting_index(
const secondary_index::secondary_index_manager& index_manager,
expr::allow_local_index allow_local) const {
// Single column restrictions can be handled by the existing code
if (!expr::contains_multi_column_restriction(_clustering_columns_restrictions)) {
return expr::index_supports_some_column(_clustering_columns_restrictions, index_manager, allow_local);
}
// Multi column restrictions have to be handled separately
for (const auto& index : index_manager.list_indexes()) {
if (!allow_local && index.metadata().local()) {
continue;
}
if (multi_column_clustering_restrictions_are_supported_by(index)) {
return true;
}
}
return false;
}
bool statement_restrictions::multi_column_clustering_restrictions_are_supported_by(
const secondary_index::index& index) const {
// Slice restrictions have to be checked depending on the clustering slice
if (has_slice(_clustering_columns_restrictions)) {
bounds_slice clustering_slice = get_clustering_slice();
const expr::column_value* supported_column =
find_in_expression<expr::column_value>(_clustering_columns_restrictions,
[&](const expr::column_value& cval) -> bool {
return clustering_slice.is_supported_by(*cval.col, index);
}
);
return supported_column != nullptr;
}
// Otherwise it has to be a singe binary operator with EQ or IN.
// This is checked earlier during add_restriction.
const expr::binary_operator* single_binop =
expr::as_if<expr::binary_operator>(&_clustering_columns_restrictions);
if (single_binop == nullptr) {
on_internal_error(rlogger, format(
"multi_column_clustering_restrictions_are_supported_by more than one non-slice restriction: {}",
_clustering_columns_restrictions));
}
if (single_binop->op != expr::oper_t::IN && single_binop->op != expr::oper_t::EQ) {
on_internal_error(rlogger, format("Disallowed multi column restriction: {}", *single_binop));
}
const expr::column_value* supported_column =
find_in_expression<expr::column_value>(_clustering_columns_restrictions,
[&](const expr::column_value& cval) -> bool {
return index.supports_expression(*cval.col, single_binop->op);
}
);
return supported_column != nullptr;
}
bounds_slice statement_restrictions::get_clustering_slice() const {
std::optional<bounds_slice> result;
expr::for_each_expression<expr::binary_operator>(_clustering_columns_restrictions,
[&](const expr::binary_operator& binop) {
bounds_slice cur_slice = bounds_slice::from_binary_operator(binop);
if (!result.has_value()) {
result = cur_slice;
} else {
result->merge(cur_slice);
}
}
);
return *result;
}
bool statement_restrictions::parition_key_restrictions_have_supporting_index(const secondary_index::secondary_index_manager& index_manager,
expr::allow_local_index allow_local) const {
// Token restrictions can't be supported by an index
if (has_token_restrictions()) {
return false;
}
return expr::index_supports_some_column(_partition_key_restrictions, index_manager, allow_local);
}
void statement_restrictions::process_clustering_columns_restrictions(bool for_view, bool allow_filtering) {
if (!has_clustering_columns_restriction()) {
return;
}
if (find_binop(_clustering_columns_restrictions, expr::is_on_collection)
&& !_has_queriable_ck_index && !allow_filtering) {
throw exceptions::invalid_request_exception(
"Cannot restrict clustering columns by a CONTAINS relation without a secondary index or filtering");
}
if (has_clustering_columns_restriction() && clustering_key_restrictions_need_filtering()) {
if (_has_queriable_ck_index) {
_uses_secondary_indexing = true;
} else if (!allow_filtering && !for_view) {
auto clustering_columns_iter = _schema->clustering_key_columns().begin();
for (auto&& restricted_column : expr::get_sorted_column_defs(_clustering_columns_restrictions)) {
const column_definition* clustering_column = &(*clustering_columns_iter);
++clustering_columns_iter;
if (clustering_column != restricted_column) {
throw exceptions::invalid_request_exception(format("PRIMARY KEY column \"{}\" cannot be restricted as preceding column \"{}\" is not restricted",
restricted_column->name_as_text(), clustering_column->name_as_text()));
}
}
}
}
}
namespace {
using namespace expr;
/// Computes partition-key ranges from token atoms in ex.
dht::partition_range_vector partition_ranges_from_token(const expr::expression& ex,
const query_options& options,
const schema& table_schema) {
auto values = possible_partition_token_values(ex, options, table_schema);