blib/lib/EV/ClickHouse.pm

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