forked from fastio/1store
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.cc
3209 lines (2967 loc) · 108 KB
/
types.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 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 <boost/lexical_cast.hpp>
#include <algorithm>
#include "types.hh"
#include "core/print.hh"
#include "net/ip.hh"
#include "utils/serialization.hh"
#include <cmath>
#include <chrono>
#include <sstream>
#include <string>
#include <regex>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/numeric.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/locale/encoding_utf.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include "utils/big_decimal.hh"
#include "utils/date.h"
/*
template<typename T>
sstring time_point_to_string(const T& tp)
{
auto timestamp = tp.time_since_epoch().count();
auto time = boost::posix_time::from_time_t(0) + boost::posix_time::milliseconds(timestamp);
return boost::posix_time::to_iso_extended_string(time);
}
static const char* byte_type_name = "org.apache.cassandra.db.marshal.ByteType";
static const char* short_type_name = "org.apache.cassandra.db.marshal.ShortType";
static const char* int32_type_name = "org.apache.cassandra.db.marshal.Int32Type";
static const char* long_type_name = "org.apache.cassandra.db.marshal.LongType";
static const char* ascii_type_name = "org.apache.cassandra.db.marshal.AsciiType";
static const char* utf8_type_name = "org.apache.cassandra.db.marshal.UTF8Type";
static const char* bytes_type_name = "org.apache.cassandra.db.marshal.BytesType";
static const char* boolean_type_name = "org.apache.cassandra.db.marshal.BooleanType";
static const char* timeuuid_type_name = "org.apache.cassandra.db.marshal.TimeUUIDType";
static const char* timestamp_type_name = "org.apache.cassandra.db.marshal.TimestampType";
static const char* date_type_name = "org.apache.cassandra.db.marshal.DateType";
static const char* simple_date_type_name = "org.apache.cassandra.db.marshal.SimpleDateType";
static const char* time_type_name = "org.apache.cassandra.db.marshal.TimeType";
static const char* uuid_type_name = "org.apache.cassandra.db.marshal.UUIDType";
static const char* inet_addr_type_name = "org.apache.cassandra.db.marshal.InetAddressType";
static const char* double_type_name = "org.apache.cassandra.db.marshal.DoubleType";
static const char* float_type_name = "org.apache.cassandra.db.marshal.FloatType";
static const char* varint_type_name = "org.apache.cassandra.db.marshal.IntegerType";
static const char* decimal_type_name = "org.apache.cassandra.db.marshal.DecimalType";
static const char* counter_type_name = "org.apache.cassandra.db.marshal.CounterColumnType";
static const char* empty_type_name = "org.apache.cassandra.db.marshal.EmptyType";
template<typename T>
struct simple_type_traits {
static T read_nonempty(bytes_view v) {
return read_simple_exactly<T>(v);
}
};
template<>
struct simple_type_traits<bool> {
static bool read_nonempty(bytes_view v) {
return read_simple_exactly<int8_t>(v) != 0;
}
};
template<>
struct simple_type_traits<db_clock::time_point> {
static db_clock::time_point read_nonempty(bytes_view v) {
return db_clock::time_point(db_clock::duration(read_simple_exactly<int64_t>(v)));
}
};
template <typename T>
struct simple_type_impl : concrete_type<T> {
simple_type_impl(sstring name) : concrete_type<T>(std::move(name)) {}
virtual int32_t compare(bytes_view v1, bytes_view v2) const override {
if (v1.empty()) {
return v2.empty() ? 0 : -1;
}
if (v2.empty()) {
return 1;
}
T a = simple_type_traits<T>::read_nonempty(v1);
T b = simple_type_traits<T>::read_nonempty(v2);
return a == b ? 0 : a < b ? -1 : 1;
}
virtual bool less(bytes_view v1, bytes_view v2) const override {
return compare(v1, v2) < 0;
}
virtual bool is_byte_order_equal() const override {
return true;
}
virtual size_t hash(bytes_view v) const override {
return std::hash<bytes_view>()(v);
}
virtual bool references_user_type(const sstring& keyspace, const bytes& name) const {
return false;
}
virtual std::experimental::optional<data_type> update_user_type(const shared_ptr<const user_type_impl> updated) const {
return std::experimental::nullopt;
}
};
template<typename T>
struct integer_type_impl : simple_type_impl<T> {
integer_type_impl(sstring name) : simple_type_impl<T>(name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto v1 = this->from_value(value);
if (v1.empty()) {
return;
}
auto v = v1.get();
auto u = net::hton(v);
out = std::copy_n(reinterpret_cast<const char*>(&u), sizeof(u), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value) {
return 0;
}
auto v = this->from_value(value);
if (v.empty()) {
return 0;
}
return sizeof(v.get());
}
virtual data_value deserialize(bytes_view v) const override {
auto x = read_simple_opt<T>(v);
if (!x) {
return this->make_empty();
} else {
return this->make_value(*x);
}
}
T compose_value(const bytes& b) const {
if (b.size() != sizeof(T)) {
throw marshal_exception();
}
return (T)net::ntoh(*reinterpret_cast<const T*>(b.begin()));
}
bytes decompose_value(T v) const {
bytes b(bytes::initialized_later(), sizeof(v));
*reinterpret_cast<T*>(b.begin()) = (T)net::hton(v);
return b;
}
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != sizeof(T)) {
throw marshal_exception();
}
}
T parse_int(sstring_view s) const {
try {
auto value64 = boost::lexical_cast<int64_t>(s.begin(), s.size());
auto value = static_cast<T>(value64);
if (value != value64) {
throw marshal_exception(sprint("Value out of range for type %s: '%s'", this->name(), s));
}
return static_cast<T>(value);
} catch (const boost::bad_lexical_cast& e) {
throw marshal_exception(sprint("Invalid number format '%s'", s));
}
}
virtual bytes from_string(sstring_view s) const override {
return decompose_value(parse_int(s));
}
virtual sstring to_string(const bytes& b) const override {
if (b.empty()) {
return {};
}
return to_sstring(compose_value(b));
}
};
struct byte_type_impl : integer_type_impl<int8_t> {
byte_type_impl() : integer_type_impl{byte_type_name}
{ }
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 1) {
throw marshal_exception(sprint("Expected 1 byte for a tinyint (%d)", v.size()));
}
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::tinyint;
}
};
struct short_type_impl : integer_type_impl<int16_t> {
short_type_impl() : integer_type_impl{short_type_name}
{ }
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 2) {
throw marshal_exception(sprint("Expected 2 bytes for a smallint (%d)", v.size()));
}
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::smallint;
}
};
struct int32_type_impl : integer_type_impl<int32_t> {
int32_type_impl() : integer_type_impl{int32_type_name}
{ }
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::int_;
}
};
struct long_type_impl : integer_type_impl<int64_t> {
long_type_impl() : integer_type_impl{long_type_name}
{ }
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::bigint;
}
virtual bool is_value_compatible_with_internal(const abstract_type& other) const override {
return &other == this || &other == date_type.get() || &other == timestamp_type.get();
}
};
struct string_type_impl : public concrete_type<sstring> {
string_type_impl(sstring name)
: concrete_type(name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto& v = from_value(value);
out = std::copy(v.begin(), v.end(), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value) {
return 0;
}
auto& v = from_value(value);
return v.size();
}
virtual data_value deserialize(bytes_view v) const override {
// FIXME: validation?
return make_value(std::make_unique<native_type>(reinterpret_cast<const char*>(v.begin()), v.size()));
}
virtual bool less(bytes_view v1, bytes_view v2) const override {
return less_unsigned(v1, v2);
}
virtual bool is_byte_order_equal() const override {
return true;
}
virtual bool is_byte_order_comparable() const override {
return true;
}
virtual size_t hash(bytes_view v) const override {
return std::hash<bytes_view>()(v);
}
virtual void validate(bytes_view v) const override {
if (as_cql3_type() == cql3::cql3_type::ascii) {
if (std::any_of(v.begin(), v.end(), [] (int8_t b) { return b < 0; })) {
throw marshal_exception();
}
} else {
try {
boost::locale::conv::utf_to_utf<char>(v.begin(), v.end(), boost::locale::conv::stop);
} catch (const boost::locale::conv::conversion_error& ex) {
throw marshal_exception(ex.what());
}
}
}
virtual bytes from_string(sstring_view s) const override {
return to_bytes(bytes_view(reinterpret_cast<const int8_t*>(s.begin()), s.size()));
}
virtual sstring to_string(const bytes& b) const override {
return sstring(reinterpret_cast<const char*>(b.begin()), b.size());
}
};
struct ascii_type_impl final : public string_type_impl {
ascii_type_impl() : string_type_impl(ascii_type_name) {}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::ascii;
}
};
struct utf8_type_impl final : public string_type_impl {
static const char* name;
utf8_type_impl() : string_type_impl(utf8_type_name) {}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::text;
}
virtual bool is_compatible_with(const abstract_type& other) const override {
// Anything that is ascii is also utf8, and they both use bytes
// comparison
return this == &other || &other == ascii_type.get();
}
using concrete_type::from_value;
};
struct bytes_type_impl final : public concrete_type<bytes> {
bytes_type_impl() : concrete_type(bytes_type_name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto& v = from_value(value);
out = std::copy(v.begin(), v.end(), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value) {
return 0;
}
auto& v = from_value(value);
return v.size();
}
virtual data_value deserialize(bytes_view v) const override {
return make_value(std::make_unique<native_type>(v.begin(), v.end()));
}
virtual bool less(bytes_view v1, bytes_view v2) const override {
return less_unsigned(v1, v2);
}
virtual bool is_byte_order_equal() const override {
return true;
}
virtual bool is_byte_order_comparable() const override {
return true;
}
virtual size_t hash(bytes_view v) const override {
return std::hash<bytes_view>()(v);
}
virtual bytes from_string(sstring_view s) const override {
return from_hex(s);
}
virtual sstring to_string(const bytes& b) const override {
return to_hex(b);
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::blob;
}
virtual bool is_value_compatible_with_internal(const abstract_type& other) const override {
return true;
}
virtual bool is_compatible_with(const abstract_type& other) const override {
// Both asciiType and utf8Type really use bytes comparison and
// bytesType validate everything, so it is compatible with the former.
return this == &other || &other == ascii_type.get() || &other == utf8_type.get();
}
};
struct boolean_type_impl : public simple_type_impl<bool> {
boolean_type_impl() : simple_type_impl<bool>(boolean_type_name) {}
void serialize_value(maybe_empty<bool> value, bytes::iterator& out) const {
if (!value.empty()) {
*out++ = char(value);
}
}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
serialize_value(from_value(value), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value) {
return 0;
}
if (from_value(value).empty()) {
return 0;
}
return 1;
}
size_t serialized_size(bool value) const {
return 1;
}
virtual data_value deserialize(bytes_view v) const override {
if (v.empty()) {
return make_empty();
}
if (v.size() != 1) {
throw marshal_exception();
}
return make_value(*v.begin() != 0);
}
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 1) {
throw marshal_exception();
}
}
virtual bytes from_string(sstring_view s) const override {
sstring s_lower(s.begin(), s.end());
std::transform(s_lower.begin(), s_lower.end(), s_lower.begin(), ::tolower);
if (s.empty() || s_lower == "false") {
return ::serialize_value(*this, false);
} else if (s_lower == "true") {
return ::serialize_value(*this, true);
} else {
throw marshal_exception(sprint("unable to make boolean from '%s'", s));
}
}
virtual sstring to_string(const bytes& b) const override {
if (b.empty()) {
return "";
}
if (b.size() != 1) {
throw marshal_exception();
}
return *b.begin() ? "true" : "false";
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::boolean;
}
};
class date_type_impl : public concrete_type<db_clock::time_point> {
static logging::logger _logger;
public:
date_type_impl() : concrete_type(date_type_name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto& v = from_value(value);
if (v.empty()) {
return;
}
int64_t i = v.get().time_since_epoch().count();
i = net::hton(uint64_t(i));
out = std::copy_n(reinterpret_cast<const char*>(&i), sizeof(i), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value || from_value(value).empty()) {
return 0;
}
return 8;
}
virtual data_value deserialize(bytes_view v) const override {
if (v.empty()) {
return make_empty();
}
auto tmp = read_simple_exactly<uint64_t>(v);
return make_value(db_clock::time_point(db_clock::duration(tmp)));
}
virtual bool less(bytes_view b1, bytes_view b2) const override {
return compare_unsigned(b1, b2);
}
virtual bool is_byte_order_comparable() const override {
return true;
}
virtual size_t hash(bytes_view v) const override {
return std::hash<bytes_view>()(v);
}
virtual bytes from_string(sstring_view s) const override;
virtual sstring to_string(const bytes& b) const override {
auto v = deserialize(b);
if (v.is_null()) {
return "";
}
return time_point_to_string(from_value(v).get());
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::timestamp;
}
virtual bool is_value_compatible_with_internal(const abstract_type& other) const override {
return &other == this || &other == timestamp_type.get() || &other == long_type.get();
}
virtual bool is_compatible_with(const abstract_type& other) const override {
if (&other == this) {
return true;
}
if (&other == timestamp_type.get()) {
_logger.warn("Changing from TimestampType to DateType is allowed, but be wary that they sort differently for pre-unix-epoch timestamps "
"(negative timestamp values) and thus this change will corrupt your data if you have such negative timestamp. There is no "
"reason to switch from DateType to TimestampType except if you were using DateType in the first place and switched to "
"TimestampType by mistake.");
return true;
}
return false;
}
};
logging::logger date_type_impl::_logger(date_type_name);
struct timeuuid_type_impl : public concrete_type<utils::UUID> {
timeuuid_type_impl() : concrete_type<utils::UUID>(timeuuid_type_name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto& uuid1 = from_value(value);
if (uuid1.empty()) {
return;
}
auto uuid = uuid1.get();
out = std::copy_n(uuid.to_bytes().begin(), sizeof(uuid), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value || from_value(value).empty()) {
return 0;
}
return 16;
}
virtual data_value deserialize(bytes_view v) const override {
if (v.empty()) {
return make_empty();
}
uint64_t msb, lsb;
msb = read_simple<uint64_t>(v);
lsb = read_simple<uint64_t>(v);
if (!v.empty()) {
throw marshal_exception();
}
return make_value(utils::UUID(msb, lsb));
}
virtual bool less(bytes_view b1, bytes_view b2) const override {
if (b1.empty()) {
return b2.empty() ? false : true;
}
if (b2.empty()) {
return false;
}
auto r = compare_bytes(b1, b2);
if (r != 0) {
return r < 0;
} else {
return std::lexicographical_compare(b1.begin(), b1.end(), b2.begin(), b2.end());
}
}
virtual bool is_byte_order_equal() const override {
return true;
}
virtual size_t hash(bytes_view v) const override {
return std::hash<bytes_view>()(v);
}
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 16) {
throw marshal_exception();
}
auto msb = read_simple<uint64_t>(v);
auto lsb = read_simple<uint64_t>(v);
utils::UUID uuid(msb, lsb);
if (uuid.version() != 1) {
throw marshal_exception();
}
}
virtual bytes from_string(sstring_view s) const override {
if (s.empty()) {
return bytes();
}
static const std::regex re("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$");
if (!std::regex_match(s.begin(), s.end(), re)) {
throw marshal_exception();
}
utils::UUID v(s);
if (v.version() != 1) {
throw marshal_exception();
}
return v.to_bytes();
}
virtual sstring to_string(const bytes& b) const override {
auto v = deserialize(b);
if (v.is_null()) {
return "";
}
return from_value(v).get().to_sstring();
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::timeuuid;
}
private:
static int compare_bytes(bytes_view o1, bytes_view o2) {
auto compare_pos = [&] (unsigned pos, int mask, int ifequal) {
int d = (o1[pos] & mask) - (o2[pos] & mask);
return d ? d : ifequal;
};
return compare_pos(6, 0xf,
compare_pos(7, 0xff,
compare_pos(4, 0xff,
compare_pos(5, 0xff,
compare_pos(0, 0xff,
compare_pos(1, 0xff,
compare_pos(2, 0xff,
compare_pos(3, 0xff, 0))))))));
}
friend class uuid_type_impl;
};
class timestamp_type_impl : public simple_type_impl<db_clock::time_point> {
static logging::logger _logger;
public:
timestamp_type_impl() : simple_type_impl(timestamp_type_name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto&& v1 = from_value(value);
if (v1.empty()) {
return;
}
uint64_t v = v1.get().time_since_epoch().count();
v = net::hton(v);
out = std::copy_n(reinterpret_cast<const char*>(&v), sizeof(v), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value || from_value(value).empty()) {
return 0;
}
return 8;
}
virtual data_value deserialize(bytes_view in) const override {
if (in.empty()) {
return make_empty();
}
auto v = read_simple_exactly<uint64_t>(in);
return make_value(db_clock::time_point(db_clock::duration(v)));
}
// FIXME: isCompatibleWith(timestampuuid)
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != sizeof(uint64_t)) {
throw marshal_exception();
}
}
static boost::posix_time::ptime get_time(const std::smatch& sm) {
// Unfortunately boost::date_time parsers are more strict with regards
// to the expected date format than we need to be.
auto year = boost::lexical_cast<int>(sm[1]);
auto month = boost::lexical_cast<int>(sm[2]);
auto day = boost::lexical_cast<int>(sm[3]);
boost::gregorian::date date(year, month, day);
auto hour = sm[5].length() ? boost::lexical_cast<int>(sm[5]) : 0;
auto minute = sm[6].length() ? boost::lexical_cast<int>(sm[6]) : 0;
auto second = sm[8].length() ? boost::lexical_cast<int>(sm[8]) : 0;
boost::posix_time::time_duration time(hour, minute, second);
if (sm[10].length()) {
static constexpr auto milliseconds_string_length = 3;
auto length = sm[10].length();
if (length > milliseconds_string_length) {
throw marshal_exception();
}
auto value = boost::lexical_cast<int>(sm[10]);
while (length < milliseconds_string_length) {
value *= 10;
length++;
}
time += boost::posix_time::milliseconds(value);
}
return boost::posix_time::ptime(date, time);
}
static boost::posix_time::time_duration get_utc_offset(const std::string& s) {
static constexpr const char* formats[] = {
"%H:%M",
"%H%M",
};
for (auto&& f : formats) {
auto tif = new boost::posix_time::time_input_facet(f);
std::istringstream ss(s);
ss.imbue(std::locale(ss.getloc(), tif));
auto sign = ss.get();
boost::posix_time::ptime p;
ss >> p;
if (ss.good() && ss.peek() == std::istringstream::traits_type::eof()) {
return p.time_of_day() * (sign == '-' ? -1 : 1);
}
}
throw marshal_exception();
}
static int64_t timestamp_from_string(sstring_view s) {
try {
std::string str;
str.resize(s.size());
std::transform(s.begin(), s.end(), str.begin(), ::tolower);
if (str == "now") {
return db_clock::now().time_since_epoch().count();
}
char* end;
auto v = std::strtoll(s.begin(), &end, 10);
if (end == s.begin() + s.size()) {
return v;
}
std::regex date_re("^(\\d{4})-(\\d+)-(\\d+)([ t](\\d+):(\\d+)(:(\\d+)(\\.(\\d+))?)?)?");
std::smatch dsm;
if (!std::regex_search(str, dsm, date_re)) {
throw marshal_exception();
}
auto t = get_time(dsm);
auto tz = dsm.suffix().str();
std::regex tz_re("([\\+-]\\d{2}:?(\\d{2})?)");
std::smatch tsm;
if (std::regex_match(tz, tsm, tz_re)) {
t -= get_utc_offset(tsm.str());
} else if (tz.empty()) {
typedef boost::date_time::c_local_adjustor<boost::posix_time::ptime> local_tz;
// local_tz::local_to_utc(), where are you?
auto t1 = local_tz::utc_to_local(t);
auto tz_offset = t1 - t;
auto t2 = local_tz::utc_to_local(t - tz_offset);
auto dst_offset = t2 - t;
t -= tz_offset + dst_offset;
} else {
throw marshal_exception();
}
return (t - boost::posix_time::from_time_t(0)).total_milliseconds();
} catch (...) {
throw marshal_exception(sprint("unable to parse date '%s'", s));
}
}
virtual bytes from_string(sstring_view s) const override {
if (s.empty()) {
return bytes();
}
int64_t ts = net::hton(timestamp_from_string(s));
bytes b(bytes::initialized_later(), sizeof(int64_t));
std::copy_n(reinterpret_cast<const int8_t*>(&ts), sizeof(ts), b.begin());
return b;
}
virtual sstring to_string(const bytes& b) const override {
auto v = deserialize(b);
if (v.is_null()) {
return "";
}
return time_point_to_string(from_value(v).get());
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::timestamp;
}
virtual bool is_value_compatible_with_internal(const abstract_type& other) const override {
return &other == this || &other == date_type.get() || &other == long_type.get();
}
virtual bool is_compatible_with(const abstract_type& other) const override {
if (&other == this) {
return true;
}
if (&other == date_type.get()) {
_logger.warn("Changing from DateType to TimestampType is allowed, but be wary that they sort differently for pre-unix-epoch timestamps "
"(negative timestamp values) and thus this change will corrupt your data if you have such negative timestamp. So unless you "
"know that you don't have *any* pre-unix-epoch timestamp you should change back to DateType");
return true;
}
return false;
}
};
logging::logger timestamp_type_impl::_logger(timestamp_type_name);
struct simple_date_type_impl : public simple_type_impl<uint32_t> {
simple_date_type_impl() : simple_type_impl{simple_date_type_name}
{ }
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto&& v1 = from_value(value);
if (v1.empty()) {
return;
}
uint32_t v = v1.get();
v = net::hton(v);
out = std::copy_n(reinterpret_cast<const char*>(&v), sizeof(v), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value || from_value(value).empty()) {
return 0;
}
return 4;
}
virtual data_value deserialize(bytes_view in) const override {
if (in.empty()) {
return make_empty();
}
auto v = read_simple_exactly<uint32_t>(in);
return make_value(v);
}
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 4) {
throw marshal_exception(sprint("Expected 4 byte long for date (%d)", v.size()));
}
}
virtual bytes from_string(sstring_view s) const override {
if (s.empty()) {
return bytes();
}
uint32_t ts = net::hton(days_from_string(s));
bytes b(bytes::initialized_later(), sizeof(int32_t));
std::copy_n(reinterpret_cast<const int8_t*>(&ts), sizeof(ts), b.begin());
return b;
}
static uint32_t days_from_string(sstring_view s) {
std::string str;
str.resize(s.size());
std::transform(s.begin(), s.end(), str.begin(), ::tolower);
char* end;
auto v = std::strtoll(s.begin(), &end, 10);
if (end == s.begin() + s.size()) {
return v;
}
static std::regex date_re("^(-?\\d+)-(\\d+)-(\\d+)");
std::smatch dsm;
if (!std::regex_match(str, dsm, date_re)) {
throw marshal_exception(sprint("Unable to coerce '%s' to a formatted date (long)", str));
}
auto t = get_time(dsm);
return serialize(str, date::local_days(t).time_since_epoch().count());
}
static date::year_month_day get_time(const std::smatch& sm) {
auto year = boost::lexical_cast<long>(sm[1]);
auto month = boost::lexical_cast<unsigned>(sm[2]);
auto day = boost::lexical_cast<unsigned>(sm[3]);
return date::year_month_day{date::year{year}, date::month{month}, date::day{day}};
}
static uint32_t serialize(const std::string& input, int64_t days) {
if (days < std::numeric_limits<int32_t>::min()) {
throw marshal_exception(sprint("Input date %s is less than min supported date -5877641-06-23", input));
}
if (days > std::numeric_limits<int32_t>::max()) {
throw marshal_exception(sprint("Input date %s is greater than max supported date 5881580-07-11", input));
}
days += 1UL << 31;
return static_cast<uint32_t>(days);
}
virtual sstring to_string(const bytes& b) const override {
auto v = deserialize(b);
if (v.is_null()) {
return "";
}
date::days days{from_value(v).get() - (1UL << 31)};
date::year_month_day ymd{date::local_days{days}};
std::ostringstream str;
str << ymd;
return str.str();
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::date;
}
};
struct time_type_impl : public simple_type_impl<int64_t> {
time_type_impl() : simple_type_impl{time_type_name}
{ }
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto&& v1 = from_value(value);
if (v1.empty()) {
return;
}
uint64_t v = v1.get();
v = net::hton(v);
out = std::copy_n(reinterpret_cast<const char*>(&v), sizeof(v), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value || from_value(value).empty()) {
return 0;
}
return 8;
}
virtual data_value deserialize(bytes_view in) const override {
if (in.empty()) {
return make_empty();
}
auto v = read_simple_exactly<int64_t>(in);
return make_value(v);
}
virtual void validate(bytes_view v) const override {
if (v.size() != 0 && v.size() != 8) {
throw marshal_exception(sprint("Expected 8 byte long for time (%d)", v.size()));
}
}
virtual bytes from_string(sstring_view s) const override {
if (s.empty()) {
return bytes();
}
int64_t ts = net::hton(parse_time(s));
bytes b(bytes::initialized_later(), sizeof(int64_t));
std::copy_n(reinterpret_cast<const int8_t*>(&ts), sizeof(ts), b.begin());
return b;
}
static int64_t parse_time(sstring_view s) {
static auto format_error = "Timestamp format must be hh:mm:ss[.fffffffff]";
auto hours_end = s.find(':');
if (hours_end == std::string::npos) {
throw marshal_exception(format_error);
}
int64_t hours = std::stol(s.substr(0, hours_end).to_string());
if (hours < 0 || hours >= 24) {
throw marshal_exception("Hour out of bounds.");
}
auto minutes_end = s.find(':', hours_end+1);
if (minutes_end == std::string::npos) {
throw marshal_exception(format_error);
}
int64_t minutes = std::stol(s.substr(hours_end + 1, hours_end-minutes_end).to_string());
if (minutes < 0 || minutes >= 60) {
throw marshal_exception("Minute out of bounds.");
}
auto seconds_end = s.find('.', minutes_end+1);
if (seconds_end == std::string::npos) {
seconds_end = s.length();
}
int64_t seconds = std::stol(s.substr(minutes_end + 1, minutes_end-seconds_end).to_string());
if (seconds < 0 || seconds >= 60) {
throw marshal_exception("Second out of bounds.");
}
int64_t nanoseconds = 0;
if (seconds_end < s.length()) {
nanoseconds = std::stol(s.substr(seconds_end + 1).to_string());
nanoseconds *= std::pow(10, 9-(s.length() - (seconds_end + 1)));
if (nanoseconds < 0 || nanoseconds >= 1000 * 1000 * 1000) {
throw marshal_exception("Nanosecond out of bounds.");
}
}
std::chrono::nanoseconds result{};
result += std::chrono::hours(hours);
result += std::chrono::minutes(minutes);
result += std::chrono::seconds(seconds);
result += std::chrono::nanoseconds(nanoseconds);
return result.count();
}
virtual sstring to_string(const bytes& b) const override {
auto v = deserialize(b);
if (v.is_null()) {
return "";
}
std::chrono::nanoseconds nanoseconds{from_value(v).get()};
auto time = date::make_time(nanoseconds);
std::ostringstream str;
str << time;
return str.str();
}
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() const override {
return cql3::cql3_type::time;
}
};
struct uuid_type_impl : concrete_type<utils::UUID> {
uuid_type_impl() : concrete_type(uuid_type_name) {}
virtual void serialize(const void* value, bytes::iterator& out) const override {
if (!value) {
return;
}
auto& uuid = from_value(value);
out = std::copy_n(uuid.get().to_bytes().begin(), sizeof(uuid.get()), out);
}
virtual size_t serialized_size(const void* value) const override {
if (!value) {
return 0;
}
return 16;
}
virtual data_value deserialize(bytes_view v) const override {
if (v.empty()) {
return make_empty();
}
auto msb = read_simple<uint64_t>(v);
auto lsb = read_simple<uint64_t>(v);
if (!v.empty()) {
throw marshal_exception();
}
return make_value(utils::UUID(msb, lsb));
}
virtual bool less(bytes_view b1, bytes_view b2) const override {
if (b1.size() < 16) {
return b2.size() < 16 ? false : true;
}
if (b2.size() < 16) {
return false;
}
auto v1 = (b1[6] >> 4) & 0x0f;
auto v2 = (b2[6] >> 4) & 0x0f;
if (v1 != v2) {
return v1 < v2;
}