/
statement_restrictions.cc
1752 lines (1552 loc) · 81.5 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
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#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 "query-result-reader.hh"
#include "statement_restrictions.hh"
#include "multi_column_restriction.hh"
#include "token_restriction.hh"
#include "database.hh"
#include "cartesian_product.hh"
#include "cql3/constants.hh"
#include "cql3/lists.hh"
#include "cql3/selection/selection.hh"
#include "cql3/single_column_relation.hh"
#include "cql3/statements/request_validations.hh"
#include "cql3/tuples.hh"
#include "types/list.hh"
#include "types/map.hh"
#include "types/set.hh"
namespace cql3 {
namespace restrictions {
static logging::logger rlogger("restrictions");
using boost::adaptors::filtered;
using boost::adaptors::transformed;
using statements::request_validations::invalid_request;
template<typename T>
class statement_restrictions::initial_key_restrictions : public primary_key_restrictions<T> {
bool _allow_filtering;
public:
initial_key_restrictions(bool allow_filtering)
: _allow_filtering(allow_filtering) {
this->expression = true;
}
::shared_ptr<primary_key_restrictions<T>> do_merge_to(schema_ptr schema, ::shared_ptr<restriction> restriction) const {
return ::make_shared<single_column_primary_key_restrictions<T>>(schema, _allow_filtering)->merge_to(schema, restriction);
}
::shared_ptr<primary_key_restrictions<T>> merge_to(schema_ptr schema, ::shared_ptr<restriction> restriction) override {
if (has_token(restriction->expression)) {
return static_pointer_cast<token_restriction>(restriction);
}
return ::make_shared<single_column_primary_key_restrictions<T>>(schema, _allow_filtering)->merge_to(restriction);
}
void merge_with(::shared_ptr<restriction> restriction) override {
throw exceptions::unsupported_operation_exception();
}
bytes_opt value_for(const column_definition& cdef, const query_options& options) const override {
return {};
}
std::vector<const column_definition*> get_column_defs() const override {
// throw? should not reach?
return {};
}
bool empty() const override {
return true;
}
uint32_t size() const override {
return 0;
}
virtual bool has_supporting_index(const secondary_index::secondary_index_manager& index_manager,
expr::allow_local_index allow_local) const override {
return false;
}
};
template<>
::shared_ptr<primary_key_restrictions<partition_key>>
statement_restrictions::initial_key_restrictions<partition_key>::merge_to(schema_ptr schema, ::shared_ptr<restriction> restriction) {
if (has_token(restriction->expression)) {
return static_pointer_cast<token_restriction>(restriction);
}
return do_merge_to(std::move(schema), std::move(restriction));
}
template<>
::shared_ptr<primary_key_restrictions<clustering_key_prefix>>
statement_restrictions::initial_key_restrictions<clustering_key_prefix>::merge_to(schema_ptr schema, ::shared_ptr<restriction> restriction) {
if (auto p = dynamic_pointer_cast<multi_column_restriction>(restriction)) {
return p;
}
return do_merge_to(std::move(schema), std::move(restriction));
}
::shared_ptr<partition_key_restrictions> statement_restrictions::get_initial_partition_key_restrictions(bool allow_filtering) {
static thread_local ::shared_ptr<partition_key_restrictions> initial_kr_true = ::make_shared<initial_key_restrictions<partition_key>>(true);
static thread_local ::shared_ptr<partition_key_restrictions> initial_kr_false = ::make_shared<initial_key_restrictions<partition_key>>(false);
return allow_filtering ? initial_kr_true : initial_kr_false;
}
::shared_ptr<clustering_key_restrictions> statement_restrictions::get_initial_clustering_key_restrictions(bool allow_filtering) {
static thread_local ::shared_ptr<clustering_key_restrictions> initial_kr_true = ::make_shared<initial_key_restrictions<clustering_key>>(true);
static thread_local ::shared_ptr<clustering_key_restrictions> initial_kr_false = ::make_shared<initial_key_restrictions<clustering_key>>(false);
return allow_filtering ? initial_kr_true : initial_kr_false;
}
statement_restrictions::statement_restrictions(schema_ptr schema, bool allow_filtering)
: _schema(schema)
, _partition_key_restrictions(get_initial_partition_key_restrictions(allow_filtering))
, _clustering_columns_restrictions(get_initial_clustering_key_restrictions(allow_filtering))
, _nonprimary_key_restrictions(::make_shared<single_column_restrictions>(schema))
, _partition_range_is_simple(true)
{ }
#if 0
static const column_definition*
to_column_definition(const schema_ptr& schema, const ::shared_ptr<column_identifier::raw>& entity) {
return get_column_definition(schema,
*entity->prepare_column_identifier(schema));
}
#endif
template <typename Visitor>
concept visitor_with_binary_operator_context = requires (Visitor v) {
{ v.current_binary_operator } -> std::same_as<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 {
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) { std::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;
std::visit(*this, *b.lhs);
current_binary_operator = nullptr;
}
void operator()(const token&) {
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 column_value_tuple& s) {
// Partition key columns are not legal in tuples, so ignore tuples.
}
void operator()(bool) {}
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 function_call&) {
on_internal_error(rlogger, "extract_partition_range(function_call)");
}
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 null&) {
on_internal_error(rlogger, "extract_partition_range(null)");
}
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 tuple_constructor&) {
on_internal_error(rlogger, "extract_partition_range(tuple_constructor)");
}
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)");
}
} v;
std::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 {
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) { std::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;
std::visit(*this, *b.lhs);
current_binary_operator = nullptr;
}
void operator()(const column_value_tuple&) {
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 token&) {
// A token cannot be a clustering prefix restriction
}
void operator()(bool) {}
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 function_call&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(function_call)");
}
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 null&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(null)");
}
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 tuple_constructor&) {
on_internal_error(rlogger, "extract_clustering_prefix_restrictions(tuple_constructor)");
}
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)");
}
} v;
std::visit(v, where_clause);
if (!v.multi.empty()) {
return 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(database& db,
schema_ptr schema,
statements::statement_type type,
const std::vector<::shared_ptr<relation>>& where_clause,
prepare_context& ctx,
bool selects_only_static_columns,
bool for_view,
bool allow_filtering)
: statement_restrictions(schema, allow_filtering)
{
if (!where_clause.empty()) {
for (auto&& relation : where_clause) {
if (relation->get_operator() == expr::oper_t::IS_NOT) {
single_column_relation* r =
dynamic_cast<single_column_relation*>(relation.get());
// The "IS NOT NULL" restriction is only supported (and
// mandatory) for materialized view creation:
if (!r) {
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
assert(std::holds_alternative<expr::null>(*r->get_value()));
auto col_id = r->get_entity()->prepare_column_identifier(*schema);
const auto *cd = get_column_definition(*schema, *col_id);
if (!cd) {
throw exceptions::invalid_request_exception(format("restriction '{}' unknown column {}", relation->to_string(), r->get_entity()->to_string()));
}
_not_null_columns.insert(cd);
if (!for_view) {
throw exceptions::invalid_request_exception(format("restriction '{}' is only supported in materialized view creation", relation->to_string()));
}
} else {
const auto restriction = relation->to_restriction(db, schema, ctx);
if (dynamic_pointer_cast<multi_column_restriction>(restriction)) {
_clustering_columns_restrictions = _clustering_columns_restrictions->merge_to(_schema, restriction);
} else if (has_token(restriction->expression)) {
_partition_key_restrictions = _partition_key_restrictions->merge_to(_schema, restriction);
} else {
auto single = ::static_pointer_cast<single_column_restriction>(restriction);
auto& def = single->get_column_def();
if (def.is_partition_key()) {
// View definition allows PK slices, because it's not a performance problem.
if (has_slice(restriction->expression) && !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)");
}
_partition_key_restrictions = _partition_key_restrictions->merge_to(_schema, restriction);
_partition_range_is_simple &= !find(restriction->expression, expr::oper_t::IN);
} else if (def.is_clustering_key()) {
_clustering_columns_restrictions = _clustering_columns_restrictions->merge_to(_schema, restriction);
} else {
_nonprimary_key_restrictions->add_restriction(single);
}
}
_where = _where.has_value() ? make_conjunction(std::move(*_where), restriction->expression) : restriction->expression;
}
}
}
if (_where.has_value()) {
_clustering_prefix_restrictions = extract_clustering_prefix_restrictions(*_where, _schema);
_partition_range_restrictions = extract_partition_range(*_where, _schema);
}
auto& cf = db.find_column_family(schema);
auto& sim = cf.get_index_manager();
const expr::allow_local_index allow_local(
!_partition_key_restrictions->has_unrestricted_components(*_schema)
&& _partition_key_restrictions->is_all_eq());
_has_multi_column = find_atom(_clustering_columns_restrictions->expression, expr::is_multi_column);
_has_queriable_ck_index = _clustering_columns_restrictions->has_supporting_index(sim, allow_local);
_has_queriable_pk_index = _partition_key_restrictions->has_supporting_index(sim, allow_local);
_has_queriable_regular_index = _nonprimary_key_restrictions->has_supporting_index(sim, allow_local);
// 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 || _partition_key_restrictions->needs_filtering(*_schema)) {
_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_columns_restrictions->needs_filtering(*_schema)) {
_index_restrictions.push_back(_clustering_columns_restrictions);
} else if (find_atom(_clustering_columns_restrictions->expression, expr::is_on_collection)) {
fail(unimplemented::cause::INDEXES);
#if 0
_index_restrictions.push_back(new Forwardingprimary_key_restrictions() {
@Override
protected primary_key_restrictions getDelegate()
{
return _clustering_columns_restrictions;
}
@Override
public void add_index_expression_to(List<::shared_ptr<index_expression>> expressions, const query_options& options) throws InvalidRequestException
{
List<::shared_ptr<index_expression>> list = new ArrayList<>();
super.add_index_expression_to(list, options);
for (::shared_ptr<index_expression> expression : list)
{
if (expression.is_contains() || expression.is_containsKey())
expressions.add(expression);
}
}
});
uses_secondary_indexing = true;
#endif
}
if (!_nonprimary_key_restrictions->empty()) {
if (_has_queriable_regular_index) {
_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);
}
}
const std::vector<::shared_ptr<restrictions>>& 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 = !_partition_key_restrictions->has_unrestricted_components(*_schema) && _partition_key_restrictions->is_all_eq();
return allow_local ? 2 : 0;
}
return 1;
}
namespace {
using namespace cql3::restrictions;
/// If rs contains a restrictions_map of individual columns to their restrictions, returns it. Otherwise, returns null.
const single_column_restrictions::restrictions_map* get_individual_restrictions_map(const restrictions* rs) {
if (auto regular = dynamic_cast<const single_column_restrictions*>(rs)) {
return ®ular->restrictions();
} else if (auto partition = dynamic_cast<const single_column_partition_key_restrictions*>(rs)) {
return &partition->restrictions();
} else if (auto clustering = dynamic_cast<const single_column_clustering_key_restrictions*>(rs)) {
return &clustering->restrictions();
}
return nullptr;
}
} // anonymous namespace
std::pair<std::optional<secondary_index::index>, ::shared_ptr<cql3::restrictions::restrictions>> statement_restrictions::find_idx(secondary_index::secondary_index_manager& sim) const {
std::optional<secondary_index::index> chosen_index;
int chosen_index_score = 0;
::shared_ptr<cql3::restrictions::restrictions> chosen_index_restrictions;
for (const auto& index : sim.list_indexes()) {
auto cdef = _schema->get_column_definition(to_bytes(index.target_column()));
for (::shared_ptr<cql3::restrictions::restrictions> restriction : index_restrictions()) {
if (auto rmap = get_individual_restrictions_map(restriction.get())) {
const auto found = rmap->find(cdef);
if (found != rmap->end() && is_supported_by(found->second->expression, index)
&& score(index) > chosen_index_score) {
chosen_index = index;
chosen_index_score = score(index);
chosen_index_restrictions = restriction;
}
}
}
}
return {chosen_index, chosen_index_restrictions};
}
std::vector<const column_definition*> statement_restrictions::get_column_defs_for_filtering(database& db) const {
std::vector<const column_definition*> column_defs_for_filtering;
if (need_filtering()) {
auto& sim = db.find_column_family(_schema).get_index_manager();
auto opt_idx = std::get<0>(find_idx(sim));
auto column_uses_indexing = [&opt_idx] (const column_definition* cdef, ::shared_ptr<single_column_restriction> restr) {
return opt_idx && restr && is_supported_by(restr->expression, *opt_idx);
};
auto single_pk_restrs = dynamic_pointer_cast<single_column_partition_key_restrictions>(_partition_key_restrictions);
if (_partition_key_restrictions->needs_filtering(*_schema)) {
for (auto&& cdef : _partition_key_restrictions->get_column_defs()) {
::shared_ptr<single_column_restriction> restr;
if (single_pk_restrs) {
auto it = single_pk_restrs->restrictions().find(cdef);
if (it != single_pk_restrs->restrictions().end()) {
restr = dynamic_pointer_cast<single_column_restriction>(it->second);
}
}
if (!column_uses_indexing(cdef, restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
auto single_ck_restrs = dynamic_pointer_cast<single_column_clustering_key_restrictions>(_clustering_columns_restrictions);
const bool pk_has_unrestricted_components = _partition_key_restrictions->has_unrestricted_components(*_schema);
if (pk_has_unrestricted_components || _clustering_columns_restrictions->needs_filtering(*_schema)) {
column_id first_filtering_id = pk_has_unrestricted_components ? 0 : _schema->clustering_key_columns().begin()->id +
_clustering_columns_restrictions->num_prefix_columns_that_need_not_be_filtered();
for (auto&& cdef : _clustering_columns_restrictions->get_column_defs()) {
::shared_ptr<single_column_restriction> restr;
if (single_ck_restrs) {
auto it = single_ck_restrs->restrictions().find(cdef);
if (it != single_ck_restrs->restrictions().end()) {
restr = dynamic_pointer_cast<single_column_restriction>(it->second);
}
}
if (cdef->id >= first_filtering_id && !column_uses_indexing(cdef, restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
for (auto&& cdef : _nonprimary_key_restrictions->get_column_defs()) {
auto restr = dynamic_pointer_cast<single_column_restriction>(_nonprimary_key_restrictions->get_restriction(*cdef));
if (!column_uses_indexing(cdef, restr)) {
column_defs_for_filtering.emplace_back(cdef);
}
}
}
return column_defs_for_filtering;
}
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(_partition_key_restrictions->expression)) {
_is_key_range = true;
} else if (_partition_key_restrictions->empty()) {
_is_key_range = true;
_uses_secondary_indexing = _has_queriable_pk_index;
}
if (_partition_key_restrictions->needs_filtering(*_schema)) {
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 {
return _partition_key_restrictions->has_unrestricted_components(*_schema);
}
bool statement_restrictions::has_unrestricted_clustering_columns() const {
return _clustering_columns_restrictions->has_unrestricted_components(*_schema);
}
void statement_restrictions::process_clustering_columns_restrictions(bool for_view, bool allow_filtering) {
if (!has_clustering_columns_restriction()) {
return;
}
if (find_atom(_clustering_columns_restrictions->expression, 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_columns_restrictions->needs_filtering(*_schema)) {
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 : _clustering_columns_restrictions->get_column_defs()) {
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) {
auto values = possible_lhs_values(nullptr, ex, options);
if (values == expr::value_set(expr::value_list{})) {
return {};
}
const auto bounds = expr::to_range(values);
const auto start_token = bounds.start() ? bounds.start()->value().with_linearized([] (bytes_view bv) { return dht::token::from_bytes(bv); })
: dht::minimum_token();
auto end_token = bounds.end() ? bounds.end()->value().with_linearized([] (bytes_view bv) { return dht::token::from_bytes(bv); })
: dht::maximum_token();
const bool include_start = bounds.start() && bounds.start()->is_inclusive();
const auto include_end = bounds.end() && bounds.end()->is_inclusive();
auto start = dht::partition_range::bound(include_start
? dht::ring_position::starting_at(start_token)
: dht::ring_position::ending_at(start_token));
auto end = dht::partition_range::bound(include_end
? dht::ring_position::ending_at(end_token)
: dht::ring_position::starting_at(end_token));
return {{std::move(start), std::move(end)}};
}
/// Turns a partition-key value into a partition_range. \p pk must have elements for all partition columns.
dht::partition_range range_from_bytes(const schema& schema, const std::vector<managed_bytes>& pk) {
const auto k = partition_key::from_exploded(pk);
const auto tok = dht::get_token(schema, k);
const query::ring_position pos(std::move(tok), std::move(k));
return dht::partition_range::make_singular(std::move(pos));
}
void error_if_exceeds(size_t size, size_t limit) {
if (size > limit) {
throw std::runtime_error(
fmt::format("clustering-key cartesian product size {} is greater than maximum {}", size, limit));
}
}
/// Computes partition-key ranges from expressions, which contains EQ/IN for every partition column.
dht::partition_range_vector partition_ranges_from_singles(
const std::vector<expr::expression>& expressions, const query_options& options, const schema& schema) {
const size_t size_limit =
options.get_cql_config().restrictions.partition_key_restrictions_max_cartesian_product_size;
// Each element is a vector of that column's possible values:
std::vector<std::vector<managed_bytes>> column_values(schema.partition_key_size());
size_t product_size = 1;
for (const auto& e : expressions) {
if (const auto arbitrary_binop = find_atom(e, [] (const binary_operator&) { return true; })) {
if (auto cv = std::get_if<expr::column_value>(&*arbitrary_binop->lhs)) {
const value_set vals = possible_lhs_values(cv->col, e, options);
if (auto lst = std::get_if<value_list>(&vals)) {
if (lst->empty()) {
return {};
}
product_size *= lst->size();
error_if_exceeds(product_size, size_limit);
column_values[schema.position(*cv->col)] = move(*lst);
} else {
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)");
}
}
}
}
cartesian_product cp(column_values);
dht::partition_range_vector ranges(product_size);
std::transform(cp.begin(), cp.end(), ranges.begin(), std::bind_front(range_from_bytes, std::ref(schema)));
return ranges;
}
/// Computes partition-key ranges from EQ restrictions on each partition column. Returns a single singleton range if
/// the EQ restrictions are not mutually conflicting. Otherwise, returns an empty vector.
dht::partition_range_vector partition_ranges_from_EQs(
const std::vector<expr::expression>& eq_expressions, const query_options& options, const schema& schema) {
std::vector<managed_bytes> pk_value(schema.partition_key_size());
for (const auto& e : eq_expressions) {
const auto col = std::get<column_value>(*find(e, oper_t::EQ)->lhs).col;
const auto vals = std::get<value_list>(possible_lhs_values(col, e, options));
if (vals.empty()) { // Case of C=1 AND C=2.
return {};
}
pk_value[schema.position(*col)] = std::move(vals[0]);
}
return {range_from_bytes(schema, pk_value)};
}
} // anonymous namespace
dht::partition_range_vector statement_restrictions::get_partition_key_ranges(const query_options& options) const {
if (_partition_range_restrictions.empty()) {
return {dht::partition_range::make_open_ended_both_sides()};
}
if (has_token(_partition_range_restrictions[0])) {
if (_partition_range_restrictions.size() != 1) {
on_internal_error(
rlogger,
format("Unexpected size of token restrictions: {}", _partition_range_restrictions.size()));
}
return partition_ranges_from_token(_partition_range_restrictions[0], options);
} else if (_partition_range_is_simple) {
// Special case to avoid extra allocations required for a Cartesian product.
return partition_ranges_from_EQs(_partition_range_restrictions, options, *_schema);
}
return partition_ranges_from_singles(_partition_range_restrictions, options, *_schema);
}
namespace {
using namespace expr;
clustering_key_prefix::prefix_equal_tri_compare get_unreversed_tri_compare(const schema& schema) {
clustering_key_prefix::prefix_equal_tri_compare cmp(schema);
std::vector<data_type> types = cmp.prefix_type->types();
for (auto& t : types) {
if (t->is_reversed()) {
t = t->underlying_type();
}
}
cmp.prefix_type = make_lw_shared<compound_type<allow_prefixes::yes>>(types);
return cmp;
}
/// True iff r1 start is strictly before r2 start.
bool starts_before_start(
const query::clustering_range& r1,
const query::clustering_range& r2,
const clustering_key_prefix::prefix_equal_tri_compare& cmp) {
if (!r2.start()) {
return false; // r2 start is -inf, nothing is before that.
}
if (!r1.start()) {
return true; // r1 start is -inf, while r2 start is finite.
}
const auto diff = cmp(r1.start()->value(), r2.start()->value());
if (diff < 0) { // r1 start is strictly before r2 start.
return true;
}
if (diff > 0) { // r1 start is strictly after r2 start.
return false;
}
const auto len1 = r1.start()->value().representation().size();
const auto len2 = r2.start()->value().representation().size();
if (len1 == len2) { // The values truly are equal.
return r1.start()->is_inclusive() && !r2.start()->is_inclusive();
} else if (len1 < len2) { // r1 start is a prefix of r2 start.
// (a)>=(1) starts before (a,b)>=(1,1), but (a)>(1) doesn't.
return r1.start()->is_inclusive();
} else { // r2 start is a prefix of r1 start.
// (a,b)>=(1,1) starts before (a)>(1) but after (a)>=(1).
return r2.start()->is_inclusive();
}
}
/// True iff r1 start is before (or identical as) r2 end.
bool starts_before_or_at_end(
const query::clustering_range& r1,
const query::clustering_range& r2,
const clustering_key_prefix::prefix_equal_tri_compare& cmp) {
if (!r1.start()) {
return true; // r1 start is -inf, must be before r2 end.
}
if (!r2.end()) {
return true; // r2 end is +inf, everything is before it.
}
const auto diff = cmp(r1.start()->value(), r2.end()->value());
if (diff < 0) { // r1 start is strictly before r2 end.
return true;
}
if (diff > 0) { // r1 start is strictly after r2 end.
return false;
}
const auto len1 = r1.start()->value().representation().size();
const auto len2 = r2.end()->value().representation().size();
if (len1 == len2) { // The values truly are equal.
return r1.start()->is_inclusive() && r2.end()->is_inclusive();
} else if (len1 < len2) { // r1 start is a prefix of r2 end.
// a>=(1) starts before (a,b)<=(1,1) ends, but (a)>(1) doesn't.
return r1.start()->is_inclusive();
} else { // r2 end is a prefix of r1 start.
// (a,b)>=(1,1) starts before (a)<=(1) ends but after (a)<(1) ends.
return r2.end()->is_inclusive();
}
}
/// True if r1 end is strictly before r2 end.
bool ends_before_end(
const query::clustering_range& r1,
const query::clustering_range& r2,
const clustering_key_prefix::prefix_equal_tri_compare& cmp) {
if (!r1.end()) {
return false; // r1 end is +inf, which is after everything.
}
if (!r2.end()) {
return true; // r2 end is +inf, while r1 end is finite.
}
const auto diff = cmp(r1.end()->value(), r2.end()->value());
if (diff < 0) { // r1 end is strictly before r2 end.
return true;
}
if (diff > 0) { // r1 end is strictly after r2 end.
return false;
}
const auto len1 = r1.end()->value().representation().size();
const auto len2 = r2.end()->value().representation().size();
if (len1 == len2) { // The values truly are equal.
return !r1.end()->is_inclusive() && r2.end()->is_inclusive();
} else if (len1 < len2) { // r1 end is a prefix of r2 end.
// (a)<(1) ends before (a,b)<=(1,1), but (a)<=(1) doesn't.
return !r1.end()->is_inclusive();
} else { // r2 end is a prefix of r1 end.
// (a,b)<=(1,1) ends before (a)<=(1) but after (a)<(1).
return r2.end()->is_inclusive();
}
}
/// Correct clustering_range intersection. See #8157.
std::optional<query::clustering_range> intersection(
const query::clustering_range& r1,
const query::clustering_range& r2,
const clustering_key_prefix::prefix_equal_tri_compare& cmp) {
// Assume r1's start is to the left of r2's start.
if (starts_before_start(r2, r1, cmp)) {
return intersection(r2, r1, cmp);
}
if (!starts_before_or_at_end(r2, r1, cmp)) {
return {};
}
const auto& intersection_start = r2.start();
const auto& intersection_end = ends_before_end(r1, r2, cmp) ? r1.end() : r2.end();
if (intersection_start == intersection_end && intersection_end.has_value()) {
return query::clustering_range::make_singular(intersection_end->value());
}
return query::clustering_range(intersection_start, intersection_end);
}
struct range_less {
const class schema& s;
clustering_key_prefix::less_compare cmp = clustering_key_prefix::less_compare(s);
bool operator()(const query::clustering_range& x, const query::clustering_range& y) const {
if (!x.start() && !y.start()) {
return false;
}
if (!x.start()) {
return true;
}
if (!y.start()) {
return false;
}
return cmp(x.start()->value(), y.start()->value());
}
};
/// An expression visitor that translates multi-column atoms into clustering ranges.
struct multi_column_range_accumulator {
const query_options& options;
const schema_ptr schema;
std::vector<query::clustering_range> ranges{query::clustering_range::make_open_ended_both_sides()};
const clustering_key_prefix::prefix_equal_tri_compare prefix3cmp = get_unreversed_tri_compare(*schema);
void operator()(const binary_operator& binop) {
if (is_compare(binop.op)) {
auto opt_values = dynamic_pointer_cast<tuples::value>(binop.rhs->bind(options))->get_elements();
auto& lhs = std::get<column_value_tuple>(*binop.lhs);
std::vector<managed_bytes> values(lhs.elements.size());
for (size_t i = 0; i < lhs.elements.size(); ++i) {
values[i] = *statements::request_validations::check_not_null(
opt_values[i],
"Invalid null value in condition for column %s", lhs.elements.at(i).col->name_as_text());
}
intersect_all(to_range(binop.op, clustering_key_prefix(std::move(values))));
} else if (binop.op == oper_t::IN) {
if (auto dv = dynamic_pointer_cast<lists::delayed_value>(binop.rhs)) {
process_in_values(
dv->get_elements() | transformed(
[&] (const ::shared_ptr<term>& t) {
return static_pointer_cast<tuples::value>(t->bind(options))->get_elements();
}));
} else if (auto mkr = dynamic_pointer_cast<tuples::in_marker>(binop.rhs)) {
// This is `(a,b) IN ?`. RHS elements are themselves tuples, represented as vector<bytes_opt>.
const auto tup = static_pointer_cast<tuples::in_value>(mkr->bind(options));