SQL.pm untested

filter: Statementstmt 0.0% 0 / 579 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 61 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 63 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 938 CC 91 SCAR 49.0
CC
91
Cov
0%
add_single_benchmark
600.0
search_array
156.0
subsume
132.0
CRAP 134.7
1 package BenchmarkAnything::Storage::Backend::SQL;
2 # git description: v0.028-6-g8b3d653
3  
4 our $AUTHORITY = 'cpan:TAPPER';
5 # ABSTRACT: Autonomous SQL backend to store benchmarks
6 $BenchmarkAnything::Storage::Backend::SQL::VERSION = '0.029';
7 use 5.008;
8 use utf8;
9 use strict;
10 use warnings;
11 use Try::Tiny;
12 use Data::Dumper;
13  
14 my $hr_default_config = {
15 select_cache => 0,
16 default_aggregation => 'min',
17 tables => {
18 unit_table => 'bench_units',
19 benchmark_table => 'benchs',
20 benchmark_value_table => 'bench_values',
21 subsume_type_table => 'bench_subsume_types',
22 benchmark_backup_value_table => 'bench_backup_values',
23 additional_type_table => 'bench_additional_types',
24 additional_value_table => 'bench_additional_values',
25 additional_relation_table => 'bench_additional_relations',
26 additional_type_relation_table => 'bench_additional_type_relations',
27 backup_additional_relation_table => 'bench_backup_additional_relations',
28 },
29 };
30  
31 my $hr_column_ba_mapping = {
32 bench_value_id => 'VALUE_ID',
33 bench => 'NAME',
34 bench_value => 'VALUE',
35 bench_unit => 'UNIT',
36 created_at => 'CREATED',
37 };
38  
39 my $fn_add_subsumed_point = sub {
40  
41 my ( $or_self, $hr_atts ) = @_;
42  
43 $or_self->{query}->start_transaction();
44  
45 eval {
46  
47 # insert subsumed benchmark value
48 $or_self->{query}->insert_benchmark_value(
49 $hr_atts->{rows}[0]{bench_id},
50 $hr_atts->{type_id},
51 $hr_atts->{VALUE},
52 );
53 my $i_bench_value_id = $or_self->{query}->last_insert_id(
54 $or_self->{config}{tables}{benchmark_value_table},
55 'bench_value_id',
56 );
57  
58 # insert subsumed benchmark additional values
59 $or_self->{query}->copy_additional_values({
60 new_bench_value_id => $i_bench_value_id,
61 old_bench_value_id => $hr_atts->{rows}[0]{bench_value_id},
62 });
63  
64 for my $hr_backup_row ( @{$hr_atts->{rows}} ) {
65  
66 if ( $hr_backup_row->{bench_subsume_type_rank} == 1 ) {
67 if ( $hr_atts->{backup} ) {
68 # copy data rows to backup table
69 $or_self->{query}->copy_benchmark_backup_value({
70 new_bench_value_id => $i_bench_value_id,
71 old_bench_value_id => $hr_backup_row->{bench_value_id},
72 });
73 my $i_bench_backup_value_id = $or_self->{query}->last_insert_id(
74 $or_self->{config}{tables}{benchmark_backup_value_table},
75 'bench_backup_value_id',
76 );
77 $or_self->{query}->copy_benchmark_backup_additional_relations({
78 new_bench_value_id => $i_bench_backup_value_id,
79 old_bench_value_id => $hr_backup_row->{bench_value_id},
80 });
81 }
82 }
83 else {
84 # update bench_value_id in backup table
85 $or_self->{query}->update_benchmark_backup_value({
86 new_bench_value_id => $i_bench_value_id,
87 old_bench_value_id => $hr_backup_row->{bench_value_id},
88 });
89 }
90  
91 # now lets remove the old rows
92 $or_self->{query}->delete_benchmark_additional_relations(
93 $hr_backup_row->{bench_value_id},
94 );
95 $or_self->{query}->delete_benchmark_value(
96 $hr_backup_row->{bench_value_id},
97 );
98  
99 }
100  
101 };
102  
103 $or_self->{query}->finish_transaction( $@ );
104  
105 return 1;
106  
107 };
108  
109 sub new {
110  
111 my ( $s_self, $hr_atts ) = @_;
112  
113 my $or_self = bless {}, $s_self;
114  
115 for my $s_key (qw/ dbh /) {
116 if (! $hr_atts->{$s_key} ) {
117 require Carp;
118 Carp::confess("missing '$s_key' parameter");
119 return;
120 }
121 }
122  
123 # get tapper benchmark configuration
124 $or_self->{config} = { %{$hr_default_config} };
125  
126 if ( $hr_atts->{config} ) {
127 require Hash::Merge;
128 $or_self->{config} = {
129 Hash::Merge
130 ->new('LEFT_PRECEDENT')
131 ->merge(
132 %{$hr_atts->{config}},
133 %{$or_self->{config}},
134 )
135 };
136 }
137  
138 require CHI;
139 if ( $or_self->{config}{select_cache} ) {
140 $or_self->{cache} = CHI->new( driver => 'RawMemory', global => 1 );
141 }
142  
143 my $s_module = "BenchmarkAnything::Storage::Backend::SQL::Query::$hr_atts->{dbh}{Driver}{Name}";
144  
145 my $fn_new_sub;
146 eval {
147 require Module::Load;
148 Module::Load::load( $s_module );
149 $fn_new_sub = $s_module->can('new');
150 };
151  
152 if ( $@ || !$fn_new_sub ) {
153 require Carp;
154 Carp::confess("database engine '$hr_atts->{dbh}{Driver}{Name}' not supported");
155 return;
156 }
157 else {
158 $or_self->{query} = $s_module->new({
159 dbh => $hr_atts->{dbh},
160 driver => $hr_atts->{dbh}{Driver}{Name},
161 debug => $hr_atts->{debug} || 0,
162 verbose=> $hr_atts->{verbose} || 0,
163 config => $or_self->{config},
164 });
165 }
166  
167 $or_self->{searchengine} = $hr_atts->{searchengine} if $hr_atts->{searchengine};
168 $or_self->{debug} = $hr_atts->{debug} || 0;
169 $or_self->{verbose} = $hr_atts->{verbose} || 0;
170 $or_self->{dbh_config} = $hr_atts->{dbh_config};
171  
172 return $or_self;
173  
174 }
175  
176  
177 sub add_single_benchmark {
178  
179 my ( $or_self, $hr_benchmark, $hr_options ) = @_;
180  
181 my $hr_config = $or_self->{config};
182  
183 my $VALUE_ID; # same spelling as reserved key in BenchmarkAnything schema
184  
185 # benchmark
186 my $i_benchmark_id;
187 if ( $hr_benchmark->{NAME} ) {
188 if (
189 my $hr_bench_select = $or_self->{query}
190 ->select_benchmark( $hr_benchmark->{NAME} )
191 ->fetchrow_hashref()
192 ) {
193 $i_benchmark_id = $hr_bench_select->{bench_id};
194 }
195 else {
196 my $i_unit_id;
197 if ( $hr_benchmark->{UNIT} ) {
198 if (
199 my $hr_unit_select = $or_self->{query}
200 ->select_unit( $hr_benchmark->{UNIT} )
201 ->fetchrow_hashref()
202 ) {
203 $i_unit_id = $hr_unit_select->{bench_unit_id};
204 }
205 else {
206 $or_self->{query}->insert_unit(
207 $hr_benchmark->{UNIT},
208 );
209 $i_unit_id = $or_self->{query}->last_insert_id(
210 $hr_config->{tables}{unit_table},
211 'bench_unit_id',
212 );
213 }
214 }
215 $or_self->{query}->insert_benchmark(
216 $hr_benchmark->{NAME}, $i_unit_id,
217 );
218 $i_benchmark_id = $or_self->{query}->last_insert_id(
219 $hr_config->{tables}{benchmark_table},
220 'bench_id',
221 );
222 }
223 }
224 else {
225 require Carp;
226 Carp::confess('missing element "NAME"');
227 return 0;
228 }
229  
230 if (
231 $hr_benchmark->{data}
232 && ref( $hr_benchmark->{data} ) eq 'ARRAY'
233 && @{$hr_benchmark->{data}}
234 ) {
235  
236 my $i_benchmark_subsume_type_id = $or_self->{query}
237 ->select_min_subsume_type()
238 ->fetchrow_hashref()
239 ->{bench_subsume_type_id}
240 ;
241  
242 my $i_counter = 1;
243 for my $hr_point ( @{$hr_benchmark->{data}} ) {
244  
245 if ( not exists $hr_point->{VALUE} ) {
246 require Carp;
247 if ( $hr_options->{force} ) {
248 Carp::cluck("missing parameter 'VALUE' in element $i_counter");
249 }
250 else {
251 Carp::confess("missing parameter 'VALUE' in element $i_counter");
252 }
253 }
254  
255 # benchmark value
256 $or_self->{query}->insert_benchmark_value(
257 $i_benchmark_id, $i_benchmark_subsume_type_id, $hr_point->{VALUE},
258 );
259 my $i_benchmark_value_id = $or_self->{query}->last_insert_id(
260 $hr_config->{tables}{benchmark_value_table},
261 'bench_value_id',
262 );
263 $VALUE_ID = $i_benchmark_value_id;
264  
265 ADDITIONAL: for my $s_key ( keys %{$hr_point} ) {
266  
267 next ADDITIONAL if $s_key eq 'VALUE';
268 next ADDITIONAL if not defined $hr_point->{$s_key};
269  
270 # additional type
271 my $i_addtype_id;
272 if ( $or_self->{cache} ) {
273 $i_addtype_id = $or_self->{cache}->get("addtype||$s_key");
274 }
275 if ( !$i_addtype_id ) {
276 if (
277 my $hr_addtype_select = $or_self->{query}
278 ->select_addtype( $s_key )
279 ->fetchrow_hashref()
280 ) {
281 $i_addtype_id = $hr_addtype_select->{bench_additional_type_id};
282 }
283 else {
284 $or_self->{query}->insert_addtype(
285 $s_key,
286 );
287 $i_addtype_id = $or_self->{query}->last_insert_id(
288 $hr_config->{tables}{addition_type_table},
289 'bench_additional_type_id',
290 );
291 }
292 if ( $or_self->{cache} ) {
293 $or_self->{cache}->set( "addtype||$s_key" => $i_addtype_id );
294 }
295 }
296  
297 # benchmark - additional type - relation
298 my $b_inserted = 0;
299 my $s_addtyperel = "$i_benchmark_id|$i_addtype_id";
300 if ( $or_self->{cache} ) {
301 if ( $or_self->{cache}->get("addtyperel||$s_addtyperel") ) {
302 $b_inserted = 1;
303 }
304 }
305 if (! $b_inserted ) {
306 if(!
307 $or_self->{query}
308 ->select_addtyperelation( $i_benchmark_id, $i_addtype_id )
309 ->fetchrow_hashref()
310 ) {
311 $or_self->{query}
312 ->insert_addtyperelation( $i_benchmark_id, $i_addtype_id )
313 ;
314 }
315 if ( $or_self->{cache} ) {
316 $or_self->{cache}->set("addtyperel||$s_addtyperel" => 1 );
317 }
318 }
319  
320 # additional value
321 my $i_addvalue_id;
322 my $s_addvalue_key = "$i_addtype_id|$hr_point->{$s_key}";
323 if ( $or_self->{cache} ) {
324 $i_addvalue_id = $or_self->{cache}->get("addvalue||$s_addvalue_key");
325 }
326 if (! $i_addvalue_id ) {
327 if (
328 my $hr_addvalue_select = $or_self->{query}
329 ->select_addvalue( $i_addtype_id, $hr_point->{$s_key} )
330 ->fetchrow_hashref()
331 ) {
332 $i_addvalue_id = $hr_addvalue_select->{bench_additional_value_id};
333 }
334 else {
335 $or_self->{query}->insert_addvalue(
336 $i_addtype_id, $hr_point->{$s_key},
337 );
338 $i_addvalue_id = $or_self->{query}->last_insert_id(
339 $hr_config->{tables}{addition_type_table},
340 'bench_additional_value_id',
341 );
342 }
343 if ( $or_self->{cache} ) {
344 $or_self->{cache}->set( "addvalue||$s_addvalue_key" => $i_addvalue_id );
345 }
346 }
347  
348 # additional value relation
349 $or_self->{query}->insert_addvaluerelation(
350 $i_benchmark_value_id, $i_addvalue_id,
351 );
352  
353 } # ADDITIONAL
354  
355 $i_counter++;
356  
357 }
358 }
359 else {
360 require Carp;
361 Carp::cluck('no benchmark data found');
362 return 0;
363 }
364  
365 if ( $or_self->{searchengine}{elasticsearch}{index_single_added_values_immediately} )
366 {
367 require BenchmarkAnything::Storage::Search::Elasticsearch;
368 my ($or_es, $s_index, $s_type) = BenchmarkAnything::Storage::Search::Elasticsearch::get_elasticsearch_client
369 (
370 {searchengine => $or_self->{searchengine}, ownjson => 1}
371 );
372  
373 # Sic, we re-read from DB to get the very same data we
374 # *really got* stored, not just what we wish it should
375 # have stored. That gives us translations like
376 # num->string, CREATED date, etc., etc.
377  
378 my $hr_bmk = $or_self->get_single_benchmark_point($VALUE_ID);
379 my $ret = $or_es->index(index => $s_index,
380 id => $VALUE_ID,
381 body => $hr_bmk);
382 }
383  
384 return 1;
385  
386 }
387  
388 sub enqueue_multi_benchmark {
389  
390 my ( $or_self, $ar_data_points, $hr_options ) = @_;
391  
392 require Sereal::Encoder;
393  
394 my $s_serialized = Sereal::Encoder->new->encode($ar_data_points);
395 $or_self->{query}->insert_raw_bench_bundle($s_serialized);
396  
397 return 1;
398  
399 }
400  
401 # dequeues a single bundle (can contain multiple data points)
402 sub process_queued_multi_benchmark {
403  
404 my ( $or_self, $bulkcount, $hr_options ) = @_;
405  
406 my $i_id;
407 my $ar_results_lock;
408 my @a_bench_bundle_ids;
409  
410 my $driver = $or_self->{query}{dbh}{Driver}{Name};
411  
412 $or_self->{query}{dbh}->do("set transaction isolation level read committed") if $driver eq "mysql"; # avoid deadlocks due to gap locking
413 $or_self->{query}->start_transaction;
414  
415 # ===== exclusively pick single raw entry =====
416 # Lock single row via processing=1 so that only one worker handles it!
417 eval {
418 try {
419 $ar_results_lock = $or_self->{query}->select_raw_bench_bundle_for_lock2($bulkcount);
420 @a_bench_bundle_ids = map { $_->[0] } @{$ar_results_lock->fetchall_arrayref()};
421 }
422 catch {
423 if (/Deadlock found when trying to get lock/) {
424 # very normal, handled by eval{} and finish_transaction() in this sub.
425 # warn("IGNORED - DEADLOCK\n");
426 die $_;
427 } elsif (/DBD::mysql::st fetchrow_hashref failed: fetch.. without execute/) {
428 # very normal with multiple workers, usually related
429 # to above deadlock. It is handled by eval{} and
430 # finish_transaction() in this sub.
431 warn("IGNORED - FETCH-WITHOUT-EXECUTE\n");
432 die $_;
433 } else {
434 # An unexpected exception can happen anytime. It is
435 # handled by eval{} and finish_transaction() in this
436 # sub. Still, we print it to know what's happening.
437 require Carp;
438 Carp::cluck("SQL DATABASE EXCEPTION: {{{\n$_\n}}}\n");
439 die $_;
440 }
441 };
442  
443 if (@a_bench_bundle_ids) {
444  
445 my @a_serialized;
446 my $ar_results_process;
447  
448 $ar_results_process = $or_self->{query}->select_raw_bench_bundle_for_processing2(@a_bench_bundle_ids);
449 @a_serialized = map { $_->[0] } @{$ar_results_process->fetchall_arrayref()};
450 require Sereal::Decoder;
451 my @a_data_points = map { @{Sereal::Decoder::decode_sereal($_) || []}; } @a_serialized;
452  
453 # please note, this reorders data points for efficiency,
454 # read the comments there.
455 # (maybe this bulk insert is broken - use with care, double check)
456 # $or_self->add_multi_benchmark(\@a_data_points, $hr_options);
457  
458 # preserve order by adding each data_point separately,
459 # otherwise add_multi_benchmark() would reorder to optimize insert
460 eval {
461 foreach my $hr_data_point (@a_data_points) {
462 eval {
463 $or_self->add_multi_benchmark([$hr_data_point], $hr_options);
464 };
465 if ($@) {
466 if ($@ =~ /failed to parse field.*VALUE/) {
467 print STDERR "IGNORE - field parse failure on VALUE: ".Dumper($hr_data_point);
468 } else {
469 print STDERR "UNEXPECTED ERROR during add_multi_benchmark\n";
470 die $@;
471 }
472 }
473 }
474 $or_self->{query}->update_raw_bench_bundle_set_processed3(@a_bench_bundle_ids);
475 }
476 }
477 };
478  
479 $or_self->{query}->finish_transaction($@, { silent => 1 });
480  
481 $or_self->{query}{dbh}->do("set transaction isolation level repeatable read") if $driver eq "mysql"; # reset to normal gap locking
482 my $err = $@;
483 print STDERR "err: ".$err."\n" if $err && $or_self->{debug};
484 return ($err ? () : @a_bench_bundle_ids);
485  
486 }
487  
488 # garbage collect - initially raw_bench_bundles, but also other stuff.
489 sub gc {
490  
491 my ( $or_self, $hr_options ) = @_;
492  
493 $or_self->{query}->delete_processed_raw_bench_bundles;
494 if ($or_self->{searchengine}{elasticsearch}{enable_query}) {
495 require BenchmarkAnything::Storage::Search::Elasticsearch;
496 my ($or_es, $s_index, $s_type) = BenchmarkAnything::Storage::Search::Elasticsearch::get_elasticsearch_client
497 (
498 {searchengine => $or_self->{searchengine}}
499 );
500 $or_es->indices->clear_cache(index => $s_index);
501 }
502 }
503  
504 sub add_multi_benchmark {
505  
506 # How ordering happens:
507 #
508 # We keep the order inside points of the same NAME and process
509 # NAMEs in order they appeared inside a group of processed
510 # bundles.
511 #
512 # However, if multiple reports were processed, where each report
513 # contains a metric A, B, and C, and we process 10 such reports at
514 # once, then the we get first 10 different As in order, then 10
515 # different B in order, then 10 different C in order, BUT NOT: the
516 # 1st A, 1st B, 1st C, then 2nd A, 2nd B, 2nd C, etc.
517  
518 my ( $or_self, $ar_data_points, $hr_options ) = @_;
519  
520 my $i_counter = 1;
521 my %h_benchmarks = ();
522 my @a_name_order = ();
523  
524 for my $hr_data_point ( @{$ar_data_points} ) {
525  
526 for my $s_param (qw/ NAME VALUE /) {
527 if ( not exists $hr_data_point->{$s_param} ) {
528 require Carp;
529 if ( $hr_options->{force} ) {
530 Carp::cluck("missing parameter '$s_param' in element $i_counter");
531 }
532 else {
533 Carp::confess("missing parameter '$s_param' in element $i_counter");
534 }
535 }
536 }
537  
538 my ( $s_name, $s_unit ) = delete @{$hr_data_point}{qw/ NAME UNIT /};
539  
540 if (! $h_benchmarks{$s_name} ) {
541 $h_benchmarks{$s_name} = {
542 NAME => $s_name,
543 UNIT => $s_unit,
544 data => [],
545 };
546 push @a_name_order, $s_name;
547 }
548 else {
549 $h_benchmarks{$s_name}{UNIT} ||= $s_unit;
550 }
551  
552 push @{$h_benchmarks{$s_name}{data}}, $hr_data_point;
553  
554 $i_counter++;
555  
556 }
557  
558 foreach (@a_name_order) {
559 my $hr_benchmark = $h_benchmarks{$_};
560 $or_self->add_single_benchmark( $hr_benchmark, $hr_options );
561 }
562  
563 return 1;
564  
565 }
566  
567 sub search {
568  
569 my ( $or_self, $hr_search ) = @_;
570  
571 return $or_self->{query}->select_benchmark_values(
572 $hr_search
573 );
574  
575 }
576  
577 sub list_benchmark_names {
578  
579 my ( $or_self, $s_pattern ) = @_;
580  
581 my $ar_pattern = defined($s_pattern) ? [$s_pattern] : [];
582  
583 my $s_key;
584 if ( $or_self->{cache} ) {
585 require JSON::XS;
586 $s_key = JSON::XS::encode_json($ar_pattern);
587 if ( my $ar_search_data = $or_self->{cache}->get("list_benchmark_names||$s_key") ) {
588 return $ar_search_data;
589 }
590 }
591  
592 my $ar_result = $or_self->{query}
593 ->select_benchmark_names( @$ar_pattern )
594 ->fetchall_arrayref([0]);
595 my $ar_benchmark_names = [ map { $_->[0] } @$ar_result ];
596  
597 if ( $or_self->{cache} ) {
598 $or_self->{cache}->set( "list_benchmark_names||$s_key" => $ar_benchmark_names );
599 }
600  
601 return $ar_benchmark_names;
602  
603 }
604  
605 sub list_additional_keys {
606  
607 my ( $or_self, $s_pattern ) = @_;
608  
609 my $ar_pattern = defined($s_pattern) ? [$s_pattern] : [];
610  
611 my $s_key;
612 if ( $or_self->{cache} ) {
613 require JSON::XS;
614 $s_key = JSON::XS::encode_json($ar_pattern);
615 if ( my $ar_search_data = $or_self->{cache}->get("list_additional_keys||$s_key") ) {
616 return $ar_search_data;
617 }
618 }
619  
620 my $ar_result = $or_self->{query}
621 ->select_additional_keys( @$ar_pattern )
622 ->fetchall_arrayref([0]);
623 my $ar_key_names = [ map { $_->[0] } @$ar_result ];
624  
625 if ( $or_self->{cache} ) {
626 $or_self->{cache}->set( "list_additional_keys||$s_key" => $ar_key_names );
627 }
628  
629 return $ar_key_names;
630  
631 }
632  
633 sub get_stats {
634  
635 my ( $or_self ) = @_;
636  
637 my %h_searchengine_stats = ();
638 my %h_flat_searchengine_stats = ();
639 my %stats = ();
640  
641 # Not strictly *stats* but useful information.
642 if ( $or_self->{searchengine}{elasticsearch}{index} )
643 {
644 require BenchmarkAnything::Storage::Search::Elasticsearch;
645 my ($or_es, $s_index, $s_type) = BenchmarkAnything::Storage::Search::Elasticsearch::get_elasticsearch_client
646 (
647 {searchengine => $or_self->{searchengine}}
648 );
649  
650 $stats{count_datapoints} = (map {chomp; $_} split(qr/ +/, $or_es->cat->count))[2];
651 %h_searchengine_stats =
652 (
653 index => $or_self->{searchengine}{elasticsearch}{index} || 'UNKNOWN',
654 type => $or_self->{searchengine}{elasticsearch}{type} || 'UNKNOWN',
655 enable_query => $or_self->{searchengine}{elasticsearch}{enable_query} || 0,
656 cluster_health => $or_es->cluster->health,
657 index_single_added_values_immediately => $or_self->{searchengine}{elasticsearch}{index_single_added_values_immediately} || 0,
658 );
659 # boolean -> 0/1
660 for (values %{$h_searchengine_stats{elasticsearch}{cluster_health}}) {
661 $_ = $_ ? 1 : 0 if ref eq 'JSON::XS::Boolean';
662 }
663 $h_flat_searchengine_stats{"elasticsearch_$_"} = $h_searchengine_stats{$_}
664 for qw(index type enable_query index_single_added_values_immediately);
665 $h_flat_searchengine_stats{"elasticsearch_cluster_health_$_"} = $h_searchengine_stats{cluster_health}{$_}
666 for qw(cluster_name active_shards_percent_as_number active_primary_shards number_of_nodes status);
667 }
668  
669 $stats{count_datapoints} ||= 0+$or_self->{query}->select_count_datapoints->fetch->[0];
670 $stats{count_datapointkeys} = 0+$or_self->{query}->select_count_datapointkeys->fetch->[0] if $or_self->{verbose};
671 $stats{count_metrics} = 0+$or_self->{query}->select_count_metrics->fetch->[0] if $or_self->{verbose};
672 $stats{count_keys} = 0+$or_self->{query}->select_count_keys->fetch->[0] if $or_self->{verbose};
673  
674 %stats = (%stats, %h_flat_searchengine_stats);
675  
676 return \%stats;
677 }
678  
679 sub get_single_benchmark_point {
680  
681 my ( $or_self, $i_bench_value_id ) = @_;
682  
683 return {} unless $i_bench_value_id;
684  
685 # cache?
686 my $s_key;
687 if ( $or_self->{cache} ) {
688 require JSON::XS;
689 $s_key = JSON::XS::encode_json({bench_value_id => $i_bench_value_id});
690 if ( my $hr_search_data = $or_self->{cache}->get("get_single_benchmark_point||$s_key") ) {
691 return $hr_search_data;
692 }
693 }
694  
695 # fetch all additional key/value fields
696 my $ar_query_result = $or_self->{query}
697 ->select_complete_benchmark_point( $i_bench_value_id )
698 ->fetchall_arrayref({});
699  
700 # fetch essentials, like NAME, VALUE, UNIT
701 my $hr_essentials = $or_self->{query}
702 ->select_benchmark_point_essentials( $i_bench_value_id )
703 ->fetchrow_hashref();
704  
705 # create complete BenchmarkAnything-like key/value entry
706 my $hr_result;
707 $hr_result = { map { ($_->{bench_additional_type} => $_->{bench_additional_value} ) } @$ar_query_result };
708 $hr_result->{NAME} = $hr_essentials->{bench};
709 $hr_result->{VALUE} = $hr_essentials->{bench_value};
710 $hr_result->{VALUE_ID} = $hr_essentials->{bench_value_id};
711 $hr_result->{CREATED} = $hr_essentials->{created_at};
712 $hr_result->{UNIT} = $hr_essentials->{bench_unit} if $hr_essentials->{bench_unit};
713  
714 # cache!
715 if ( $or_self->{cache} ) {
716 $or_self->{cache}->set( "get_single_benchmark_point||$s_key" => $hr_result );
717 }
718  
719 return $hr_result;
720 }
721  
722 sub get_full_benchmark_points {
723  
724 my ( $or_self, $i_bench_value_id, $i_count ) = @_;
725  
726 return [] unless $i_bench_value_id;
727  
728 $i_count ||= 1;
729  
730 # cache?
731 my $s_key;
732 if ( $or_self->{cache} ) {
733 require JSON::XS;
734 $s_key = JSON::XS::encode_json({bench_value_id => $i_bench_value_id});
735 if ( my $hr_search_data = $or_self->{cache}->get("get_full_benchmark_points||$s_key") ) {
736 return $hr_search_data;
737 }
738 }
739  
740 # fetch essentials, like NAME, VALUE, UNIT
741 my $ar_essentials = $or_self->{query}
742 ->select_multiple_benchmark_points_essentials($i_bench_value_id, $i_count)
743 ->fetchall_arrayref({});
744 # additional key/value pairs
745 my $ar_additional_values = $or_self->{query}
746 ->select_multiple_benchmark_points_additionals($i_bench_value_id, $i_count)
747 ->fetchall_arrayref({});
748  
749 # map columns into BenchmarkAnything schema
750 my $hr_bmk;
751 foreach my $k (keys %$hr_column_ba_mapping)
752 {
753 my $K = $hr_column_ba_mapping->{$k};
754 foreach my $e (@$ar_essentials) {
755 $hr_bmk->{$e->{bench_value_id}}{$K} = $e->{$k} if $k ne 'bench_unit' or defined $e->{$k};
756 }
757 }
758 foreach (@$ar_additional_values) {
759 $hr_bmk->{$_->{bench_value_id}}{$_->{bench_additional_type}} = $_->{bench_additional_value};
760 }
761 # sorted (by VALUE_ID) array of BenchmarkAnything entries
762 my @a_bmk = map { $hr_bmk->{$_} } sort keys %$hr_bmk;
763  
764 # cache!
765 if ( $or_self->{cache} ) {
766 $or_self->{cache}->set( "get_full_benchmark_points||$s_key" => \@a_bmk );
767 }
768  
769 return \@a_bmk;
770 }
771  
772 sub search_array {
773  
774 my ( $or_self, $hr_search ) = @_;
775  
776 my $debug = $or_self->{debug} || $or_self->{searchengine}{elasticsearch}{debug};
777  
778 my $s_key;
779 if ( $or_self->{cache} ) {
780 require JSON::XS;
781 $s_key = JSON::XS::encode_json($hr_search);
782 if ( my $ar_search_data = $or_self->{cache}->get("search_array||$s_key") ) {
783 return $ar_search_data;
784 }
785 }
786  
787 if ( $debug )
788 {
789 require JSON::XS;
790 require Data::Dumper;
791 print STDERR ',-------------------'."\n";
792 print STDERR "benchmarkanything query:\n";
793 print STDERR "benchmarkanything-storage search -d '\n";
794 print STDERR JSON::XS->new->pretty->encode($hr_search);
795 print STDERR "'\n";
796 print STDERR '`-------------------'."\n";
797 }
798  
799 if ( $or_self->{searchengine}{elasticsearch}{enable_query} )
800 {
801 # If anything goes wrong with Elasticsearch we just continue
802 # below with relational backend query.
803  
804 require BenchmarkAnything::Storage::Search::Elasticsearch;
805 my $hr_es_query = BenchmarkAnything::Storage::Search::Elasticsearch::get_elasticsearch_query($hr_search);
806  
807 if ($debug)
808 {
809 require JSON::XS;
810 require Data::Dumper;
811 print STDERR ',-------------------'."\n";
812 print STDERR "elasticsearch query:\n";
813 print STDERR "curl -s -XGET 'http://localhost:9200/tapper/benchmarkanything/_search?pretty' -d '\n";
814 print STDERR JSON::XS->new->pretty->encode($hr_es_query);
815 print STDERR "'\n";
816 print STDERR '`-------------------'."\n";
817 }
818  
819 # If we could transform the query then we run it against Elasticsearch and return its result.
820 if (defined $hr_es_query)
821 {
822 # ===== client =====
823  
824 require BenchmarkAnything::Storage::Search::Elasticsearch;
825 my ($or_es, $s_index, $s_type) = BenchmarkAnything::Storage::Search::Elasticsearch::get_elasticsearch_client
826 (
827 {searchengine => $or_self->{searchengine}, ownjson => 1}
828 );
829  
830 # ===== prepare =====
831  
832 # If sort fields are of type 'text' then those fields needs to
833 # get their properties being declared as "fielddata":true.
834 my $field_mapping = {};
835 my @sort_fields = map {keys %$_} @{$hr_es_query->{sort}||[]};
836 if (@sort_fields) {
837 $field_mapping =
838 $or_es->indices->get_mapping->{$s_index}{mappings}{properties} || # > v5
839 $or_es->indices->get_mapping->{$s_index}{mappings}{$s_type}{properties}; # = v5
840 }
841 foreach my $sort_field (@sort_fields)
842 {
843 if ($field_mapping->{$sort_field}{type} and $field_mapping->{$sort_field}{type} eq 'text')
844 {
845 require BenchmarkAnything::Storage::Backend::SQL::Search;
846 $or_es->indices->put_mapping
847 (
848 index => $s_index,
849 body => {
850 properties => {
851 $sort_field => {
852 type => 'text',
853 fielddata => BenchmarkAnything::Storage::Backend::SQL::Search::json_true(),
854 },
855 },
856 },
857 );
858 }
859 }
860  
861 # ===== search =====
862 my $hr_es_answer = $or_es->search(index => $s_index,
863 body => $hr_es_query);
864  
865 if (
866 !$hr_es_answer->{timed_out} and
867 !$hr_es_answer->{_shards}{failed}
868 )
869 {
870 my @ar_es_result = map { $_->{_source} } @{$hr_es_answer->{hits}{hits} || []};
871 return \@ar_es_result;
872 }
873 } else {
874 print STDERR "Did not get Elasticsearch query, fall back to SQL.\n" if $debug;
875 }
876  
877 # Else no-op, continue with relational backend query.
878 }
879  
880 my $ar_result = $or_self
881 ->search( $hr_search )
882 ->fetchall_arrayref({})
883 ;
884  
885 if ( $or_self->{cache} ) {
886 $or_self->{cache}->set( "search_array||$s_key" => $ar_result );
887 }
888  
889 return $ar_result;
890  
891 }
892  
893 sub search_hash {
894  
895 my ( $or_self, $hr_search ) = @_;
896  
897 my $s_key;
898 if ( $or_self->{cache} ) {
899 require JSON::XS;
900 $s_key = JSON::XS::encode_json($hr_search);
901 if ( my $hr_search_data = $or_self->{cache}->get( "search_hash||$s_key" ) ) {
902 return $hr_search_data;
903 }
904 }
905  
906 if (! $hr_search->{keys} ) {
907 require Carp;
908 Carp::confess(q#cannot get hash search result without 'keys'#);
909 return;
910 }
911  
912 my $hr_result = $or_self
913 ->search( $hr_search )
914 ->fetchall_hashref($hr_search->{keys})
915 ;
916  
917 if ( $or_self->{cache} ) {
918 $or_self->{cache}->set( "search_hash||$s_key" => $hr_result )
919 }
920  
921 return $hr_result;
922  
923 }
924  
925 sub subsume {
926  
927 my ( $or_self, $hr_options ) = @_;
928  
929 for my $s_parameter (qw/ subsume_type /) {
930 if (! $hr_options->{$s_parameter}) {
931 require Carp;
932 Carp::confess("missing parameter '$s_parameter'");
933 return;
934 }
935 }
936  
937 # check if subsume type exists
938 my $hr_subsume_type = $or_self->{query}
939 ->select_subsume_type( $hr_options->{subsume_type} )
940 ->fetchrow_hashref()
941 ;
942 if (! $hr_subsume_type ) {
943 require Carp;
944 Carp::confess("subsume type '$hr_options->{subsume_type}' not exists");
945 return;
946 }
947 if ( $hr_subsume_type->{bench_subsume_type_rank} == 1 ) {
948 require Carp;
949 Carp::confess("cannot subsume with type '$hr_options->{subsume_type}'");
950 return;
951 }
952  
953 # looking for values with with a higher rank subsume type
954 if (
955 $or_self->{query}
956 ->select_check_subsumed_values({
957 date_to => $hr_options->{date_to},
958 date_from => $hr_options->{date_from},
959 subsume_type_id => $hr_subsume_type->{bench_subsume_type_id},
960 })
961 ->rows()
962 ) {
963 require Carp;
964 Carp::confess(
965 "cannot use subsume type '$hr_options->{subsume_type}' " .
966 'because a higher rank subsume type is already used for this date period'
967 );
968 return;
969 }
970  
971 # look if excluded additional types really exists
972 my @a_excluded_adds;
973 if ( $hr_options->{exclude_additionals} ) {
974 for my $s_additional_type ( @{$hr_options->{exclude_additionals}} ) {
975 if (
976 my $hr_addtype = $or_self->{query}
977 ->select_addtype( $s_additional_type )
978 ->fetchrow_hashref()
979 ) {
980 push @a_excluded_adds, $hr_addtype->{bench_additional_type_id}
981 }
982 else {
983 require Carp;
984 Carp::confess( "additional type '$s_additional_type' not exists" );
985 return;
986 }
987 }
988 }
989  
990 # get all data points for subsume
991 my $or_data_values = $or_self->{query}->select_data_values_for_subsume({
992 date_to => $hr_options->{date_to},
993 date_from => $hr_options->{date_from},
994 exclude_additionals => \@a_excluded_adds,
995 subsume_type_id => $hr_subsume_type->{bench_subsume_type_id},
996 });
997  
998 require DateTime::Format::Strptime;
999 my $or_strp = DateTime::Format::Strptime->new( pattern => '%F %T', );
1000  
1001 my @a_rows;
1002 my $i_counter = 0;
1003 my $i_sum_value = 0;
1004 my $b_backup = ((not exists $hr_options->{backup}) || $hr_options->{backup}) ? 1 : 0;
1005 my $s_last_key = q##;
1006  
1007 while ( my $hr_values = $or_data_values->fetchrow_hashref() ) {
1008  
1009 my $s_act_key = join '__',
1010 $hr_values->{bench_id},
1011 $or_strp->parse_datetime( $hr_values->{created_at} )->strftime( $hr_subsume_type->{datetime_strftime_pattern} ),
1012 $hr_values->{additionals} || q##,
1013 ;
1014  
1015 if ( $s_last_key ne $s_act_key ) {
1016  
1017 if ( $i_counter ) {
1018 $or_self->$fn_add_subsumed_point({
1019 rows => \@a_rows,
1020 VALUE => $i_sum_value / $i_counter,
1021 backup => $b_backup,
1022 type_id => $hr_subsume_type->{bench_subsume_type_id}
1023 });
1024 }
1025  
1026 @a_rows = ();
1027 $i_counter = 0;
1028 $i_sum_value = 0;
1029 $s_last_key = $s_act_key;
1030  
1031 }
1032  
1033 $i_counter += 1;
1034 $i_sum_value += $hr_values->{bench_value};
1035  
1036 push @a_rows, $hr_values;
1037  
1038 }
1039  
1040 if ( $i_counter ) {
1041 $or_self->$fn_add_subsumed_point({
1042 rows => \@a_rows,
1043 VALUE => $i_sum_value / $i_counter,
1044 backup => $b_backup,
1045 type_id => $hr_subsume_type->{bench_subsume_type_id}
1046 });
1047 }
1048  
1049 return 1;
1050  
1051 }
1052  
1053 sub _get_additional_key_id {
1054  
1055 my ( $or_self, $s_key ) = @_;
1056  
1057 return $or_self->{query}->select_additional_key_id($s_key)->fetch->[0];
1058  
1059 }
1060  
1061 sub default_columns {
1062  
1063 my ( $or_self ) = @_;
1064  
1065 return $or_self->{query}->default_columns;
1066  
1067 }
1068  
1069 sub benchmark_operators {
1070  
1071 my ( $or_self ) = @_;
1072  
1073 return $or_self->{query}->benchmark_operators;
1074  
1075 }
1076  
1077 sub init_search_engine
1078 {
1079 my ( $or_self, $b_force) = @_;
1080  
1081 require BenchmarkAnything::Storage::Backend::SQL::Search;
1082 BenchmarkAnything::Storage::Backend::SQL::Search::init_search_engine (@_);
1083 }
1084  
1085 sub sync_search_engine
1086 {
1087 require BenchmarkAnything::Storage::Backend::SQL::Search;
1088 BenchmarkAnything::Storage::Backend::SQL::Search::sync_search_engine (@_);
1089 }
1090  
1091 1;
1092  
1093 __END__