-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathquerying.cpp
1341 lines (1176 loc) · 40 KB
/
querying.cpp
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
#include "querying.hpp"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "descriptor_db.hpp"
#include "postgres_protobuf_common.hpp"
#include "postgres_utils.hpp"
// Protobuf headers must be included before any Postgres headers because
// the latter pollute names like 'FATAL' used by macros in the former.
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/wire_format_lite.h>
extern "C" {
// Must be included before other Postgres headers
#include <postgres.h>
}
namespace pb = ::google::protobuf;
namespace postgres_protobuf {
namespace querying {
namespace {
struct FieldInfo {
int number;
uint32 wire_type;
union Value {
uint32 as_uint32;
uint64 as_uint64;
int as_size;
} value;
bool ValueEquals(const FieldInfo& that) {
if (this->wire_type != that.wire_type) {
return false;
}
switch (wire_type) {
case 0:
case 1:
return this->value.as_uint64 == that.value.as_uint64;
case 2:
return this->value.as_size == that.value.as_size;
case 5:
return this->value.as_uint32 == that.value.as_uint32;
default:
return false;
}
}
std::string ToString() const {
std::stringstream ss;
ss << "{num=" << number << ",wt=" << wire_type;
switch (wire_type) {
case 0:
case 1:
ss << ",as_uint64=0x" << std::hex << value.as_uint64;
break;
case 2:
ss << ",as_size=" << value.as_size;
break;
case 5:
ss << ",as_uint32=0x" << std::hex << value.as_uint32;
break;
break;
default:
break;
}
ss << "}";
return ss.str();
}
};
enum class LengthDelimitedFieldTreatment {
Skip,
Buffer,
AsString,
AsBytes,
AsSubmessage,
AsPackedVarint,
AsPacked32,
AsPacked64
};
struct DescPtrs {
pb::FieldDescriptor::Type ty; // Type of thing being pointed at
const pb::Descriptor* desc; // Message descriptor when ty == TYPE_MESSAGE
const pb::EnumDescriptor* enum_desc; // Enum descriptor when ty == TYPE_ENUM
bool is_repeated;
bool is_map;
};
// Thrown as an exception for convenience.
// TODO: this goes against some best practices. Is this worth changing?
class LimitReached {};
class ProtobufTraverser;
class ProtobufVisitor {
public:
ProtobufVisitor() : next_(&ProtobufVisitor::noOp) {}
virtual ~ProtobufVisitor() {}
void SetNext(ProtobufVisitor* next) { next_ = next; }
virtual void Pushed(ProtobufTraverser* traverser) {}
virtual ProtobufVisitor* BeginField(int number, int wire_type) {
return this;
}
virtual void ReadPrimitive(const FieldInfo& field) {}
virtual std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) {
return std::make_pair(LengthDelimitedFieldTreatment::Skip, this);
}
virtual void ReadString(std::string&& str) {}
virtual void ReadBytes(std::string&& bytes) {}
virtual void BufferedValue(std::string&& value) {}
virtual ProtobufVisitor* BeginMessage() { return this; }
virtual void EndField() {}
virtual void Popped() {}
static ProtobufVisitor noOp;
protected:
ProtobufVisitor* next_;
LengthDelimitedFieldTreatment CompositeFieldTreatmentForType(
pb::FieldDescriptor::Type ty) {
switch (ty) {
case pb::FieldDescriptor::Type::TYPE_MESSAGE:
return LengthDelimitedFieldTreatment::AsSubmessage;
case pb::FieldDescriptor::Type::TYPE_STRING:
return LengthDelimitedFieldTreatment::AsString;
case pb::FieldDescriptor::Type::TYPE_BYTES:
return LengthDelimitedFieldTreatment::AsBytes;
default:
return LengthDelimitedFieldTreatment::Skip;
}
}
LengthDelimitedFieldTreatment PackedCompositeFieldTreatmentForType(
pb::FieldDescriptor::Type ty) {
int wire_type = pb::internal::WireFormat::WireTypeForFieldType(ty);
switch (wire_type) {
case 0:
return LengthDelimitedFieldTreatment::AsPackedVarint;
case 1:
return LengthDelimitedFieldTreatment::AsPacked64;
case 5:
return LengthDelimitedFieldTreatment::AsPacked32;
default:
return LengthDelimitedFieldTreatment::Skip;
}
}
};
ProtobufVisitor ProtobufVisitor::noOp;
class ProtobufTraverser {
public:
ProtobufTraverser() : visitor_(&ProtobufVisitor::noOp), depth_(0) {}
void PushVisitor(ProtobufVisitor* v) {
PGPROTO_DEBUG("PUSH %lx", intptr_t(v));
assert(v != nullptr);
visitor_stack_.push_back(StackElement(v, depth_));
visitor_ = v;
v->Pushed(this);
}
void PopVisitor() {
PGPROTO_DEBUG("POP");
if (!visitor_stack_.empty()) {
ProtobufVisitor* popped = visitor_stack_.back().visitor;
visitor_stack_.pop_back();
popped->Popped();
}
if (!visitor_stack_.empty()) {
visitor_ = visitor_stack_.back().visitor;
} else {
visitor_ = &ProtobufVisitor::noOp;
}
}
void ScanField(const FieldInfo& field, pb::io::CodedInputStream* stream) {
if (field.wire_type != 2) {
visitor_->ReadPrimitive(field);
return;
}
LengthDelimitedFieldTreatment treatment;
ProtobufVisitor* new_visitor;
std::tie(treatment, new_visitor) =
visitor_->ReadLengthDelimitedField(field);
PGPROTO_DEBUG("ReadLengthDelimitedField returned %d for visitor %lx",
static_cast<int>(treatment), intptr_t(visitor_));
bool got_new_visitor = new_visitor != visitor_;
if (got_new_visitor) {
PushVisitor(new_visitor);
IncrementDepthAndCallBeginField(field.number, field.wire_type);
}
switch (treatment) {
case LengthDelimitedFieldTreatment::Skip: {
stream->Skip(field.value.as_size);
break;
}
case LengthDelimitedFieldTreatment::Buffer: {
std::string s;
if (!stream->ReadString(&s, field.value.as_size)) {
throw BadProto("failed to fully read length-delimited field");
}
visitor_->BufferedValue(std::move(s));
break;
}
case LengthDelimitedFieldTreatment::AsString: {
std::string s;
if (!stream->ReadString(&s, field.value.as_size)) {
throw BadProto("failed to fully read string field");
}
visitor_->ReadString(std::move(s));
break;
}
case LengthDelimitedFieldTreatment::AsBytes: {
std::string s;
if (!stream->ReadString(&s, field.value.as_size)) {
throw BadProto("failed to fully read bytes field");
}
visitor_->ReadBytes(std::move(s));
break;
}
case LengthDelimitedFieldTreatment::AsSubmessage: {
auto depth_and_limit =
stream->IncrementRecursionDepthAndPushLimit(field.value.as_size);
if (depth_and_limit.second < 0) {
throw RecursionDepthExceeded();
}
visitor_->BeginMessage();
// TODO: avoid actual recursion in case our stack is small
ScanMessage(stream);
stream->DecrementRecursionDepthAndPopLimit(depth_and_limit.first);
break;
}
case LengthDelimitedFieldTreatment::AsPackedVarint: {
ReadPacked(stream, field.number, field.value.as_size, 0);
break;
}
case LengthDelimitedFieldTreatment::AsPacked32: {
ReadPacked(stream, field.number, field.value.as_size, 5);
break;
}
case LengthDelimitedFieldTreatment::AsPacked64: {
ReadPacked(stream, field.number, field.value.as_size, 1);
break;
}
}
if (got_new_visitor) {
DecrementDepthAndEndFieldAndPopVisitors();
}
}
private:
struct StackElement {
ProtobufVisitor* visitor;
int depth_added;
StackElement(ProtobufVisitor* visitor, int depth_added)
: visitor(visitor), depth_added(depth_added) {}
};
std::vector<StackElement> visitor_stack_;
ProtobufVisitor* visitor_;
int depth_;
void ScanMessage(pb::io::CodedInputStream* stream) {
CallBeginMessage();
while (true) {
uint32 tag = stream->ReadTag();
if (tag == 0) {
if (!stream->ConsumedEntireMessage()) {
throw BadProto("Unexpected tag=0");
}
return;
}
FieldInfo field;
field.number = tag >> 3;
field.wire_type = tag & 0x7;
ReadFieldValueOrSize(stream, &field);
IncrementDepthAndCallBeginField(field.number, field.wire_type);
ScanField(field, stream);
DecrementDepthAndEndFieldAndPopVisitors();
}
}
void IncrementDepthAndCallBeginField(int field_number, int wire_type) {
++depth_;
while (true) {
PGPROTO_DEBUG("BeginField %d on visitor %lx", field_number,
intptr_t(visitor_));
ProtobufVisitor* new_visitor =
visitor_->BeginField(field_number, wire_type);
if (new_visitor != visitor_) {
PushVisitor(new_visitor);
} else {
break;
}
}
}
void CallBeginMessage() {
while (true) {
PGPROTO_DEBUG("BeginMessage on visitor %lx", intptr_t(visitor_));
ProtobufVisitor* new_visitor = visitor_->BeginMessage();
if (new_visitor != visitor_) {
PushVisitor(new_visitor);
} else {
break;
}
}
}
void DecrementDepthAndEndFieldAndPopVisitors() {
--depth_;
visitor_->EndField();
while (!visitor_stack_.empty() &&
visitor_stack_.back().depth_added > depth_) {
PopVisitor();
visitor_->EndField();
}
}
void ReadPacked(pb::io::CodedInputStream* stream, int number, int size,
int wire_type) {
FieldInfo f;
f.number = number;
f.wire_type = wire_type;
auto limit = stream->PushLimit(size);
while (stream->BytesUntilLimit() > 0) {
ReadFieldValueOrSize(stream, &f);
IncrementDepthAndCallBeginField(f.number, f.wire_type);
visitor_->ReadPrimitive(f);
DecrementDepthAndEndFieldAndPopVisitors();
}
stream->PopLimit(limit);
}
void ReadFieldValueOrSize(pb::io::CodedInputStream* stream,
FieldInfo* field) {
switch (field->wire_type) {
case 0: // varint
if (!stream->ReadVarint64(&field->value.as_uint64)) {
throw BadProto("failed to read varint field");
}
break;
case 1: // 64-bit
if (!stream->ReadLittleEndian64(&field->value.as_uint64)) {
throw BadProto("failed to read 64-bit field");
}
break;
case 2: // length-delimited
if (!stream->ReadVarintSizeAsInt(&field->value.as_size)) {
throw BadProto("failed to read size varint");
}
break;
// We don't support wire types 3 and 4 (groups)
case 5: // 32-bit
if (!stream->ReadLittleEndian32(&field->value.as_uint32)) {
throw BadProto("failed to read 32-bit field");
}
break;
default:
throw BadProto(std::string("unrecognized wire_type ") +
std::to_string(field->wire_type));
}
}
};
class Emitter;
class PrimitiveEmitter;
class EnumEmitter;
class MessageEmitter;
class Emitter : public ProtobufVisitor {
public:
static std::unique_ptr<Emitter> Create(const DescPtrs& desc_ptrs,
pb::util::TypeResolver* type_resolver,
std::optional<uint64_t> limit);
std::vector<std::string> rows;
protected:
Emitter(pb::FieldDescriptor::Type ty, std::optional<uint64_t> limit)
: ty_(ty) {}
const pb::FieldDescriptor::Type ty_;
const std::string type_url_;
const std::optional<uint64_t> limit_;
template <typename T>
void Emit(const T& value) {
EmitStr(std::move(std::to_string(value)));
}
void EmitStr(std::string&& str) {
PGPROTO_DEBUG("EmitStr(%s)", str.c_str());
rows.push_back(str);
if (limit_ && rows.size() >= *limit_) {
PGPROTO_DEBUG("Result limit reached");
throw LimitReached();
}
}
};
class PrimitiveEmitter : public Emitter {
public:
PrimitiveEmitter(pb::FieldDescriptor::Type ty, std::optional<uint64_t> limit)
: Emitter(ty, limit) {
PGPROTO_DEBUG("Created primitive emitter %d %lx", static_cast<int>(ty_),
intptr_t(this));
}
using T = pb::FieldDescriptor::Type;
using WFL = pb::internal::WireFormatLite;
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
return std::make_pair(CompositeFieldTreatmentForType(ty_), this);
}
void ReadPrimitive(const FieldInfo& field) override {
#ifndef PROTOBUF_LITTLE_ENDIAN
#error "big-endian not yet supported"
#endif
PGPROTO_DEBUG("Emit primitive %d (wt %d, ty %d)", field.number,
field.wire_type, ty_);
switch (ty_) {
case T::TYPE_DOUBLE:
EmitStr(std::move(postgres_utils::double_to_string(
WFL::DecodeDouble(field.value.as_uint64))));
break;
case T::TYPE_FLOAT:
EmitStr(std::move(postgres_utils::float_to_string(
WFL::DecodeFloat(field.value.as_uint32))));
break;
case T::TYPE_INT64:
case T::TYPE_SFIXED64:
Emit(static_cast<int64_t>(field.value.as_uint64));
break;
case T::TYPE_UINT64:
case T::TYPE_FIXED64:
Emit(field.value.as_uint64);
break;
case T::TYPE_INT32:
case T::TYPE_SFIXED32:
Emit(static_cast<int32_t>(field.value.as_uint32));
break;
case T::TYPE_FIXED32:
case T::TYPE_UINT32:
Emit(field.value.as_uint32);
break;
case T::TYPE_BOOL:
EmitStr(std::string(field.value.as_uint64 != 0 ? "true" : "false"));
break;
case T::TYPE_SINT32:
Emit(WFL::ZigZagDecode32(field.value.as_uint32));
break;
case T::TYPE_SINT64:
Emit(WFL::ZigZagDecode64(field.value.as_uint64));
break;
default:
throw BadProto(std::string("unrecognized primitive field type: ") +
std::to_string(ty_));
}
}
void ReadString(std::string&& s) override { EmitStr(std::move(s)); }
void ReadBytes(std::string&& s) override {
std::stringstream ss;
ss << "\\x";
ss << std::hex << std::setfill('0') << std::uppercase;
for (char c : s) {
ss << std::setw(2) << static_cast<unsigned int>(c);
}
EmitStr(ss.str());
}
};
class EnumEmitter : public Emitter {
public:
EnumEmitter(const pb::EnumDescriptor* ed, std::optional<uint64_t> limit)
: Emitter(pb::FieldDescriptor::Type::TYPE_ENUM, limit), ed_(ed) {
PGPROTO_DEBUG("Created enum emitter %s %lx", ed_->full_name().c_str(),
intptr_t(this));
}
void ReadPrimitive(const FieldInfo& field) override {
uint64_t n = field.value.as_uint64;
const pb::EnumValueDescriptor* vd = ed_->FindValueByNumber(n);
if (vd != nullptr) {
EmitStr(std::string(vd->name()));
} else {
return Emit(n);
}
}
private:
const pb::EnumDescriptor* ed_;
};
class MessageEmitter : public Emitter {
public:
MessageEmitter(pb::util::TypeResolver* type_resolver, std::string&& type_url,
std::optional<uint64_t> limit)
: Emitter(pb::FieldDescriptor::Type::TYPE_MESSAGE, limit),
type_resolver_(type_resolver),
type_url_(type_url) {
PGPROTO_DEBUG("Created message emitter %d %lx", static_cast<int>(ty_),
intptr_t(this));
}
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
return std::make_pair(LengthDelimitedFieldTreatment::Buffer, this);
}
void BufferedValue(std::string&& s) override {
std::string json;
if (type_url_.empty()) {
throw BadQuery("result type not known"); // Should not happen
}
PGPROTO_DEBUG("Converting %lu bytes to JSON: %s", s.size(),
type_url_.c_str());
if (!pb::util::BinaryToJsonString(type_resolver_, type_url_, s, &json)
.ok()) {
throw BadProto("failed to convert submessage to JSON");
}
EmitStr(std::move(json));
}
private:
pb::util::TypeResolver* const type_resolver_;
const std::string type_url_;
};
std::unique_ptr<Emitter> Emitter::Create(const DescPtrs& desc_ptrs,
pb::util::TypeResolver* type_resolver,
std::optional<uint64_t> limit) {
if (desc_ptrs.ty == pb::FieldDescriptor::Type::TYPE_MESSAGE) {
assert(desc_ptrs.desc != nullptr);
std::string type_url;
type_url += "type.googleapis.com/";
type_url += desc_ptrs.desc->full_name();
return std::unique_ptr<Emitter>(
new MessageEmitter(type_resolver, std::move(type_url), limit));
} else if (desc_ptrs.ty == pb::FieldDescriptor::Type::TYPE_ENUM) {
assert(desc_ptrs.enum_desc != nullptr);
return std::unique_ptr<Emitter>(
new EnumEmitter(desc_ptrs.enum_desc, limit));
} else {
return std::unique_ptr<Emitter>(new PrimitiveEmitter(desc_ptrs.ty, limit));
}
}
class DescendIntoSubmessage : public ProtobufVisitor {
public:
DescendIntoSubmessage() {
PGPROTO_DEBUG("Created descend-into-submessage %lx", intptr_t(this));
}
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
return std::make_pair(LengthDelimitedFieldTreatment::AsSubmessage, this);
}
ProtobufVisitor* BeginMessage() override { return next_; }
};
class FieldSelector : public ProtobufVisitor {
public:
FieldSelector(int wanted_field, pb::FieldDescriptor::Type ty, bool is_packed)
: traverser_(nullptr),
wanted_field_(wanted_field),
ty_(ty),
is_packed_(is_packed),
wanted_index_(),
state_(State::Scanning),
current_field_(0),
current_index_(0) {
PGPROTO_DEBUG("Created field selector %d %lx", wanted_field,
intptr_t(this));
}
void SetWantedIndex(int wanted_index) { wanted_index_ = wanted_index; }
void Pushed(ProtobufTraverser* traverser) override { traverser_ = traverser; }
ProtobufVisitor* BeginField(int number, int wire_type) override {
current_field_ = number;
if (wire_type == 2) {
if (is_packed_) {
state_ = State::EmittingPacked;
} else {
if (ShouldEmitCurrentIndex()) {
if (ty_ == pb::FieldDescriptor::Type::TYPE_MESSAGE) {
return next_;
} else {
state_ = State::EmittingOtherComposite;
}
}
}
} else if (ShouldEmitCurrentIndex()) {
return next_;
}
return this;
}
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
if (state_ == State::EmittingPacked) {
return std::make_pair(PackedCompositeFieldTreatmentForType(ty_), this);
} else if (ShouldEmitCurrentIndex()) {
if (state_ == State::EmittingOtherComposite) {
return std::make_pair(CompositeFieldTreatmentForType(ty_), next_);
} else {
return std::make_pair(CompositeFieldTreatmentForType(ty_), this);
}
} else {
return std::make_pair(LengthDelimitedFieldTreatment::Skip, this);
}
}
void EndField() override {
if (current_field_ == wanted_field_) {
++current_index_;
}
}
void Popped() override {
state_ = State::Scanning;
current_field_ = 0;
current_index_ = 0;
}
private:
ProtobufTraverser* traverser_;
const int wanted_field_;
const pb::FieldDescriptor::Type ty_;
const bool is_packed_;
std::optional<int> wanted_index_;
enum class State {
Scanning,
EmittingPacked,
EmittingOtherComposite,
};
State state_;
int current_field_;
int current_index_;
bool ShouldEmitCurrentIndex() const {
return current_field_ == wanted_field_ &&
(!wanted_index_.has_value() ||
current_index_ == wanted_index_.value());
}
};
class MapFilter : public ProtobufVisitor {
public:
MapFilter(const FieldInfo& wanted_key_field,
const std::string& wanted_key_contents,
pb::FieldDescriptor::Type value_type)
: wanted_key_field_(wanted_key_field),
wanted_key_contents_(wanted_key_contents),
value_type_(value_type),
scope_(Scope::Outermost) {
PGPROTO_DEBUG("Created map filter %d %s %lx", wanted_key_field.wire_type,
wanted_key_contents.c_str(), intptr_t(this));
}
ProtobufVisitor* BeginField(int number, int wire_type) override {
if (wire_type == 2 && scope_ == Scope::Outermost) {
PGPROTO_DEBUG("Map in entry");
scope_ = Scope::InEntry;
} else if (scope_ == Scope::InEntry) {
// There is (I think) no guarantee that keys come before values
if (number == 1) {
PGPROTO_DEBUG("Map in key");
scope_ = Scope::InKey;
} else if (number == 2) {
PGPROTO_DEBUG("Map in value");
scope_ = Scope::InValue;
}
}
return this;
}
// TODO: unnecessary?
ProtobufVisitor* BeginMessage() override {
if (scope_ == Scope::Outermost) {
scope_ = Scope::InEntry;
}
return this;
}
void ReadPrimitive(const FieldInfo& field) override {
switch (scope_) {
case Scope::InKey:
buffered_key_field_ = field;
break;
case Scope::InValue:
buffered_value_field_ = field;
break;
default:
break;
}
}
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
switch (scope_) {
case Scope::InEntry:
return std::make_pair(LengthDelimitedFieldTreatment::AsSubmessage,
this);
case Scope::InKey:
buffered_key_field_ = field;
return std::make_pair(LengthDelimitedFieldTreatment::Buffer, this);
case Scope::InValue:
buffered_value_field_ = field;
return std::make_pair(LengthDelimitedFieldTreatment::Buffer, this);
default:
return std::make_pair(LengthDelimitedFieldTreatment::Skip, this);
}
}
// TODO: instead of buffering the value, record its position in the stream and
// reread it
void BufferedValue(std::string&& value) override {
switch (scope_) {
case Scope::InKey:
PGPROTO_DEBUG("Map buffered key (%lu bytes)", value.size());
buffered_key_contents_ = value;
break;
case Scope::InValue:
PGPROTO_DEBUG("Map buffered value (%lu bytes)", value.size());
buffered_value_contents_ = value;
break;
default:
break;
}
}
void EndField() override {
PGPROTO_DEBUG("Map field end");
bool entry_ended = scope_ == Scope::InEntry;
switch (scope_) {
case Scope::InKey:
case Scope::InValue:
scope_ = Scope::InEntry;
break;
default:
scope_ = Scope::Outermost;
break;
}
if (entry_ended) {
if (buffered_key_field_.ValueEquals(wanted_key_field_) &&
buffered_key_contents_ == wanted_key_contents_) {
PGPROTO_DEBUG("Map entry matched.");
ForwardBufferedValue();
} else {
PGPROTO_DEBUG("Map entry did not match. Key: %s, wanted %s %s",
buffered_key_field_.ToString().c_str(),
wanted_key_field_.ToString().c_str(),
buffered_key_contents_ == wanted_key_contents_
? "(contents matched)"
: "(contents did not match)");
}
Reset();
}
}
void Popped() override { Reset(); }
private:
const FieldInfo wanted_key_field_;
const std::string wanted_key_contents_;
pb::FieldDescriptor::Type value_type_;
enum class Scope {
Outermost,
InEntry,
InKey,
InValue,
};
Scope scope_;
FieldInfo buffered_key_field_;
std::string buffered_key_contents_;
FieldInfo buffered_value_field_;
std::string buffered_value_contents_;
void ForwardBufferedValue() {
pb::io::CodedInputStream substream(
reinterpret_cast<uint8*>(buffered_value_contents_.data()),
buffered_value_contents_.size());
ProtobufTraverser subtraverser;
subtraverser.PushVisitor(next_);
subtraverser.ScanField(buffered_value_field_, &substream);
subtraverser.PopVisitor();
}
void Reset() {
scope_ = Scope::Outermost;
std::memset(&buffered_key_field_, 0, sizeof(buffered_key_field_));
std::memset(&buffered_value_field_, 0, sizeof(buffered_value_field_));
buffered_key_contents_.clear();
buffered_value_contents_.clear();
}
};
class AllMapEntries : public ProtobufVisitor {
public:
AllMapEntries(bool want_keys, pb::FieldDescriptor::Type ty)
: want_keys_(want_keys), ty_(ty), scope_(Scope::Outermost) {
PGPROTO_DEBUG("Created all-map-entries %s %lx",
want_keys ? "(keys)" : "(values)", intptr_t(this));
}
ProtobufVisitor* BeginField(int number, int wire_type) override {
switch (scope_) {
case Scope::Outermost:
scope_ = Scope::InEntry;
return this;
case Scope::InEntry:
if (((number == 1 && want_keys_) || (number == 2 && !want_keys_))) {
scope_ = Scope::InWantedField;
return next_;
} else {
scope_ = Scope::InUnwantedOtherField;
return this;
}
default:
PGPROTO_DEBUG("AllMapEntries: unexpected BeginField (num=%d, wt=%d)",
number, wire_type);
return this;
}
}
std::pair<LengthDelimitedFieldTreatment, ProtobufVisitor*>
ReadLengthDelimitedField(const FieldInfo& field) override {
switch (scope_) {
case Scope::InEntry:
return std::make_pair(LengthDelimitedFieldTreatment::AsSubmessage,
this);
case Scope::InWantedField:
return std::make_pair(CompositeFieldTreatmentForType(ty_), next_);
default:
return std::make_pair(LengthDelimitedFieldTreatment::Skip, this);
}
}
void EndField() override {
switch (scope_) {
case Scope::InWantedField:
case Scope::InUnwantedOtherField:
scope_ = Scope::InEntry;
break;
default:
scope_ = Scope::Outermost;
break;
}
}
private:
const bool want_keys_;
const pb::FieldDescriptor::Type ty_;
enum class Scope {
Outermost,
InEntry,
InWantedField,
InUnwantedOtherField,
};
Scope scope_;
};
} // namespace
class QueryImpl {
public:
QueryImpl(const descriptor_db::DescDb& desc_db, const std::string& query,
std::optional<uint64_t> limit);
QueryImpl(const QueryImpl&) = delete;
void operator=(const QueryImpl&) = delete;
std::vector<std::string> Run(const std::uint8_t* proto_data,
size_t proto_len);
private:
std::vector<std::unique_ptr<ProtobufVisitor>> visitors_;
Emitter* emitter_;
pb::util::TypeResolver* type_resolver_;
void CompileQuery(const descriptor_db::DescDb& desc_db,
const std::string& query, std::optional<uint64_t> limit);
static const descriptor_db::DescSet& GetDescSet(
const descriptor_db::DescDb& desc_db, const std::string& query,
std::string::size_type* query_start);
static const pb::Descriptor* GetDesc(const descriptor_db::DescSet& desc_set,
const std::string& query,
std::string::size_type* query_start);
void CompileQueryPart(const std::string& part, DescPtrs* desc_ptrs);
static void ParseNumericMapKey(const std::string& s,
pb::FieldDescriptor::Type ty,
FieldInfo::Value* v);
};
Query::Query(const std::string& query, std::optional<uint64_t> limit) {
std::shared_ptr<descriptor_db::DescDb> desc_db =
descriptor_db::DescDb::GetOrCreateCached();
impl_ = new QueryImpl(*desc_db, query, limit);
}
Query::~Query() { delete impl_; }
std::vector<std::string> Query::Run(const std::uint8_t* proto_data,
size_t proto_len) {
return impl_->Run(proto_data, proto_len);
}
QueryImpl::QueryImpl(const descriptor_db::DescDb& desc_db,
const std::string& query, std::optional<uint64_t> limit) {
CompileQuery(desc_db, query, limit);
assert(!visitors_.empty()); // There should be at least an Emitter
}
std::vector<std::string> QueryImpl::Run(const std::uint8_t* proto_data,
size_t proto_len) {
pb::io::CodedInputStream stream(proto_data, proto_len);
ProtobufTraverser traverser;
try {
traverser.PushVisitor(visitors_[0].get());
FieldInfo fake_root_field;
fake_root_field.number = 0;
fake_root_field.wire_type = 2;
fake_root_field.value.as_size = proto_len;
traverser.ScanField(fake_root_field, &stream);
traverser.PopVisitor();
} catch (const LimitReached&) {
// early exit
}
std::vector<std::string> result = std::move(emitter_->rows);
emitter_->rows = std::vector<std::string>();
return result;
}
void QueryImpl::CompileQuery(const descriptor_db::DescDb& desc_db,
const std::string& query,
std::optional<uint64_t> limit) {
visitors_.clear();
emitter_ = nullptr;