blib/lib/EV/ClickHouse.pm

filter: Statementstmt 21.2% 214 / 1008 Branchbran 14.2% 78 / 546 Conditioncond 11.0% 45 / 408 MC/DCmcdc 2.5% 6 / 232 Subroutinesub 15.8% 23 / 145 Podpod 92.8% 26 / 28 totaltotal 16.5% 392 / 2367 CC 463 SCAR 48.6
CC
463
Cov
17%
new
656.7
insert_aggregated
650.0
__ANON__
272.0
CRAP 128.4
↑ Summary cityhash.h »
1 package EV::ClickHouse;
2 79 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 79 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 79 ▶use EV;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 79 ▶use Scalar::Util qw(refaddr weaken looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 # Identifier validation regexes — single source of truth for the table
9 # / column / function names that get spliced into SQL via the helpers.
10 79 my $RE_IDENT = qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
11 79 my $RE_TABLE = qr/\A[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?\z/;
12  
13 79 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
14 79 our $VERSION = '0.09';
15 79 ▶ use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 79 XSLoader::load __PACKAGE__, $VERSION;
17 }
18  
19 # Holds in-flight EV::cares resolvers so they aren't garbage-collected
20 # before their callback fires. Keyed by refaddr of the resolver itself
21 # (not the connection) — see new() for the rationale. Each entry is
22 # deleted from inside its own resolved callback via a deferred timer.
23 # Plain package hash (not Hash::Util::FieldHash) so module load doesn't
24 # add tied/magic SVs that Test::LeakTrace would flag.
25 79 our %_failover;
26  
27 79 *q = \&query;
28 79 *reconnect = \&reset;
29 79 *disconnect = \&finish;
30 79 *ddl = \&query; # readability at call sites for DDL/DML
31  
32 0 ▶sub _uri_unescape { my $s = $_[0]; $s =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge; $s }
Subroutine _uri_unescape: called CC=1 SCAR=0.2
33  
34 # Parse a URI query string into a hash. Bare keys (no `=`) are stored
35 # as 1 (standard URL flag convention); existing keys in $h are preserved
36 # (path-derived host/port/etc win over query-string overrides).
37 2 ▶sub _uri_qs_into {
Subroutine _uri_qs_into: called CC=8 SCAR=23.4
38 2 my ($qs, $h) = @_;
39 2 ▶ return unless defined $qs && length $qs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $qs and length $qs 1 1 2
Condition66%2/3
defined $qs and length $qs
!ll&&!rl&&r
101
MC/DC50%1/2
defined $qs and length $qs
defined $qs length $qs
Truth table66%2/3
A and B
A= defined $qsB= length $qs
ABresult
0X0
100
111
40 1 for my $pair (split /&/, $qs) {
41 1 my ($k, $v) = split /=/, $pair, 2;
42 1 ▶ next unless defined $k && length $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k and length $k 0 1 1
Condition33%1/3
defined $k and length $k
!ll&&!rl&&r
001
MC/DC0%0/2
defined $k and length $k
defined $k length $k
Truth table33%1/3
A and B
A= defined $kB= length $k
ABresult
0X0
100
111
43 1 ▶ $h->{$k} //= defined $v ? _uri_unescape($v) : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 1 0 1
Condition33%1/3
$h->{$k} //= defined $v ? _uri_unescape($v) : 1
l!l&&r!l&&!r
010
MC/DC0%0/2
$h->{$k} //= defined $v ? _uri_unescape($v) : 1
$h->{$k} defined $v ? _uri_unescape($v) : 1
Truth table33%1/3
A //= B
A= $h->{$k}B= defined $v ? _uri_unescape($v) : 1
ABresult
1X1
011
000
44 }
45 }
46  
47 48 ▶sub new {
Subroutine new: called CC=58 SCAR=64.9
Pod documented
48 48 my ($class, %args) = @_;
49  
50 # Connection URI: clickhouse://user:pass@host:port/database
51 # host accepts a bracketed IPv6 literal (e.g. clickhouse://[::1]:9000/db)
52 48 ▶ if (my $uri = delete $args{uri}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $uri = delete $args{"uri"}) 0 48 48
53 # userinfo splits at the LAST @ before the path (RFC 3986), so a
54 # literal @ in the password parses instead of corrupting the host.
55 0 ▶ if ($uri =~ m{^clickhouse(?:\+(\w+))?://(?:([^:@]*?)(?::([^/]*))?\@)?(\[[^\]]+\]|[^/:?]+)(?::(\d+))?(?:/([^?]*))?(?:\?(.*))?$}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uri =~ m(^clickhouse(?:\+(\w+))?://(?:([^:\@]*?)(?::([^/]*))?\@)?(\[[^\]]+\]|[^/:?]+)(?::(\d+))?(?:/([^?]*))?(?:\?(.*))?$)) { } 0 0 0
56 0 my ($proto, $u, $pw, $h, $p, $db, $qs) = ($1, $2, $3, $4, $5, $6, $7);
57 0 $h =~ s/^\[(.*)\]$/$1/;
58 0 ▶ $args{protocol} //= $proto if $proto;
Branch: 1 branch
BranchTrueFalseTotal
if $proto 0 0 0
Condition0%0/3
$args{"protocol"} //= $proto
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"protocol"} //= $proto
$args{"protocol"} $proto
Truth table0%0/3
A //= B
A= $args{"protocol"}B= $proto
ABresult
1X1
011
000
59 0 ▶ $args{user} //= _uri_unescape($u) if defined $u && $u ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $u and $u ne "" 0 0 0
Condition0%0/6
defined $u and $u ne ""
!ll&&!rl&&r
000
$args{"user"} //= _uri_unescape($u)
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $u and $u ne ""
defined $u $u ne ""
MC/DC0%0/2
$args{"user"} //= _uri_unescape($u)
$args{"user"} _uri_unescape($u)
Truth table0%0/3
A and B
A= defined $uB= $u ne ""
ABresult
0X0
100
111
Truth table0%0/3
A //= B
A= $args{"user"}B= _uri_unescape($u)
ABresult
1X1
011
000
60 0 ▶ $args{password} //= _uri_unescape($pw) if defined $pw;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pw 0 0 0
Condition0%0/3
$args{"password"} //= _uri_unescape($pw)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"password"} //= _uri_unescape($pw)
$args{"password"} _uri_unescape($pw)
Truth table0%0/3
A //= B
A= $args{"password"}B= _uri_unescape($pw)
ABresult
1X1
011
000
61 0 ▶ $args{host} //= $h;
Condition0%0/3
$args{"host"} //= $h
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"host"} //= $h
$args{"host"} $h
Truth table0%0/3
A //= B
A= $args{"host"}B= $h
ABresult
1X1
011
000
62 0 ▶ $args{port} //= $p if defined $p;
Branch: 1 branch
BranchTrueFalseTotal
if defined $p 0 0 0
Condition0%0/3
$args{"port"} //= $p
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"port"} //= $p
$args{"port"} $p
Truth table0%0/3
A //= B
A= $args{"port"}B= $p
ABresult
1X1
011
000
63 0 ▶ $args{database} //= _uri_unescape($db) if defined $db && $db ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $db and $db ne "" 0 0 0
Condition0%0/6
defined $db and $db ne ""
!ll&&!rl&&r
000
$args{"database"} //= _uri_unescape($db)
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $db and $db ne ""
defined $db $db ne ""
MC/DC0%0/2
$args{"database"} //= _uri_unescape($db)
$args{"database"} _uri_unescape($db)
Truth table0%0/3
A and B
A= defined $dbB= $db ne ""
ABresult
0X0
100
111
Truth table0%0/3
A //= B
A= $args{"database"}B= _uri_unescape($db)
ABresult
1X1
011
000
64 0 _uri_qs_into($qs, \%args);
65 } else {
66 0 die "EV::ClickHouse: invalid URI '$uri'\n";
67 }
68 }
69  
70 48 ▶ my $loop = delete $args{loop} || EV::default_loop;
Condition66%2/3
delete $args{'loop'} || &EV::default_loop()
l!l&&r!l&&!r
1470
MC/DC0%0/2
delete $args{'loop'} || &EV::default_loop()
delete $args{'loop'} &EV::default_loop()
Truth table66%2/3
A || B
A= delete $args{'loop'}B= &EV::default_loop()
ABresult
1X1
011
000
71 48 my $self = $class->_new($loop);
72  
73 # Multi-host failover: hosts => ['a', 'b', 'c'] or ['a:9000', 'b:9001'].
74 # On a connect-phase failure, advance to the next host and reconnect
75 # via auto_reconnect (or the user calling reset). Falls back to single
76 # host => '...' when not provided.
77 48 my $hosts_list;
78 my $hosts_explicit_port;
79 48 ▶ if (my $h = delete $args{hosts}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $h = delete $args{"hosts"}) 1 47 48
80 1 ▶ die "hosts must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $h eq "ARRAY" and @$h 0 1 1
Condition33%1/3
ref $h eq "ARRAY" and @$h
!ll&&!rl&&r
001
MC/DC0%0/2
ref $h eq "ARRAY" and @$h
ref $h eq "ARRAY" @$h
Truth table33%1/3
A and B
A= ref $h eq "ARRAY"B= @$h
ABresult
0X0
100
111
81 unless ref($h) eq 'ARRAY' && @$h;
82 1 $hosts_list = $h;
83 # Capture before the embedded-port fill below: an explicit
84 # port => overrides embedded entry ports on rotation too.
85 1 $hosts_explicit_port = $args{port};
86 1 ▶ if (!defined $args{host}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args{"host"}) 1 0 1
87 1 my ($h0, $p0) = _split_host_port($h->[0], $args{port});
88 1 $args{host} = $h0;
89 1 ▶ $args{port} //= $p0;
Condition33%1/3
$args{"port"} //= $p0
l!l&&r!l&&!r
010
MC/DC0%0/2
$args{"port"} //= $p0
$args{"port"} $p0
Truth table33%1/3
A //= B
A= $args{"port"}B= $p0
ABresult
1X1
011
000
90 }
91 }
92  
93 # Failover state + on_failover both live in the connection's C struct
94 # now: emit_error advances the host ring before firing on_error,
95 # which keeps the hot error path off the Perl stack.
96 my $user_on_error = exists $args{on_error}
97 0 ▶ ? delete $args{on_error} : sub { die @_ };
Subroutine __ANON__: not called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'on_error'} ? : 47 1 48
98 48 $self->on_error($user_on_error);
99 48 ▶ if (my $cb = delete $args{on_failover}) { $self->on_failover($cb) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = delete $args{"on_failover"}) 1 47 48
100 48 for my $h (qw(on_connect on_progress on_disconnect on_trace on_query_complete on_query_start on_log)) {
101 336 ▶ $self->$h(delete $args{$h}) if exists $args{$h};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{$h} 54 282 336
102 }
103  
104 48 ▶ my $host = delete $args{host} // '127.0.0.1';
Condition100%2/2
delete $args{"host"} // "127.0.0.1"
l!l
471
MC/DC100%1/1
delete $args{"host"} // "127.0.0.1"
delete $args{"host"}
Truth table100%2/2
A
A= delete $args{"host"}
Aresult
11
00
105 48 my $port = delete $args{port};
106 48 ▶ my $protocol = delete $args{protocol} // 'http';
Condition100%2/2
delete $args{"protocol"} // "http"
l!l
471
MC/DC100%1/1
delete $args{"protocol"} // "http"
delete $args{"protocol"}
Truth table100%2/2
A
A= delete $args{"protocol"}
Aresult
11
00
107 48 ▶ my $user = delete $args{user} // 'default';
Condition50%1/2
delete $args{"user"} // "default"
l!l
048
MC/DC0%0/1
delete $args{"user"} // "default"
delete $args{"user"}
Truth table50%1/2
A
A= delete $args{"user"}
Aresult
11
00
108 48 ▶ my $password = delete $args{password} // '';
Condition50%1/2
delete $args{"password"} // ""
l!l
048
MC/DC0%0/1
delete $args{"password"} // ""
delete $args{"password"}
Truth table50%1/2
A
A= delete $args{"password"}
Aresult
11
00
109 48 ▶ my $database = delete $args{database} // delete $args{db} // 'default';
Condition40%2/5
(delete $args{"database"} // delete $args{"db"}) // "default"
l!l
048
delete $args{"database"} // delete $args{"db"}
l!l&&r!l&&!r
0048
MC/DC0%0/2
(delete $args{"database"} // delete $args{"db"}) // "default"
delete $args{"database"} delete $args{"db"}
Truth table33%1/3
A // B
A= delete $args{"database"}B= delete $args{"db"}
ABresult
1X1
011
000
110  
111 48 ▶ die "EV::ClickHouse: unknown protocol '$protocol' (expected 'http' or 'native')\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $protocol eq "http" or $protocol eq "native" 0 48 48
Condition66%2/3
$protocol eq "http" or $protocol eq "native"
l!l&&r!l&&!r
22260
MC/DC0%0/2
$protocol eq "http" or $protocol eq "native"
$protocol eq "http" $protocol eq "native"
Truth table66%2/3
A or B
A= $protocol eq "http"B= $protocol eq "native"
ABresult
1X1
011
000
112 unless $protocol eq 'http' || $protocol eq 'native';
113  
114 48 ▶ $port //= ($protocol eq 'native') ? 9000 : 8123;
Branch: 1 branch
BranchTrueFalseTotal
$protocol eq 'native' ? : 0 1 1
Condition100%2/2
$port //= $protocol eq "native" ? 9000 : 8123
l!l
471
MC/DC100%1/1
$port //= $protocol eq "native" ? 9000 : 8123
$port
Truth table100%2/2
A
A= $port
Aresult
11
00
115  
116 # Stringify now: the async-DNS connect reuses these closures after
117 # new() returns, where an overload would run user code against a
118 # live $self. No $self escapes yet, so firing them here is safe.
119 48 $_ = "$_" for ($host, $user, $password, $database);
120 48 $port = 0 + $port;
121  
122 48 ▶ $self->_set_protocol($protocol eq 'native' ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$protocol eq 'native' ? : 26 22 48
123  
124 # Pass-through setters. Skip only when the key was absent — explicit
125 # 0/'' must reach the setter so e.g. `compress => 0` is honored, not
126 # ignored. (Use `exists` rather than `defined` so a deliberate undef
127 # is also passed through and rejected by the setter if invalid.)
128 48 for my $opt (qw(compress tls tls_skip_verify auto_reconnect
129 keepalive reconnect_delay reconnect_max_delay
130 reconnect_jitter reconnect_max_attempts
131 progress_period http_basic_auth
132 connect_timeout query_timeout
133 max_query_size max_recv_buffer)) {
134 720 ▶ next unless exists $args{$opt};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{$opt} 650 70 720
135 70 my $val = delete $args{$opt};
136 70 my $setter = "_set_$opt";
137 70 $self->$setter($val);
138 }
139 48 for my $opt (qw(session_id tls_ca_file tls_cert_file tls_key_file)) {
140 192 ▶ defined(my $val = delete $args{$opt}) or next;
Branch: 1 branch
BranchTrueFalseTotal
defined(my $val = delete $args{$opt}) or next 0 192 192
141 0 my $setter = "_set_$opt";
142 0 $self->$setter($val);
143 }
144  
145 # query_log_comment: 1 = auto-generate "ev_ch user=$ENV{USER} pid=$$";
146 # any other truthy value is taken literally; falsy disables.
147 {
148 48 my $qlc = delete $args{query_log_comment};
149 48 ▶ if ($qlc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($qlc) 0 48 48
150 my $cmt = (!ref($qlc) && "$qlc" ne '1')
151 ? $qlc
152 0 ▶ : sprintf 'ev_ch user=%s pid=%d', $ENV{USER} // 'na', $$;
Branch: 1 branch
BranchTrueFalseTotal
!ref($qlc) && "$qlc" ne '1' ? : 0 0 0
Condition0%0/5
not ref $qlc and "$qlc" ne 1
!ll&&!rl&&r
000
$ENV{"USER"} // "na"
l!l
00
MC/DC0%0/2
not ref $qlc and "$qlc" ne 1
not ref $qlc "$qlc" ne 1
MC/DC0%0/1
$ENV{"USER"} // "na"
$ENV{"USER"}
Truth table0%0/3
not(A) and B
A= not ref $qlcB= "$qlc" ne 1
ABresult
0X0
100
111
Truth table0%0/2
A
A= $ENV{"USER"}
Aresult
11
00
153 0 $cmt =~ s{\*/}{*\\/}g;
154 0 $self->_set_query_log_comment($cmt);
155 }
156 }
157  
158 # decode_flags bitmask (DT_STR=1, DEC_SCALE=2, ENUM_STR=4, NAMED_ROWS=8)
159 my $decode_flags = (delete $args{decode_datetime} ? 1 : 0)
160 | (delete $args{decode_decimal} ? 2 : 0)
161 | (delete $args{decode_enum} ? 4 : 0)
162 48 ▶ | (delete $args{named_rows} ? 8 : 0);
Branch: 4 branches
BranchTrueFalseTotal
delete $args{'decode_datetime'} ? : 0 48 48
delete $args{'decode_decimal'} ? : 0 48 48
delete $args{'decode_enum'} ? : 0 48 48
delete $args{'named_rows'} ? : 0 48 48
163 48 ▶ $self->_set_decode_flags($decode_flags) if $decode_flags;
Branch: 1 branch
BranchTrueFalseTotal
if $decode_flags 0 48 48
164  
165 0 ▶ if (my $settings = delete $args{settings}) { $self->_set_settings($settings) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $settings = delete $args{"settings"}) 0 48 48
166  
167 48 ▶ warn "EV::ClickHouse->new: unknown parameter(s): " . join(', ', sort keys %args) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %args 0 48 48
168 if %args;
169  
170 48 ▶ if ($hosts_list) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hosts_list) 1 47 48
171 1 ▶ $self->_set_failover($hosts_list, $port, $hosts_explicit_port // 0);
Condition50%1/2
$hosts_explicit_port // 0
l!l
01
MC/DC0%0/1
$hosts_explicit_port // 0
$hosts_explicit_port
Truth table50%1/2
A
A= $hosts_explicit_port
Aresult
11
00
172 }
173  
174 # Async DNS via EV::cares when available — non-IP hostnames are
175 # resolved off-loop so the constructor returns immediately and the
176 # main EV loop never blocks on getaddrinfo. Pre-connect-queued
177 # queries fire once the resolved-address connect completes. Falls
178 # back to the XS blocking resolver if EV::cares isn't installed
179 # or the host is already an IP literal.
180 # An IPv6 literal carries 2+ colons; anything else that merely
181 # looks hex ("db", "cache") is a hostname. The old hex-class regex
182 # misclassified those and sent them down the blocking resolver.
183 48 ▶ my $is_literal = $host =~ /^[\d.]+$/ || $host =~ tr/:/:/ > 1;
Condition33%1/3
$host =~ /^[\d.]+$/ || $host =~ tr/:// > 1
l!l&&r!l&&!r
4800
MC/DC0%0/2
$host =~ /^[\d.]+$/ || $host =~ tr/:// > 1
$host =~ /^[\d.]+$/ $host =~ tr/:// > 1
Truth table33%1/3
A || B
A= $host =~ /^[\d.]+$/B= $host =~ tr/:// > 1
ABresult
1X1
011
000
184 0 ▶ if (!$is_literal && eval { require EV::cares; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_literal and eval { do { require EV::cares; 1 } }) { } 0 48 48
Condition33%1/3
not $is_literal and eval { do { require EV::cares; 1 } }
!ll&&!rl&&r
4800
MC/DC0%0/2
not $is_literal and eval { do { require EV::cares; 1 } }
not $is_literal eval { do { require EV::cares; 1 } }
Truth table33%1/3
not(A) and B
A= not $is_literalB= eval { do { require EV::cares; 1 } }
ABresult
0X0
100
111
185 # Stash the resolver in %_failover, keyed by refaddr of the
186 # resolver itself (NOT of $self). Two reasons:
187 # - never delete the resolver from inside its own callback —
188 # ares_destroy from a c-ares cb corrupts the channel heap.
189 # We defer the delete via EV::timer(0,...) so it runs from
190 # a clean stack frame.
191 # - keying by refaddr($self) was racy: A's deferred-delete
192 # could fire after A's struct was freed and B got the same
193 # refaddr, dropping B's resolver. refaddr($r) is unique
194 # while $r is alive in %_failover.
195 0 my $r = EV::cares->new;
196 0 my $key = refaddr($r);
197 0 $_failover{$key} = $r;
198 0 my $weak2 = $self; weaken $weak2;
199 0 $self->_set_conn_params($host, $port, $user, $password, $database);
200 0 $self->_set_dns_pending(1);
201 0 ▶ $r->resolve($host, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
202 0 my ($status, @addrs) = @_;
203 0 ▶ my $w; $w = EV::timer(0, 0, sub { undef $w; delete $_failover{$key} });
Subroutine __ANON__: not called CC=1 SCAR=6.9
204 # Skip if the connection has been DESTROYed or the user
205 # finished it while DNS was in flight (cleanup_connection
206 # clears dns_pending; if it's 0 here, finish ran already).
207 0 ▶ return unless $weak2 && $weak2->_take_dns_pending;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak2 and $weak2->_take_dns_pending 0 0 0
Condition0%0/3
$weak2 and $weak2->_take_dns_pending
!ll&&!rl&&r
000
MC/DC0%0/2
$weak2 and $weak2->_take_dns_pending
$weak2 $weak2->_take_dns_pending
Truth table0%0/3
A and B
A= $weak2B= $weak2->_take_dns_pending
ABresult
0X0
100
111
208 0 ▶ if ($status != 0 || !@addrs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status != 0 or not @addrs) 0 0 0
Condition0%0/3
$status != 0 or not @addrs
l!l&&r!l&&!r
000
MC/DC0%0/2
$status != 0 or not @addrs
$status != 0 not @addrs
Truth table0%0/3
A or not(B)
A= $status != 0B= not @addrs
ABresult
1X1
011
000
209 # Same treatment as a blocking getaddrinfo failure:
210 # failover rotation + auto_reconnect, not a bare error.
211 0 $weak2->_dns_failed("DNS resolution failed for '$host'");
212 0 return;
213 }
214 0 my ($v4) = grep /^[\d.]+$/, @addrs;
215 0 ▶ $weak2->connect($v4 // $addrs[0], $port, $user, $password, $database);
Condition0%0/3
$v4 // $addrs[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$v4 // $addrs[0]
$v4 $addrs[0]
Truth table0%0/3
A // B
A= $v4B= $addrs[0]
ABresult
1X1
011
000
216 0 });
217 } else {
218 48 $self->connect($host, $port, $user, $password, $database);
219 }
220  
221 48 $self;
222 }
223  
224 1 ▶sub _split_host_port {
Subroutine _split_host_port: called CC=4 SCAR=18.7
225 1 my ($entry, $default_port) = @_;
226 1 ▶ if ($entry =~ /^\[([^\]]+)\](?::(\d+))?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry =~ /^\[([^\]]+)\](?::(\d+))?$/) 0 1 1
227 0 ▶ return ($1, $2 // $default_port); # IPv6 literal in brackets
Condition0%0/3
$2 // $default_port
l!l&&r!l&&!r
000
MC/DC0%0/2
$2 // $default_port
$2 $default_port
Truth table0%0/3
A // B
A= $2B= $default_port
ABresult
1X1
011
000
228 }
229 1 ▶ if ($entry =~ /^([^:]+):(\d+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry =~ /^([^:]+):(\d+)$/) 1 0 1
230 1 return ($1, $2);
231 }
232 0 return ($entry, $default_port);
233 }
234  
235 # Pull-based result iterator: $it = $ch->iterate($sql, [\%settings])
236 # while (my $batch = $it->next($timeout)) { ... }
237 # Wraps the native on_data per-block callback in a synchronous-feeling
238 # pull interface for procedural code. The iterator drives the EV loop
239 # from inside ->next until the next block arrives, the query completes,
240 # or the optional timeout (seconds) expires.
241 0 ▶sub iterate {
Subroutine iterate: not called CC=3 SCAR=24.8
Pod documented
242 0 my ($self, $sql, $settings) = @_;
243 0 my $it = bless {
244 ch => $self,
245 batches => [],
246 done => 0,
247 err => undef,
248 }, 'EV::ClickHouse::Iterator';
249 0 ▶ my $on_data = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
250 0 push @{ $it->{batches} }, $_[0];
251 0 EV::break;
252 0 };
253 0 ▶ my %s = $settings ? %$settings : ();
Branch: 1 branch
BranchTrueFalseTotal
$settings ? : 0 0 0
254 # A caller-supplied on_data composes (fires after batch capture)
255 # instead of being overwritten or breaking the iterator.
256 0 my $user_on_data = delete $s{on_data};
257 $s{on_data} = $user_on_data
258 0 ▶ ? sub { $on_data->(@_); $user_on_data->(@_); }
Subroutine __ANON__: not called CC=1 SCAR=6.9
259 0 ▶ : $on_data;
Branch: 1 branch
BranchTrueFalseTotal
$user_on_data ? : 0 0 0
260 0 ▶ $self->query($sql, \%s, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
261 0 my (undef, $err) = @_;
262 0 $it->{done} = 1;
263 0 ▶ $it->{err} = $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
264 0 EV::break;
265 0 });
266 0 $it;
267 }
268  
269 # Streaming insert: $s = $ch->insert_streamer($table, %opts)
270 # $s->push_row([...]); ...; $s->finish(sub { my (undef, $err) = @_ });
271 # Buffers rows in batches of `batch_size` (default 10_000) and dispatches
272 # each batch as an insert(). Dispatches are serialised (the native protocol
273 # cannot pipeline INSERTs); push_row keeps buffering while a batch is in
274 # flight and the next batch fires from the in-flight callback.
275 0 ▶sub insert_streamer {
Subroutine insert_streamer: not called CC=1 SCAR=6.9
Pod documented
276 0 my ($self, $table, %opts) = @_;
277 0 return EV::ClickHouse::Streamer->_new($self, $table, %opts);
278 }
279  
280 # Generator-driven insert. $producer is a code ref returning one row
281 # per call (arrayref or hashref) and undef when exhausted. Rows pump
282 # into an insert_streamer with backpressure: when buffered_count
283 # crosses high_water (default 50_000) the producer is paused until
284 # the streamer drains below the watermark. $cb fires once with
285 # (undef) on success or (undef, $err) on first failure (same shape
286 # as Streamer::finish).
287 0 ▶sub insert_iter {
Subroutine insert_iter: not called CC=5 SCAR=34.0
Pod documented
288 0 my ($self, $table, $producer, $cb, %opts) = @_;
289 0 ▶ die "Usage: \$ch->insert_iter(\$table, \$producer, \$cb, [\%opts])"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $producer eq "CODE" and ref $cb eq "CODE" 0 0 0
Condition0%0/6
defined $table and ref $producer eq "CODE" and ref $cb eq "CODE"
!ll&&!rl&&r
000
defined $table and ref $producer eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $table and ref $producer eq "CODE" and ref $cb eq "CODE"
defined $table ref $producer eq "CODE" ref $cb eq "CODE"
Truth table0%0/4
A and B and C
A= defined $tableB= ref $producer eq "CODE"C= ref $cb eq "CODE"
ABCresult
0XX0
10X0
1100
1111
290 unless defined $table && ref($producer) eq 'CODE' && ref($cb) eq 'CODE';
291 0 ▶ my $hi = $opts{high_water} //= 50_000;
Condition0%0/2
$opts{"high_water"} //= 50000
l!l
00
MC/DC0%0/1
$opts{"high_water"} //= 50000
$opts{"high_water"}
Truth table0%0/2
A
A= $opts{"high_water"}
Aresult
11
00
292 0 my $s = $self->insert_streamer($table, %opts);
293 0 ▶ my $pump; $pump = EV::idle(sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
294 # Abort early on sticky error so we don't keep pumping rows into
295 # a streamer that will never accept them (and that would otherwise
296 # accumulate the buffer indefinitely if the producer is fast).
297 0 ▶ if (my $err = $s->sticky_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $s->sticky_error) 0 0 0
298 0 $pump->stop; undef $pump;
299 0 $s->finish($cb);
300 0 return;
301 }
302 # Backpressure: skip this tick if the buffer is at the watermark.
303 # In-flight batches are handled inside the streamer (push_row keeps
304 # buffering while one is on the wire), so we only gate on buffer
305 # size here. $hi == 0 means the caller disabled backpressure — the
306 # gate must then never fire (>= 0 would be permanently true).
307 0 ▶ return if $hi && $s->buffered_count >= $hi;
Branch: 1 branch
BranchTrueFalseTotal
if $hi and $s->buffered_count >= $hi 0 0 0
Condition0%0/3
$hi and $s->buffered_count >= $hi
!ll&&!rl&&r
000
MC/DC0%0/2
$hi and $s->buffered_count >= $hi
$hi $s->buffered_count >= $hi
Truth table0%0/3
A and B
A= $hiB= $s->buffered_count >= $hi
ABresult
0X0
100
111
308 0 my $row = eval { $producer->() };
309 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
310 0 my $err = $@;
311 0 $pump->stop; undef $pump;
312 0 ▶ $s->{sticky_err} ||= "insert_iter producer died: $err";
Condition0%0/2
$s->{"sticky_err"} ||= "insert_iter producer died: $err"
l!l
00
MC/DC0%0/1
$s->{"sticky_err"} ||= "insert_iter producer died: $err"
$s->{"sticky_err"}
Truth table0%0/2
A
A= $s->{"sticky_err"}
Aresult
11
00
313 0 $s->finish($cb);
314 0 return;
315 }
316 0 ▶ if (defined $row) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $row) { } 0 0 0
317 # push_row croaks on unusable rows (hashref without
318 # columns); a die here would be swallowed by EV and the
319 # pump would finish-success having inserted nothing.
320 0 my $ok = eval { $s->push_row($row); 1 };
321 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok) 0 0 0
322 0 ▶ my $err = $@ || "push_row failed";
Condition0%0/2
$@ || 'push_row failed'
l!l
00
MC/DC0%0/1
$@ || 'push_row failed'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
323 0 $pump->stop; undef $pump;
324 0 ▶ $s->{sticky_err} ||= "insert_iter push_row failed: $err";
Condition0%0/2
$s->{"sticky_err"} ||= "insert_iter push_row failed: $err"
l!l
00
MC/DC0%0/1
$s->{"sticky_err"} ||= "insert_iter push_row failed: $err"
$s->{"sticky_err"}
Truth table0%0/2
A
A= $s->{"sticky_err"}
Aresult
11
00
325 0 $s->finish($cb);
326 0 return;
327 }
328 } else {
329 0 $pump->stop;
330 0 undef $pump;
331 0 $s->finish($cb);
332 }
333 0 });
334 0 return;
335 }
336  
337 # Ergonomic wrapper around server-side async_insert. Defaults to
338 # wait_for_flush => 1 so the callback fires after the asynchronous batch
339 # has been committed, matching the wait_for_async_insert=1 semantics in
340 # clickhouse-server. Set wait_for_flush => 0 for fire-and-forget (the
341 # callback then resolves as soon as the server has accepted the row
342 # into the in-memory async batch).
343 #
344 # $ch->insert_async('events', \@rows, sub {
345 # my (undef, $err) = @_;
346 # die "async insert: $err" if $err;
347 # });
348 1 ▶sub insert_async {
Subroutine insert_async: called CC=8 SCAR=27.7
Pod documented
349 1 my ($self, $table, $data, $cb, %opts) = @_;
350 1 ▶ die "Usage: \$ch->insert_async(\$table, \$data, \$cb, [%opts])"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and defined $data and ref $cb eq "CODE" 0 1 1
Condition33%2/6
defined $table and defined $data and ref $cb eq "CODE"
!ll&&!rl&&r
001
defined $table and defined $data
!ll&&!rl&&r
001
MC/DC0%0/3
defined $table and defined $data and ref $cb eq "CODE"
defined $table defined $data ref $cb eq "CODE"
Truth table25%1/4
A and B and C
A= defined $tableB= defined $dataC= ref $cb eq "CODE"
ABCresult
0XX0
10X0
1100
1111
351 unless defined $table && defined $data && ref($cb) eq 'CODE';
352 1 ▶ my $wait = exists $opts{wait_for_flush} ? delete($opts{wait_for_flush}) : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'wait_for_flush'} ? : 0 1 1
353 1 ▶ my %extra = %{ delete($opts{settings}) // {} };
Condition50%1/2
delete $opts{"settings"} // {}
l!l
01
MC/DC0%0/1
delete $opts{"settings"} // {}
delete $opts{"settings"}
Truth table50%1/2
A
A= delete $opts{"settings"}
Aresult
11
00
354 1 ▶ die "insert_async: unknown option(s): " . join(', ', sort keys %opts) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 0 1
355 if %opts;
356 0 ▶ my %settings = (
Branch: 1 branch
BranchTrueFalseTotal
$wait ? : 0 0 0
357 async_insert => 1,
358 wait_for_async_insert => $wait ? 1 : 0,
359 %extra,
360 );
361 0 $self->insert($table, $data, \%settings, $cb);
362 }
363  
364 # Server-side insert into AggregateFunction columns. Per-aggregator
365 # state binary format isn't replicable client-side, so each per-row
366 # value is wrapped in the ${func}State combinator inside a single-row
367 # select, all union all'd into one insert.
368 0 ▶sub insert_aggregated {
Subroutine insert_aggregated: not called CC=25 SCAR=64.8
Pod documented
369 0 my ($self, $table, %opts) = @_;
370 0 ▶ my $cb = delete $opts{cb} // die "insert_aggregated: cb required";
Condition0%0/2
delete $opts{"cb"} // die("insert_aggregated: cb required")
l!l
00
MC/DC0%0/1
delete $opts{"cb"} // die("insert_aggregated: cb required")
delete $opts{"cb"}
Truth table0%0/2
A
A= delete $opts{"cb"}
Aresult
11
00
371 0 ▶ my $rows = delete $opts{rows} // die "insert_aggregated: rows required";
Condition0%0/2
delete $opts{"rows"} // die("insert_aggregated: rows required")
l!l
00
MC/DC0%0/1
delete $opts{"rows"} // die("insert_aggregated: rows required")
delete $opts{"rows"}
Truth table0%0/2
A
A= delete $opts{"rows"}
Aresult
11
00
372 0 ▶ die "insert_aggregated: cb must be a coderef" if ref($cb) ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $cb ne "CODE" 0 0 0
373 0 ▶ die "insert_aggregated: rows must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
if ref $rows ne "ARRAY" or not @$rows 0 0 0
Condition0%0/3
ref $rows ne "ARRAY" or not @$rows
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $rows ne "ARRAY" or not @$rows
ref $rows ne "ARRAY" not @$rows
Truth table0%0/3
A or not(B)
A= ref $rows ne "ARRAY"B= not @$rows
ABresult
1X1
011
000
374 if ref($rows) ne 'ARRAY' || !@$rows;
375 0 ▶ my $key_cols = delete $opts{key_cols} || [];
Condition0%0/2
delete $opts{'key_cols'} || []
l!l
00
MC/DC0%0/1
delete $opts{'key_cols'} || []
delete $opts{'key_cols'}
Truth table0%0/2
A
A= delete $opts{'key_cols'}
Aresult
11
00
376 0 ▶ die "insert_aggregated: key_cols must be an arrayref"
Branch: 1 branch
BranchTrueFalseTotal
if ref $key_cols ne "ARRAY" 0 0 0
377 if ref($key_cols) ne 'ARRAY';
378 0 my @agg = grep { ref $opts{$_} eq 'HASH' } sort keys %opts;
379 0 ▶ die "insert_aggregated: no aggregate columns specified" unless @agg;
Branch: 1 branch
BranchTrueFalseTotal
unless @agg 0 0 0
380 0 ▶ die "insert_aggregated: invalid table '$table'"
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
381 unless $table =~ $RE_TABLE;
382 0 for my $c (@$key_cols, @agg) {
383 0 ▶ die "insert_aggregated: invalid column '$c'"
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /$RE_IDENT/ 0 0 0
384 unless $c =~ $RE_IDENT;
385 }
386 0 my @agg_meta;
387 0 for my $ac (@agg) {
388 0 my $spec = $opts{$ac};
389 0 ▶ my $func = $spec->{func} // die "insert_aggregated: $ac.func required";
Condition0%0/2
$spec->{"func"} // die("insert_aggregated: $ac.func required")
l!l
00
MC/DC0%0/1
$spec->{"func"} // die("insert_aggregated: $ac.func required")
$spec->{"func"}
Truth table0%0/2
A
A= $spec->{"func"}
Aresult
11
00
390 0 ▶ my $args = $spec->{args} // die "insert_aggregated: $ac.args required";
Condition0%0/2
$spec->{"args"} // die("insert_aggregated: $ac.args required")
l!l
00
MC/DC0%0/1
$spec->{"args"} // die("insert_aggregated: $ac.args required")
$spec->{"args"}
Truth table0%0/2
A
A= $spec->{"args"}
Aresult
11
00
391 0 ▶ die "insert_aggregated: $ac.func must be a simple identifier"
Branch: 1 branch
BranchTrueFalseTotal
unless $func =~ /$RE_IDENT/ 0 0 0
392 unless $func =~ $RE_IDENT;
393 0 for my $t (@$args) {
394 0 ▶ die "insert_aggregated: $ac arg type contains illegal chars"
Branch: 1 branch
BranchTrueFalseTotal
unless $t =~ /\A[A-Za-z0-9_(),\s'=]+\z/ 0 0 0
395 unless $t =~ /\A[A-Za-z0-9_(),\s'=]+\z/;
396 }
397 0 push @agg_meta, { col => $ac, func => $func, types => [@$args] };
398 }
399 0 my $expected_cols = @$key_cols;
400 0 $expected_cols += @{ $_->{types} } for @agg_meta;
401 0 for my $r (@$rows) {
402 0 ▶ die sprintf("insert_aggregated: row width mismatch (got %d, want %d)",
Branch: 1 branch
BranchTrueFalseTotal
if @$r != $expected_cols 0 0 0
403 scalar @$r, $expected_cols)
404 if @$r != $expected_cols;
405 }
406 0 my $col_list = join ', ', @$key_cols, @agg;
407 # VALUES doesn't permit aggregate combinators (treated as non-constant),
408 # so build a UNION ALL of single-row SELECTs.
409 0 my @selects;
410 0 for my $r (@$rows) {
411 0 my $offset = 0;
412 0 my @parts;
413 0 for my $kc (@$key_cols) {
414 0 push @parts, _sql_quote_value($r->[$offset++]) . " as $kc";
415 }
416 0 for my $m (@agg_meta) {
417 0 my @args;
418 0 for my $t (@{ $m->{types} }) {
419 0 push @args, "cast(" . _sql_quote_value($r->[$offset++]) . " as $t)";
420 }
421 0 push @parts, "$m->{func}State(" . join(', ', @args) . ") as $m->{col}";
422 }
423 0 push @selects, "select " . join(', ', @parts);
424 }
425 0 my $sql = "insert into $table ($col_list) " . join(' union all ', @selects);
426 0 $self->query($sql, $cb);
427 }
428  
429 # Minimal SQL literal quoter for insert_aggregated. Numbers go raw,
430 # strings get single-quoted with embedded ' and \ escaped, undef → NULL.
431 0 ▶sub _sql_quote_value {
Subroutine _sql_quote_value: not called CC=4 SCAR=30.0
432 0 my ($v) = @_;
433 0 ▶ return 'null' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
434 0 ▶ die "insert_aggregated: cannot quote a reference (got " . ref($v) . ")"
Branch: 1 branch
BranchTrueFalseTotal
if ref $v 0 0 0
435 if ref $v;
436 0 ▶ return $v if $v =~ /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?\z/ 0 0 0
437 0 my $s = $v;
438 0 $s =~ s/\\/\\\\/g;
439 0 $s =~ s/'/\\'/g;
440 0 return "'$s'";
441 }
442  
443 2 ▶sub kill_query {
Subroutine kill_query: called CC=6 SCAR=24.6
Pod documented
444 2 my ($self, $query_id, $cb, %opts) = @_;
445 2 ▶ die "Usage: \$ch->kill_query(\$query_id, \$cb, [%opts])"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $query_id and ref $cb eq "CODE" 0 2 2
Condition33%1/3
defined $query_id and ref $cb eq "CODE"
!ll&&!rl&&r
002
MC/DC0%0/2
defined $query_id and ref $cb eq "CODE"
defined $query_id ref $cb eq "CODE"
Truth table33%1/3
A and B
A= defined $query_idB= ref $cb eq "CODE"
ABresult
0X0
100
111
446 unless defined $query_id && ref($cb) eq 'CODE';
447 2 ▶ die "kill_query: invalid query_id '$query_id'"
Branch: 1 branch
BranchTrueFalseTotal
unless $query_id =~ m[\A[A-Za-z0-9_.:/-]+\z] 1 1 2
448 unless $query_id =~ /\A[A-Za-z0-9_.:\/-]+\z/;
449 1 ▶ my $mode = delete($opts{async}) ? 'async' : 'sync';
Branch: 1 branch
BranchTrueFalseTotal
delete $opts{'async'} ? : 0 1 1
450 1 ▶ die "kill_query: unknown option(s): " . join(', ', sort keys %opts) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 0 1
451 if %opts;
452 # Newer servers fail with Code 785 "No query to kill" where older ones return no rows.
453 0 ▶ $self->query("kill query where query_id = '$query_id' $mode", sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
454 0 ▶ return $cb->(undef) if defined $_[1] && $_[1] =~ /\bCode: 785\b/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[1] and $_[1] =~ /\bCode: 785\b/ 0 0 0
Condition0%0/3
defined $_[1] and $_[1] =~ /\bCode: 785\b/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $_[1] and $_[1] =~ /\bCode: 785\b/
defined $_[1] $_[1] =~ /\bCode: 785\b/
Truth table0%0/3
A and B
A= defined $_[1]B= $_[1] =~ /\bCode: 785\b/
ABresult
0X0
100
111
455 0 $cb->(@_);
456 0 });
457 }
458  
459 # Per-connection latency tracking. EV::ClickHouse is a blessed scalar
460 # (XS struct pointer) so we can't stash hash slots on it. We keep a
461 # lexical refaddr-keyed map and hold the entry's lifetime via a guard
462 # object stored inside the wrapper closure: when the user replaces
463 # on_query_complete (or XS DESTROY clears it), the closure is freed,
464 # the guard goes out of scope, and the %DUR_STATE entry is reaped.
465 79 my %DUR_STATE;
466 {
467 package EV::ClickHouse::_DurGuard;
468 # During global destruction %DUR_STATE may have already been
469 # reaped; touching it then is undefined.
470 0 ▶ sub DESTROY {
Subroutine DESTROY: not called CC=2 SCAR=17.9
471 0 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 0 0
472 0 delete $DUR_STATE{ ${ $_[0] } };
473 }
474 }
475  
476 79 ▶sub track_query_durations {
Subroutine track_query_durations: not called CC=10 SCAR=46.6
Pod documented
477 0 my ($self, $size) = @_;
478 0 ▶ $size //= 1024;
Condition0%0/2
$size //= 1024
l!l
00
MC/DC0%0/1
$size //= 1024
$size
Truth table0%0/2
A
A= $size
Aresult
11
00
479 0 my $key = refaddr($self);
480 0 ▶ if ($size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($size == 0) 0 0 0
481 0 ▶ if (my $st = delete $DUR_STATE{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $st = delete $DUR_STATE{$key}) 0 0 0
482 # Restore prev only when our wrapper still owns the slot;
483 # a stacked helper installed later keeps its handler.
484 0 my $cur = $self->on_query_complete;
485 $self->on_query_complete($st->{prev}) # undef restores no-handler
486 0 ▶ if $cur && $st->{wrapper} && refaddr($cur) == refaddr($st->{wrapper});
Branch: 1 branch
BranchTrueFalseTotal
if $cur and $st->{"wrapper"} and builtin::refaddr($cur) == builtin::refaddr($st->{"wrapper"}) 0 0 0
Condition0%0/6
$cur and $st->{"wrapper"} and builtin::refaddr($cur) == builtin::refaddr($st->{"wrapper"})
!ll&&!rl&&r
000
$cur and $st->{"wrapper"}
!ll&&!rl&&r
000
MC/DC0%0/3
$cur and $st->{"wrapper"} and builtin::refaddr($cur) == builtin::refaddr($st->{"wrapper"})
$cur $st->{"wrapper"} builtin::refaddr($cur) == builtin::refaddr($st->{"wrapper"})
Truth table0%0/4
A and B and C
A= $curB= $st->{"wrapper"}C= builtin::refaddr($cur) == builtin::refaddr($st->{"wrapper"})
ABCresult
0XX0
10X0
1100
1111
487 }
488 0 return $self;
489 }
490 0 my $st = $DUR_STATE{$key};
491 0 ▶ if (!$st) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $st) { } 0 0 0
492 0 $st = $DUR_STATE{$key} = {
493 size => $size,
494 buf => [],
495 pos => 0,
496 prev => $self->on_query_complete,
497 };
498 0 my $guard = bless \(my $k = $key), 'EV::ClickHouse::_DurGuard';
499 0 my $prev = $st->{prev};
500 0 my $wrapper;
501 0 ▶ $wrapper = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
502 0 ▶ $prev->(@_) if $prev;
Branch: 1 branch
BranchTrueFalseTotal
if $prev 0 0 0
503 # Captured $key (not refaddr at fire time); fetched after
504 # $prev runs so a disable inside $prev isn't resurrected.
505 0 my $ring = $DUR_STATE{$key};
506 0 ▶ if ($ring) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ring) 0 0 0
507 0 my $dur = $_[4];
508 0 ▶ if (defined $dur && $dur >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dur and $dur >= 0) 0 0 0
Condition0%0/3
defined $dur and $dur >= 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $dur and $dur >= 0
defined $dur $dur >= 0
Truth table0%0/3
A and B
A= defined $durB= $dur >= 0
ABresult
0X0
100
111
509 0 ▶ if (@{ $ring->{buf} } < $ring->{size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ring->{'buf'};} < $ring->{'size'}) { } 0 0 0
510 0 push @{ $ring->{buf} }, $dur;
511 } else {
512 0 $ring->{buf}[ $ring->{pos} ] = $dur;
513 0 $ring->{pos} = ($ring->{pos} + 1) % $ring->{size};
514 }
515 }
516 }
517 0 $guard; # keep the guard alive for the closure's lifetime
518 0 };
519 0 $self->on_query_complete($wrapper);
520 # Weak: a strong hold here would pin the guard and leak the
521 # entry past handler replacement (and risk refaddr reuse).
522 0 $st->{wrapper} = $wrapper;
523 0 weaken($st->{wrapper});
524 } else {
525 # Resize: linearize chronological order (oldest at $st->{pos}
526 # once the ring is full), keep the newest min(N, $size) samples.
527 # Plain shift would drop by physical index instead of by age.
528 0 my $buf = $st->{buf};
529 0 ▶ if (@$buf >= $st->{size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$buf >= $st->{"size"}) 0 0 0
530 # Ring full: chronological is buf[pos..end] then buf[0..pos-1].
531 0 my $pos = $st->{pos} % $st->{size};
532 0 @$buf = (@{$buf}[$pos .. $#$buf], @{$buf}[0 .. $pos - 1]);
533 }
534 # Insertion order is now buf[0..n-1] — already chronological.
535 0 ▶ shift @$buf while @$buf > $size;
Branch: 1 branch
BranchTrueFalseTotal
@$buf > $size and do { shift @$buf } 0 0 0
536 0 $st->{size} = $size;
537 # After linearization the oldest item is at index 0. While the
538 # ring is still filling, push appends and pos is ignored; once
539 # full, the next overwrite must target the oldest (index 0).
540 0 $st->{pos} = 0;
541 }
542 0 return $self;
543 }
544  
545 0 ▶sub query_duration_p {
Subroutine query_duration_p: not called CC=6 SCAR=37.4
Pod undocumented
546 0 my ($self, $p) = @_;
547 0 ▶ my $st = $DUR_STATE{ refaddr($self) } or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $st = $DUR_STATE{builtin::refaddr($self)} or return undef 0 0 0
548 0 my @s = sort { $a <=> $b } @{ $st->{buf} };
549 0 ▶ return undef unless @s;
Branch: 1 branch
BranchTrueFalseTotal
unless @s 0 0 0
550 0 ▶ $p //= 0.5;
Condition0%0/2
$p //= "0.5"
l!l
00
MC/DC0%0/1
$p //= "0.5"
$p
Truth table0%0/2
A
A= $p
Aresult
11
00
551 0 ▶ $p = 0 if $p < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $p < 0 0 0 0
552 0 ▶ $p = 1 if $p > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $p > 1 0 0 0
553 0 $s[ int($p * (@s - 1) + 0.5) ];
554 }
555  
556 0 ▶sub query_duration_count {
Subroutine query_duration_count: not called CC=2 SCAR=17.9
Pod undocumented
557 0 ▶ my $st = $DUR_STATE{ refaddr($_[0]) } or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $st = $DUR_STATE{builtin::refaddr($_[0])} or return 0 0 0 0
558 0 scalar @{ $st->{buf} };
559 }
560  
561 # Local in-flight cancel guarded by query_id match. Only triggers
562 # cancel() if the connection's current in-flight query (last_query_id)
563 # matches $query_id, so a race where the intended query has already
564 # finished and a different one is now running can't silently kill the
565 # wrong query. Returns 1 if it cancelled, 0 if the id didn't match.
566 0 ▶sub cancel_by_query_id {
Subroutine cancel_by_query_id: not called CC=7 SCAR=40.3
Pod documented
567 0 my ($self, $query_id) = @_;
568 0 ▶ die "cancel_by_query_id: query_id required" unless defined $query_id && length $query_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $query_id and length $query_id 0 0 0
Condition0%0/3
defined $query_id and length $query_id
!ll&&!rl&&r
000
MC/DC0%0/2
defined $query_id and length $query_id
defined $query_id length $query_id
Truth table0%0/3
A and B
A= defined $query_idB= length $query_id
ABresult
0X0
100
111
569 # last_query_id persists after its query completes, so match only
570 # against a query that is actually in flight right now.
571 0 my $pend = $self->pending_queries;
572 0 my $head = $pend->[0];
573 return 0 unless $head && $head->{state} eq 'in_flight'
574 0 ▶ && defined $head->{query_id} && $head->{query_id} eq $query_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $head and $head->{"state"} eq "in_flight" and defined $head->{"query_id"} and $head->{"query_id"} eq $query_id 0 0 0
Condition0%0/9
$head and $head->{"state"} eq "in_flight" and defined $head->{"query_id"} and $head->{"query_id"} eq $query_id
!ll&&!rl&&r
000
$head and $head->{"state"} eq "in_flight" and defined $head->{"query_id"}
!ll&&!rl&&r
000
$head and $head->{"state"} eq "in_flight"
!ll&&!rl&&r
000
MC/DC0%0/4
$head and $head->{"state"} eq "in_flight" and defined $head->{"query_id"} and $head->{"query_id"} eq $query_id
$head $head->{"state"} eq "in_flight" defined $head->{"query_id"} $head->{"query_id"} eq $query_id
Truth table0%0/5
A and B and C and D
A= $headB= $head->{"state"} eq "in_flight"C= defined $head->{"query_id"}D= $head->{"query_id"} eq $query_id
ABCDresult
0XXX0
10XX0
110X0
11100
11111
575 0 $self->cancel;
576 0 return 1;
577 }
578  
579 # Retry a query over the same connection with exponential backoff,
580 # only on retryable server errors. Falls through to the user's $cb
581 # with the final result (success or last error) — never invokes $cb
582 # more than once. Per-attempt $settings are honored; pass via the
583 # settings => \%hash key.
584 #
585 # $ch->retry("select * from t",
586 # retries => 3, backoff => 0.5, jitter => 0.25,
587 # cb => sub { my ($rows, $err) = @_; ... });
588 0 ▶sub retry {
Subroutine retry: not called CC=7 SCAR=40.3
Pod documented
589 0 my ($self, $sql, %opts) = @_;
590 0 ▶ my $cb = delete $opts{cb} // die "retry: cb required";
Condition0%0/2
delete $opts{"cb"} // die("retry: cb required")
l!l
00
MC/DC0%0/1
delete $opts{"cb"} // die("retry: cb required")
delete $opts{"cb"}
Truth table0%0/2
A
A= delete $opts{"cb"}
Aresult
11
00
591 0 ▶ my $tries = delete $opts{retries} // 3;
Condition0%0/2
delete $opts{"retries"} // 3
l!l
00
MC/DC0%0/1
delete $opts{"retries"} // 3
delete $opts{"retries"}
Truth table0%0/2
A
A= delete $opts{"retries"}
Aresult
11
00
592 0 ▶ my $delay = delete $opts{backoff} // 0.25;
Condition0%0/2
delete $opts{"backoff"} // "0.25"
l!l
00
MC/DC0%0/1
delete $opts{"backoff"} // "0.25"
delete $opts{"backoff"}
Truth table0%0/2
A
A= delete $opts{"backoff"}
Aresult
11
00
593 0 ▶ my $jitter = delete $opts{jitter} // 0;
Condition0%0/2
delete $opts{"jitter"} // 0
l!l
00
MC/DC0%0/1
delete $opts{"jitter"} // 0
delete $opts{"jitter"}
Truth table0%0/2
A
A= delete $opts{"jitter"}
Aresult
11
00
594 0 my $settings = delete $opts{settings};
595 0 ▶ die "retry: cb must be a coderef" if ref($cb) ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $cb ne "CODE" 0 0 0
596 0 ▶ die "retry: unknown option(s): " . join(', ', sort keys %opts) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 0 0
597 if %opts;
598  
599 0 my $attempt = 0;
600 0 my $timer;
601 my $dispatch;
602 0 ▶ $dispatch = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
603 0 $attempt++;
604 0 ▶ my $on_done = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
605 0 my ($rows, $err) = @_;
606 0 ▶ if (!$err || $attempt > $tries
Branch: 1 branch
BranchTrueFalseTotal
if (not $err or $attempt > $tries or not "EV::ClickHouse"->is_retryable_error($self->last_error_code)) 0 0 0
Condition0%0/6
not $err or $attempt > $tries or not "EV::ClickHouse"->is_retryable_error($self->last_error_code)
l!l&&r!l&&!r
000
not $err or $attempt > $tries
l!l&&r!l&&!r
000
MC/DC0%0/3
not $err or $attempt > $tries or not "EV::ClickHouse"->is_retryable_error($self->last_error_code)
not $err $attempt > $tries not "EV::ClickHouse"->is_retryable_error($self->last_error_code)
Truth table0%0/4
not(A) or B or not(C)
A= not $errB= $attempt > $triesC= not "EV::ClickHouse"->is_retryable_error($self->last_error_code)
ABCresult
1XX1
01X1
0011
0000
607 || !EV::ClickHouse->is_retryable_error($self->last_error_code)) {
608 0 undef $dispatch; # collapse the cycle on terminal call
609 0 return $cb->($rows, $err);
610 }
611 0 my $wait = $delay * (2 ** ($attempt - 1));
612 0 ▶ $wait += rand($wait * $jitter) if $jitter > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $jitter > 0 0 0 0
613 0 ▶ $timer = EV::timer($wait, 0, sub { undef $timer; $dispatch->() });
Subroutine __ANON__: not called CC=1 SCAR=6.9
614 0 };
615 # Synchronous query() can croak (e.g. "not connected" if the
616 # connection was finish()d between attempts). Catch and route to
617 # the user cb instead of letting it escape into the event loop.
618 0 my $ok = eval {
619 0 ▶ if ($settings) { $self->query($sql, $settings, $on_done) }
Branch: 1 branch
BranchTrueFalseTotal
if ($settings) { } 0 0 0
620 0 else { $self->query($sql, $on_done) }
621 0 1;
622 };
623 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok) 0 0 0
624 0 ▶ my $e = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
625 0 undef $dispatch;
626 0 $cb->(undef, $e);
627 }
628 0 };
629 0 $dispatch->();
630 0 return;
631 }
632  
633 # Schema introspection: $ch->for_table('db.t', sub { my ($info, $err) = @_; ... })
634 # Delivers { columns => [{name=>..., type=>...}, ...] } or (undef, $err).
635 0 ▶sub for_table {
Subroutine for_table: not called CC=5 SCAR=34.0
Pod documented
636 0 my ($self, $table, $cb) = @_;
637 0 ▶ die "Usage: \$ch->for_table(\$table, \$cb)" unless defined $table && ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $table and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and ref $cb eq "CODE"
defined $table ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $tableB= ref $cb eq "CODE"
ABresult
0X0
100
111
638 0 ▶ die "for_table: invalid table name '$table'"
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
639 unless $table =~ $RE_TABLE;
640 # HTTP needs an explicit FORMAT; native ignores it and returns
641 # typed rows that respect the connection's named_rows setting.
642 0 my $sql = "describe table $table";
643 0 ▶ $sql .= " format TabSeparated" if !$self->server_revision;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->server_revision 0 0 0
644 0 ▶ $self->query($sql, sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
645 0 my ($rows, $err) = @_;
646 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
647 # Connection may be in named_rows mode, in which case each row
648 # is a hashref keyed by the DESCRIBE column names. Handle both.
649 my @cols = map {
650 ref $_ eq 'HASH'
651 ? { name => $_->{name}, type => $_->{type} }
652 0 ▶ : { name => $_->[0], type => $_->[1] };
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
653 0 ▶ } @{ $rows // [] };
Condition0%0/2
$rows // []
l!l
00
MC/DC0%0/1
$rows // []
$rows
Truth table0%0/2
A
A= $rows
Aresult
11
00
654 0 $cb->({ columns => \@cols });
655 0 });
656 }
657  
658 # Functions ClickHouse marks non-deterministic (system.functions has no
659 # such flag before 24.x, so the list is kept here): a DEFAULT calling one
660 # is not a constant.
661 79 my $RE_NONDET_FN = do {
662 79 my @names = qw(
663 UTCTimestamp UTC_timestamp DATABASE FQDN SCHEMA arrayJoin
664 arrayPartialReverseSort arrayPartialShuffle arrayPartialSort
665 arrayRandomSample arrayShuffle assignCentroid authUser
666 authenticatedUser blockNumber blockSerializedSize blockSize buildId
667 connectionId connection_id curdate currentDatabase currentHandler
668 currentProfiles currentQueryID currentRequestURL currentRoles
669 currentSchemas currentUser current_database current_date
670 current_query_id current_schema current_schemas current_setting
671 current_timestamp current_timezone current_user dateTimeToUUIDv7
672 defaultProfiles defaultRoles displayName dumpColumnStructure
673 enabledProfiles enabledRoles file filesystemAvailable
674 filesystemCapacity filesystemUnreserved
675 financialNetPresentValueExtended fullHostName fuzzBits
676 generateRandomStructure generateSerialID generateSnowflakeID
677 generateULID generateUUIDv4 generateUUIDv7 getMacro
678 getMergeTreeSetting getOSKernelVersion getServerPort
679 getServerSetting getSetting getSettingOrDefault hasColumnInTable
680 hostName hostname initialQueryID initialQueryStartTime
681 initial_query_id initial_query_start_time isConstant joinGet
682 joinGetOrNull localtime localtimestamp lowCardinalityIndices
683 lowCardinalityKeys now now64 nowInBlock nowInBlock64 obfuscateQuery
684 pgGetUserById pg_get_userbyid queryID query_id revision
685 rowNumberInAllBlocks rowNumberInBlock runningConcurrency
686 serverTimeZone serverTimezone serverUUID session_user shardCount
687 shardNum showCertificate tcpPort timeZone timezone today
688 toColumnTypeName transactionID unnest uptime user uuid version
689 yesterday zookeeperSessionUptime neighbor url aiClassify aiExtract
690 aiFilter aiGenerate aiRedact aiTranslate
691 );
692 79 my $alt = join '|', map { quotemeta } @names;
693 79 qr/(?<![\w.])(?:$alt|rand\w*|dictGet\w*|dictHas|dictIsIn|timeSeries\w*
694 |naiveBayes\w*|running\w+)\s*\(/xi;
695 };
696  
697 # A backquoted identifier's name: ClickHouse escapes decoded.
698 0 ▶sub _unbackquote {
Subroutine _unbackquote: not called CC=4 SCAR=30.0
699 0 my ($s) = @_;
700 0 ▶ return $s unless $s =~ s/\A`(.*)`\z/$1/s;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ s/\A`(.*)`\z/$1/s 0 0 0
701 0 my %esc = (b => "\b", f => "\f", r => "\r", n => "\n", t => "\t",
702 0 => "\0", a => "\a", v => "\x0b", e => "\e");
703 0 $s =~ s/\\(?:x([0-9A-Fa-f]{2})|(.))/
704 0 ▶ defined $1 ? chr(hex $1) : exists $esc{$2} ? $esc{$2} : $2/gse;
Branch: 2 branches
BranchTrueFalseTotal
defined $1 ? : 0 0 0
exists $esc{$2} ? : 0 0 0
705 0 return $s;
706 }
707  
708 # 1 when a DEFAULT expression references no column and calls nothing
709 # non-deterministic.
710 0 ▶sub _constant_default {
Subroutine _constant_default: not called CC=5 SCAR=34.0
711 0 my ($expr, $cols) = @_;
712 0 (my $code = $expr) =~ s/'(?:[^'\\]|\\.|'')*'/''/gs;
713 0 ▶ return 0 if $code =~ $RE_NONDET_FN;
Branch: 1 branch
BranchTrueFalseTotal
if $code =~ /$RE_NONDET_FN/ 0 0 0
714 0 ▶ while ($code =~ /(`(?:[^`\\]|\\.)*`)|\b([A-Za-z_]\w*)\b(?!\s*\()/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code =~ /(`(?:[^`\\]|\\.)*`)|\b([A-Za-z_]\w*)\b(?!\s*\()/g) 0 0 0
715 0 ▶ return 0 if $cols->{ defined $1 ? _unbackquote($1) : $2 };
Branch: 2 branches
BranchTrueFalseTotal
if $$cols{defined $1 ? _unbackquote($1) : $2} 0 0 0
defined $1 ? : 0 0 0
716 }
717 0 return 1;
718 }
719  
720 # $ch->table_defaults('db.t', sub { my ($defaults, $err) = @_ })
721 # Constant DEFAULTs evaluated by the server, as { column => value } for
722 # insert(..., { defaults => $defaults }).
723 0 ▶sub table_defaults {
Subroutine table_defaults: not called CC=7 SCAR=40.3
Pod documented
724 0 my ($self, $table, $cb) = @_;
725 0 ▶ die "Usage: \$ch->table_defaults(\$table, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $table and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and ref $cb eq "CODE"
defined $table ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $tableB= ref $cb eq "CODE"
ABresult
0X0
100
111
726 unless defined $table && ref($cb) eq 'CODE';
727 0 my $part = qr/`(?:[^`\\]|\\.)+`|[A-Za-z_][A-Za-z0-9_]*/;
728 0 ▶ my ($db, $name) = $table =~ /\A(?:($part)\.)?($part)\z/
Branch: 1 branch
BranchTrueFalseTotal
() = $table =~ /\A(?:($part)\.)?($part)\z/ or die "table_defaults: invalid table name '${table}'" 0 0 0
729 or die "table_defaults: invalid table name '$table'";
730 0 ▶ $db = _unbackquote($db) if defined $db;
Branch: 1 branch
BranchTrueFalseTotal
if defined $db 0 0 0
731 0 $name = _unbackquote($name);
732 0 my $http = !$self->server_revision;
733 # string literals, not query parameters: a parameter value is parsed
734 # as escaped text, so a tab in a name would end it
735 0 ▶ my $lit = sub { "'" . ($_[0] =~ s/([\\'])/\\$1/gr) . "'" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
736 0 ▶ my $sql = "select name, type, default_kind, default_expression"
Branch: 1 branch
BranchTrueFalseTotal
defined $db ? : 0 0 0
737 . " from system.columns where database = "
738 . (defined $db ? $lit->($db) : 'currentDatabase()')
739 . " and table = " . $lit->($name) . " order by position";
740 0 ▶ $sql .= " format TabSeparated" if $http;
Branch: 1 branch
BranchTrueFalseTotal
if $http 0 0 0
741 0 ▶ $self->query($sql, sub {
Subroutine __ANON__: not called CC=11 SCAR=48.8
742 0 my ($rows, $err) = @_;
743 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
744 my @cols = map {
745 ref $_ eq 'HASH'
746 0 ▶ ? [ @$_{qw(name type default_kind default_expression)} ]
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
747 : $_
748 0 ▶ } @{ $rows // [] };
Condition0%0/2
$rows // []
l!l
00
MC/DC0%0/1
$rows // []
$rows
Truth table0%0/2
A
A= $rows
Aresult
11
00
749 0 ▶ return $cb->(undef, "table_defaults: no table '$table'") unless @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 0 0 0
750 0 my %is_col = map { $_->[0] => 1 } @cols;
751 my @want = grep {
752 0 ▶ ($_->[2] // '') eq 'DEFAULT' && length($_->[3] // '')
Condition0%0/13
($_->[2] // '') eq 'DEFAULT' && length($_->[3] // '') && !($_->[1] =~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/) && _constant_default($_->[3], \%is_col)
!ll&&!rl&&r
000
($_->[2] // "") eq "DEFAULT" and length($_->[3] // "") and not $_->[1] =~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/
!ll&&!rl&&r
000
($_->[2] // "") eq "DEFAULT" and length($_->[3] // "")
!ll&&!rl&&r
000
$_->[2] // ""
l!l
00
$_->[3] // ""
l!l
00
MC/DC0%0/4
($_->[2] // '') eq 'DEFAULT' && length($_->[3] // '') && !($_->[1] =~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/) && _constant_default($_->[3], \%is_col)
$_->[2] $_->[3] not $_->[1] =~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/ _constant_default($_->[3], \%is_col)
Truth table0%0/5
A and B and not(C) && D
A= $_->[2]B= $_->[3]C= not $_->[1] =~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/D= _constant_default($_->[3], \%is_col)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
753 && $_->[1] !~ /\A(?:Map|Nested|JSON|Object|Variant|Dynamic)\b/
754 && _constant_default($_->[3], \%is_col)
755 } @cols;
756 0 my %out;
757 0 ▶ my $value = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
758 0 my ($col, $v) = @_;
759 0 ▶ return $v unless defined $v && $col->[1] =~ /\A(?:Array|Tuple)\(/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and $col->[1] =~ /\A(?:Array|Tuple)\(/ 0 0 0
Condition0%0/3
defined $v and $col->[1] =~ /\A(?:Array|Tuple)\(/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $v and $col->[1] =~ /\A(?:Array|Tuple)\(/
defined $v $col->[1] =~ /\A(?:Array|Tuple)\(/
Truth table0%0/3
A and B
A= defined $vB= $col->[1] =~ /\A(?:Array|Tuple)\(/
ABresult
0X0
100
111
760 0 my @lit = EV::ClickHouse::_literal_value($v);
761 0 ▶ return @lit ? $lit[0] : ();
Branch: 1 branch
BranchTrueFalseTotal
@lit ? : 0 0 0
762 0 };
763 0 ▶ my $expr = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
764 0 my ($col) = @_;
765 # Not cast((expr) as T): older servers read ((1, 'a')) as a
766 # tuple of a tuple.
767 0 my $e = "CAST($col->[3], '" . ($col->[1] =~ s/([\\'])/\\$1/gr) . "')";
768 0 ▶ $e = "toUInt8($e)"
Branch: 1 branch
BranchTrueFalseTotal
if $col->[1] =~ /\A(?:Nullable\(|LowCardinality\()*Bool\b/ 0 0 0
769 if $col->[1] =~ /\A(?:Nullable\(|LowCardinality\()*Bool\b/;
770 0 return "toString($e)";
771 0 };
772 # query() croaks synchronously once the connection is gone
773 0 ▶ my $ask = sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
774 0 my ($sql, $done) = @_;
775 0 ▶ $sql .= " format TabSeparated" if $http;
Branch: 1 branch
BranchTrueFalseTotal
if $http 0 0 0
776 0 ▶ eval { $self->query($sql, $done); 1 } or $done->(undef, $@ || 'query failed');
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->query($sql, $done); 1 } } or &$done(undef, $@ || "query failed") 0 0 0
Condition0%0/2
$@ || 'query failed'
l!l
00
MC/DC0%0/1
$@ || 'query failed'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
777 0 };
778 0 my ($one, $evaluated, $last_err) = (undef, 0);
779 0 ▶ $one = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
780 0 my ($i) = @_;
781 0 ▶ if ($i >= @want) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= @want) 0 0 0
782 0 undef $one;
783 0 ▶ return $evaluated ? $cb->(\%out) : $cb->(undef, $last_err);
Branch: 1 branch
BranchTrueFalseTotal
$evaluated ? : 0 0 0
784 }
785 0 ▶ $ask->("select " . $expr->($want[$i]), sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
786 0 my ($r, $e) = @_;
787 0 ▶ if (!$e && $r && @$r) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $e and $r and @$r) { } 0 0 0
Condition0%0/6
not $e and $r and @$r
!ll&&!rl&&r
000
not $e and $r
!ll&&!rl&&r
000
MC/DC0%0/3
not $e and $r and @$r
not $e $r @$r
Truth table0%0/4
not(A) and B and C
A= not $eB= $rC= @$r
ABCresult
0XX0
10X0
1100
1111
788 0 my $row = $r->[0];
789 0 ▶ my ($v) = ref $row eq 'HASH' ? values %$row : @$row;
Branch: 1 branch
BranchTrueFalseTotal
ref $row eq 'HASH' ? : 0 0 0
790 0 my @v = $value->($want[$i], $v);
791 0 ▶ $out{ $want[$i][0] } = $v[0] if @v;
Branch: 1 branch
BranchTrueFalseTotal
if @v 0 0 0
792 0 $evaluated++;
793 } else {
794 0 ▶ $last_err = $e // 'empty result';
Condition0%0/2
$e // "empty result"
l!l
00
MC/DC0%0/1
$e // "empty result"
$e
Truth table0%0/2
A
A= $e
Aresult
11
00
795 }
796 0 $one->($i + 1);
797 0 });
798 0 };
799 0 ▶ unless (@want) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@want) 0 0 0
800 0 undef $one;
801 0 return $cb->(\%out);
802 }
803 $ask->("select "
804 0 ▶ . join(', ', map { $expr->($want[$_]) . " as c$_" } 0 .. $#want), sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
805 0 my ($r, $e) = @_;
806 # One failing expression fails the whole select: evaluate one
807 # at a time, keeping those that work; all failing is an error.
808 0 ▶ return $one->(0) if $e || !$r || !@$r;
Branch: 1 branch
BranchTrueFalseTotal
if $e or not $r or not @$r 0 0 0
Condition0%0/6
$e or not $r or not @$r
l!l&&r!l&&!r
000
$e or not $r
l!l&&r!l&&!r
000
MC/DC0%0/3
$e or not $r or not @$r
$e not $r not @$r
Truth table0%0/4
A or not(B) or not(C)
A= $eB= not $rC= not @$r
ABCresult
1XX1
01X1
0011
0000
809 0 my $row = $r->[0];
810 0 ▶ my @vals = ref $row eq 'HASH' ? @$row{ map { "c$_" } 0 .. $#want } : @$row;
Branch: 1 branch
BranchTrueFalseTotal
ref $row eq 'HASH' ? : 0 0 0
811 0 for my $i (0 .. $#want) {
812 0 my @v = $value->($want[$i], $vals[$i]);
813 0 ▶ $out{ $want[$i][0] } = $v[0] if @v;
Branch: 1 branch
BranchTrueFalseTotal
if @v 0 0 0
814 }
815 0 undef $one;
816 0 $cb->(\%out);
817 0 });
818 0 });
819 }
820  
821 # Discover the dynamic JSON path layout for a JSON/Object('json') column.
822 # Walks the Map(String, String) returned by JSONAllPathsWithTypes, deduped
823 # across the table.
824 0 ▶sub for_json_paths {
Subroutine for_json_paths: not called CC=7 SCAR=40.3
Pod documented
825 0 my ($self, $table, $column, $cb) = @_;
826 0 ▶ die "Usage: \$ch->for_json_paths(\$table, \$column, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and defined $column and ref $cb eq "CODE" 0 0 0
Condition0%0/6
defined $table and defined $column and ref $cb eq "CODE"
!ll&&!rl&&r
000
defined $table and defined $column
!ll&&!rl&&r
000
MC/DC0%0/3
defined $table and defined $column and ref $cb eq "CODE"
defined $table defined $column ref $cb eq "CODE"
Truth table0%0/4
A and B and C
A= defined $tableB= defined $columnC= ref $cb eq "CODE"
ABCresult
0XX0
10X0
1100
1111
827 unless defined $table && defined $column && ref($cb) eq 'CODE';
828 0 ▶ die "for_json_paths: invalid table '$table'"
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
829 unless $table =~ $RE_TABLE;
830 0 ▶ die "for_json_paths: invalid column '$column'"
Branch: 1 branch
BranchTrueFalseTotal
unless $column =~ /$RE_IDENT/ 0 0 0
831 unless $column =~ $RE_IDENT;
832 # Single arrayJoin to avoid Cartesian; reference the alias to look
833 # up the type so each (path, type) pair stays correlated.
834 0 my $sql = "select distinct path, m[path] as type from ("
835 . " select m, arrayJoin(mapKeys(m)) as path"
836 . " from (select JSONAllPathsWithTypes($column) as m from $table)"
837 . ") order by path";
838 # HTTP needs explicit format; native returns typed rows directly.
839 0 ▶ $sql .= " format TabSeparated" if !$self->server_revision;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->server_revision 0 0 0
840 0 ▶ $self->query($sql, sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
841 0 my ($rows, $err) = @_;
842 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
843 # Handle both arrayref and named_rows hashref shapes — same idiom
844 # as for_table.
845 $cb->([ map {
846 ref $_ eq 'HASH'
847 ? { path => $_->{path}, type => $_->{type} }
848 0 ▶ : { path => $_->[0], type => $_->[1] }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'HASH' ? : 0 0 0
849 0 ▶ } @{ $rows // [] } ]);
Condition0%0/2
$rows // []
l!l
00
MC/DC0%0/1
$rows // []
$rows
Truth table0%0/2
A
A= $rows
Aresult
11
00
850 0 });
851 }
852  
853 # is_healthy: ping with a deadline. Callback receives (1, undef) on
854 # success or (0, $err_msg) on timeout or ping error. The connection
855 # itself isn't disturbed - failure does not call finish/reset; the
856 # caller decides recovery.
857 1 ▶sub is_healthy {
Subroutine is_healthy: called CC=5 SCAR=20.6
Pod documented
858 1 my ($self, $cb, $timeout) = @_;
859 1 ▶ die "Usage: \$ch->is_healthy(\$cb, [\$timeout])" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 1 1
860 1 ▶ $timeout //= 5;
Condition50%1/2
$timeout //= 5
l!l
01
MC/DC0%0/1
$timeout //= 5
$timeout
Truth table50%1/2
A
A= $timeout
Aresult
11
00
861 1 my $done = 0;
862 1 EV::now_update();
863 0 ▶ my $t = EV::timer($timeout, 0, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
864 0 ▶ return if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 0 0 0
865 0 $done = 1;
866 0 $cb->(0, "health check timeout after ${timeout}s");
867 1 });
868 1 my $sent = eval {
869 0 ▶ $self->ping(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
870 0 ▶ return if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 0 0 0
871 0 $done = 1;
872 0 undef $t;
873 0 my (undef, $err) = @_;
874 0 $cb->(!$err, $err);
875 1 });
876 0 1;
877 };
878 1 ▶ if (!$sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sent) 1 0 1
879 1 ▶ my $e = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
880 1 $done = 1;
881 1 undef $t;
882 1 $cb->(0, $e);
883 }
884 1 return;
885 }
886  
887 # Single PING + measure wall-clock latency. Callback receives
888 # ($seconds, undef) on success or (undef, $err) on failure.
889 # Cheaper than installing track_query_durations for a one-shot probe.
890 1 ▶sub ping_round_trip {
Subroutine ping_round_trip: called CC=4 SCAR=16.6
Pod documented
891 1 my ($self, $cb) = @_;
892 1 ▶ die "Usage: \$ch->ping_round_trip(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 1 1
893 1 my $start = EV::time();
894 1 my $sent = eval {
895 0 ▶ $self->ping(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
896 0 my (undef, $err) = @_;
897 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
898 0 $cb->(EV::time() - $start, undef);
899 1 });
900 0 1;
901 };
902 1 ▶ if (!$sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sent) 1 0 1
903 1 ▶ my $e = $@ || 'unknown error';
Condition50%1/2
$@ || 'unknown error'
l!l
10
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
904 1 $cb->(undef, $e);
905 }
906 1 return;
907 }
908  
909 # Filter callback that fires only when a query exceeds $threshold
910 # seconds. Installs an on_query_complete observer that composes with
911 # any existing handler. Returns the previous on_query_complete so the
912 # caller can restore it later.
913 0 ▶sub slow_query_log {
Subroutine slow_query_log: not called CC=4 SCAR=30.0
Pod documented
914 0 my ($self, $threshold, $cb) = @_;
915 0 ▶ die "Usage: \$ch->slow_query_log(\$threshold, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $threshold and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $threshold and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $threshold and ref $cb eq "CODE"
defined $threshold ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $thresholdB= ref $cb eq "CODE"
ABresult
0X0
100
111
916 unless defined $threshold && ref($cb) eq 'CODE';
917 0 ▶ die "slow_query_log: threshold must be a number"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($threshold) 0 0 0
918 unless looks_like_number($threshold);
919 0 my $prev = $self->on_query_complete;
920 0 ▶ $self->on_query_complete(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
921 # on_query_complete args: ($query_id, $rows, $bytes, $code, $dur, $err)
922 0 my $dur = $_[4];
923 0 ▶ $cb->(@_) if defined $dur && $dur >= $threshold;
Branch: 1 branch
BranchTrueFalseTotal
if defined $dur and $dur >= $threshold 0 0 0
Condition0%0/3
defined $dur and $dur >= $threshold
!ll&&!rl&&r
000
MC/DC0%0/2
defined $dur and $dur >= $threshold
defined $dur $dur >= $threshold
Truth table0%0/3
A and B
A= defined $durB= $dur >= $threshold
ABresult
0X0
100
111
924 0 ▶ $prev->(@_) if $prev;
Branch: 1 branch
BranchTrueFalseTotal
if $prev 0 0 0
925 0 });
926 0 return $prev;
927 }
928  
929 # First-row cell access that tolerates named_rows hashrefs (native)
930 # as well as plain arrayref rows. $key is the column name used when
931 # the row is a hashref; $col the position otherwise.
932 0 ▶sub _cell {
Subroutine _cell: not called CC=4 SCAR=30.0
933 0 my ($rows, $col, $key) = @_;
934 0 ▶ return undef unless $rows && @$rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows and @$rows 0 0 0
Condition0%0/3
$rows and @$rows
!ll&&!rl&&r
000
MC/DC0%0/2
$rows and @$rows
$rows @$rows
Truth table0%0/3
A and B
A= $rowsB= @$rows
ABresult
0X0
100
111
935 0 my $r = $rows->[0];
936 0 ▶ return ref $r eq 'HASH' ? $r->{$key} : $r->[$col];
Branch: 1 branch
BranchTrueFalseTotal
ref $r eq 'HASH' ? : 0 0 0
937 }
938  
939 # Fetch one value from system.settings. Identifier-safe ($name is
940 # validated; the lookup uses parameter binding so a bad name produces
941 # a server-side error rather than SQL injection).
942 0 ▶sub server_setting {
Subroutine server_setting: not called CC=4 SCAR=30.0
Pod documented
943 0 my ($self, $name, $cb) = @_;
944 0 ▶ die "Usage: \$ch->server_setting(\$name, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $name and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and ref $cb eq "CODE"
defined $name ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $nameB= ref $cb eq "CODE"
ABresult
0X0
100
111
945 unless defined $name && ref($cb) eq 'CODE';
946 0 ▶ die "server_setting: invalid setting name '$name'"
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$RE_IDENT/ 0 0 0
947 unless $name =~ $RE_IDENT;
948 $self->query(
949 "select value from system.settings where name = {n:String}",
950 { params => { n => $name } },
951 0 ▶ sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
952 0 my ($rows, $err) = @_;
953 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
954 0 $cb->(_cell($rows, 0, 'value'));
955 },
956 0 );
957 }
958  
959 # Count rows in a table, optionally with a server-side WHERE filter.
960 # $where is interpolated literally so the caller is responsible for
961 # its safety (use parameterized queries via settings.params for
962 # user-supplied predicates). Returns the integer count or (undef, $err).
963 0 ▶sub row_count {
Subroutine row_count: not called CC=7 SCAR=40.3
Pod documented
964 0 my ($self, $table, $where, $cb) = @_;
965 0 ▶ ($where, $cb) = (undef, $where) if ref($where) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $where eq "CODE" 0 0 0
966 0 ▶ die "Usage: \$ch->row_count(\$table, [\$where], \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $table and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and ref $cb eq "CODE"
defined $table ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $tableB= ref $cb eq "CODE"
ABresult
0X0
100
111
967 unless defined $table && ref($cb) eq 'CODE';
968 0 ▶ die "row_count: invalid table '$table'" unless $table =~ $RE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
969 0 my $tbl = EV::ClickHouse->bind_ident($table);
970 0 my $sql = "select count() from $tbl";
971 0 ▶ $sql .= " where $where" if defined $where && length $where;
Branch: 1 branch
BranchTrueFalseTotal
if defined $where and length $where 0 0 0
Condition0%0/3
defined $where and length $where
!ll&&!rl&&r
000
MC/DC0%0/2
defined $where and length $where
defined $where length $where
Truth table0%0/3
A and B
A= defined $whereB= length $where
ABresult
0X0
100
111
972 0 ▶ $self->query($sql, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
973 0 my ($rows, $err) = @_;
974 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
975 0 ▶ $cb->(_cell($rows, 0, 'count()') // 0);
Condition0%0/2
_cell($rows, 0, "count()") // 0
l!l
00
MC/DC0%0/1
_cell($rows, 0, "count()") // 0
_cell($rows, 0, "count()")
Truth table0%0/2
A
A= _cell($rows, 0, "count()")
Aresult
11
00
976 0 });
977 }
978  
979 # Approx on-disk + uncompressed sizes from system.parts. Returns
980 # { rows => N, bytes_on_disk => N, data_uncompressed_bytes => N }.
981 0 ▶sub table_size {
Subroutine table_size: not called CC=7 SCAR=40.3
Pod documented
982 0 my ($self, $table, $cb) = @_;
983 0 ▶ die "Usage: \$ch->table_size(\$table, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $table and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and ref $cb eq "CODE"
defined $table ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $tableB= ref $cb eq "CODE"
ABresult
0X0
100
111
984 unless defined $table && ref($cb) eq 'CODE';
985 0 ▶ die "table_size: invalid table '$table'" unless $table =~ $RE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
986 0 ▶ my ($db, $name) = $table =~ /\./ ? split(/\./, $table, 2)
Branch: 1 branch
BranchTrueFalseTotal
$table =~ /\./ ? : 0 0 0
987 : (undef, $table);
988 0 ▶ my $sql = "select sum(rows), sum(bytes_on_disk),"
Branch: 1 branch
BranchTrueFalseTotal
defined $db ? : 0 0 0
989 . " sum(data_uncompressed_bytes)"
990 . " from system.parts where active and table = {t:String}"
991 . (defined $db ? " and database = {d:String}" : "");
992 $self->query($sql, {
993 params => {
994 t => $name,
995 (defined $db ? (d => $db) : ()),
996 },
997 0 ▶ }, sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
998 0 my ($rows, $err) = @_;
999 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
1000 0 ▶ $cb->({
Condition0%0/6
_cell($rows, 0, "sum(rows)") // 0
l!l
00
_cell($rows, 1, "sum(bytes_on_disk)") // 0
l!l
00
_cell($rows, 2, "sum(data_uncompressed_bytes)") // 0
l!l
00
MC/DC0%0/1
_cell($rows, 0, "sum(rows)") // 0
_cell($rows, 0, "sum(rows)")
MC/DC0%0/1
_cell($rows, 1, "sum(bytes_on_disk)") // 0
_cell($rows, 1, "sum(bytes_on_disk)")
MC/DC0%0/1
_cell($rows, 2, "sum(data_uncompressed_bytes)") // 0
_cell($rows, 2, "sum(data_uncompressed_bytes)")
Truth table0%0/2
A
A= _cell($rows, 0, "sum(rows)")
Aresult
11
00
Truth table0%0/2
A
A= _cell($rows, 1, "sum(bytes_on_disk)")
Aresult
11
00
Truth table0%0/2
A
A= _cell($rows, 2, "sum(data_uncompressed_bytes)")
Aresult
11
00
1001 rows => _cell($rows, 0, 'sum(rows)') // 0,
1002 bytes_on_disk => _cell($rows, 1, 'sum(bytes_on_disk)') // 0,
1003 data_uncompressed_bytes => _cell($rows, 2, 'sum(data_uncompressed_bytes)') // 0,
1004 });
1005 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
defined $db ? : 0 0 0
1006 }
1007  
1008 # SYSTEM RELOAD DICTIONARY shortcut. Validates the dictionary name.
1009 0 ▶sub dictionary_reload {
Subroutine dictionary_reload: not called CC=4 SCAR=30.0
Pod documented
1010 0 my ($self, $name, $cb) = @_;
1011 0 ▶ die "Usage: \$ch->dictionary_reload(\$name, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $name and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and ref $cb eq "CODE"
defined $name ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $nameB= ref $cb eq "CODE"
ABresult
0X0
100
111
1012 unless defined $name && ref($cb) eq 'CODE';
1013 0 ▶ die "dictionary_reload: invalid name '$name'" unless $name =~ $RE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$RE_TABLE/ 0 0 0
1014 0 $self->query("system reload dictionary " . EV::ClickHouse->bind_ident($name),
1015 $cb);
1016 }
1017  
1018 # REFRESH MATERIALIZED VIEW (server >= 23.12). Validates the view name.
1019 0 ▶sub refresh_view {
Subroutine refresh_view: not called CC=4 SCAR=30.0
Pod documented
1020 0 my ($self, $name, $cb) = @_;
1021 0 ▶ die "Usage: \$ch->refresh_view(\$name, \$cb)"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $name and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and ref $cb eq "CODE"
defined $name ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $nameB= ref $cb eq "CODE"
ABresult
0X0
100
111
1022 unless defined $name && ref($cb) eq 'CODE';
1023 0 ▶ die "refresh_view: invalid name '$name'" unless $name =~ $RE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$RE_TABLE/ 0 0 0
1024 0 $self->query("system refresh view " . EV::ClickHouse->bind_ident($name),
1025 $cb);
1026 }
1027  
1028 # Poll system.mutations until a table's incomplete mutations finish.
1029 # ALTER ... UPDATE/DELETE is asynchronous; this resolves once the
1030 # mutation(s) reach is_done=1. $cb->({ pending => 0 }) on success,
1031 # $cb->(undef, $err) on a failed mutation / query error / timeout.
1032 # poll => seconds between polls (default 1)
1033 # timeout => give up after N seconds (optional)
1034 # mutation_id => wait only for this specific mutation (optional)
1035 0 ▶sub wait_mutation {
Subroutine wait_mutation: not called CC=11 SCAR=48.8
Pod documented
1036 0 my ($self, $table, $cb, %opts) = @_;
1037 0 ▶ die "Usage: \$ch->wait_mutation(\$table, \$cb, [%opts])"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $cb eq "CODE" 0 0 0
Condition0%0/3
defined $table and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $table and ref $cb eq "CODE"
defined $table ref $cb eq "CODE"
Truth table0%0/3
A and B
A= defined $tableB= ref $cb eq "CODE"
ABresult
0X0
100
111
1038 unless defined $table && ref($cb) eq 'CODE';
1039 0 ▶ die "wait_mutation: invalid table '$table'" unless $table =~ $RE_TABLE;
Branch: 1 branch
BranchTrueFalseTotal
unless $table =~ /$RE_TABLE/ 0 0 0
1040 0 ▶ my $poll = delete $opts{poll} // 1; # defined-or: an explicit poll => 0 is honored
Condition0%0/2
delete $opts{"poll"} // 1
l!l
00
MC/DC0%0/1
delete $opts{"poll"} // 1
delete $opts{"poll"}
Truth table0%0/2
A
A= delete $opts{"poll"}
Aresult
11
00
1041 0 my $timeout = delete $opts{timeout};
1042 0 my $mid = delete $opts{mutation_id};
1043 0 ▶ die "wait_mutation: unknown option(s): " . join(', ', sort keys %opts) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 0 0
1044 if %opts;
1045 0 ▶ my ($db, $name) = $table =~ /\./ ? split(/\./, $table, 2) : (undef, $table);
Branch: 1 branch
BranchTrueFalseTotal
$table =~ /\./ ? : 0 0 0
1046  
1047 # A mutation that keeps failing stays is_done=0 with latest_fail_reason
1048 # set, so filtering on is_done=0 surfaces both running and failing ones.
1049 0 ▶ my $sql = "select count() as pending,"
Branch: 2 branches
BranchTrueFalseTotal
defined $db ? : 0 0 0
defined $mid ? : 0 0 0
1050 . " anyIf(latest_fail_reason, latest_fail_reason != '') as fail"
1051 . " from system.mutations"
1052 . " where table = {t:String} and is_done = 0"
1053 . (defined $db ? " and database = {d:String}" : "")
1054 . (defined $mid ? " and mutation_id = {m:String}" : "");
1055 0 my %params = (t => $name);
1056 0 ▶ $params{d} = $db if defined $db;
Branch: 1 branch
BranchTrueFalseTotal
if defined $db 0 0 0
1057 0 ▶ $params{m} = $mid if defined $mid;
Branch: 1 branch
BranchTrueFalseTotal
if defined $mid 0 0 0
1058  
1059 0 my $started = EV::time();
1060 0 my $fail_streak = 0; # consecutive polls that saw a fail reason
1061 0 my $timer; my $poll_once;
1062 0 ▶ $poll_once = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1063 # query() can croak synchronously (e.g. "not connected" if the
1064 # connection was finished between polls); route that to $cb
1065 # instead of letting it escape into the event loop.
1066 0 my $ok = eval {
1067 0 ▶ $self->query($sql, { params => \%params }, sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
1068 0 my ($rows, $err) = @_;
1069 0 ▶ if ($err) { undef $poll_once; return $cb->(undef, $err) }
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1070 0 ▶ my $pending = _cell($rows, 0, 'pending') // 0;
Condition0%0/2
_cell($rows, 0, "pending") // 0
l!l
00
MC/DC0%0/1
_cell($rows, 0, "pending") // 0
_cell($rows, 0, "pending")
Truth table0%0/2
A
A= _cell($rows, 0, "pending")
Aresult
11
00
1071 0 my $fail = _cell($rows, 1, 'fail');
1072 # Require a fail reason to persist across polls: a single
1073 # transient latest_fail_reason can clear on the mutation's
1074 # next retry, so one sighting is not a terminal failure.
1075 0 ▶ if (defined $fail && length $fail) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fail and length $fail) { } 0 0 0
Condition0%0/3
defined $fail and length $fail
!ll&&!rl&&r
000
MC/DC0%0/2
defined $fail and length $fail
defined $fail length $fail
Truth table0%0/3
A and B
A= defined $failB= length $fail
ABresult
0X0
100
111
1076 0 ▶ if (++$fail_streak >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (++$fail_streak >= 2) 0 0 0
1077 0 undef $poll_once;
1078 0 return $cb->(undef, "wait_mutation: $fail");
1079 }
1080 } else {
1081 0 $fail_streak = 0;
1082 }
1083 0 ▶ if (!$pending) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pending) 0 0 0
1084 0 undef $poll_once;
1085 0 return $cb->({ pending => 0 });
1086 }
1087 0 ▶ if (defined $timeout && EV::time() - $started >= $timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout and &EV::time() - $started >= $timeout) 0 0 0
Condition0%0/3
defined $timeout and &EV::time() - $started >= $timeout
!ll&&!rl&&r
000
MC/DC0%0/2
defined $timeout and &EV::time() - $started >= $timeout
defined $timeout &EV::time() - $started >= $timeout
Truth table0%0/3
A and B
A= defined $timeoutB= &EV::time() - $started >= $timeout
ABresult
0X0
100
111
1088 0 undef $poll_once;
1089 0 return $cb->(undef,
1090 "wait_mutation: timed out after ${timeout}s");
1091 }
1092 0 ▶ $timer = EV::timer($poll, 0, sub { undef $timer; $poll_once->() });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1093 0 });
1094 0 1;
1095 };
1096 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ok) 0 0 0
1097 0 ▶ my $e = $@ || 'unknown error';
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1098 0 undef $poll_once;
1099 0 $cb->(undef, $e);
1100 }
1101 0 };
1102 0 $poll_once->();
1103 0 return;
1104 }
1105  
1106 # Parse a clickhouse[+native]:// URI into a hash without opening a
1107 # connection. Lets tooling validate user-supplied URIs ahead of
1108 # instantiation. Returns undef on a malformed URI.
1109 3 ▶sub parse_uri {
Subroutine parse_uri: called CC=14 SCAR=27.8
Pod documented
1110 3 my ($class, $uri) = @_;
1111 3 ▶ return undef unless defined $uri;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $uri 0 3 3
1112 3 ▶ return undef unless $uri =~ m{
Branch: 1 branch
BranchTrueFalseTotal
unless $uri =~ m( ^clickhouse(?:\+(\w+))?:// (?:([^:\@]*?)(?::([^/]*))?\@)? (\[[^\]]+\]|[^/:?]+) (?::(\d+))? (?:/([^?]*))? (?:\?(.*))?$ )x 0 3 3
1113 ^clickhouse(?:\+(\w+))?://
1114 (?:([^:@]*?)(?::([^/]*))?\@)?
1115 (\[[^\]]+\]|[^/:?]+)
1116 (?::(\d+))?
1117 (?:/([^?]*))?
1118 (?:\?(.*))?$
1119 }x;
1120 3 my ($proto, $user, $pass, $host, $port, $db, $qs) =
1121 ($1, $2, $3, $4, $5, $6, $7);
1122 return undef
1123 3 ▶ if defined $proto && $proto !~ /^(?:http|native)$/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $proto and not $proto =~ /^(?:http|native)$/ 1 2 3
Condition100%3/3
defined $proto and not $proto =~ /^(?:http|native)$/
!ll&&!rl&&r
111
MC/DC100%2/2
defined $proto and not $proto =~ /^(?:http|native)$/
defined $proto not $proto =~ /^(?:http|native)$/
Truth table100%3/3
A and not(B)
A= defined $protoB= not $proto =~ /^(?:http|native)$/
ABresult
0X0
100
111
1124 2 $host =~ s/^\[(.*)\]$/$1/;
1125 2 my %out = (host => $host);
1126 2 ▶ $out{protocol} = $proto if defined $proto;
Branch: 1 branch
BranchTrueFalseTotal
if defined $proto 1 1 2
1127 2 ▶ $out{user} = _uri_unescape($user) if defined $user && $user ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $user and $user ne "" 0 2 2
Condition33%1/3
defined $user and $user ne ""
!ll&&!rl&&r
200
MC/DC0%0/2
defined $user and $user ne ""
defined $user $user ne ""
Truth table33%1/3
A and B
A= defined $userB= $user ne ""
ABresult
0X0
100
111
1128 2 ▶ $out{password} = _uri_unescape($pass) if defined $pass;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pass 0 2 2
1129 2 ▶ $out{port} = $port + 0 if defined $port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 1 1 2
1130 2 ▶ $out{database} = _uri_unescape($db) if defined $db && $db ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $db and $db ne "" 2 0 2
Condition33%1/3
defined $db and $db ne ""
!ll&&!rl&&r
002
MC/DC0%0/2
defined $db and $db ne ""
defined $db $db ne ""
Truth table33%1/3
A and B
A= defined $dbB= $db ne ""
ABresult
0X0
100
111
1131 # Query-string keys land at the top level (path-derived host/port/etc
1132 # win on collision) so the resulting hash can be passed verbatim to new().
1133 2 _uri_qs_into($qs, \%out);
1134 2 ▶ $out{protocol} //= 'http'; # apply default after QS merge
Condition50%1/2
$out{"protocol"} //= "http"
l!l
20
MC/DC0%0/1
$out{"protocol"} //= "http"
$out{"protocol"}
Truth table50%1/2
A
A= $out{"protocol"}
Aresult
11
00
1135 2 ▶ return undef unless $out{protocol} =~ /^(?:http|native)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $out{"protocol"} =~ /^(?:http|native)$/ 1 1 2
1136 1 return \%out;
1137 }
1138  
1139 # is_retryable_error($code) -> bool. Class method (no $self required).
1140 # Identifies the common transient ClickHouse error codes that warrant
1141 # an automatic retry. Source: ClickHouse src/Common/ErrorCodes.cpp.
1142 79 my %RETRYABLE = map { $_ => 1 } (
1143 159, # TIMEOUT_EXCEEDED
1144 202, # TOO_MANY_SIMULTANEOUS_QUERIES
1145 203, # NO_FREE_CONNECTION
1146 209, # SOCKET_TIMEOUT
1147 210, # NETWORK_ERROR
1148 241, # MEMORY_LIMIT_EXCEEDED (often transient under contention)
1149 242, # TABLE_IS_READ_ONLY (replica catching up)
1150 252, # TOO_MANY_PARTS (merge backlog, retry after backoff)
1151 285, # TOO_FEW_LIVE_REPLICAS
1152 319, # UNKNOWN_STATUS_OF_INSERT (idempotent insert salvages this)
1153 373, # SESSION_IS_LOCKED
1154 # NB: deliberately NOT including 394 (QUERY_WAS_CANCELLED). A
1155 # cancellation expresses caller intent; auto-retrying would loop
1156 # and burn server resources for no benefit.
1157 439, # CANNOT_SCHEDULE_TASK
1158 999, # KEEPER_EXCEPTION
1159 );
1160 0 ▶sub is_retryable_error {
Subroutine is_retryable_error: not called CC=3 SCAR=24.8
Pod documented
1161 0 my ($self_or_class, $code) = @_;
1162 0 ▶ return 0 unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 0 0 0
1163 0 ▶ $RETRYABLE{ $code + 0 } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$RETRYABLE{$code + 0} ? : 0 0 0
1164 }
1165  
1166 # bind_ident($name) -> backtick-quoted identifier safe for SQL splicing.
1167 # ClickHouse identifier rules: alnum + _, no leading digit, optional
1168 # dotted form ("db.table"). We accept that subset, croak otherwise.
1169 # The $RE_IDENT validation rejects backticks outright, so the quoter
1170 # can just wrap each part without escaping.
1171 0 ▶sub bind_ident {
Subroutine bind_ident: not called CC=7 SCAR=40.3
Pod documented
1172 0 my ($self_or_class, $name) = @_;
1173 0 ▶ die "bind_ident: identifier must be defined and non-empty"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 0 0
Condition0%0/3
defined $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table0%0/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1174 unless defined $name && length $name;
1175 0 my @parts = split /\./, $name, -1;
1176 0 ▶ die "bind_ident: expected 'table' or 'db.table', got '$name'"
Branch: 1 branch
BranchTrueFalseTotal
if @parts > 2 0 0 0
1177 if @parts > 2;
1178 die "bind_ident: empty component in '$name'"
1179 0 ▶ if grep { !length } @parts;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not length $_;} @parts 0 0 0
1180 0 for my $p (@parts) {
1181 0 ▶ die "bind_ident: invalid identifier component '$p' in '$name'"
Branch: 1 branch
BranchTrueFalseTotal
unless $p =~ /$RE_IDENT/ 0 0 0
1182 unless $p =~ $RE_IDENT;
1183 }
1184 0 join '.', map { "`$_`" } @parts;
1185 }
1186  
1187 # Capability table: feature name → minimum native server revision.
1188 # Lets user code branch cleanly on protocol features instead of
1189 # hard-coding numeric revisions all over the place. HTTP connections
1190 # have no protocol revision (server_revision == 0), so server_supports
1191 # returns false for any non-trivial feature on HTTP - by design.
1192 79 my %FEATURES = (
1193 block_info => 51903, # DBMS_MIN_REVISION_WITH_BLOCK_INFO
1194 server_display_name => 54372,
1195 version_patch => 54401,
1196 progress_writes => 54420,
1197 server_timezone => 54423,
1198 addendum => 54458,
1199 );
1200 0 ▶sub server_supports {
Subroutine server_supports: not called CC=5 SCAR=34.0
Pod documented
1201 0 my ($self, $feature) = @_;
1202 0 ▶ return 0 unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 0 0
1203 0 ▶ return 0 unless defined $feature;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $feature 0 0 0
1204 0 my $required = $FEATURES{$feature};
1205 0 ▶ return 0 unless defined $required;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $required 0 0 0
1206 0 ▶ my $have = $self->server_revision or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $have = $self->server_revision or return 0 0 0 0
1207 0 $have >= $required;
1208 }
1209  
1210 package EV::ClickHouse::Streamer;
1211  
1212 0 ▶sub _new {
Subroutine _new: not called CC=11 SCAR=48.8
1213 0 my ($class, $ch, $table, %opts) = @_;
1214 # `columns => [@names]` enables named-row mode: push_row({}) hashes
1215 # are reordered into arrayref by the streamer instead of the caller
1216 # having to know column position. `named => 1` is a tolerated alias
1217 # but `columns` is what actually drives the lookup.
1218 0 my %known = map { $_ => 1 }
1219 qw(columns named settings batch_size on_batch_error high_water
1220 on_high_water low_water);
1221 die "insert_streamer: unknown option(s): "
1222 0 . join(', ', sort grep { !$known{$_} } keys %opts) . "\n"
1223 0 ▶ if grep { !$known{$_} } keys %opts;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $known{$_};} keys %opts 0 0 0
1224 0 my $columns = $opts{columns};
1225 0 ▶ die "insert_streamer: columns must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
if defined $columns and ref $columns ne "ARRAY" || !@$columns 0 0 0
Condition0%0/6
defined $columns and ref $columns ne "ARRAY" || !@$columns
!ll&&!rl&&r
000
ref $columns ne "ARRAY" or not @$columns
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $columns and ref $columns ne "ARRAY" || !@$columns
defined $columns ref $columns ne "ARRAY" not @$columns
Truth table0%0/4
A and B or not(C)
A= defined $columnsB= ref $columns ne "ARRAY"C= not @$columns
ABCresult
0XX0
1000
11X1
1011
1226 if defined $columns && (ref($columns) ne 'ARRAY' || !@$columns);
1227 bless {
1228 ch => $ch,
1229 table => $table,
1230 settings => $opts{settings}, # per-insert hashref
1231 batch_size => $opts{batch_size} || 10_000,
1232 0 ▶ on_batch_error => $opts{on_batch_error} || sub { }, # per-failure cb
Subroutine __ANON__: not called CC=1 SCAR=0.0
1233 high_water => $opts{high_water} || 0, # 0 = disabled
1234 0 ▶ on_high_water => $opts{on_high_water} || sub { }, # ($buffered, $in_flight)
Subroutine __ANON__: not called CC=1 SCAR=0.0
1235 # low_water: threshold at which await_drain callbacks fire.
1236 # Defaults to half of high_water; honoured only when high_water
1237 # is set (otherwise await_drain fires whenever buffer is empty).
1238 # Use defined() so an explicit `low_water => 0` (fire only when
1239 # the buffer is fully empty) is respected, not treated as unset.
1240 low_water => defined($opts{low_water})
1241 ? $opts{low_water}
1242 0 ▶ : (($opts{high_water} || 0) / 2),
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'low_water'} ? : 0 0 0
Condition0%0/12
$opts{'batch_size'} || 10000
l!l
00
$opts{'on_batch_error'} || sub { }
l!l&&r!l&&!r
000
$opts{'high_water'} || 0
l!l
00
$opts{'on_high_water'} || sub { }
l!l&&r!l&&!r
000
$opts{'high_water'} || 0
l!l
00
MC/DC0%0/1
$opts{'batch_size'} || 10000
$opts{'batch_size'}
MC/DC0%0/2
$opts{'on_batch_error'} || sub { }
$opts{'on_batch_error'} sub { }
MC/DC0%0/1
$opts{'high_water'} || 0
$opts{'high_water'}
MC/DC0%0/2
$opts{'on_high_water'} || sub { }
$opts{'on_high_water'} sub { }
MC/DC0%0/1
$opts{'high_water'} || 0
$opts{'high_water'}
Truth table0%0/2
A
A= $opts{'batch_size'}
Aresult
11
00
Truth table0%0/3
A || B
A= $opts{'on_batch_error'}B= sub { }
ABresult
1X1
011
000
Truth table0%0/2
A
A= $opts{'high_water'}
Aresult
11
00
Truth table0%0/3
A || B
A= $opts{'on_high_water'}B= sub { }
ABresult
1X1
011
000
Truth table0%0/2
A
A= $opts{'high_water'}
Aresult
11
00
1243 columns => $columns,
1244 high_water_active => 0,
1245 buffer => [],
1246 in_flight => 0,
1247 pending_finish => undef,
1248 drain_waiters => [],
1249 sticky_err => undef,
1250 }, $class;
1251 }
1252  
1253 0 ▶sub push_row { EV::ClickHouse::_streamer_push_row(@_) }
Subroutine push_row: not called CC=1 SCAR=6.9
1254  
1255 0 ▶sub _flush {
Subroutine _flush: not called CC=6 SCAR=37.4
1256 0 my $self = shift;
1257 0 ▶ return if $self->{in_flight} || !@{ $self->{buffer} };
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_flight"} or not @{$self->{"buffer"};} 0 0 0
Condition0%0/3
$self->{"in_flight"} or not @{$self->{"buffer"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"in_flight"} or not @{$self->{"buffer"};}
$self->{"in_flight"} not @{$self->{"buffer"};}
Truth table0%0/3
A or not(B)
A= $self->{"in_flight"}B= not @{$self->{"buffer"};}
ABresult
1X1
011
000
1258 0 my $batch = $self->{buffer};
1259 0 $self->{buffer} = [];
1260 0 $self->{in_flight} = 1;
1261 0 ▶ my $cb = sub {
Subroutine __ANON__: not called CC=16 SCAR=56.1
1262 0 my (undef, $err) = @_;
1263 0 $self->{in_flight} = 0;
1264 0 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1265 0 ▶ $self->{sticky_err} //= $err;
Condition0%0/3
$self->{"sticky_err"} //= $err
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"sticky_err"} //= $err
$self->{"sticky_err"} $err
Truth table0%0/3
A //= B
A= $self->{"sticky_err"}B= $err
ABresult
1X1
011
000
1266 0 ▶ eval { $self->{on_batch_error}->($err); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{"on_batch_error"}->($err); 1 } } or warn "EV::ClickHouse: on_batch_error died: $@" 0 0 0
1267 or warn "EV::ClickHouse: on_batch_error died: $@";
1268 }
1269 # Drain any buffered rows queued during the batch
1270 0 $self->_flush;
1271 # Reset high_water latch once we drop below the threshold
1272 $self->{high_water_active} = 0
1273 if $self->{high_water_active}
1274 0 ▶ && @{ $self->{buffer} } < $self->{high_water};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"high_water_active"} and @{$self->{"buffer"};} < $self->{"high_water"} 0 0 0
Condition0%0/3
$self->{"high_water_active"} and @{$self->{"buffer"};} < $self->{"high_water"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"high_water_active"} and @{$self->{"buffer"};} < $self->{"high_water"}
$self->{"high_water_active"} @{$self->{"buffer"};} < $self->{"high_water"}
Truth table0%0/3
A and B
A= $self->{"high_water_active"}B= @{$self->{"buffer"};} < $self->{"high_water"}
ABresult
0X0
100
111
1275 # Fire await_drain waiters only when the buffer is at/below
1276 # low_water AND nothing is in flight. _flush above may have
1277 # immediately re-dispatched (in_flight=1, buffer=[]); waking
1278 # the waiter then would lie about the streamer being idle.
1279 0 my $low = $self->{low_water};
1280 0 ▶ if (!$self->{in_flight}
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{"in_flight"} and @{$self->{"drain_waiters"};} and @{$self->{"buffer"};} <= ($low || 0)) 0 0 0
Condition0%0/6
not $self->{"in_flight"} and @{$self->{"drain_waiters"};} and @{$self->{"buffer"};} <= ($low || 0)
!ll&&!rl&&r
000
not $self->{"in_flight"} and @{$self->{"drain_waiters"};}
!ll&&!rl&&r
000
MC/DC0%0/3
not $self->{"in_flight"} and @{$self->{"drain_waiters"};} and @{$self->{"buffer"};} <= ($low || 0)
not $self->{"in_flight"} @{$self->{"drain_waiters"};} @{$self->{"buffer"};} <= ($low || 0)
Truth table0%0/4
not(A) and B and C
A= not $self->{"in_flight"}B= @{$self->{"drain_waiters"};}C= @{$self->{"buffer"};} <= ($low || 0)
ABCresult
0XX0
10X0
1100
1111
1281 0 && @{ $self->{drain_waiters} }
1282 0 ▶ && @{ $self->{buffer} } <= ($low || 0)) {
Condition0%0/2
$low || 0
l!l
00
MC/DC0%0/1
$low || 0
$low
Truth table0%0/2
A
A= $low
Aresult
11
00
1283 0 my @w = @{ $self->{drain_waiters} };
1284 0 $self->{drain_waiters} = [];
1285 # One dying waiter must not starve the rest (same eval+warn
1286 # shape as on_batch_error above).
1287 0 for (@w) {
1288 0 ▶ eval { $_->(undef); 1 } # undef err = normal drain
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_(undef); 1 } } or warn "EV::ClickHouse: await_drain callback died: $@" 0 0 0
1289 or warn "EV::ClickHouse: await_drain callback died: $@";
1290 }
1291 }
1292 # Notify finish() if no work remains
1293 0 ▶ if ($self->{pending_finish}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pending_finish"} and not $self->{"in_flight"} and not @{$self->{"buffer"};}) 0 0 0
Condition0%0/6
$self->{"pending_finish"} and not $self->{"in_flight"} and not @{$self->{"buffer"};}
!ll&&!rl&&r
000
$self->{"pending_finish"} and not $self->{"in_flight"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"pending_finish"} and not $self->{"in_flight"} and not @{$self->{"buffer"};}
$self->{"pending_finish"} not $self->{"in_flight"} not @{$self->{"buffer"};}
Truth table0%0/4
A and not(B) and not(C)
A= $self->{"pending_finish"}B= not $self->{"in_flight"}C= not @{$self->{"buffer"};}
ABCresult
0XX0
10X0
1100
1111
1294 && !$self->{in_flight}
1295 0 && !@{ $self->{buffer} }) {
1296 0 my $fcb = delete $self->{pending_finish};
1297 0 ▶ eval { $fcb->(undef, $self->{sticky_err}); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$fcb(undef, $self->{"sticky_err"}); 1 } } or warn "EV::ClickHouse: finish callback died: $@" 0 0 0
1298 or warn "EV::ClickHouse: finish callback died: $@";
1299 }
1300 0 };
1301 0 ▶ my @opt = $self->{settings} ? ($self->{settings}) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->{'settings'} ? : 0 0 0
1302 # insert() croaks synchronously when the connection is definitively down,
1303 # and via XS _streamer_push_row that croak is swallowed by G_EVAL — so
1304 # without this in_flight would stay 1 forever and finish() never fire.
1305 # Route the failure through $cb to keep the bookkeeping in one place.
1306 0 ▶ unless (eval { $self->{ch}->insert($self->{table}, $batch, @opt, $cb); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->{"ch"}->insert($self->{"table"}, $batch, @opt, $cb); 1 } }) 0 0 0
1307 0 ▶ my $err = $@ || "insert failed";
Condition0%0/2
$@ || 'insert failed'
l!l
00
MC/DC0%0/1
$@ || 'insert failed'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1308 0 $cb->(undef, $err);
1309 }
1310 }
1311  
1312 0 ▶sub finish {
Subroutine finish: not called CC=5 SCAR=34.0
1313 0 my ($self, $cb) = @_;
1314 0 ▶ die "Usage: \$streamer->finish(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1315 0 $self->_flush;
1316 0 ▶ if (!$self->{in_flight} && !@{ $self->{buffer} }) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $self->{'in_flight'} || @{$self->{'buffer'};}) { } 0 0 0
elsif ($self->{'pending_finish'}) { } 0 0 0
Condition0%0/3
$self->{'in_flight'} || @{$self->{'buffer'};}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{'in_flight'} || @{$self->{'buffer'};}
$self->{'in_flight'} @{$self->{'buffer'};}
Truth table0%0/3
A || B
A= $self->{'in_flight'}B= @{$self->{'buffer'};}
ABresult
1X1
011
000
1317 0 $cb->(undef, $self->{sticky_err});
1318 } elsif ($self->{pending_finish}) {
1319 0 my ($prev, $next) = ($self->{pending_finish}, $cb);
1320 0 ▶ $self->{pending_finish} = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1321 0 ▶ eval { $prev->(@_); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$prev(@_); 1 } } or warn "EV::ClickHouse: finish callback died: $@" 0 0 0
1322 or warn "EV::ClickHouse: finish callback died: $@";
1323 0 ▶ eval { $next->(@_); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$next(@_); 1 } } or warn "EV::ClickHouse: finish callback died: $@" 0 0 0
1324 or warn "EV::ClickHouse: finish callback died: $@";
1325 0 };
1326 } else {
1327 0 $self->{pending_finish} = $cb;
1328 }
1329 0 return;
1330 }
1331  
1332 0 ▶sub buffered_count { scalar @{ $_[0]{buffer} } }
Subroutine buffered_count: not called CC=1 SCAR=6.9
1333 0 ▶sub in_flight { $_[0]{in_flight} }
Subroutine in_flight: not called CC=1 SCAR=6.9
1334 0 ▶sub sticky_error { $_[0]{sticky_err} }
Subroutine sticky_error: not called CC=1 SCAR=6.9
1335  
1336 # Register a callback that fires once the buffered row count drops
1337 # to low_water (defaults to high_water/2; 0 if high_water not set).
1338 # Pairs with on_high_water to close the backpressure loop:
1339 # on_high_water => sub { $producer->pause },
1340 # $streamer->await_drain(sub { $producer->resume });
1341 # Fires synchronously if the buffer is already at/below the threshold.
1342 0 ▶sub await_drain {
Subroutine await_drain: not called CC=5 SCAR=34.0
1343 0 my ($self, $cb) = @_;
1344 0 ▶ die "Usage: \$streamer->await_drain(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1345 0 ▶ my $low = $self->{low_water} || 0;
Condition0%0/2
$self->{'low_water'} || 0
l!l
00
MC/DC0%0/1
$self->{'low_water'} || 0
$self->{'low_water'}
Truth table0%0/2
A
A= $self->{'low_water'}
Aresult
11
00
1346 # Fire synchronously when nothing is in flight AND the buffer is
1347 # at/below low_water: there's no flush pending so no waiter would
1348 # ever fire otherwise.
1349 0 ▶ return $cb->(undef) if !$self->{in_flight} && @{ $self->{buffer} } <= $low;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"in_flight"} and @{$self->{"buffer"};} <= $low 0 0 0
Condition0%0/3
not $self->{"in_flight"} and @{$self->{"buffer"};} <= $low
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->{"in_flight"} and @{$self->{"buffer"};} <= $low
not $self->{"in_flight"} @{$self->{"buffer"};} <= $low
Truth table0%0/3
not(A) and B
A= not $self->{"in_flight"}B= @{$self->{"buffer"};} <= $low
ABresult
0X0
100
111
1350 0 push @{ $self->{drain_waiters} }, $cb;
1351 0 return;
1352 }
1353  
1354 # Discard buffered rows + sticky error without finishing. Useful for
1355 # "retry after permanent error" patterns where the producer wants to
1356 # wipe the slate clean (typically after a schema-level fix) and keep
1357 # pushing into the same streamer object. The underlying $ch is NOT
1358 # touched - any in-flight batch already on the wire still completes.
1359 0 ▶sub reset {
Subroutine reset: not called CC=6 SCAR=37.4
1360 0 my ($self) = @_;
1361 0 $self->{buffer} = [];
1362 0 $self->{sticky_err} = undef;
1363 0 $self->{high_water_active} = 0;
1364 # Deliver any pending finish/drain callbacks with a reset error
1365 # rather than silently dropping them - quiet loss of a finish cb
1366 # leaves the producer waiting forever.
1367 0 my $pf = delete $self->{pending_finish};
1368 0 ▶ my @dw = @{ delete $self->{drain_waiters} || [] };
Condition0%0/2
delete $self->{'drain_waiters'} || []
l!l
00
MC/DC0%0/1
delete $self->{'drain_waiters'} || []
delete $self->{'drain_waiters'}
Truth table0%0/2
A
A= delete $self->{'drain_waiters'}
Aresult
11
00
1369 0 $self->{drain_waiters} = [];
1370 # Eval-guarded like _flush: one dying callback must not starve
1371 # the rest when reset runs inside a callback chain.
1372 0 ▶ eval { $pf->(undef, 'streamer reset'); 1 }
Branch: 1 branch
BranchTrueFalseTotal
if $pf 0 0 0
Condition0%0/5
$pf && (eval { do { &$pf(undef, 'streamer reset'); 1 } } || warn("EV::ClickHouse: finish callback died: $@"))
!ll&&!rl&&r
000
eval { do { &$pf(undef, "streamer reset"); 1 } } or warn "EV::ClickHouse: finish callback died: $@"
l!l
00
MC/DC0%0/2
$pf && (eval { do { &$pf(undef, 'streamer reset'); 1 } } || warn("EV::ClickHouse: finish callback died: $@"))
$pf eval { do { &$pf(undef, "streamer reset"); 1 } }
Truth table0%0/3
A && B
A= $pfB= eval { do { &$pf(undef, "streamer reset"); 1 } }
ABresult
0X0
100
111
1373 or warn "EV::ClickHouse: finish callback died: $@" if $pf;
1374 0 for (@dw) {
1375 0 ▶ eval { $_->('streamer reset'); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_("streamer reset"); 1 } } or warn "EV::ClickHouse: await_drain callback died: $@" 0 0 0
1376 or warn "EV::ClickHouse: await_drain callback died: $@";
1377 }
1378 0 return $self;
1379 }
1380  
1381 # Discover column names from the target table via for_table, then
1382 # enable named-rows mode by populating $self->{columns}. Callback
1383 # receives undef on success, error string on failure. Useful when
1384 # the producer side doesn't know (or shouldn't care about) the
1385 # schema in advance.
1386 0 ▶sub columns_from_table {
Subroutine columns_from_table: not called CC=2 SCAR=17.9
1387 0 my ($self, $cb) = @_;
1388 0 ▶ die "Usage: \$streamer->columns_from_table(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1389 0 ▶ $self->{ch}->for_table($self->{table}, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1390 0 my ($info, $err) = @_;
1391 0 ▶ return $cb->($err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
1392 0 $self->{columns} = [ map { $_->{name} } @{ $info->{columns} } ];
1393 0 $cb->(undef);
1394 0 });
1395 0 return;
1396 }
1397  
1398 package EV::ClickHouse::Pool;
1399 79 ▶use Scalar::Util qw(refaddr weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
1400  
1401 # Built-in connection pool. Round-robin dispatch with least-busy fallback;
1402 # each connection is independent (own auto_reconnect, own send_queue),
1403 # so a hung query on one doesn't block the others. Pass any EV::ClickHouse
1404 # constructor option in %args; it's applied to every pool member.
1405 #
1406 # my $pool = EV::ClickHouse::Pool->new(host => 'ch', size => 10, ...);
1407 # $pool->query($sql, $cb);
1408 # $pool->insert($table, $data, $cb);
1409 # $pool->drain(sub { ... }); # all connections drained
1410 # $pool->finish;
1411 1 ▶sub new {
Subroutine new: called CC=6 SCAR=18.6
1412 1 my ($class, %args) = @_;
1413 1 ▶ my $size = delete $args{size} // 4;
Condition50%1/2
delete $args{"size"} // 4
l!l
10
MC/DC0%0/1
delete $args{"size"} // 4
delete $args{"size"}
Truth table50%1/2
A
A= delete $args{"size"}
Aresult
11
00
1414 1 ▶ die "Pool size must be >= 1" if $size < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $size < 1 0 1 1
1415 # Circuit breaker per member. After `circuit_threshold` consecutive
1416 # query/insert failures, mark the member dead for `circuit_cooldown`
1417 # seconds; _pick skips dead members. 0 disables.
1418 1 ▶ my $threshold = delete $args{circuit_threshold} || 0;
Condition50%1/2
delete $args{'circuit_threshold'} || 0
l!l
01
MC/DC0%0/1
delete $args{'circuit_threshold'} || 0
delete $args{'circuit_threshold'}
Truth table50%1/2
A
A= delete $args{'circuit_threshold'}
Aresult
11
00
1419 1 ▶ my $cooldown = delete $args{circuit_cooldown} || 30;
Condition50%1/2
delete $args{'circuit_cooldown'} || 30
l!l
01
MC/DC0%0/1
delete $args{'circuit_cooldown'} || 30
delete $args{'circuit_cooldown'}
Truth table50%1/2
A
A= delete $args{'circuit_cooldown'}
Aresult
11
00
1420 1 my @conns;
1421 1 for (1 .. $size) {
1422 2 push @conns, EV::ClickHouse->new(%args);
1423 }
1424 bless {
1425 conns => \@conns,
1426 idx => 0,
1427 cb_thresh => $threshold,
1428 cb_cool => $cooldown,
1429 1 cb_state => [ map { { fails => 0, dead_until => 0 } } @conns ],
1430 }, $class;
1431 }
1432  
1433 # Pick the connection with the fewest in-flight queries; ties broken by
1434 # round-robin. With circuit_threshold > 0, dead members are skipped
1435 # (unless all are dead - then the breaker is bypassed). Hot path - the
1436 # implementation lives in XS for ~5x lower per-pick cost.
1437 0 ▶sub _pick { EV::ClickHouse::_pool_pick($_[0]) }
Subroutine _pick: not called CC=1 SCAR=6.9
1438  
1439 # Find the {fails,dead_until} slot for a given $ch (object identity match).
1440 0 ▶sub _slot_for {
Subroutine _slot_for: not called CC=3 SCAR=24.8
1441 0 my ($self, $ch) = @_;
1442 0 my $r = refaddr $ch;
1443 0 for my $i (0 .. $#{ $self->{conns} }) {
1444 0 ▶ return $self->{cb_state}[$i] if refaddr($self->{conns}[$i]) == $r;
Branch: 1 branch
BranchTrueFalseTotal
if builtin::refaddr($self->{"conns"}[$i]) == $r 0 0 0
1445 }
1446 0 return undef;
1447 }
1448  
1449 # Wrap the user callback so the circuit breaker can observe success/failure.
1450 # The user's $cb is the LAST argument of query/insert/ping (per the public
1451 # API). The slot update itself is in XS (_breaker_observe) so the wrapper
1452 # closure body is one XSUB call rather than a handful of Perl ops.
1453 2 ▶sub _cb_observer {
Subroutine _cb_observer: called CC=6 SCAR=31.1
1454 2 my ($self, $ch, $user_cb, $observe_failures) = @_;
1455 2 ▶ $observe_failures //= 1;
Condition50%1/2
$observe_failures //= 1
l!l
20
MC/DC0%0/1
$observe_failures //= 1
$observe_failures
Truth table50%1/2
A
A= $observe_failures
Aresult
11
00
1456 2 ▶ return $user_cb unless $self->{cb_thresh} && ref($user_cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cb_thresh"} and ref $user_cb eq "CODE" 2 0 2
Condition33%1/3
$self->{"cb_thresh"} and ref $user_cb eq "CODE"
!ll&&!rl&&r
200
MC/DC0%0/2
$self->{"cb_thresh"} and ref $user_cb eq "CODE"
$self->{"cb_thresh"} ref $user_cb eq "CODE"
Truth table33%1/3
A and B
A= $self->{"cb_thresh"}B= ref $user_cb eq "CODE"
ABresult
0X0
100
111
1457 0 ▶ my $slot = ref($ch) ? $self->_slot_for($ch) : $self->{cb_state}[$ch];
Branch: 1 branch
BranchTrueFalseTotal
ref $ch ? : 0 0 0
1458 0 ▶ return $user_cb unless $slot;
Branch: 1 branch
BranchTrueFalseTotal
unless $slot 0 0 0
1459 0 my $thresh = $self->{cb_thresh};
1460 0 my $cool = $self->{cb_cool};
1461 0 ▶ sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1462 # all-dead fallback: observe successes only (resets the breaker
1463 # on recovery), skip failures (so under-load loss doesn't extend
1464 # dead_until repeatedly).
1465 0 ▶ EV::ClickHouse::_breaker_observe($slot, $_[1], $thresh, $cool)
Branch: 1 branch
BranchTrueFalseTotal
if $observe_failures or not $_[1] 0 0 0
Condition0%0/3
$observe_failures or not $_[1]
l!l&&r!l&&!r
000
MC/DC0%0/2
$observe_failures or not $_[1]
$observe_failures not $_[1]
Truth table0%0/3
A or not(B)
A= $observe_failuresB= not $_[1]
ABresult
1X1
011
000
1466 if $observe_failures || !$_[1];
1467 0 $user_cb->(@_);
1468 0 };
1469 }
1470  
1471 # Dispatch a method on a picked connection, wrapping the trailing CODE arg
1472 # (the user callback) with the circuit-breaker observer so success/failure
1473 # updates the per-member slot.
1474 0 ▶sub _dispatch {
Subroutine _dispatch: not called CC=2 SCAR=17.9
1475 0 my ($self, $method, @rest) = @_;
1476 0 my $ch = $self->_pick;
1477 0 ▶ $rest[-1] = $self->_cb_observer($ch, $rest[-1]) if ref $rest[-1] eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $rest[-1] eq "CODE" 0 0 0
1478 0 $ch->$method(@rest);
1479 }
1480  
1481 0 ▶sub query { shift->_dispatch(query => @_) }
Subroutine query: not called CC=1 SCAR=6.9
1482 0 ▶sub insert { shift->_dispatch(insert => @_) }
Subroutine insert: not called CC=1 SCAR=6.9
1483 0 ▶sub ping { shift->_dispatch(ping => @_) }
Subroutine ping: not called CC=1 SCAR=6.9
1484  
1485 0 ▶sub for_table { shift->_dispatch(for_table => @_) }
Subroutine for_table: not called CC=1 SCAR=6.9
1486 0 ▶sub table_defaults { shift->_dispatch(table_defaults => @_) }
Subroutine table_defaults: not called CC=1 SCAR=6.9
1487 0 ▶sub iterate { shift->_pick->iterate(@_) }
Subroutine iterate: not called CC=1 SCAR=6.9
1488 0 ▶sub insert_streamer { shift->_pick->insert_streamer(@_) }
Subroutine insert_streamer: not called CC=1 SCAR=6.9
1489  
1490 # Same as _dispatch but pins the target to $conn[$idx] instead of
1491 # polling _pick. Circuit-breaker observation still applies.
1492 0 ▶sub _dispatch_to {
Subroutine _dispatch_to: not called CC=5 SCAR=34.0
1493 0 my ($self, $method, $idx, @rest) = @_;
1494 0 ▶ die "${method}_to: index required" unless defined $idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $idx 0 0 0
1495 die "${method}_to: index $idx out of range"
1496 0 ▶ unless $idx =~ /^\d+$/ && $idx < @{ $self->{conns} };
Branch: 1 branch
BranchTrueFalseTotal
unless $idx =~ /^\d+$/ and $idx < @{$self->{"conns"};} 0 0 0
Condition0%0/3
$idx =~ /^\d+$/ and $idx < @{$self->{"conns"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$idx =~ /^\d+$/ and $idx < @{$self->{"conns"};}
$idx =~ /^\d+$/ $idx < @{$self->{"conns"};}
Truth table0%0/3
A and B
A= $idx =~ /^\d+$/B= $idx < @{$self->{"conns"};}
ABresult
0X0
100
111
1497 0 my $ch = $self->{conns}[$idx];
1498 0 ▶ $rest[-1] = $self->_cb_observer($ch, $rest[-1]) if ref $rest[-1] eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $rest[-1] eq "CODE" 0 0 0
1499 0 $ch->$method(@rest);
1500 }
1501 0 ▶sub query_to { shift->_dispatch_to(query => @_) }
Subroutine query_to: not called CC=1 SCAR=6.9
1502 0 ▶sub insert_to { shift->_dispatch_to(insert => @_) }
Subroutine insert_to: not called CC=1 SCAR=6.9
1503  
1504 # Nominate a member: returns its connection object so subsequent calls
1505 # stick to it. The caller is responsible for not abusing this (the pool
1506 # can't apply the circuit breaker to calls it doesn't see).
1507 0 ▶sub nominate {
Subroutine nominate: not called CC=4 SCAR=30.0
1508 0 my ($self, $idx) = @_;
1509 0 ▶ die "nominate: index required" unless defined $idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $idx 0 0 0
1510 die "nominate: index $idx out of range"
1511 0 ▶ unless $idx =~ /^\d+$/ && $idx < @{ $self->{conns} };
Branch: 1 branch
BranchTrueFalseTotal
unless $idx =~ /^\d+$/ and $idx < @{$self->{"conns"};} 0 0 0
Condition0%0/3
$idx =~ /^\d+$/ and $idx < @{$self->{"conns"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$idx =~ /^\d+$/ and $idx < @{$self->{"conns"};}
$idx =~ /^\d+$/ $idx < @{$self->{"conns"};}
Truth table0%0/3
A and B
A= $idx =~ /^\d+$/B= $idx < @{$self->{"conns"};}
ABresult
0X0
100
111
1512 0 $self->{conns}[$idx];
1513 }
1514  
1515 # Hedged read: dispatch the same query to N (default 2) distinct
1516 # members and resolve with whichever returns first. Subsequent
1517 # completions are silently dropped. Errors are reported only if every
1518 # member fails. Recommended for tail-latency-sensitive selects on
1519 # replicated tables; do NOT use for insert (would silently double-write
1520 # on dedupe miss). $cb receives ($rows, undef, $member_idx) on success
1521 # or (undef, $err) when every member fails.
1522 1 ▶sub hedged_query {
Subroutine hedged_query: called CC=13 SCAR=27.2
1523 1 my ($self, $sql, @rest) = @_;
1524 1 my $cb = pop @rest;
1525 1 my %opts = @rest;
1526 1 ▶ my $hedge_n = delete $opts{hedge} // 2;
Condition50%1/2
delete $opts{"hedge"} // 2
l!l
01
MC/DC0%0/1
delete $opts{"hedge"} // 2
delete $opts{"hedge"}
Truth table50%1/2
A
A= delete $opts{"hedge"}
Aresult
11
00
1527 1 my $settings = delete $opts{settings};
1528 1 ▶ die "hedged_query: callback required" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 1 1
1529 1 ▶ die "hedged_query: unknown options: " . join(', ', sort keys %opts)
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 1 1
1530 if %opts;
1531 1 my @c = @{ $self->{conns} };
1532 1 ▶ die "hedged_query: no members" unless @c;
Branch: 1 branch
BranchTrueFalseTotal
unless @c 0 1 1
1533 # Filter out circuit-broken members. If the breaker tripped everywhere
1534 # fall back to the full set so the caller still hears something — but
1535 # in that fallback skip _cb_observer too, otherwise every failed hedge
1536 # extends each member's dead_until (resetting cooldown indefinitely
1537 # under load).
1538 1 my $now = EV::time();
1539 1 my @alive = grep { $self->{cb_state}[$_]{dead_until} <= $now } 0 .. $#c;
1540 1 my $all_dead = !@alive;
1541 1 ▶ @alive = (0 .. $#c) if $all_dead;
Branch: 1 branch
BranchTrueFalseTotal
if $all_dead 0 1 1
1542 1 ▶ $hedge_n = @alive if $hedge_n > @alive;
Branch: 1 branch
BranchTrueFalseTotal
if $hedge_n > @alive 0 1 1
1543 1 ▶ $hedge_n = 1 if $hedge_n < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $hedge_n < 1 0 1 1
1544 # Reservoir-style shuffle for distinct random picks.
1545 1 my @pool = @alive;
1546 1 my @idx;
1547 1 ▶ while (@idx < $hedge_n) { push @idx, splice(@pool, int(rand(scalar @pool)), 1) }
Branch: 1 branch
BranchTrueFalseTotal
if (@idx < $hedge_n) 2 1 3
1548 1 my $fired = 0;
1549 1 my $pending = scalar @idx;
1550 1 my $first_err;
1551 1 for my $i (@idx) {
1552 2 my $ch = $c[$i];
1553 2 ▶ my $inner = sub {
Subroutine __ANON__: called CC=5 SCAR=17.4
1554 2 my ($rows, $err) = @_;
1555 2 $pending--;
1556 2 ▶ return if $fired;
Branch: 1 branch
BranchTrueFalseTotal
if $fired 0 2 2
1557 2 ▶ if (!$err) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($err) 0 2 2
1558 0 $fired = 1;
1559 # 3rd arg = winning member index, so callers can attribute
1560 # wins / track per-replica latency without scanning conns.
1561 0 $cb->($rows, undef, $i);
1562 0 return;
1563 }
1564 2 ▶ $first_err //= $err;
Condition66%2/3
$first_err //= $err
l!l&&r!l&&!r
110
MC/DC0%0/2
$first_err //= $err
$first_err $err
Truth table66%2/3
A //= B
A= $first_errB= $err
ABresult
1X1
011
000
1565 2 ▶ if (!$pending) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $pending) 1 1 2
1566 1 $fired = 1;
1567 1 $cb->(undef, $first_err);
1568 }
1569 2 };
1570 # Pass $i (not $ch) so _cb_observer can index cb_state directly
1571 # instead of walking conns via _slot_for.
1572 2 my $obs = $self->_cb_observer($i, $inner, !$all_dead);
1573 # A member that is momentarily unconnected croaks synchronously;
1574 # record it as that member's async result (fan_out precedent) so
1575 # $pending accounting still converges on (undef, $err).
1576 eval {
1577 0 ▶ if ($settings) { $ch->query($sql, $settings, $obs) }
Branch: 1 branch
BranchTrueFalseTotal
if ($settings) { } 0 2 2
1578 2 else { $ch->query($sql, $obs) }
1579 0 1;
1580 2 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { if ($settings) { $ch->query($sql, $settings, $obs); } else { $ch->query($sql, $obs); } ; 1 } } or do { &$obs(undef, "$@" || "hedged_query: dispatch failed") } 0 2 2
1581 2 ▶ $obs->(undef, "$@" || 'hedged_query: dispatch failed');
Condition50%1/2
"$@" || 'hedged_query: dispatch failed'
l!l
20
MC/DC0%0/1
"$@" || 'hedged_query: dispatch failed'
"$@"
Truth table50%1/2
A
A= "$@"
Aresult
11
00
1582 };
1583 }
1584 1 return;
1585 }
1586  
1587 # Circuit breaker introspection: per-member state for monitoring.
1588 # Returns ({ fails => N, dead_until => $epoch_seconds, alive => 0|1 }, ...).
1589 0 ▶sub circuit_state {
Subroutine circuit_state: not called CC=2 SCAR=17.9
1590 0 my $self = shift;
1591 0 my $now = EV::time();
1592 my @st = map +{ %$_, alive => $_->{dead_until} <= $now },
1593 0 @{ $self->{cb_state} };
1594 0 ▶ return wantarray ? @st : \@st;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
1595 }
1596  
1597 # Aggregate stats
1598 0 ▶sub size { scalar @{ $_[0]{conns} } }
Subroutine size: not called CC=1 SCAR=6.9
1599 0 ▶sub pending_count { my $t = 0; $t += $_->pending_count for @{ $_[0]{conns} }; $t }
Subroutine pending_count: not called CC=2 SCAR=17.9
1600 1 ▶sub conns { @{ $_[0]{conns} } }
Subroutine conns: called CC=1 SCAR=0.0
1601  
1602 # Apply a code ref to every pool member. The callback receives
1603 # ($conn, $idx) per call. Useful for warm-up (preload dictionaries,
1604 # set session-level variables, dispatch a probe per member). The
1605 # callback is invoked synchronously in pool order; if it throws,
1606 # subsequent members are still visited (errors silently swallowed,
1607 # matching the broadcast cancel/skip_pending/reset convention).
1608 0 ▶sub with_each {
Subroutine with_each: not called CC=3 SCAR=24.8
1609 0 my ($self, $cb) = @_;
1610 0 ▶ die "Usage: \$pool->with_each(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1611 0 my @c = @{ $self->{conns} };
1612 0 for my $i (0 .. $#c) { eval { $cb->($c[$i], $i) } }
1613 0 return;
1614 }
1615  
1616 # Broadcast the same SELECT to every member and collect per-member
1617 # results. Useful for `system.replicas`-style diagnostics where each
1618 # shard needs to be queried directly. Callback fires once with an
1619 # arrayref of { member => $i, rows => [...], err => $msg }, ordered
1620 # by member index. Per-query settings are honoured. Dead members are
1621 # included in the result with a "circuit open" error string rather
1622 # than dispatched — the breaker would refuse them anyway.
1623 0 ▶sub fan_out {
Subroutine fan_out: not called CC=10 SCAR=47.0
1624 0 my ($self, $sql, @rest) = @_;
1625 0 my $cb = pop @rest;
1626 0 my %opts = @rest;
1627 0 my $settings = delete $opts{settings};
1628 0 ▶ die "fan_out: callback required" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1629 0 ▶ die "fan_out: unknown option(s): " . join(', ', sort keys %opts) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 0 0
1630 if %opts;
1631 0 my @c = @{ $self->{conns} };
1632 0 ▶ die "fan_out: no members" unless @c;
Branch: 1 branch
BranchTrueFalseTotal
unless @c 0 0 0
1633 0 my @out = map { { member => $_, rows => undef, err => undef } } 0 .. $#c;
1634 0 my $left = scalar @c;
1635 0 ▶ my $deliver = sub { $cb->(\@out) unless --$left };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless --$left 0 0 0
1636 0 my $now = EV::time();
1637 0 for my $i (0 .. $#c) {
1638 0 my $ch = $c[$i];
1639 # Short-circuit dead members so a long cooldown doesn't stall fan_out.
1640 0 ▶ if ($self->{cb_thresh}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cb_thresh"} and $self->{"cb_state"}[$i]{"dead_until"} > $now) 0 0 0
Condition0%0/3
$self->{"cb_thresh"} and $self->{"cb_state"}[$i]{"dead_until"} > $now
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"cb_thresh"} and $self->{"cb_state"}[$i]{"dead_until"} > $now
$self->{"cb_thresh"} $self->{"cb_state"}[$i]{"dead_until"} > $now
Truth table0%0/3
A and B
A= $self->{"cb_thresh"}B= $self->{"cb_state"}[$i]{"dead_until"} > $now
ABresult
0X0
100
111
1641 && $self->{cb_state}[$i]{dead_until} > $now) {
1642 0 $out[$i]{err} = "fan_out: member $i circuit open";
1643 0 $deliver->();
1644 0 next;
1645 }
1646 0 ▶ my $obs = $self->_cb_observer($i, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1647 0 ($out[$i]{rows}, $out[$i]{err}) = @_;
1648 0 $deliver->();
1649 0 });
1650 # Wrap each member's dispatch so a synchronous croak (e.g.
1651 # "not connected" before auto_reconnect catches up) doesn't
1652 # strand the rest of the callbacks waiting on $left.
1653 eval {
1654 0 ▶ if ($settings) { $ch->query($sql, $settings, $obs) }
Branch: 1 branch
BranchTrueFalseTotal
if ($settings) { } 0 0 0
1655 0 else { $ch->query($sql, $obs) }
1656 0 1;
1657 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { if ($settings) { $ch->query($sql, $settings, $obs); } else { $ch->query($sql, $obs); } ; 1 } } or do { $out[$i]{"err"} = "$@" || "fan_out: dispatch failed"; &$deliver() } 0 0 0
1658 0 ▶ $out[$i]{err} = "$@" || "fan_out: dispatch failed";
Condition0%0/2
"$@" || 'fan_out: dispatch failed'
l!l
00
MC/DC0%0/1
"$@" || 'fan_out: dispatch failed'
"$@"
Truth table0%0/2
A
A= "$@"
Aresult
11
00
1659 0 $deliver->();
1660 };
1661 }
1662 0 return;
1663 }
1664  
1665 # Checkout-style pin: hand the user a least-busy member, run their cb
1666 # with ($conn, $release). Until $release->() is called, the pool will
1667 # avoid handing the same member to other callers via _pick — useful
1668 # for temp tables / SET / session-state work that must land on the
1669 # same connection across multiple queries.
1670 0 ▶sub with_session {
Subroutine with_session: not called CC=4 SCAR=30.0
1671 0 my ($self, $cb) = @_;
1672 0 ▶ die "Usage: \$pool->with_session(\$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1673 0 my $ch = $self->_pick;
1674 0 my $r = refaddr $ch;
1675 0 ▶ $self->{_pinned}{$r} = ($self->{_pinned}{$r} // 0) + 1;
Condition0%0/2
$self->{"_pinned"}{$r} // 0
l!l
00
MC/DC0%0/1
$self->{"_pinned"}{$r} // 0
$self->{"_pinned"}{$r}
Truth table0%0/2
A
A= $self->{"_pinned"}{$r}
Aresult
11
00
1676 0 my $released = 0;
1677 0 ▶ my $release = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1678 0 ▶ return if $released++;
Branch: 1 branch
BranchTrueFalseTotal
if $released++ 0 0 0
1679 0 ▶ if (--$self->{_pinned}{$r} <= 0) { delete $self->{_pinned}{$r} }
Branch: 1 branch
BranchTrueFalseTotal
if (--$self->{"_pinned"}{$r} <= 0) 0 0 0
1680 0 };
1681 0 ▶ eval { $cb->($ch, $release); 1 } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$cb($ch, $release); 1 } } or do { my $err = $@; &$release(); die $err } 0 0 0
1682 0 my $err = $@;
1683 0 $release->();
1684 0 die $err;
1685 };
1686 0 return;
1687 }
1688  
1689 # Drain when ALL connections have completed pending work.
1690 0 ▶sub drain {
Subroutine drain: not called CC=3 SCAR=24.8
1691 0 my ($self, $cb) = @_;
1692 0 ▶ die "drain callback must be a CODE reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1693 unless ref($cb) eq 'CODE';
1694 0 my $left = scalar @{ $self->{conns} };
1695 0 for my $c (@{ $self->{conns} }) {
1696 0 ▶ $c->drain(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1697 # Per-connection drain callback takes no arguments.
1698 0 ▶ $cb->(undef) unless --$left;
Branch: 1 branch
BranchTrueFalseTotal
unless --$left 0 0 0
1699 0 });
1700 }
1701 }
1702  
1703 0 ▶sub finish { $_->finish for @{ $_[0]{conns} } }
Subroutine finish: not called CC=2 SCAR=17.9
1704  
1705 # A pool dropped mid-shutdown still owes its chained shutdown
1706 # callbacks exactly one fire (the primary fires via finalize when
1707 # the members drain during teardown).
1708 1 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=23.8
1709 1 my ($self) = @_;
1710 1 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 1 1
1711 1 ▶ if (my $chain = delete $self->{shutdown_chain}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $chain = delete $self->{"shutdown_chain"}) 0 1 1
1712 0 for (@$chain) {
1713 0 ▶ eval { $_->('pool destroyed during shutdown'); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_("pool destroyed during shutdown"); 1 } } or warn "EV::ClickHouse: shutdown callback died: $@" 0 0 0
1714 or warn "EV::ClickHouse: shutdown callback died: $@";
1715 }
1716 }
1717 }
1718  
1719 # Coordinated graceful shutdown: drain every member, then finish. If
1720 # the optional $grace_seconds elapses before all members drain, force
1721 # finish and report a timeout in the callback. Callback receives undef
1722 # on clean shutdown, an error string on per-member drain error or
1723 # timeout. $cb is optional.
1724 #
1725 # $pool->shutdown(10, sub {
1726 # my ($err) = @_;
1727 # warn "shutdown: $err" if $err;
1728 # EV::break;
1729 # });
1730 0 ▶sub shutdown {
Subroutine shutdown: not called CC=10 SCAR=47.0
1731 0 my ($self, $grace, $cb) = @_;
1732 # Two-arg form: $pool->shutdown($cb). Treat the coderef as the cb
1733 # with no grace timer rather than silently dropping it.
1734 0 ▶ ($grace, $cb) = (undef, $grace) if ref($grace) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $grace eq "CODE" 0 0 0
1735 0 ▶ $cb //= sub { };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/3
$cb //= sub { }
l!l&&r!l&&!r
000
MC/DC0%0/2
$cb //= sub { }
$cb sub { }
Truth table0%0/3
A //= B
A= $cbB= sub { }
ABresult
1X1
011
000
1736 0 ▶ die "Usage: \$pool->shutdown([\$grace_seconds], \$cb)" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 0 0
1737 # A second shutdown while one is draining chains behind it instead
1738 # of dying on 'drain already pending' with its callback unfired.
1739 0 ▶ if ($self->{shutdown_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutdown_pending"}) 0 0 0
1740 0 push @{ $self->{shutdown_chain} }, $cb;
1741 0 return;
1742 }
1743 0 $self->{shutdown_pending} = 1;
1744 0 my $left = scalar @{ $self->{conns} };
1745 0 my $err;
1746 my $timer;
1747 0 my $fired = 0;
1748 # Weak: $finalize is reachable from the pool itself
1749 # (pool -> members -> drain cbs -> $finalize), so a strong $self
1750 # would strand the pool and its sockets when drains never
1751 # complete and the user drops the last reference.
1752 0 my $weakself = $self; weaken($weakself);
1753 0 my $aborted = 0;
1754 0 ▶ my $finalize = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
1755 0 ▶ return if $aborted;
Branch: 1 branch
BranchTrueFalseTotal
if $aborted 0 0 0
1756 0 ▶ return if $fired++;
Branch: 1 branch
BranchTrueFalseTotal
if $fired++ 0 0 0
1757 0 undef $timer;
1758 0 ▶ if ($weakself) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weakself) 0 0 0
1759 0 $weakself->finish;
1760 0 $weakself->{shutdown_pending} = 0;
1761 0 ▶ my @chained = @{ delete $weakself->{shutdown_chain} || [] };
Condition0%0/2
delete $weakself->{'shutdown_chain'} || []
l!l
00
MC/DC0%0/1
delete $weakself->{'shutdown_chain'} || []
delete $weakself->{'shutdown_chain'}
Truth table0%0/2
A
A= delete $weakself->{'shutdown_chain'}
Aresult
11
00
1762 0 for (@chained) {
1763 0 ▶ eval { $_->($err); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$_($err); 1 } } or warn "EV::ClickHouse: shutdown callback died: $@" 0 0 0
1764 or warn "EV::ClickHouse: shutdown callback died: $@";
1765 }
1766 }
1767 0 $cb->($err);
1768 0 };
1769 # Arm the grace timer before draining: idle members finish their
1770 # drains synchronously, and arming after would strand a no-op
1771 # timer that keeps the loop alive for the full grace period.
1772 0 ▶ if ($grace && $grace > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($grace and $grace > 0) 0 0 0
Condition0%0/3
$grace and $grace > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$grace and $grace > 0
$grace $grace > 0
Truth table0%0/3
A and B
A= $graceB= $grace > 0
ABresult
0X0
100
111
1773 0 EV::now_update();
1774 0 ▶ $timer = EV::timer($grace, 0, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1775 0 ▶ $err //= "Pool::shutdown timed out after ${grace}s";
Condition0%0/2
$err //= "Pool::shutdown timed out after ${grace}s"
l!l
00
MC/DC0%0/1
$err //= "Pool::shutdown timed out after ${grace}s"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
1776 0 $finalize->();
1777 0 });
1778 }
1779 0 for my $c (@{ $self->{conns} }) {
1780 # A member with a user drain already pending croaks here;
1781 # abort cleanly (no stuck flag, no spurious timeout cb) so a
1782 # later shutdown still works once that drain completes.
1783 0 my $ok = eval {
1784 0 ▶ $c->drain(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1785 # Per-connection drain callback takes no arguments.
1786 0 ▶ $finalize->() if --$left == 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$left == 0 0 0 0
1787 0 });
1788 0 1;
1789 };
1790 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
1791 0 ▶ my $e = $@ || 'drain failed';
Condition0%0/2
$@ || 'drain failed'
l!l
00
MC/DC0%0/1
$@ || 'drain failed'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
1792 0 $aborted = 1;
1793 0 undef $timer;
1794 0 $self->{shutdown_pending} = 0;
1795 0 die "Pool::shutdown: $e";
1796 }
1797 }
1798 0 return;
1799 }
1800  
1801 # Broadcast-to-all helpers — these touch every member because they affect
1802 # state owned per connection (queued queries, in-flight cancellation, the
1803 # socket itself). Picking a single member would silently leave the other
1804 # pool connections untouched.
1805 0 ▶sub cancel { for (@{ $_[0]{conns} }) { eval { $_->cancel } } }
Subroutine cancel: not called CC=2 SCAR=17.9
1806 0 ▶sub skip_pending { for (@{ $_[0]{conns} }) { eval { $_->skip_pending } } }
Subroutine skip_pending: not called CC=2 SCAR=17.9
1807 0 ▶sub reset { for (@{ $_[0]{conns} }) { eval { $_->reset } } }
Subroutine reset: not called CC=2 SCAR=17.9
1808  
1809 package EV::ClickHouse::Iterator;
1810  
1811 0 ▶sub next { EV::ClickHouse::_iterator_next(@_) }
Subroutine next: not called CC=1 SCAR=6.9
1812  
1813 0 ▶sub error { $_[0]{err} }
Subroutine error: not called CC=1 SCAR=6.9
1814 0 ▶sub is_done { $_[0]{done} && !@{ $_[0]{batches} } }
Subroutine is_done: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{"done"} and not @{$_[0]{"batches"};} 0 0 0
1815 0 ▶sub cancel {
Subroutine cancel: not called CC=3 SCAR=24.8
1816 0 my $self = shift;
1817 # The iterator shares its connection: once its own query is done
1818 # (or already cancelled), $ch->cancel would kill whatever
1819 # unrelated query happens to be in flight now. No-op instead.
1820 0 ▶ return 0 if $self->{done} || $self->{cancelled};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"done"} or $self->{"cancelled"} 0 0 0
Condition0%0/3
$self->{"done"} or $self->{"cancelled"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"done"} or $self->{"cancelled"}
$self->{"done"} $self->{"cancelled"}
Truth table0%0/3
A or B
A= $self->{"done"}B= $self->{"cancelled"}
ABresult
1X1
011
000
1821 0 $self->{cancelled} = 1;
1822 0 $self->{ch}->cancel;
1823 0 return 1;
1824 }
1825  
1826 package EV::ClickHouse::Error;
1827  
1828 # Lightweight error object — wraps the (message, code) pair callers
1829 # already get on $err, plus a symbolic name and is_retryable boolean.
1830 # Stringifies to the message so legacy callsites that string-compare
1831 # against $err keep working.
1832 0 ▶use overload '""' => sub { $_[0]{message} }, fallback => 1;
Subroutine BEGIN: called CC=1 SCAR=0.2
Subroutine __ANON__: not called CC=1 SCAR=0.2
1833  
1834 # Symbolic names for ClickHouse error codes that user code is likely
1835 # to want to branch on by name. Sourced from src/Common/ErrorCodes.cpp;
1836 # extend liberally — the table is informational only.
1837 79 my %CODE_NAME = (
1838 0 => 'OK',
1839 27 => 'CANNOT_PARSE_INPUT_ASSERTION_FAILED',
1840 32 => 'ATTEMPT_TO_READ_AFTER_EOF',
1841 33 => 'CANNOT_READ_ALL_DATA',
1842 44 => 'ILLEGAL_COLUMN',
1843 47 => 'UNKNOWN_IDENTIFIER',
1844 60 => 'UNKNOWN_TABLE',
1845 62 => 'SYNTAX_ERROR',
1846 81 => 'UNKNOWN_DATABASE',
1847 86 => 'RECEIVED_ERROR_FROM_REMOTE_IO_SERVER',
1848 113 => 'UNKNOWN_SETTING',
1849 159 => 'TIMEOUT_EXCEEDED',
1850 164 => 'READONLY',
1851 192 => 'UNKNOWN_USER',
1852 193 => 'WRONG_PASSWORD',
1853 194 => 'REQUIRED_PASSWORD',
1854 202 => 'TOO_MANY_SIMULTANEOUS_QUERIES',
1855 203 => 'NO_FREE_CONNECTION',
1856 209 => 'SOCKET_TIMEOUT',
1857 210 => 'NETWORK_ERROR',
1858 225 => 'NO_ZOOKEEPER',
1859 236 => 'ABORTED',
1860 241 => 'MEMORY_LIMIT_EXCEEDED',
1861 242 => 'TABLE_IS_READ_ONLY',
1862 252 => 'TOO_MANY_PARTS',
1863 285 => 'TOO_FEW_LIVE_REPLICAS',
1864 319 => 'UNKNOWN_STATUS_OF_INSERT',
1865 341 => 'UNFINISHED',
1866 373 => 'SESSION_IS_LOCKED',
1867 389 => 'INSERT_WAS_DEDUPLICATED',
1868 394 => 'QUERY_WAS_CANCELLED',
1869 439 => 'CANNOT_SCHEDULE_TASK',
1870 497 => 'ACCESS_DENIED',
1871 516 => 'AUTHENTICATION_FAILED',
1872 999 => 'KEEPER_EXCEPTION',
1873 );
1874  
1875 0 ▶sub new {
Subroutine new: not called CC=3 SCAR=24.8
1876 0 my ($class, %args) = @_;
1877 bless {
1878 message => $args{message} // '',
1879 0 ▶ code => $args{code} // 0,
Condition0%0/4
$args{"message"} // ""
l!l
00
$args{"code"} // 0
l!l
00
MC/DC0%0/1
$args{"message"} // ""
$args{"message"}
MC/DC0%0/1
$args{"code"} // 0
$args{"code"}
Truth table0%0/2
A
A= $args{"message"}
Aresult
11
00
Truth table0%0/2
A
A= $args{"code"}
Aresult
11
00
1880 }, $class;
1881 }
1882  
1883 # Convenience: build from ($ch, $err) — the typical pair that callbacks
1884 # receive. The ClickHouse-side code comes from $ch->last_error_code.
1885 0 ▶sub from_ch {
Subroutine from_ch: not called CC=4 SCAR=30.0
1886 0 my ($class, $ch, $err) = @_;
1887 0 ▶ return undef unless defined $err && length $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 0 0
Condition0%0/3
defined $err and length $err
!ll&&!rl&&r
000
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table0%0/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
1888 $class->new(
1889 message => "$err",
1890 0 ▶ code => (eval { $ch->last_error_code } || 0),
Condition0%0/2
eval { do { $ch->last_error_code } } || 0
l!l
00
MC/DC0%0/1
eval { do { $ch->last_error_code } } || 0
eval { do { $ch->last_error_code } }
Truth table0%0/2
A
A= eval { do { $ch->last_error_code } }
Aresult
11
00
1891 );
1892 }
1893  
1894 0 ▶sub message { $_[0]{message} }
Subroutine message: not called CC=1 SCAR=6.9
1895 0 ▶sub code { $_[0]{code} }
Subroutine code: not called CC=1 SCAR=6.9
1896 0 ▶sub name { $CODE_NAME{ $_[0]{code} } }
Subroutine name: not called CC=1 SCAR=6.9
1897 0 ▶sub is_retryable { EV::ClickHouse->is_retryable_error($_[0]{code}) }
Subroutine is_retryable: not called CC=1 SCAR=6.9
1898  
1899 # Class-level table introspection.
1900 0 ▶sub code_name { $CODE_NAME{ $_[1] // 0 } }
Subroutine code_name: not called CC=2 SCAR=17.9
Condition0%0/2
$_[1] // 0
l!l
00
MC/DC0%0/1
$_[1] // 0
$_[1]
Truth table0%0/2
A
A= $_[1]
Aresult
11
00
1901 0 ▶sub known_codes { sort { $a <=> $b } keys %CODE_NAME }
Subroutine known_codes: not called CC=1 SCAR=6.9
1902  
1903 79 1;
1904  
1905 __END__
↑ Summary cityhash.h »