-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathpgsql_operation.cc
2446 lines (2133 loc) · 94.3 KB
/
pgsql_operation.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) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/docdb/pgsql_operation.h"
#include <algorithm>
#include <functional>
#include <limits>
#include <queue>
#include <string>
#include <unordered_set>
#include <variant>
#include <utility>
#include <vector>
#include "yb/common/common.pb.h"
#include "yb/common/pg_system_attr.h"
#include "yb/common/pgsql_error.h"
#include "yb/common/ql_type.h"
#include "yb/common/ql_value.h"
#include "yb/common/row_mark.h"
#include "yb/docdb/doc_pg_expr.h"
#include "yb/docdb/doc_pgsql_scanspec.h"
#include "yb/docdb/doc_read_context.h"
#include "yb/docdb/doc_rowwise_iterator.h"
#include "yb/docdb/doc_write_batch.h"
#include "yb/docdb/docdb.messages.h"
#include "yb/docdb/docdb_debug.h"
#include "yb/docdb/docdb_pgapi.h"
#include "yb/docdb/docdb_rocksdb_util.h"
#include "yb/docdb/intent_aware_iterator.h"
#include "yb/docdb/ql_storage_interface.h"
#include "yb/dockv/doc_path.h"
#include "yb/dockv/packed_row.h"
#include "yb/dockv/packed_value.h"
#include "yb/dockv/partition.h"
#include "yb/dockv/pg_row.h"
#include "yb/dockv/primitive_value_util.h"
#include "yb/dockv/reader_projection.h"
#include "yb/gutil/macros.h"
#include "yb/qlexpr/ql_expr_util.h"
#include "yb/rpc/sidecars.h"
#include "yb/util/algorithm_util.h"
#include "yb/util/debug.h"
#include "yb/util/enums.h"
#include "yb/util/flags.h"
#include "yb/util/logging.h"
#include "yb/util/result.h"
#include "yb/util/scope_exit.h"
#include "yb/util/status_format.h"
#include "yb/util/trace.h"
#include "yb/util/yb_pg_errcodes.h"
#include "yb/vector/vectorann.h"
#include "yb/yql/pggate/util/pg_doc_data.h"
using namespace std::literals;
using yb::vectorindex::ANNPagingState;
using yb::vectorindex::DocKeyWithDistance;
using yb::vectorindex::IndexableVectorType;
using yb::vectorindex::DummyANNFactory;
using yb::vectorindex::VectorANN;
DECLARE_bool(ysql_disable_index_backfill);
DEPRECATE_FLAG(double, ysql_scan_timeout_multiplier, "10_2022");
DEFINE_UNKNOWN_uint64(ysql_scan_deadline_margin_ms, 1000,
"Scan deadline is calculated by adding client timeout to the time when the request "
"was received. It defines the moment in time when client has definitely timed out "
"and if the request is yet in processing after the deadline, it can be canceled. "
"Therefore to prevent client timeout, the request handler should return partial "
"result and paging information some time before the deadline. That's what the "
"ysql_scan_deadline_margin_ms is for. It should account for network and processing "
"delays.");
DEFINE_UNKNOWN_bool(pgsql_consistent_transactional_paging, true,
"Whether to enforce consistency of data returned for second page and beyond for YSQL "
"queries on transactional tables. If true, read restart errors could be returned to "
"prevent inconsistency. If false, no read restart errors are returned but the data may "
"be stale. The latter is preferable for long scans. The data returned for the first "
"page of results is never stale regardless of this flag.");
DEFINE_test_flag(int32, slowdown_pgsql_aggregate_read_ms, 0,
"If set > 0, slows down the response to pgsql aggregate read by this amount.");
// Disable packed row by default in debug builds.
// TODO: only enabled for new installs only for now, will enable it for upgrades in 2.22+ release.
constexpr bool kYsqlEnablePackedRowTargetVal = !yb::kIsDebug;
DEFINE_RUNTIME_AUTO_bool(ysql_enable_packed_row, kNewInstallsOnly,
!kYsqlEnablePackedRowTargetVal, kYsqlEnablePackedRowTargetVal,
"Whether packed row is enabled for YSQL.");
DEFINE_RUNTIME_bool(ysql_enable_packed_row_for_colocated_table, true,
"Whether to enable packed row for colocated tables.");
DEFINE_UNKNOWN_uint64(
ysql_packed_row_size_limit, 0,
"Packed row size limit for YSQL in bytes. 0 to make this equal to SSTable block size.");
DEFINE_test_flag(bool, ysql_suppress_ybctid_corruption_details, false,
"Whether to show less details on ybctid corruption error status message. Useful "
"during tests that require consistent output.");
DEFINE_RUNTIME_bool(ysql_enable_pack_full_row_update, false,
"Whether to enable packed row for full row update.");
DEFINE_RUNTIME_PREVIEW_bool(ysql_use_packed_row_v2, false,
"Whether to use packed row V2 when row packing is enabled.");
DEFINE_RUNTIME_AUTO_bool(ysql_skip_row_lock_for_update, kExternal, true, false,
"By default DocDB operations for YSQL take row-level locks. If set to true, DocDB will instead "
"take finer column-level locks instead of locking the whole row. This may cause issues with "
"data integrity for operations with implicit dependencies between columns.");
DECLARE_uint64(rpc_max_message_size);
namespace yb::docdb {
using dockv::DocKey;
using dockv::DocPath;
using dockv::KeyEntryValue;
using dockv::SubDocKey;
using qlexpr::QLExprResult;
using qlexpr::QLTableRow;
bool ShouldYsqlPackRow(bool is_colocated) {
return FLAGS_ysql_enable_packed_row &&
(!is_colocated || FLAGS_ysql_enable_packed_row_for_colocated_table);
}
namespace {
class DocKeyColumnPathBuilder {
public:
DocKeyColumnPathBuilder(dockv::KeyBytes* buffer, Slice encoded_doc_key)
: buffer_(*buffer), encoded_doc_key_length_(encoded_doc_key.size()) {
DCHECK(buffer_.empty());
buffer_.AppendRawBytes(encoded_doc_key);
}
[[nodiscard]] Slice Build(ColumnIdRep column_id) {
return Build(dockv::KeyEntryType::kColumnId, column_id);
}
[[nodiscard]] Slice Build(dockv::SystemColumnIds column_id) {
return Build(dockv::KeyEntryType::kSystemColumnId, to_underlying(column_id));
}
private:
[[nodiscard]] Slice Build(dockv::KeyEntryType key_entry_type, ColumnIdRep column_id) {
buffer_.Truncate(encoded_doc_key_length_);
buffer_.AppendKeyEntryType(key_entry_type);
buffer_.AppendColumnId(ColumnId(column_id));
return buffer_.AsSlice();
}
dockv::KeyBytes& buffer_;
const size_t encoded_doc_key_length_;
DISALLOW_COPY_AND_ASSIGN(DocKeyColumnPathBuilder);
};
class DocKeyColumnPathBuilderHolder {
public:
template<class... Args>
explicit DocKeyColumnPathBuilderHolder(Args&&... args)
: builder_(&buffer_, std::forward<Args>(args)...) {}
[[nodiscard]] DocKeyColumnPathBuilder& builder() { return builder_; }
private:
dockv::KeyBytes buffer_;
DocKeyColumnPathBuilder builder_;
};
YB_STRONGLY_TYPED_BOOL(KeyOnlyRequested);
YB_DEFINE_ENUM(IntentFeature, (kRegularRead)(kKeyOnlyRead)(kRowLock));
// Helper class to describe what kind of intents must be created on particular doc key:
// - regular_read - intent for regular read is required
// - key_only_read - intent for key column only read is required
// - row_lock - intent for row lock is required.
// Note: regular_read and key_only_read can't be both equaled true.
class IntentMode {
public:
IntentMode(IsolationLevel level, RowMarkType row_mark, KeyOnlyRequested key_only_requested) {
auto intent_types = dockv::GetIntentTypesForRead(level, row_mark);
const auto& read_intents = intent_types.read;
auto& lock_intents = intent_types.row_mark;
if (!read_intents.None()) {
auto all_read_intents = MakeWeak(read_intents);
if (key_only_requested) {
features_.Set(IntentFeature::kKeyOnlyRead);
} else {
all_read_intents |= read_intents;
features_.Set(IntentFeature::kRegularRead);
}
lock_intents &= ~(all_read_intents);
}
if (!lock_intents.None()) {
features_.Set(IntentFeature::kRowLock);
}
}
[[nodiscard]] bool regular_read() const {
return features_.Test(IntentFeature::kRegularRead);
}
[[nodiscard]] bool key_only_read() const {
return features_.Test(IntentFeature::kKeyOnlyRead);
}
[[nodiscard]] bool row_lock() const {
return features_.Test(IntentFeature::kRowLock);
}
private:
EnumBitSet<IntentFeature> features_;
};
class IntentInserter {
public:
explicit IntentInserter(LWKeyValueWriteBatchPB* out)
: out_(*out) {}
void Add(Slice encoded_key, const IntentMode& mode) {
if (mode.regular_read()) {
Add(encoded_key);
} else if (mode.key_only_read()) {
auto& buf = buffer();
buf.Clear();
DocKeyColumnPathBuilder doc_key_builder(&buf, encoded_key);
Add(doc_key_builder.Build(dockv::SystemColumnIds::kLivenessColumn));
}
if (mode.row_lock()) {
Add(encoded_key, /*row_lock=*/ true);
}
}
private:
[[nodiscard]] dockv::KeyBytes& buffer() {
if (!buffer_) {
buffer_.emplace();
}
return *buffer_;
}
void Add(Slice encoded_key, bool is_row_lock = false) {
auto& pair = *out_.add_read_pairs();
pair.dup_key(encoded_key);
pair.dup_value(Slice(
is_row_lock ? &dockv::ValueEntryTypeAsChar::kRowLock
: &dockv::ValueEntryTypeAsChar::kNullLow,
1));
}
std::optional<dockv::KeyBytes> buffer_;
LWKeyValueWriteBatchPB& out_;
DISALLOW_COPY_AND_ASSIGN(IntentInserter);
};
class DocKeyAccessor {
public:
explicit DocKeyAccessor(std::reference_wrapper<const Schema> schema)
: schema_(schema.get()), source_(std::nullopt), result_holder_(std::nullopt) {}
Result<Slice> GetEncoded(std::reference_wrapper<const PgsqlExpressionPB> ybctid) {
RETURN_NOT_OK(Apply(ybctid.get()));
return Encoded();
}
Result<Slice> GetEncoded(std::reference_wrapper<const yb::PgsqlReadRequestPB> req) {
RETURN_NOT_OK(Apply(req.get()));
return Encoded();
}
Result<DocKey&> GetDecoded(std::reference_wrapper<const yb::PgsqlWriteRequestPB> req) {
RETURN_NOT_OK(Apply(req.get()));
return Decoded();
}
private:
Result<DocKey&> Decoded() {
DCHECK(!std::holds_alternative<std::nullopt_t>(source_));
if (std::holds_alternative<DocKey>(source_)) {
return std::get<DocKey>(source_);
}
auto& doc_key = GetResultHolder<DocKey>();
RETURN_NOT_OK(doc_key.DecodeFrom(std::get<Slice>(source_)));
return doc_key;
}
Result<Slice> Encoded() {
DCHECK(!std::holds_alternative<std::nullopt_t>(source_));
if (std::holds_alternative<DocKey>(source_)) {
return GetResultHolder<EncodedKey>().Append(std::get<DocKey>(source_)).AsSlice();
}
auto& src = std::get<Slice>(source_);
if (!schema_.is_colocated()) {
return src;
}
return GetResultHolder<EncodedKey>().Append(src).AsSlice();
}
template<class Req>
Status Apply(const Req& req) {
// Init DocDB key using either ybctid or partition and range values.
if (req.has_ybctid_column_value()) {
return Apply(req.ybctid_column_value());
}
auto hashed_components = VERIFY_RESULT(qlexpr::InitKeyColumnPrimitiveValues(
req.partition_column_values(), schema_, 0 /* start_idx */));
auto range_components = VERIFY_RESULT(qlexpr::InitKeyColumnPrimitiveValues(
req.range_column_values(), schema_, schema_.num_hash_key_columns()));
if (hashed_components.empty()) {
source_.emplace<DocKey>(schema_, std::move(range_components));
} else {
source_.emplace<DocKey>(
schema_, req.hash_code(), std::move(hashed_components), std::move(range_components));
}
return Status::OK();
}
Status Apply(const PgsqlExpressionPB& ybctid) {
const auto& value = ybctid.value().binary_value();
SCHECK(!value.empty(), InternalError, "empty ybctid");
source_.emplace<Slice>(value);
return Status::OK();
}
template<class T>
T& GetResultHolder() {
return std::holds_alternative<T>(result_holder_)
? std::get<T>(result_holder_)
: result_holder_.emplace<T>(schema_);
}
class EncodedKey {
public:
explicit EncodedKey(std::reference_wrapper<const Schema> schema)
: schema_(schema),
prefix_length_(0) {
if (schema_.is_colocated()) {
DocKey prefix_builder(schema_);
prefix_builder.AppendTo(&data_);
DCHECK_GT(data_.size(), 1);
prefix_length_ = data_.size() - 1;
data_.Truncate(prefix_length_);
}
}
const dockv::KeyBytes& Append(const DocKey& doc_key) {
DCHECK(doc_key.colocation_id() == schema_.colocation_id() &&
doc_key.cotable_id() == schema_.cotable_id());
// Because doc_key uses same schema all encoded doc key will contain same prefix as generated
// in constructor (if any). So it is safe to reuse it in future.
data_.Clear();
doc_key.AppendTo(&data_);
return data_;
}
const dockv::KeyBytes& Append(Slice ybctid) {
// Current function must be called only in case ybctid requires prefix.
DCHECK(prefix_length_);
data_.Truncate(prefix_length_);
data_.AppendRawBytes(ybctid);
return data_;
}
private:
const Schema& schema_;
dockv::KeyBytes data_;
size_t prefix_length_;
};
const Schema& schema_;
std::variant<std::nullopt_t, Slice, DocKey> source_;
std::variant<std::nullopt_t, EncodedKey, DocKey> result_holder_;
};
Result<YQLRowwiseIteratorIf::UniPtr> CreateIterator(
const YQLStorageIf& ql_storage,
const PgsqlReadRequestPB& request,
const dockv::ReaderProjection& projection,
std::reference_wrapper<const DocReadContext> doc_read_context,
const TransactionOperationContext& txn_op_context,
const ReadOperationData& read_operation_data,
bool is_explicit_request_read_time,
std::reference_wrapper<const ScopedRWOperation> pending_op) {
VLOG_IF(2, request.is_for_backfill()) << "Creating iterator for " << yb::ToString(request);
YQLRowwiseIteratorIf::UniPtr result;
// TODO(neil) Remove the following IF block when it is completely obsolete.
// The following IF block gets used in the CREATE INDEX codepath.
if (request.has_ybctid_column_value()) {
RETURN_NOT_OK(ql_storage.GetIteratorForYbctid(
request.stmt_id(), projection, doc_read_context, txn_op_context, read_operation_data,
request.ybctid_column_value().value().binary_value(),
request.ybctid_column_value().value().binary_value(), pending_op, &result));
} else {
SubDocKey start_sub_doc_key;
auto actual_read_time = read_operation_data.read_time;
// Decode the start SubDocKey from the paging state and set scan start key.
if (request.has_paging_state() &&
request.paging_state().has_next_row_key() &&
!request.paging_state().next_row_key().empty()) {
dockv::KeyBytes start_key_bytes(request.paging_state().next_row_key());
RETURN_NOT_OK(start_sub_doc_key.FullyDecodeFrom(start_key_bytes.AsSlice()));
// TODO(dmitry) Remove backward compatibility block when obsolete.
if (!is_explicit_request_read_time) {
if (request.paging_state().has_read_time()) {
actual_read_time = ReadHybridTime::FromPB(request.paging_state().read_time());
} else {
actual_read_time.read = start_sub_doc_key.hybrid_time();
}
}
} else if (request.is_for_backfill()) {
RSTATUS_DCHECK(is_explicit_request_read_time, InvalidArgument,
"Backfill request should already be using explicit read times.");
PgsqlBackfillSpecPB spec;
spec.ParseFromString(a2b_hex(request.backfill_spec()));
if (!spec.next_row_key().empty()) {
dockv::KeyBytes start_key_bytes(spec.next_row_key());
RETURN_NOT_OK(start_sub_doc_key.FullyDecodeFrom(start_key_bytes.AsSlice()));
}
}
RETURN_NOT_OK(ql_storage.GetIterator(
request, projection, doc_read_context, txn_op_context, read_operation_data,
start_sub_doc_key.doc_key(), pending_op, &result));
}
return std::move(result);
}
template <class ColumnIds>
Status VerifyNoColsMarkedForDeletion(const TableId& table_id,
const Schema& schema,
ColumnIds&& column_refs) {
for (const auto& col : column_refs) {
const auto& id = dockv::GetColumnId(col);
int idx = schema.find_column_by_id(id);
if (idx == -1) {
return STATUS_FORMAT(IllegalState, "Column not found: $0 in table $1", id, table_id);
}
SCHECK(!schema.IsColMarkedForDeletion(idx),
InvalidArgument,
"Column with id $0 marked for deletion in table $1",
id, table_id);
}
return Status::OK();
}
template<class PB>
Status VerifyNoRefColsMarkedForDeletion(const Schema& schema, const PB& request) {
if (!request.col_refs().empty()) {
RETURN_NOT_OK(VerifyNoColsMarkedForDeletion(request.table_id(), schema, request.col_refs()));
}
// Compatibility: Either request indeed has no column refs, or it comes from a legacy node.
return VerifyNoColsMarkedForDeletion(request.table_id(), schema, request.column_refs().ids());
}
Status VerifyNoColsMarkedForDeletion(const Schema& schema, const PgsqlWriteRequestPB& request) {
// Verify that the request does not refer any columns marked for deletion.
RETURN_NOT_OK(VerifyNoRefColsMarkedForDeletion(schema, request));
// Verify columns being updated are not marked for deletion.
RETURN_NOT_OK(VerifyNoColsMarkedForDeletion(request.table_id(),
schema,
request.column_new_values()));
// Verify columns being inserted are not marked for deletion.
return VerifyNoColsMarkedForDeletion(request.table_id(), schema, request.column_values());
}
template<class PB>
void InitProjection(const Schema& schema, const PB& request, dockv::ReaderProjection* projection) {
if (!request.col_refs().empty()) {
projection->Init(schema, request.col_refs());
} else {
// Compatibility: Either request indeed has no column refs, or it comes from a legacy node.
projection->Init(schema, request.column_refs().ids());
}
}
template<class PB>
dockv::ReaderProjection CreateProjection(const Schema& schema, const PB& request) {
dockv::ReaderProjection result;
InitProjection(schema, request, &result);
return result;
}
YB_DEFINE_ENUM(FetchResult, (NotFound)(FilteredOut)(Found));
class FilteringIterator {
public:
explicit FilteringIterator(std::unique_ptr<YQLRowwiseIteratorIf>* iterator_holder)
: iterator_holder_(*iterator_holder) {}
Status Init(
const YQLStorageIf& ql_storage,
const PgsqlReadRequestPB& request,
const dockv::ReaderProjection& projection,
std::reference_wrapper<const DocReadContext> read_context,
const TransactionOperationContext& txn_op_context,
const ReadOperationData& read_operation_data,
bool is_explicit_request_read_time,
std::reference_wrapper<const ScopedRWOperation> pending_op) {
RETURN_NOT_OK(InitCommon(request, read_context.get().schema(), projection));
iterator_holder_ = VERIFY_RESULT(CreateIterator(
ql_storage, request, projection, read_context, txn_op_context, read_operation_data,
is_explicit_request_read_time, pending_op));
return Status::OK();
}
Status InitForYbctid(
const YQLStorageIf& ql_storage,
const PgsqlReadRequestPB& request,
const dockv::ReaderProjection& projection,
std::reference_wrapper<const DocReadContext> read_context,
const TransactionOperationContext& txn_op_context,
const ReadOperationData& read_operation_data,
const Slice& min_ybctid,
const Slice& max_ybctid,
std::reference_wrapper<const ScopedRWOperation> pending_op,
SkipSeek skip_seek) {
RETURN_NOT_OK(InitCommon(request, read_context.get().schema(), projection));
return ql_storage.GetIteratorForYbctid(
request.stmt_id(), projection, read_context, txn_op_context, read_operation_data,
min_ybctid, max_ybctid, pending_op, &iterator_holder_, skip_seek);
}
Result<FetchResult> FetchNext(dockv::PgTableRow* table_row) {
if (!VERIFY_RESULT(iterator_holder_->PgFetchNext(table_row))) {
return FetchResult::NotFound;
}
return CheckFilter(*table_row);
}
Result<FetchResult> FetchTuple(const Slice& tuple_id, dockv::PgTableRow* row) {
iterator_holder_->SeekTuple(tuple_id);
if (!VERIFY_RESULT(iterator_holder_->PgFetchNext(row)) ||
iterator_holder_->GetTupleId() != tuple_id) {
return FetchResult::NotFound;
}
return CheckFilter(*row);
}
private:
Status InitCommon(
const PgsqlReadRequestPB& request, const Schema& schema,
const dockv::ReaderProjection& projection) {
const auto& where_clauses = request.where_clauses();
if (where_clauses.empty()) {
return Status::OK();
}
DocPgExprExecutorBuilder builder(schema, projection);
for (const auto& exp : where_clauses) {
RETURN_NOT_OK(builder.AddWhere(exp));
}
filter_.emplace(VERIFY_RESULT(builder.Build(request.col_refs())));
return Status::OK();
}
Result<FetchResult> CheckFilter(const dockv::PgTableRow& row) {
return filter_ && !VERIFY_RESULT(filter_->Exec(row))
? FetchResult::FilteredOut : FetchResult::Found;
}
std::unique_ptr<YQLRowwiseIteratorIf>& iterator_holder_;
boost::optional<DocPgExprExecutor> filter_;
};
struct IndexState {
IndexState(
const Schema& schema, const PgsqlReadRequestPB& request,
std::unique_ptr<YQLRowwiseIteratorIf>* iterator_holder, ColumnId ybbasectid_id)
: projection(CreateProjection(schema, request)), row(projection), iter(iterator_holder),
ybbasectid_idx(projection.ColumnIdxById(ybbasectid_id)), scanned_rows(0) {
}
dockv::ReaderProjection projection;
dockv::PgTableRow row;
FilteringIterator iter;
const size_t ybbasectid_idx;
uint64_t scanned_rows;
};
Result<FetchResult> FetchTableRow(
const std::string& table_id, FilteringIterator* table_iter,
IndexState* index, dockv::PgTableRow* row) {
Slice tuple_id;
if (index) {
auto& index_row = index->row;
switch(VERIFY_RESULT(index->iter.FetchNext(&index_row))) {
case FetchResult::NotFound:
return FetchResult::NotFound;
case FetchResult::FilteredOut:
VLOG(1) << "Row filtered out by colocated index condition";
++index->scanned_rows;
return FetchResult::FilteredOut;
case FetchResult::Found:
++index->scanned_rows;
break;
}
auto optional_tuple_id = index_row.GetValueByIndex(index->ybbasectid_idx);
SCHECK(optional_tuple_id, Corruption, "ybbasectid not found in index row");
tuple_id = optional_tuple_id->binary_value();
}
const auto fetch_result = VERIFY_RESULT(
index ? table_iter->FetchTuple(tuple_id, row) : table_iter->FetchNext(row));
switch(fetch_result) {
case FetchResult::NotFound: {
if (!index) {
break;
}
if (FLAGS_TEST_ysql_suppress_ybctid_corruption_details) {
return STATUS(Corruption, "ybctid not found in indexed table");
}
return STATUS_FORMAT(
Corruption, "ybctid $0 not found in indexed table. index table id is $1",
DocKey::DebugSliceToString(tuple_id), table_id);
}
case FetchResult::FilteredOut:
VLOG(1) << "Row filtered out by the condition";
break;
case FetchResult::Found:
break;
}
return fetch_result;
}
struct RowPackerData {
SchemaVersion schema_version;
const dockv::SchemaPacking& packing;
const Schema& schema;
static Result<RowPackerData> Create(
const PgsqlWriteRequestPB& request, const DocReadContext& read_context) {
auto schema_version = request.schema_version();
return RowPackerData {
.schema_version = schema_version,
.packing = VERIFY_RESULT(read_context.schema_packing_storage.GetPacking(schema_version)),
.schema = read_context.schema()
};
}
dockv::RowPackerVariant MakePacker() const {
if (FLAGS_ysql_use_packed_row_v2) {
return MakePackerHelper<dockv::RowPackerV2>();
}
return MakePackerHelper<dockv::RowPackerV1>();
}
private:
template <class T>
dockv::RowPackerVariant MakePackerHelper() const {
return dockv::RowPackerVariant(
std::in_place_type_t<T>(), schema_version, packing, FLAGS_ysql_packed_row_size_limit,
Slice(), schema);
}
};
bool IsExpression(const PgsqlColumnValuePB& column_value) {
return qlexpr::GetTSWriteInstruction(column_value.expr()) == bfpg::TSOpcode::kPgEvalExprCall;
}
class ExpressionHelper {
public:
Status Init(
const Schema& schema, const dockv::ReaderProjection& projection,
const PgsqlWriteRequestPB& request, const dockv::PgTableRow& table_row) {
DocPgExprExecutorBuilder builder(schema, projection);
for (const auto& column_value : request.column_new_values()) {
if (IsExpression(column_value)) {
RETURN_NOT_OK(builder.AddTarget(column_value.expr()));
}
}
auto executor = VERIFY_RESULT(builder.Build(request.col_refs()));
return ResultToStatus(executor.Exec(table_row, &results_));
}
QLExprResult* NextResult(const PgsqlColumnValuePB& column_value) {
if (!IsExpression(column_value)) {
return nullptr;
}
DCHECK_LT(next_result_idx_, results_.size());
return &results_[next_result_idx_++];
}
private:
std::vector<QLExprResult> results_;
size_t next_result_idx_ = 0;
};
[[nodiscard]] inline bool NewValuesHaveExpression(const PgsqlWriteRequestPB& request) {
// In case of UPDATE row need to be protected from removing. Weak intent is enough for
// this purpose. To achieve this the path for row's SystemColumnIds::kLivenessColumn column
// is returned. The caller code will create strong intent for returned path
// (row's column doc key) and weak intents for all its prefixes (including row's doc key).
// Note: UPDATE operation may have expressions instead of exact value.
// These expressions may read column value.
// Potentially expression for updating column v1 may read value of column v2.
//
// UPDATE t SET v = v + 10 WHERE k = 1
// UPDATE t SET v1 = v2 + 10 WHERE k = 1
//
// Strong intent for the whole row is required in this case as it may be too expensive to
// determine what exact columns are read by the expression.
return std::any_of(
request.column_new_values().begin(), request.column_new_values().end(),
[](const auto& cv) { return !cv.expr().has_value(); });
}
void WriteNumRows(size_t result_rows, const WriteBufferPos& pos, WriteBuffer* buffer) {
char encoded_rows[sizeof(uint64_t)];
NetworkByteOrder::Store64(encoded_rows, result_rows);
CHECK_OK(buffer->Write(pos, encoded_rows, sizeof(encoded_rows)));
}
[[nodiscard]] inline bool IsNonKeyColumn(const Schema& schema, int32_t column_id) {
return !schema.is_key_column(ColumnId(column_id));
}
template<class Container, class Functor>
[[nodiscard]] inline bool Find(const Container& c, const Functor& f) {
auto end = std::end(c);
return std::find_if(std::begin(c), end, f) != end;
}
// Note: function return true in case request reads only key columns.
// Such kind of request is used for explicit row locking via separate RPC from postgres.
[[nodiscard]] bool IsOnlyKeyColumnsRequested(const Schema& schema, const PgsqlReadRequestPB& req) {
if (!req.col_refs().empty()) {
return !Find(
req.col_refs(),
[&schema](const PgsqlColRefPB& col) { return IsNonKeyColumn(schema, col.column_id()); });
}
return !Find(
req.column_refs().ids(),
[&schema](int32_t col_id) { return IsNonKeyColumn(schema, col_id); });
}
} // namespace
class PgsqlWriteOperation::RowPackContext {
public:
RowPackContext(const PgsqlWriteRequestPB& request,
const DocOperationApplyData& data,
const RowPackerData& packer_data)
: query_id_(request.stmt_id()),
data_(data),
write_id_(data.doc_write_batch->ReserveWriteId()),
packer_(packer_data.MakePacker()) {
}
template <class Value>
Result<bool> Add(ColumnId column_id, const Value& value) {
return std::visit([column_id, &value](auto& packer) {
return packer.AddValue(column_id, value);
}, packer_);
}
Status Complete(const RefCntPrefix& encoded_doc_key) {
return Complete(encoded_doc_key.as_slice());
}
Status Complete(Slice encoded_doc_key) {
auto encoded_value = VERIFY_RESULT(std::visit([](auto& packer) {
return packer.Complete();
}, packer_));
return data_.doc_write_batch->SetPrimitive(
DocPath(encoded_doc_key), dockv::ValueControlFields(),
ValueRef(encoded_value), data_.read_operation_data, query_id_, write_id_);
}
private:
rocksdb::QueryId query_id_;
const DocOperationApplyData& data_;
const IntraTxnWriteId write_id_;
dockv::RowPackerVariant packer_;
};
//--------------------------------------------------------------------------------------------------
PgsqlWriteOperation::PgsqlWriteOperation(
std::reference_wrapper<const PgsqlWriteRequestPB> request, DocReadContextPtr doc_read_context,
const TransactionOperationContext& txn_op_context, rpc::Sidecars* sidecars)
: DocOperationBase(request),
doc_read_context_(std::move(doc_read_context)),
txn_op_context_(txn_op_context),
sidecars_(sidecars),
ysql_skip_row_lock_for_update_(FLAGS_ysql_skip_row_lock_for_update) {}
Status PgsqlWriteOperation::Init(PgsqlResponsePB* response) {
// Initialize operation inputs.
response_ = response;
if (!request_.packed_rows().empty()) {
// When packed_rows are specified, operation could contain multiple rows.
// So we use table root key for doc_key, and have to use special handling for packed_rows in
// other places.
doc_key_ = dockv::DocKey(doc_read_context_->schema());
encoded_doc_key_ = doc_key_.EncodeAsRefCntPrefix();
} else {
DocKeyAccessor accessor(doc_read_context_->schema());
doc_key_ = std::move(VERIFY_RESULT_REF(accessor.GetDecoded(request_)));
encoded_doc_key_ = doc_key_.EncodeAsRefCntPrefix(
Slice(&dockv::KeyEntryTypeAsChar::kHighest, 1));
}
encoded_doc_key_.Resize(encoded_doc_key_.size() - 1);
return Status::OK();
}
// Check if a duplicate value is inserted into a unique index.
Result<bool> PgsqlWriteOperation::HasDuplicateUniqueIndexValue(const DocOperationApplyData& data) {
VLOG(3) << "Looking for collisions in\n" << DocDBDebugDumpToStr(data);
// We need to check backwards only for backfilled entries.
bool ret =
VERIFY_RESULT(HasDuplicateUniqueIndexValue(data, data.read_time())) ||
(request_.is_backfill() &&
VERIFY_RESULT(HasDuplicateUniqueIndexValueBackward(data)));
if (!ret) {
VLOG(3) << "No collisions found";
}
return ret;
}
Result<bool> PgsqlWriteOperation::HasDuplicateUniqueIndexValueBackward(
const DocOperationApplyData& data) {
VLOG(2) << "Looking for collision while going backward. Trying to insert " << doc_key_;
auto iter = CreateIntentAwareIterator(
data.doc_write_batch->doc_db(),
BloomFilterMode::USE_BLOOM_FILTER,
encoded_doc_key_.as_slice(),
rocksdb::kDefaultQueryId,
txn_op_context_,
data.read_operation_data.WithAlteredReadTime(ReadHybridTime::Max()));
HybridTime oldest_past_min_ht = VERIFY_RESULT(FindOldestOverwrittenTimestamp(
iter.get(), SubDocKey(doc_key_), data.read_time().read));
const HybridTime oldest_past_min_ht_liveness =
VERIFY_RESULT(FindOldestOverwrittenTimestamp(
iter.get(),
SubDocKey(doc_key_, KeyEntryValue::kLivenessColumn),
data.read_time().read));
oldest_past_min_ht.MakeAtMost(oldest_past_min_ht_liveness);
if (!oldest_past_min_ht.is_valid()) {
return false;
}
return HasDuplicateUniqueIndexValue(
data, ReadHybridTime::SingleTime(oldest_past_min_ht));
}
Result<bool> PgsqlWriteOperation::HasDuplicateUniqueIndexValue(
const DocOperationApplyData& data, const ReadHybridTime& read_time) {
// Set up the iterator to read the current primary key associated with the index key.
DocPgsqlScanSpec spec(doc_read_context_->schema(), request_.stmt_id(), doc_key_);
dockv::ReaderProjection projection(doc_read_context_->schema());
auto iterator = DocRowwiseIterator(
projection,
*doc_read_context_,
txn_op_context_,
data.doc_write_batch->doc_db(),
data.read_operation_data.WithAlteredReadTime(read_time),
data.doc_write_batch->pending_op());
RETURN_NOT_OK(iterator.Init(spec));
// It is a duplicate value if the index key exists already and the index value (corresponding to
// the indexed table's primary key) is not the same.
dockv::PgTableRow table_row(projection);
if (!VERIFY_RESULT(iterator.PgFetchNext(&table_row))) {
VLOG(2) << "No collision found while checking at " << yb::ToString(read_time);
return false;
}
ValueBuffer new_value_buffer;
ValueBuffer existing_value_buffer;
for (const auto& column_value : request_.column_values()) {
// Get the column.
if (!column_value.has_column_id()) {
return STATUS(InternalError, "column id missing", column_value.DebugString());
}
const ColumnId column_id(column_value.column_id());
// Check column-write operator.
CHECK(qlexpr::GetTSWriteInstruction(column_value.expr()) == bfpg::TSOpcode::kScalarInsert)
<< "Illegal write instruction";
size_t column_idx = table_row.projection().ColumnIdxById(column_id);
if (column_idx == dockv::ReaderProjection::kNotFoundIndex) {
continue;
}
auto existing_value = table_row.GetValueByIndex(column_idx);
if (!existing_value) {
continue;
}
existing_value_buffer.Clear();
existing_value->AppendTo(
table_row.projection().columns[column_idx].data_type, &existing_value_buffer);
// Evaluate column value.
QLExprResult expr_result;
RETURN_NOT_OK(EvalExpr(column_value.expr(), table_row, expr_result.Writer()));
new_value_buffer.Clear();
RETURN_NOT_OK(pggate::WriteColumn(expr_result.Value(), &new_value_buffer));
if (new_value_buffer.AsSlice() != existing_value_buffer.AsSlice()) {
VLOG(2) << "Found collision while checking at " << AsString(read_time)
<< "\nExisting: " << AsString(existing_value_buffer)
<< " vs New: " << AsString(new_value_buffer) << "\nUsed read time as "
<< AsString(data.read_time());
DVLOG(3) << "DocDB is now:\n" << DocDBDebugDumpToStr(data);
return true;
}
}
VLOG(2) << "No collision while checking at " << AsString(read_time);
return false;
}
Result<HybridTime> PgsqlWriteOperation::FindOldestOverwrittenTimestamp(
IntentAwareIterator* iter,
const SubDocKey& sub_doc_key,
HybridTime min_read_time) {
HybridTime result;
VLOG(3) << "Doing iter->Seek " << doc_key_;
iter->Seek(doc_key_);
if (VERIFY_RESULT_REF(iter->Fetch())) {
const auto bytes = sub_doc_key.EncodeWithoutHt();
const Slice& sub_key_slice = bytes.AsSlice();
result = VERIFY_RESULT(iter->FindOldestRecord(sub_key_slice, min_read_time));
VLOG(2) << "iter->FindOldestRecord returned " << result << " for "
<< SubDocKey::DebugSliceToString(sub_key_slice);
} else {
VLOG(3) << "iter->Seek " << doc_key_ << " turned out to be out of records";
}
return result;
}
Status PgsqlWriteOperation::Apply(const DocOperationApplyData& data) {
VLOG(4) << "Write, read time: " << data.read_time() << ", txn: " << txn_op_context_;
RETURN_NOT_OK(VerifyNoColsMarkedForDeletion(doc_read_context_->schema(), request_));
auto scope_exit = ScopeExit([this] {
if (write_buffer_) {
WriteNumRows(result_rows_, row_num_pos_, write_buffer_);
response_->set_rows_data_sidecar(narrow_cast<int32_t>(sidecars_->Complete()));
}
});
switch (request_.stmt_type()) {
case PgsqlWriteRequestPB::PGSQL_INSERT:
return ApplyInsert(data, IsUpsert::kFalse);
case PgsqlWriteRequestPB::PGSQL_UPDATE:
return ApplyUpdate(data);
case PgsqlWriteRequestPB::PGSQL_DELETE:
return ApplyDelete(data, request_.is_delete_persist_needed());
case PgsqlWriteRequestPB::PGSQL_UPSERT: {
// Upserts should not have column refs (i.e. require read).
RSTATUS_DCHECK(request_.col_refs().empty(),
IllegalState,
"Upsert operation should not have column references");
return ApplyInsert(data, IsUpsert::kTrue);
}
case PgsqlWriteRequestPB::PGSQL_TRUNCATE_COLOCATED: