blib/lib/EV/ClickHouse.pm

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