-
Notifications
You must be signed in to change notification settings - Fork 18
/
funnel.patch
2047 lines (1975 loc) · 73.2 KB
/
funnel.patch
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
diff --git a/dbms/CMakeLists.txt b/dbms/CMakeLists.txt
index 0cb5824e1..9f2e2b5be 100644
--- a/dbms/CMakeLists.txt
+++ b/dbms/CMakeLists.txt
@@ -84,6 +84,7 @@ add_headers_and_sources(dbms src/Storages/Kafka)
add_headers_and_sources(dbms src/Storages/MergeTree)
add_headers_and_sources(dbms src/Client)
add_headers_and_sources(dbms src/Formats)
+add_headers_and_sources(dbms src/Compression)
list (APPEND clickhouse_common_io_sources ${CONFIG_BUILD})
list (APPEND clickhouse_common_io_headers ${CONFIG_VERSION} ${CONFIG_COMMON})
diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp
index bf57d072f..73ea56405 100644
--- a/dbms/programs/client/Client.cpp
+++ b/dbms/programs/client/Client.cpp
@@ -844,7 +844,7 @@ private:
}
else if (print_time_to_stderr)
{
- std::cerr << watch.elapsedSeconds() << "\n";
+ std::cerr << "[Log] Cost seconds -> " << watch.elapsedSeconds() << "\n";
}
return true;
diff --git a/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp b/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp
index 4b8222963..4031854f2 100644
--- a/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp
+++ b/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp
@@ -10,6 +10,7 @@ namespace DB
namespace
{
+template <bool repeated = false>
AggregateFunctionPtr createAggregateFunctionWindowFunnel(const std::string & name, const DataTypes & arguments, const Array & params)
{
if (params.size() != 1)
@@ -21,14 +22,15 @@ AggregateFunctionPtr createAggregateFunctionWindowFunnel(const std::string & nam
if (arguments.size() > AggregateFunctionWindowFunnelData::max_events + 1)
throw Exception("Too many event arguments for aggregate function " + name, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
- return std::make_shared<AggregateFunctionWindowFunnel>(arguments, params);
+ return std::make_shared<AggregateFunctionWindowFunnel<repeated>>(arguments, params);
}
}
void registerAggregateFunctionWindowFunnel(AggregateFunctionFactory & factory)
{
- factory.registerFunction("windowFunnel", createAggregateFunctionWindowFunnel, AggregateFunctionFactory::CaseInsensitive);
+ factory.registerFunction("windowFunnel", createAggregateFunctionWindowFunnel<false>, AggregateFunctionFactory::CaseInsensitive);
+ factory.registerFunction("windowRepeatedFunnel", createAggregateFunctionWindowFunnel<true>, AggregateFunctionFactory::CaseInsensitive);
}
}
diff --git a/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.h b/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.h
index c9a4e6b32..a8d5fe1df 100644
--- a/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.h
+++ b/dbms/src/AggregateFunctions/AggregateFunctionWindowFunnel.h
@@ -18,8 +18,8 @@ namespace DB
{
namespace ErrorCodes
{
- extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
- extern const int TOO_MANY_ARGUMENTS_FOR_FUNCTION;
+extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
+extern const int TOO_MANY_ARGUMENTS_FOR_FUNCTION;
}
struct ComparePairFirst final
@@ -131,12 +131,13 @@ struct AggregateFunctionWindowFunnelData
/** Calculates the max event level in a sliding window.
* The max size of events is 32, that's enough for funnel analytics
- *
+ * repeated indicates is there any repeated conditions, default to false
* Usage:
* - windowFunnel(window)(timestamp, cond1, cond2, cond3, ....)
*/
+template <bool repeated = false>
class AggregateFunctionWindowFunnel final
- : public IAggregateFunctionDataHelper<AggregateFunctionWindowFunnelData, AggregateFunctionWindowFunnel>
+ : public IAggregateFunctionDataHelper<AggregateFunctionWindowFunnelData, AggregateFunctionWindowFunnel<repeated>>
{
private:
UInt32 window;
@@ -183,7 +184,7 @@ private:
public:
String getName() const override
{
- return "windowFunnel";
+ return !repeated ? "windowFunnel" : "windowRepeatedFunnel";
}
AggregateFunctionWindowFunnel(const DataTypes & arguments, const Array & params)
@@ -191,7 +192,7 @@ public:
const auto time_arg = arguments.front().get();
if (!WhichDataType(time_arg).isDateTime() && !WhichDataType(time_arg).isUInt32())
throw Exception{"Illegal type " + time_arg->getName() + " of first argument of aggregate function " + getName()
- + ", must be DateTime or UInt32"};
+ + ", must be DateTime or UInt32"};
for (const auto i : ext::range(1, arguments.size()))
{
@@ -199,7 +200,7 @@ public:
if (!isUInt8(cond_arg))
throw Exception{"Illegal type " + cond_arg->getName() + " of argument " + toString(i + 1) + " of aggregate function "
+ getName() + ", must be UInt8",
- ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
+ ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
}
events_size = arguments.size() - 1;
@@ -214,14 +215,30 @@ public:
void add(AggregateDataPtr place, const IColumn ** columns, const size_t row_num, Arena *) const override
{
- const auto timestamp = static_cast<const ColumnVector<UInt32> *>(columns[0])->getData()[row_num];
- // reverse iteration and stable sorting are needed for events that are qualified by more than one condition.
- for (auto i = events_size; i > 0; --i)
+ if constexpr(!repeated)
{
- auto event = static_cast<const ColumnVector<UInt8> *>(columns[i])->getData()[row_num];
- if (event)
- this->data(place).add(timestamp, i);
+ for (const auto i : ext::range(1, events_size + 1))
+ {
+ auto event = static_cast<const ColumnVector<UInt8> *>(columns[i])->getData()[row_num];
+ if (event)
+ {
+ this->data(place).add(static_cast<const ColumnVector<UInt32> *>(columns[0])->getData()[row_num], i);
+ break;
+ }
+ }
+ }
+ else
+ {
+ for (size_t i = events_size; i >= 1; --i)
+ {
+ auto event = static_cast<const ColumnVector<UInt8> *>(columns[i])->getData()[row_num];
+ if (event)
+ {
+ this->data(place).add(static_cast<const ColumnVector<UInt32> *>(columns[0])->getData()[row_num], i);
+ }
+ }
}
+
}
void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs, Arena *) const override
diff --git a/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.cpp b/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.cpp
new file mode 100644
index 000000000..4ff3297ed
--- /dev/null
+++ b/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.cpp
@@ -0,0 +1,36 @@
+#include <AggregateFunctions/AggregateFunctionFactory.h>
+#include <AggregateFunctions/AggregateFunctionXFunnel.h>
+#include <AggregateFunctions/Helpers.h>
+#include <AggregateFunctions/FactoryHelpers.h>
+
+
+namespace DB
+{
+
+namespace
+{
+
+template <bool repeated = false>
+AggregateFunctionPtr createAggregateFunctionXFunnel(const std::string & name, const DataTypes & arguments, const Array & params)
+{
+ if (params.size() < 3 || params.size() > 4)
+ throw Exception{"Aggregate function " + name + " requires 3 - 4 parameter.", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH};
+
+ if (arguments.size() < 2)
+ throw Exception("Aggregate function " + name + " requires one column array argument and at least one event condition.", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
+
+ if (arguments.size() > AggregateFunctionXFunnelData::max_events + 1)
+ throw Exception("Too many event arguments for aggregate function " + name, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
+
+ return std::make_shared<AggregateFunctionXFunnel<repeated>>(arguments, params);
+}
+
+}
+
+void registerAggregateFunctionXFunnel(AggregateFunctionFactory & factory)
+{
+ factory.registerFunction("xFunnel", createAggregateFunctionXFunnel<false>, AggregateFunctionFactory::CaseInsensitive);
+ factory.registerFunction("xRepeatedFunnel", createAggregateFunctionXFunnel<true>, AggregateFunctionFactory::CaseInsensitive);
+}
+
+}
diff --git a/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.h b/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.h
new file mode 100644
index 000000000..f257a354a
--- /dev/null
+++ b/dbms/src/AggregateFunctions/AggregateFunctionXFunnel.h
@@ -0,0 +1,542 @@
+#pragma once
+
+#include <iostream>
+#include <sstream>
+#include <unordered_set>
+#include <Columns/ColumnArray.h>
+#include <Columns/ColumnTuple.h>
+#include <Columns/ColumnsNumber.h>
+#include <Common/ArenaAllocator.h>
+#include <Common/typeid_cast.h>
+#include <DataTypes/DataTypeArray.h>
+#include <DataTypes/DataTypeDateTime.h>
+#include <DataTypes/DataTypeTuple.h>
+#include <DataTypes/DataTypesNumber.h>
+#include <IO/ReadHelpers.h>
+#include <IO/WriteHelpers.h>
+
+#include <common/logger_useful.h>
+
+#include <Core/Field.h>
+#include <boost/algorithm/string/split.hpp>
+#include <ext/range.h>
+
+#include <AggregateFunctions/IAggregateFunction.h>
+
+namespace DB
+{
+namespace ErrorCodes
+{
+extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
+extern const int TOO_MANY_ARGUMENTS_FOR_FUNCTION;
+}
+
+struct TimestampEvent
+{
+ UInt32 timestamp;
+ UInt16 day;
+ Tuple tuple;
+ UInt8 event;
+
+ TimestampEvent(const UInt32 & timestamp_, const UInt16 & day_, Tuple & tuple_, const UInt8 & event_)
+ : timestamp{timestamp_}, day{day_}, tuple{std::move(tuple_)}, event{event_}
+ {
+ }
+};
+
+struct ComparePairFirst final
+{
+ bool operator()(const TimestampEvent & lhs, const TimestampEvent & rhs) const
+ {
+ return lhs.timestamp < rhs.timestamp;
+ }
+};
+
+
+static constexpr size_t bytes_on_stack = 4096;
+//using TimestampEvents = PODArray<TimestampEvent, bytes_on_stack>;
+using TimestampEvents = std::vector<TimestampEvent>;
+using validataFunc = std::function<bool(const Tuple & tuple, const Tuple & pre_tuple)>;
+using Comparator = ComparePairFirst;
+
+struct AggregateFunctionXFunnelData
+{
+ static constexpr auto max_events = 32;
+
+ bool sorted = true;
+ TimestampEvents events_list;
+
+
+ size_t size() const
+ {
+ return events_list.size();
+ }
+
+ void add(const UInt32 & timestamp, const UInt16 & day, Tuple & node, UInt8 event)
+ {
+ // Since most events should have already been sorted by timestamp.
+ if (sorted && events_list.size() > 0 && events_list.back().timestamp > timestamp)
+ {
+ sorted = false;
+ }
+ events_list.emplace_back(timestamp, day, node, event);
+ }
+
+ void merge(const AggregateFunctionXFunnelData & other)
+ {
+ const auto size = events_list.size();
+ // events_list.insert(std::begin(other.events_list), std::end(other.events_list));
+ events_list.insert(events_list.end(), other.events_list.begin(), other.events_list.end());
+
+ /// either sort whole container or do so partially merging ranges afterwards
+ if (!sorted && !other.sorted)
+ std::stable_sort(std::begin(events_list), std::end(events_list), Comparator{});
+ else
+ {
+ const auto begin = std::begin(events_list);
+ const auto middle = std::next(begin, size);
+ const auto end = std::end(events_list);
+
+ if (!sorted)
+ std::stable_sort(begin, middle, Comparator{});
+
+ if (!other.sorted)
+ std::stable_sort(middle, end, Comparator{});
+
+ std::inplace_merge(begin, middle, end, Comparator{});
+ }
+
+ sorted = true;
+ }
+
+ void sort()
+ {
+ if (!sorted)
+ {
+ std::stable_sort(std::begin(events_list), std::end(events_list), Comparator{});
+ sorted = true;
+ }
+ }
+
+ void serialize(WriteBuffer & buf) const
+ {
+ writeBinary(sorted, buf);
+ writeBinary(events_list.size(), buf);
+
+ for (const auto & events : events_list)
+ {
+ writeBinary(events.timestamp, buf);
+ writeBinary(events.day, buf);
+ auto & tuple = events.tuple;
+ writeBinary(tuple, buf);
+ writeBinary(events.event, buf);
+ }
+ }
+
+ void deserialize(ReadBuffer & buf)
+ {
+ readBinary(sorted, buf);
+
+ size_t size;
+ readBinary(size, buf);
+
+ /// TODO Protection against huge size
+
+ events_list.clear();
+ events_list.reserve(size);
+
+ UInt32 timestamp;
+ UInt16 day;
+ UInt8 event;
+
+ for (size_t i = 0; i < size; ++i)
+ {
+ readBinary(timestamp, buf);
+ readBinary(day, buf);
+
+ Tuple node;
+ readTuple(node, buf);
+
+ readBinary(event, buf);
+ events_list.emplace_back(timestamp, day, node, event);
+ }
+ }
+};
+
+
+/** Calculates the max event level in a sliding window.
+ * The max size of events is 32, that's enough for funnel analytics
+ * repeated indicates is there any repeated conditions, default to false
+ * Usage:
+ * - xFunnel(windowSize, 2, rule)( (timestamp, col1, col2....) , cond1, cond2, cond3, ....)
+ */
+template <bool repeated = false>
+class AggregateFunctionXFunnel final : public IAggregateFunctionDataHelper<AggregateFunctionXFunnelData, AggregateFunctionXFunnel<repeated>>
+{
+private:
+ UInt32 window;
+ UInt8 events_size;
+ UInt8 max_output_idx;
+ String rule_arg{""};
+ size_t tuple_size;
+
+ DataTypes dataTypes;
+
+ using validataIdxFuncs = std::vector<std::pair<UInt8, validataFunc>>;
+ std::vector<validataIdxFuncs> validators;
+
+ using Indexs = std::vector<UInt16>;
+ using DayIndexs = std::vector<Indexs>;
+
+ // 多维数组,第一维度表示某天开头的所有可能事件流序列
+ using DayIndexsPattern = std::vector<std::vector<DayIndexs>>;
+
+ /// 匹配算法
+ ALWAYS_INLINE DayIndexs getFunnelIndexArray(const AggregateFunctionXFunnelData & data) const
+ {
+ if (data.size() == 0)
+ return {};
+
+ const_cast<AggregateFunctionXFunnelData &>(data).sort();
+
+ // 返回多个漏斗匹配事件流,按天分组
+ UInt16 first_day = data.events_list.front().day;
+ int count = data.events_list.back().day - first_day + 1;
+ DayIndexs res(count);
+ DayIndexsPattern patterns(count, std::vector<DayIndexs>(events_size));
+
+// LOG_TRACE(&Logger::get("xFunnel"), "list=>" << data.events_list.size() << ",day_size" << count << "~" << "min=>" << first_day << "max=>" << data.events_list.back().day);
+
+
+ bool ok;
+ int tmp_idx;
+
+ /// let's fuck the BT rules
+ /// 最大目标一样的, 从右边开始,越靠近最大目标的
+ /// 类似多叉树, 没满足最后目标求最大深度最右节点序列, 满足最后目标后,只需要第一个
+
+ for (UInt16 idx = 0; idx < data.events_list.size(); idx++)
+ {
+ const auto & event = data.events_list[idx];
+ const auto & timestamp = event.timestamp;
+ const auto & tuple = event.tuple;
+ const auto & event_idx = event.event;
+ const auto & day = event.day;
+
+
+ if (event_idx == 0)
+ {
+ if (!res[day - first_day].empty())
+ {
+ continue;
+ }
+ Indexs tmp = Indexs{idx};
+ patterns[day - first_day][0].push_back(std::move(tmp));
+ }
+
+ else
+ {
+ for (UInt16 day_idx = 0; day_idx < patterns.size(); ++day_idx)
+ {
+ if (!res[day_idx].empty() || day < first_day + day_idx)
+ continue;
+
+ //tmp_idx 表示 该天 event_idx = 0 的时间最大值,如果这个值也不满足时间窗口,则我们可以取多叉树最右值
+ tmp_idx = patterns[day_idx].front().empty() ? -1 : patterns[day_idx].front().back().front();
+ if (tmp_idx != -1 && data.events_list[tmp_idx].timestamp + window < timestamp)
+ {
+ for (size_t event = events_size - 1; event > 0; --event)
+ {
+ if (!patterns[day_idx][event - 1].empty())
+ {
+ res[day_idx] = patterns[day_idx][event - 1].back();
+ count --;
+ break;
+ }
+ }
+ continue;
+ }
+
+ for (const auto & pre_indexes : patterns[day_idx][event_idx - 1])
+ {
+ if (pre_indexes.size() < 1)
+ break;
+
+ tmp_idx = pre_indexes.front();
+ if (data.events_list[tmp_idx].timestamp + window >= timestamp)
+ {
+ ok = true;
+
+ const auto & idx_funcs = validators[event_idx];
+ for (const auto & idxFunc : idx_funcs)
+ {
+ const auto & pre_tuple = data.events_list[pre_indexes[idxFunc.first]].tuple;
+ if (!idxFunc.second(tuple, pre_tuple))
+ {
+ ok = false;
+ break;
+ }
+ }
+
+ if (ok)
+ {
+ //如果是最后一个,只需要取最后一个!!
+ Indexs current_indexes = pre_indexes;
+ current_indexes.push_back(idx);
+ patterns[day_idx][event_idx].push_back(std::move(current_indexes));
+ }
+ }
+ }
+ /// now we reach the final goal~ but we should continue ...
+ if (event_idx + 1 == events_size && res[day_idx].empty() && !patterns[day_idx][event_idx].empty())
+ {
+ res[day_idx] = patterns[day_idx][event_idx].back();
+ count--;
+ }
+ }
+ }
+ }
+
+
+ /// for the days never reach final goal, let's gather them all.
+ if (count != 0)
+ {
+ for (UInt16 day_idx = 0; day_idx < patterns.size(); ++day_idx)
+ {
+ if (!res[day_idx].empty())
+ continue;
+
+ /// return the rightest event sequences
+ for (size_t event = events_size - 1; event > 0; --event)
+ {
+ if (!patterns[day_idx][event - 1].empty()) {
+ res[day_idx] = patterns[day_idx][event - 1].back();
+// LOG_TRACE(&Logger::get("xFunnel"), "filling=> " << day_idx << "size=>" << res[day_idx].size());
+ break;
+ }
+ }
+ }
+ }
+ return std::move(res);
+ }
+
+public:
+ String getName() const override
+ {
+ return !repeated ? "xFunnel" : "xRepeatedFunnel";
+ }
+
+ AggregateFunctionXFunnel(const DataTypes & arguments, const Array & params)
+ {
+ window = params.at(0).safeGet<UInt64>();
+
+ // [min_ouput_idx, max_output_idx]
+ max_output_idx = params.at(1).safeGet<UInt64>() - 1;
+ if (max_output_idx < 1)
+ throw Exception{"Invalid number of " + toString(max_output_idx+1) + ", must greater than 2"};
+
+ const auto col_arg = arguments[0].get();
+ auto tuple_args = typeid_cast<const DataTypeTuple *>(col_arg);
+ if (!tuple_args)
+ throw Exception{
+ "Illegal type " + col_arg->getName() + " of first argument of aggregate function " + getName() + ", must be tuple"};
+ tuple_size = tuple_args->getElements().size();
+ events_size = arguments.size() - 1;
+ validators.resize(events_size);
+
+ for (const auto & i : ext::range(1, arguments.size()))
+ {
+ const auto & cond_arg = arguments[i].get();
+ if (!typeid_cast<const DataTypeUInt8 *>(cond_arg))
+ throw Exception{"Illegal type " + cond_arg->getName() + " of argument " + toString(i + 1) + " of aggregate function "
+ + getName() + ", must be UInt8",
+ ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
+ }
+
+ // (timestamp, day, a,b,c,d,...) ) => (timestamp, day, a) for max_output_idx == 3
+ const auto & tupleType = typeid_cast<const DataTypeTuple *>(arguments[0].get());
+ const auto & time_arg = static_cast<const DataTypeUInt32 *>(tupleType->getElements()[0].get());
+ if (!time_arg)
+ throw Exception{"Illegal type " + time_arg->getName() + " 1st of first tuple argument of aggregate function " + getName()
+ + ", must be DateTime or UInt32"};
+
+ const auto & day_arg = static_cast<const DataTypeUInt16 *>(tupleType->getElements()[1].get());
+ if (!day_arg)
+ throw Exception{"Illegal type " + day_arg->getName() + " 2st of first tuple argument of aggregate function " + getName()
+ + ", must be Date or UInt16"};
+
+
+ for (const auto & idx : ext::range(0, max_output_idx + 1))
+ {
+ dataTypes.emplace_back(tupleType->getElements()[idx]);
+ }
+
+ if (params.size() > 2)
+ {
+ rule_arg = params.at(2).safeGet<String>();
+ if (!rule_arg.empty())
+ initRule();
+ }
+ LOG_TRACE(&Logger::get("xFunnel"), "tuple_size " << tuple_size << " rule_args " << rule_arg << " window " << window);
+ }
+
+ // 初始化rule规则
+ ALWAYS_INLINE void initRule()
+ {
+ std::vector<String> ruleStrs;
+ // eg 1.1=2.1,3.2=2.2
+ boost::split(ruleStrs, rule_arg, [](char c) { return c == ','; });
+ if (ruleStrs.size() < 1)
+ return;
+
+ for (String & ruleStr : ruleStrs)
+ {
+ std::vector<String> ruleKvs;
+ boost::split(ruleKvs, ruleStr, [](char c) { return c == '='; });
+
+ // eg [1.1,2.2]
+ if (ruleKvs.size() != 2)
+ throw Exception{"Illegal rule " + ruleStr, ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT};
+
+ std::vector<String> ruleKeys;
+ std::vector<String> ruleValues;
+ boost::split(ruleKeys, ruleKvs[0], [](char c) { return c == '.'; });
+ boost::split(ruleValues, ruleKvs[1], [](char c) { return c == '.'; });
+
+ int previous_event_level = std::atoi(ruleKeys[0].c_str());
+ int previous_label_idx = std::atoi(ruleKeys[1].c_str());
+
+ int current_event_level = std::atoi(ruleValues[0].c_str());
+ int current_label_idx = std::atoi(ruleValues[1].c_str());
+
+ if (previous_event_level < current_event_level)
+ {
+ addRule(previous_event_level - 1, previous_label_idx - 3, current_event_level - 1, current_label_idx - 3);
+ }
+ else
+ {
+ addRule(current_event_level - 1, current_label_idx - 3, previous_event_level - 1, previous_label_idx - 3);
+ }
+ }
+ }
+
+ ALWAYS_INLINE void addRule(const size_t & previous_event_level,
+ const size_t & previous_label_idx,
+ const size_t & current_event_level,
+ const size_t & current_label_idx)
+ {
+ auto func = [=](const Tuple & current_label, const Tuple & pre_label) {
+ const TupleBackend & current_arr = current_label.toUnderType();
+ const TupleBackend & previous_arr = pre_label.toUnderType();
+
+ return current_arr[current_label_idx] == previous_arr[previous_label_idx];
+ };
+ validators[current_event_level].push_back(std::make_pair(previous_event_level, func));
+ }
+
+ DataTypePtr getReturnType() const override
+ {
+ return std::make_shared<DataTypeArray>(std::make_shared<DataTypeArray>(std::make_shared<DataTypeTuple>(dataTypes)));
+ }
+
+ void add(AggregateDataPtr place, const IColumn ** columns, const size_t row_num, Arena *) const override
+ {
+ if constexpr (!repeated)
+ {
+ for (const auto idx : ext::range(1, events_size + 1))
+ {
+ auto event = static_cast<const ColumnVector<UInt8> *>(columns[idx])->getData()[row_num];
+ if (event)
+ {
+ auto labelCol = static_cast<const ColumnTuple *>(columns[0]);
+
+ /// 这里将timestamp和day抽离出来
+ Tuple tuple = Tuple(TupleBackend(tuple_size - 2));
+ auto & arr = tuple.toUnderType();
+ for (const auto i : ext::range(2, tuple_size))
+ {
+ labelCol->getColumn(i).get(row_num, arr[i - 2]);
+ }
+ this->data(place).add(labelCol->getColumn(0).getInt(row_num), labelCol->getColumn(1).getInt(row_num), tuple, idx - 1);
+ break;
+ }
+ }
+ }
+ else
+ {
+ for (auto idx = events_size; idx >= 1; --idx)
+ {
+ auto event = static_cast<const ColumnVector<UInt8> *>(columns[idx])->getData()[row_num];
+ if (event)
+ {
+ auto labelCol = static_cast<const ColumnTuple *>(columns[0]);
+
+ /// 这里将timestamp和day抽离出来
+ Tuple tuple = Tuple(TupleBackend(tuple_size - 2));
+ auto & arr = tuple.toUnderType();
+ for (const auto i : ext::range(2, tuple_size))
+ {
+ labelCol->getColumn(i).get(row_num, arr[i - 2]);
+ }
+ this->data(place).add(labelCol->getColumn(0).getInt(row_num), labelCol->getColumn(1).getInt(row_num), tuple, idx - 1);
+ }
+ }
+ }
+ }
+
+ void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs, Arena *) const override
+ {
+ this->data(place).merge(this->data(rhs));
+ }
+
+ void serialize(ConstAggregateDataPtr place, WriteBuffer & buf) const override
+ {
+ this->data(place).serialize(buf);
+ }
+
+ void deserialize(AggregateDataPtr place, ReadBuffer & buf, Arena *) const override
+ {
+ this->data(place).deserialize(buf);
+ }
+
+ void insertResultInto(ConstAggregateDataPtr place, IColumn & to) const override
+ {
+ const auto & funnel_index_array = getFunnelIndexArray(this->data(place));
+ ColumnArray & arr_to = static_cast<ColumnArray &>(to);
+ ColumnArray::Offsets & offsets_to = arr_to.getOffsets();
+
+ int count = funnel_index_array.size();
+ for (const auto & funnel_index : funnel_index_array)
+ {
+ if (funnel_index.empty())
+ {
+ count --;
+ continue;
+ }
+ //static_cast<ColumnUInt8 &>(static_cast<ColumnArray &>(to).getData()).getData();
+ auto & arr_tuple_to = static_cast<ColumnArray &>(arr_to.getData());
+ auto & offset_tuple_to = arr_tuple_to.getOffsets();
+
+ for (const auto & index : funnel_index)
+ {
+ auto & timestamp_event = this->data(place).events_list[index];
+ auto & tuple_data = static_cast<ColumnTuple &>(arr_tuple_to.getData());
+
+ tuple_data.getColumn(0).insert(static_cast<UInt64>(timestamp_event.timestamp));
+ tuple_data.getColumn(1).insert(static_cast<UInt64>(timestamp_event.day));
+ for (size_t idx = 2; idx <= max_output_idx; idx++)
+ {
+ tuple_data.getColumn(idx).insert(timestamp_event.tuple.toUnderType()[idx - 2]);
+ }
+ }
+ offset_tuple_to.push_back(offset_tuple_to.size() == 0 ? funnel_index.size() : offset_tuple_to.back() + funnel_index.size());
+ }
+ offsets_to.push_back(offsets_to.size() == 0 ? count : offsets_to.back() + count);
+ }
+
+ const char * getHeaderFilePath() const override
+ {
+ return __FILE__;
+ }
+};
+}
diff --git a/dbms/src/AggregateFunctions/QuantileExact.h b/dbms/src/AggregateFunctions/QuantileExact.h
index 7ac639b8f..57c93f98f 100644
--- a/dbms/src/AggregateFunctions/QuantileExact.h
+++ b/dbms/src/AggregateFunctions/QuantileExact.h
@@ -70,11 +70,19 @@ struct QuantileExact
if (!array.empty())
{
size_t n = level < 1
- ? level * array.size()
- : (array.size() - 1);
+ ? level * array.size()
+ : (array.size() - 1);
std::nth_element(array.begin(), array.begin() + n, array.end()); /// NOTE You can think of the radix-select algorithm.
- return array[n];
+
+ //TODO https://stackoverflow.com/questions/1719070/what-is-the-right-approach-when-using-stl-container-for-median-calculation
+ // some hacks
+ auto med = array[n];
+ if (!(array.size() & 1) && level == 0.5) {
+ auto max_it = std::max_element(array.begin(), array.begin()+n);
+ return (*max_it + med) / 2.0;
+ }
+ return med;
}
return std::numeric_limits<Value>::quiet_NaN();
diff --git a/dbms/src/AggregateFunctions/registerAggregateFunctions.cpp b/dbms/src/AggregateFunctions/registerAggregateFunctions.cpp
index 3517ad57a..bd7ffff70 100644
--- a/dbms/src/AggregateFunctions/registerAggregateFunctions.cpp
+++ b/dbms/src/AggregateFunctions/registerAggregateFunctions.cpp
@@ -15,6 +15,7 @@ void registerAggregateFunctionGroupArrayInsertAt(AggregateFunctionFactory &);
void registerAggregateFunctionsQuantile(AggregateFunctionFactory &);
void registerAggregateFunctionsSequenceMatch(AggregateFunctionFactory &);
void registerAggregateFunctionWindowFunnel(AggregateFunctionFactory &);
+void registerAggregateFunctionXFunnel(AggregateFunctionFactory &);
void registerAggregateFunctionsMinMaxAny(AggregateFunctionFactory &);
void registerAggregateFunctionsStatisticsStable(AggregateFunctionFactory &);
void registerAggregateFunctionsStatisticsSimple(AggregateFunctionFactory &);
@@ -49,6 +50,7 @@ void registerAggregateFunctions()
registerAggregateFunctionsQuantile(factory);
registerAggregateFunctionsSequenceMatch(factory);
registerAggregateFunctionWindowFunnel(factory);
+ registerAggregateFunctionXFunnel(factory);
registerAggregateFunctionsMinMaxAny(factory);
registerAggregateFunctionsStatisticsStable(factory);
registerAggregateFunctionsStatisticsSimple(factory);
diff --git a/dbms/src/CMakeLists.txt b/dbms/src/CMakeLists.txt
index 30bd7c134..a9ccdb559 100644
--- a/dbms/src/CMakeLists.txt
+++ b/dbms/src/CMakeLists.txt
@@ -14,3 +14,4 @@ add_subdirectory (Client)
add_subdirectory (TableFunctions)
add_subdirectory (Analyzers)
add_subdirectory (Formats)
+add_subdirectory (Compression)
diff --git a/dbms/src/Common/ErrorCodes.cpp b/dbms/src/Common/ErrorCodes.cpp
index 4e724c995..7dd03459c 100644
--- a/dbms/src/Common/ErrorCodes.cpp
+++ b/dbms/src/Common/ErrorCodes.cpp
@@ -396,6 +396,8 @@ namespace ErrorCodes
extern const int MULTIPLE_ASSIGNMENTS_TO_COLUMN = 419;
extern const int CANNOT_UPDATE_COLUMN = 420;
extern const int CANNOT_ADD_DIFFERENT_AGGREGATE_STATES = 421;
+ extern const int ILLEGAL_SYNTAX_FOR_CODEC_TYPE = 422;
+ extern const int UNKNOWN_CODEC = 423;
extern const int KEEPER_EXCEPTION = 999;
extern const int POCO_EXCEPTION = 1000;
diff --git a/dbms/src/Compression/CMakeLists.txt b/dbms/src/Compression/CMakeLists.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/dbms/src/Compression/CompressionCodecLZ4.cpp b/dbms/src/Compression/CompressionCodecLZ4.cpp
new file mode 100644
index 000000000..610b81a69
--- /dev/null
+++ b/dbms/src/Compression/CompressionCodecLZ4.cpp
@@ -0,0 +1,50 @@
+#include <Compression/CompressionCodecLZ4.h>
+#include <lz4.h>
+#include <lz4hc.h>
+#include <IO/CompressedStream.h>
+#include <Compression/CompressionFactory.h>
+#include "CompressionCodecLZ4.h"
+
+
+namespace DB
+{
+
+char CompressionCodecLZ4::getMethodByte()
+{
+ return static_cast<char>(CompressionMethodByte::LZ4);
+}
+
+void CompressionCodecLZ4::getCodecDesc(String & codec_desc)
+{
+ codec_desc = "LZ4";
+}
+
+void CompressionCodecLZ4::compress(char * uncompressed_buf, size_t uncompressed_size, PODArray<char> & compressed_buf, size_t & compressed_size)
+{
+ static constexpr size_t header_size = 1 + sizeof(UInt32) + sizeof(UInt32);
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+ compressed_buf.resize(header_size + LZ4_COMPRESSBOUND(uncompressed_size));
+#pragma GCC diagnostic pop
+
+ compressed_size = header_size + LZ4_compress_default(
+ uncompressed_buf,
+ &compressed_buf[header_size],
+ uncompressed_size,
+ LZ4_COMPRESSBOUND(uncompressed_size));
+
+ UInt32 compressed_size_32 = compressed_size;
+ UInt32 uncompressed_size_32 = uncompressed_size;
+ unalignedStore(&compressed_buf[1], compressed_size_32);
+ unalignedStore(&compressed_buf[5], uncompressed_size_32);
+}
+
+void registerCodecLZ4(CompressionCodecFactory & factory)
+{
+ factory.registerSimpleCompressionCodec("LZ4", static_cast<char>(CompressionMethodByte::LZ4), [&](){
+ return std::make_shared<CompressionCodecLZ4>();
+ });
+}
+
+}
diff --git a/dbms/src/Compression/CompressionCodecLZ4.h b/dbms/src/Compression/CompressionCodecLZ4.h
new file mode 100644
index 000000000..9ba8da3c3
--- /dev/null
+++ b/dbms/src/Compression/CompressionCodecLZ4.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include <IO/WriteBuffer.h>
+#include <Compression/ICompressionCodec.h>
+#include <IO/BufferWithOwnMemory.h>
+#include <Parsers/StringRange.h>
+
+namespace DB
+{
+
+class CompressionCodecLZ4 : public ICompressionCodec
+{
+public:
+ char getMethodByte() override;
+
+ void getCodecDesc(String & codec_desc) override;
+
+ void compress(char * uncompressed_buf, size_t uncompressed_size, PODArray<char> & compressed_buf, size_t & compressed_size) override;
+};
+
+}
\ No newline at end of file
diff --git a/dbms/src/Compression/CompressionCodecMultiple.cpp b/dbms/src/Compression/CompressionCodecMultiple.cpp
new file mode 100644
index 000000000..b866aebbc
--- /dev/null
+++ b/dbms/src/Compression/CompressionCodecMultiple.cpp
@@ -0,0 +1,50 @@
+#include <Compression/CompressionCodecMultiple.h>
+#include <IO/CompressedStream.h>
+#include "CompressionCodecMultiple.h"
+
+
+namespace DB
+{
+
+CompressionCodecMultiple::CompressionCodecMultiple(Codecs codecs)
+ : codecs(codecs)
+{
+ /// TODO initialize inner_methods_code
+ for (size_t idx = 0; idx < codecs.size(); idx++)
+ {
+ if (idx != 0)
+ codec_desc = codec_desc + ',';
+
+ const auto codec = codecs[idx];
+ String inner_codec_desc;
+ codec->getCodecDesc(inner_codec_desc);
+ codec_desc = codec_desc + inner_codec_desc;
+ }
+}
+
+char CompressionCodecMultiple::getMethodByte()
+{
+ return static_cast<char>(CompressionMethodByte::Multiple);
+}
+
+void CompressionCodecMultiple::getCodecDesc(String & codec_desc_)
+{
+ codec_desc_ = codec_desc;
+}
+
+void CompressionCodecMultiple::compress(char * uncompressed_buf, size_t uncompressed_size, PODArray<char> & compressed_buf, size_t & compressed_size)
+{
+ char reserve = 1;
+
+ PODArray<char> un_compressed_buf(uncompressed_size);
+ un_compressed_buf.emplace_back(reserve);
+ un_compressed_buf.insert(uncompressed_buf, uncompressed_buf + uncompressed_size);
+
+ for (auto & codec : codecs)
+ {
+ codec->compress(&un_compressed_buf[1], uncompressed_size, compressed_buf, compressed_size);
+ uncompressed_size = compressed_size;
+ compressed_buf.swap(un_compressed_buf);
+ }
+}
+}
\ No newline at end of file
diff --git a/dbms/src/Compression/CompressionCodecMultiple.h b/dbms/src/Compression/CompressionCodecMultiple.h
new file mode 100644
index 000000000..2fc0aef2e
--- /dev/null
+++ b/dbms/src/Compression/CompressionCodecMultiple.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include <Compression/ICompressionCodec.h>
+
+namespace DB
+{
+
+class CompressionCodecMultiple final : public ICompressionCodec
+{
+public:
+ CompressionCodecMultiple(Codecs codecs);
+
+ char getMethodByte() override;
+
+ void getCodecDesc(String & codec_desc) override;
+
+ void compress(char * uncompressed_buf, size_t uncompressed_size, PODArray<char> & compressed_buf, size_t & compressed_size) override;
+
+private:
+ Codecs codecs;
+ String codec_desc;
+
+};
+
+}
diff --git a/dbms/src/Compression/CompressionCodecNone.cpp b/dbms/src/Compression/CompressionCodecNone.cpp
new file mode 100644
index 000000000..49e4e4f01
--- /dev/null
+++ b/dbms/src/Compression/CompressionCodecNone.cpp
@@ -0,0 +1,41 @@
+#include <Compression/CompressionCodecNone.h>
+#include <IO/CompressedStream.h>
+#include <Compression/CompressionFactory.h>
+
+
+namespace DB
+{
+
+char CompressionCodecNone::getMethodByte()
+{