ClickHouse.xs

filter: Statementstmt 52.4% 828 / 1580 Branchbran 31.0% 529 / 1704 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 41.3% 1357 / 3284 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« xs/proto_native_parse.c ↑ Summary xs/proto_http.c »
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4  
5 #include "EVAPI.h"
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <netinet/tcp.h>
10 #include <netdb.h>
11 #include <arpa/inet.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <errno.h>
15 #include <string.h>
16 #include <signal.h>
17 #include <zlib.h>
18  
19 #define CH_MAX_DECOMPRESS_SIZE (128 * 1024 * 1024) /* 128 MB safety limit */
20  
21 #ifdef HAVE_LZ4
22 #include <lz4.h>
23 #include "cityhash.h"
24  
25 #define CH_LZ4_METHOD 0x82
26 #define CH_CHECKSUM_SIZE 16
27 #define CH_COMPRESS_HEADER_SIZE 9 /* 1 (method) + 4 (compressed_size) + 4 (uncompressed_size) */
28 #endif
29  
30 #ifdef HAVE_OPENSSL
31 #include <openssl/ssl.h>
32 #include <openssl/err.h>
33 #include <openssl/x509v3.h>
34 #endif
35  
36 #include "ngx_queue.h"
37  
38 typedef struct ev_clickhouse_s ev_clickhouse_t;
39 typedef struct ev_ch_cb_s ev_ch_cb_t;
40 typedef struct ev_ch_send_s ev_ch_send_t;
41 typedef struct tc_cols_s tc_cols_t;
42  
43 typedef ev_clickhouse_t* EV__ClickHouse;
44 typedef struct ev_loop* EV__Loop;
45  
46 #define EV_CH_MAGIC 0xC11C4011
47 #define EV_CH_FREED 0xFEEDFACE
48  
49 #define PROTO_HTTP 0
50 #define PROTO_NATIVE 1
51  
52 #define RECV_BUF_INIT 8192
53 #define SEND_BUF_INIT 4096
54  
55 /* ClickHouse native protocol client info */
56 #define CH_CLIENT_NAME "EV::ClickHouse"
57 #define CH_CLIENT_VERSION_MAJOR 0
58 #define CH_CLIENT_VERSION_MINOR 1
59 /* CH_CLIENT_REVISION is the protocol revision we negotiate. Bumping it
60 * unlocks server features (extra Progress fields, parallel-replica
61 * extensions, quota-key handshake additions, …) but each step requires
62 * matching client-side handling, otherwise the server starts sending
63 * fields we'd misframe. 54459 is the conservative anchor that lights up
64 * everything we currently parse. */
65 #define CH_CLIENT_REVISION 54459
66  
67 /* Protocol revision thresholds */
68 #define DBMS_MIN_REVISION_WITH_BLOCK_INFO 51903
69 #define DBMS_MIN_REVISION_WITH_SERVER_DISPLAY_NAME 54372
70 #define DBMS_MIN_REVISION_WITH_VERSION_PATCH 54401
71 #define DBMS_MIN_REVISION_WITH_PROGRESS_WRITES 54420
72 #define DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE 54423
73 #define DBMS_MIN_PROTOCOL_VERSION_WITH_ADDENDUM 54458
74 #define DBMS_MIN_REVISION_WITH_PARAMETERS 54459
75 /* Highest revision whose fields we unconditionally emit (ClientHello
76 * parallel_replicas) or consume (Data custom-serialization flag):
77 * older servers desync instead of erroring, so Hello below this
78 * fails fast. */
79 #define DBMS_MIN_SUPPORTED_SERVER_REVISION 54453
80  
81 /* Client packet types */
82 #define CLIENT_HELLO 0
83 #define CLIENT_QUERY 1
84 #define CLIENT_DATA 2
85 #define CLIENT_CANCEL 3
86 #define CLIENT_PING 4
87  
88 /* Server packet types */
89 #define SERVER_HELLO 0
90 #define SERVER_DATA 1
91 #define SERVER_EXCEPTION 2
92 #define SERVER_PROGRESS 3
93 #define SERVER_PONG 4
94 #define SERVER_END_OF_STREAM 5
95 #define SERVER_PROFILE_INFO 6
96 #define SERVER_TOTALS 7
97 #define SERVER_EXTREMES 8
98 #define SERVER_LOG 10
99 #define SERVER_TABLE_COLUMNS 11
100 #define SERVER_PROFILE_EVENTS 14
101 #define SERVER_TIMEZONE_UPDATE 17
102  
103 /* Query kind */
104 #define QUERY_INITIAL 1
105  
106 /* Query stage */
107 #define STAGE_COMPLETE 2
108  
109 /* Native protocol states */
110 #define NATIVE_IDLE 0
111 #define NATIVE_WAIT_HELLO 1
112 #define NATIVE_WAIT_RESULT 2
113 #define NATIVE_WAIT_INSERT_META 3
114  
115 /* Decode flags for column value formatting (opt-in) */
116 #define DECODE_DT_STR (1 << 0) /* Date/DateTime/DateTime64 → string */
117 #define DECODE_DEC_SCALE (1 << 1) /* Decimal → scaled NV */
118 #define DECODE_ENUM_STR (1 << 2) /* Enum → string label */
119 #define DECODE_NAMED_ROWS (1 << 3) /* results as arrayref of hashrefs */
120  
121 struct ev_clickhouse_s {
122 unsigned int magic;
123 struct ev_loop *loop;
124 SV *loop_sv; /* owned ref to the EV::Loop guts (mirrors
125 EV watchers): keeps a custom loop alive
126 while our watchers are registered */
127  
128 int fd;
129 ev_io rio, wio;
130 ev_timer timer;
131 int reading, writing, timing;
132 int connected, connecting;
133 int handshaking; /* TCP up, TLS/ServerHello still pending;
134 queues like connecting, never "ready" */
135 int dns_pending; /* set while EV::cares is resolving the host;
136 query()/insert()/ping() queue against this
137 state so calls between new() and connect
138 don't croak with "not connected" */
139 int in_disconnect; /* set while on_disconnect runs; lets the
140 handler queue queries per the documented
141 contract (they dispatch on reconnect, or
142 error at teardown if none comes) */
143 unsigned int connect_gen; /* bumped by every start_connect and by
144 finish; lets fail_connection and the other
145 teardown paths notice when the user took
146 over from inside a callback */
147 int protocol; /* PROTO_HTTP or PROTO_NATIVE */
148  
149 #ifdef HAVE_OPENSSL
150 SSL_CTX *ssl_ctx;
151 SSL *ssl;
152 #endif
153 int tls_enabled;
154 char *tls_ca_file;
155 char *tls_cert_file; /* client certificate (mutual TLS) */
156 char *tls_key_file; /* client private key (mutual TLS) */
157  
158 /* connection params */
159 char *host, *user, *password, *database;
160 unsigned int port;
161  
162 /* send/recv buffers */
163 char *send_buf;
164 size_t send_len, send_pos, send_cap;
165 char *recv_buf;
166 size_t recv_len, recv_cap;
167 char *http_decoded; /* chunked body accumulated so far (NULL = none) */
168 size_t http_decoded_len;
169 size_t http_decoded_cap;
170 size_t http_chunk_off; /* offset into recv_buf of next unparsed chunk hdr */
171 int http_chunk_active; /* 1 = a partially decoded chunked body is held */
172  
173 /* native protocol state */
174 char *server_name;
175 char *server_display_name;
176 char *server_timezone;
177 char *query_session_tz; /* in-flight query's session_timezone */
178 unsigned int server_version_major, server_version_minor, server_revision;
179 unsigned int server_version_patch;
180 int native_state; /* NATIVE_IDLE, NATIVE_WAIT_HELLO, NATIVE_WAIT_RESULT, ... */
181 AV *native_rows; /* accumulate rows across Data blocks */
182 char *insert_data; /* pending TabSeparated data for two-phase INSERT */
183 size_t insert_data_len;
184 SV *insert_av; /* snapshot_insert_av() of an arrayref INSERT */
185 char *insert_err; /* deferred error from unsupported INSERT encoding */
186 int insert_empty_as_default;/* empty cells fall back to column DEFAULT */
187 HV *insert_defaults; /* per-column caller defaults (owned) */
188 tc_cols_t *insert_tc; /* parsed TableColumns for pending INSERT */
189  
190 /* queues */
191 ngx_queue_t cb_queue;
192 ngx_queue_t send_queue;
193 int pending_count;
194 int send_count;
195  
196 /* options */
197 char *session_id;
198 char *query_log_comment; /* prepended as a SQL block comment per query */
199 int compress;
200 double connect_timeout;
201 HV *default_settings; /* connection-level ClickHouse settings */
202  
203 SV *on_connect;
204 SV *on_error;
205 SV *on_progress;
206 SV *on_disconnect;
207 SV *on_query_complete; /* fires after each query (success or error) */
208 SV *on_query_start; /* fires when a query is dispatched */
209 SV *on_log; /* native SERVER_LOG packets */
210 SV *on_failover; /* multi-host: ($oh, $op, $nh, $np, $msg) */
211 char *last_tls_error; /* OpenSSL error from last failed handshake */
212 char **failover_hosts; /* parallel arrays: hosts + ports. */
213 unsigned int *failover_ports; /* NULL if multi-host failover disabled. */
214 int failover_n;
215 int failover_idx;
216 unsigned int failover_default_port;
217 double query_start_time; /* ev_now() captured in pipeline_advance */
218 int tls_skip_verify;
219 double query_timeout;
220 size_t max_query_size; /* 0 = unlimited; client-side croak guard */
221 size_t max_recv_buffer; /* 0 = unlimited; defensive recv ceiling */
222 int http_basic_auth; /* 0=X-ClickHouse-{User,Key} (default);
223 * 1=Authorization: Basic ... (for proxies) */
224 int auto_reconnect;
225 uint32_t decode_flags;
226 AV *native_col_names; /* column names from last native result */
227 AV *native_col_types; /* column type strings from last native result */
228 SV *on_drain; /* callback fired when pending_count drops to 0 */
229 char *last_query_id; /* query_id of the last dispatched query */
230 SV *on_trace; /* debug trace callback */
231 ev_timer ka_timer; /* keepalive timer */
232 double keepalive; /* keepalive interval (0 = disabled) */
233 int ka_timing;
234 int callback_depth;
235 /* error info from last SERVER_EXCEPTION or HTTP error */
236 int32_t last_error_code;
237 /* profile info from last SERVER_PROFILE_INFO */
238 uint64_t profile_rows;
239 uint64_t profile_bytes;
240 uint64_t profile_rows_before_limit;
241 /* totals / extremes from last native query */
242 AV *native_totals;
243 AV *native_extremes;
244 /* reconnect backoff */
245 double reconnect_delay;
246 double reconnect_max_delay;
247 double reconnect_jitter; /* fractional [0, 1+]: actual delay
248 picks uniformly in [d, d*(1+jitter)] */
249 int reconnect_attempts;
250 int reconnect_max_attempts; /* 0 = unlimited */
251 int pending_addendum_finish; /* set when addendum partially written;
252 * io_cb completes finish_connect after drain */
253 ev_timer reconnect_timer;
254 int reconnect_timing;
255 int cancel_after_meta; /* cancel() during NATIVE_WAIT_INSERT_META:
256 * the sample-block reply path appends
257 * CLIENT_CANCEL after the data block instead
258 * of letting send_replace drop it */
259 int in_trace; /* emit_trace re-entry guard: a trace handler
260 * that calls reset()/finish() would otherwise
261 * recurse through a fresh trace; nested
262 * emissions drop while this is set */
263 int force_zero_dur; /* one-shot: the next on_query_complete reports
264 * dur 0.0 (consumed by the fire, for teardown
265 * of never-dispatched entries) */
266 int in_dispatch; /* set while on_query_start runs: the entry is
267 * dequeued but send_count isn't bumped yet, so
268 * cancel() consults this instead of no-op'ing */
269 int dispatch_cancelled; /* cancel() from on_query_start (native): drop
270 * the staged entry without writing anything */
271 int cancelled; /* native CLIENT_CANCEL sent for the in-flight
272 * query: EOS then reports "query cancelled"
273 * instead of a misleading empty success */
274 unsigned dispatch_seq; /* bumped per dispatch; lets on_query_complete
275 * tell a nested dispatch from its own query */
276 /* on_progress throttling (0 = fire every packet) */
277 double progress_period;
278 double progress_last; /* ev_now() of last on_progress dispatch */
279 uint64_t progress_acc[5]; /* coalesced totals since last dispatch */
280 /* LowCardinality cross-block dictionary state */
281 SV ***lc_dicts; /* array of dictionaries, one per column */
282 uint64_t *lc_dict_sizes; /* size of each dictionary */
283 int lc_num_cols; /* number of columns with LC state */
284 };
285  
286 struct ev_ch_cb_s {
287 SV *cb;
288 int raw; /* return raw response body instead of parsed rows */
289 SV *on_data; /* per-query streaming callback (fires per block) */
290 SV *on_complete;/* per-query on_query_complete override (or NULL) */
291 double query_timeout; /* per-query timeout (0=use default) */
292 ngx_queue_t queue;
293 };
294  
295 struct ev_ch_send_s {
296 char *data; /* full HTTP request or native packet */
297 size_t data_len;
298 SV *cb;
299 char *insert_data; /* deferred TSV data for native INSERT */
300 size_t insert_data_len;
301 SV *insert_av; /* snapshot_insert_av() for native INSERT */
302 int insert_empty_as_default;
303 HV *insert_defaults;
304 int raw; /* return raw response body */
305 SV *on_data; /* per-query streaming callback */
306 SV *on_complete; /* per-query on_query_complete override */
307 double query_timeout; /* per-query timeout */
308 char *query_id; /* query_id for tracking */
309 char *session_tz; /* per-query session_timezone setting */
310 /* Pre-connect native builds: server_revision is unknown at enqueue,
311 * so the packet (whose params block depends on it) is built at
312 * dispatch from these retained inputs. data==NULL while deferred;
313 * non-NULL deferred_sql marks the entry. Snapshots: owned copies. */
314 char *deferred_sql;
315 size_t deferred_sql_len;
316 HV *deferred_defaults;
317 HV *deferred_overrides;
318 char *deferred_ext;
319 size_t deferred_ext_len;
320 ngx_queue_t queue;
321 };
322  
323 /* Forward declarations for helpers defined further down (or in xs/io.c)
324 * but called from earlier code in this file or from xs/*.c included
325 * before the definition site. */
326 static void timer_cb(EV_P_ ev_timer *w, int revents);
327 static void stop_keepalive(ev_clickhouse_t *self);
328 static void schedule_reconnect(ev_clickhouse_t *self);
329 static void lc_free_dicts(ev_clickhouse_t *self);
330 static void free_insert_default_state(ev_clickhouse_t *self);
331 static void start_reading(ev_clickhouse_t *self);
332 static void stop_reading(ev_clickhouse_t *self);
333 static void start_writing(ev_clickhouse_t *self);
334 static void stop_writing(ev_clickhouse_t *self);
335 static void emit_error(ev_clickhouse_t *self, const char *msg);
336 static void emit_trace(ev_clickhouse_t *self, const char *fmt, ...);
337 static int cleanup_connection(ev_clickhouse_t *self, int reconnecting);
338 static int cancel_pending(ev_clickhouse_t *self, const char *errmsg,
339 int fail_requeues);
340 static int cancel_or_preserve(ev_clickhouse_t *self, const char *errmsg);
341 static int check_destroyed(ev_clickhouse_t *self);
342 static char *safe_strdup(const char *s);
343 static void store_conn_params(ev_clickhouse_t *self, const char *host,
344 unsigned int port, const char *user,
345 const char *password, const char *database);
346 static void failover_free(ev_clickhouse_t *self);
347 static int finish_connect(ev_clickhouse_t *self);
348 static int try_write(ev_clickhouse_t *self);
349 static int pipeline_advance(ev_clickhouse_t *self);
350 #ifdef HAVE_OPENSSL
351 static void capture_tls_error(ev_clickhouse_t *self);
352 #endif
353  
354 /* Two helpers shared between the PL_dirty and normal arms of DESTROY:
355 * adding a new on_* slot or persistent string requires touching only
356 * one place. on_failover is omitted from CONNECTION_HANDLERS because
357 * failover_free() handles it together with the host ring. */
358 #define CLEAR_CONNECTION_HANDLERS(self) do { \
359 CLEAR_SV((self)->on_connect); \
360 CLEAR_SV((self)->on_error); \
361 CLEAR_SV((self)->on_progress); \
362 CLEAR_SV((self)->on_disconnect); \
363 CLEAR_SV((self)->on_query_complete); \
364 CLEAR_SV((self)->on_query_start); \
365 CLEAR_SV((self)->on_log); \
366 CLEAR_SV((self)->on_drain); \
367 CLEAR_SV((self)->on_trace); \
368 } while (0)
369  
370 #define CLEAR_PERSISTENT_STATE(self) do { \
371 CLEAR_STR((self)->last_tls_error); \
372 CLEAR_STR((self)->last_query_id); \
373 CLEAR_STR((self)->host); \
374 CLEAR_STR((self)->user); \
375 CLEAR_STR((self)->password); \
376 CLEAR_STR((self)->database); \
377 CLEAR_STR((self)->session_id); \
378 CLEAR_STR((self)->query_log_comment); \
379 CLEAR_STR((self)->tls_ca_file); \
380 CLEAR_STR((self)->tls_cert_file); \
381 CLEAR_STR((self)->tls_key_file); \
382 CLEAR_STR((self)->server_name); \
383 CLEAR_STR((self)->server_display_name); \
384 CLEAR_STR((self)->server_timezone); \
385 CLEAR_STR((self)->query_session_tz); \
386 CLEAR_STR((self)->insert_err); \
387 CLEAR_STR((self)->recv_buf); \
388 CLEAR_STR((self)->http_decoded); \
389 CLEAR_STR((self)->send_buf); \
390 CLEAR_SV((self)->native_rows); \
391 CLEAR_SV((self)->native_col_names); \
392 CLEAR_SV((self)->native_col_types); \
393 CLEAR_SV((self)->native_totals); \
394 CLEAR_SV((self)->native_extremes); \
395 CLEAR_SV((self)->default_settings); \
396 } while (0)
397  
398 #include "xs/macros.h"
399 #include "xs/queues.c"
400  
401 /* --- watcher helpers --- */
402  
403 110 static void start_reading(ev_clickhouse_t *self) {
404 110 ▶ if (!self->reading && self->fd >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->reading && self->fd >= 0) { 58 52 110
if (!self->reading && self->fd >= 0) { 58 0 58
405 58 ev_io_start(self->loop, &self->rio);
406 58 self->reading = 1;
407 }
408 110 }
409  
410 194 static void stop_reading(ev_clickhouse_t *self) {
411 194 ▶ if (self->reading) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reading) { 58 136 194
412 58 ev_io_stop(self->loop, &self->rio);
413 58 self->reading = 0;
414 }
415 194 }
416  
417 107 static void start_writing(ev_clickhouse_t *self) {
418 107 ▶ if (!self->writing && self->fd >= 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (!self->writing && self->fd >= 0) { 107 0 107
if (!self->writing && self->fd >= 0) { 107 0 107
419 107 ev_io_start(self->loop, &self->wio);
420 107 self->writing = 1;
421 }
422 107 }
423  
424 450 static void stop_writing(ev_clickhouse_t *self) {
425 450 ▶ if (self->writing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->writing) { 107 343 450
426 107 ev_io_stop(self->loop, &self->wio);
427 107 self->writing = 0;
428 }
429 450 }
430  
431 270 static void stop_timing(ev_clickhouse_t *self) {
432 270 ▶ if (self->timing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->timing) { 1 269 270
433 1 ev_timer_stop(self->loop, &self->timer);
434 1 self->timing = 0;
435 }
436 270 }
437  
438 435 static int check_destroyed(ev_clickhouse_t *self) {
439 435 ▶ if (self->magic == EV_CH_FREED && self->callback_depth == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->magic == EV_CH_FREED && self->callback_depth == 0) { 0 435 435
if (self->magic == EV_CH_FREED && self->callback_depth == 0) { 0 0 0
440 0 ▶ CLEAR_STR(self->recv_buf);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->recv_buf); 0 0 0
441 0 Safefree(self);
442 0 return 1;
443 }
444 435 return 0;
445 }
446  
447 /* Free the per-connection failover host list (allocated by setter). */
448 /* Free just the host-list arrays. Called from _set_failover before
449 * re-populating + from failover_free below. Keeps on_failover alive. */
450 49 static void failover_free_hosts(ev_clickhouse_t *self) {
451 49 ▶ if (self->failover_hosts) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->failover_hosts) { 1 48 49
452 3 ▶ for (int i = 0; i < self->failover_n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (int i = 0; i < self->failover_n; i++) 2 1 3
453 2 ▶ if (self->failover_hosts[i]) Safefree(self->failover_hosts[i]);
Branch: 1 branch
BranchTrueFalseTotal
if (self->failover_hosts[i]) Safefree(self->failover_hosts[i]); 2 0 2
454 1 Safefree(self->failover_hosts);
455 1 self->failover_hosts = NULL;
456 }
457 49 ▶ if (self->failover_ports) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->failover_ports) { 1 48 49
458 1 Safefree(self->failover_ports);
459 1 self->failover_ports = NULL;
460 }
461 49 self->failover_n = 0;
462 49 self->failover_idx = 0;
463 49 }
464  
465 /* Full failover-state teardown including the on_failover SV. DESTROY only. */
466 48 static void failover_free(ev_clickhouse_t *self) {
467 48 failover_free_hosts(self);
468 48 ▶ if (self->on_failover) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_failover) { 0 48 48
469 0 SvREFCNT_dec(self->on_failover);
470 0 self->on_failover = NULL;
471 }
472 48 }
473  
474 /* Word-boundary case-insensitive match against the failover-trigger
475 * keyword set. Used by emit_error to decide whether to rotate the
476 * multi-host ring. Returns 1 on match, 0 otherwise. */
477 1 static int failover_msg_match(const char *msg) {
478 static const char *KEYWORDS[] = {
479 "connect", "refused", "timeout", "unreachable", "route",
480 "reset", "closed", "broken", "down", "dns", "resolution",
481 "getaddrinfo", NULL,
482 };
483 1 ▶ if (!msg) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!msg) return 0; 0 1 1
484 1 ▶ for (const char **k = KEYWORDS; *k; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char **k = KEYWORDS; *k; k++) { 1 0 1
485 1 size_t kl = strlen(*k);
486 1 const char *p = msg;
487 0 for (;;) {
488 1 const char *m = NULL;
489 1 ▶ for (const char *q = p; *q; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = p; *q; q++) { 1 0 1
490 1 ▶ if (strncasecmp(q, *k, kl) == 0) { m = q; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (strncasecmp(q, *k, kl) == 0) { m = q; break; } 1 0 1
491 }
492 1 ▶ if (!m) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!m) break; 0 1 1
493 1 ▶ int boundary_l = (m == msg) || !isalnum((unsigned char)m[-1]);
Branch: 2 branches
BranchTrueFalseTotal
int boundary_l = (m == msg) || !isalnum((unsigned char)m[-1]); 0 1 1
int boundary_l = (m == msg) || !isalnum((unsigned char)m[-1]); 0 0 0
494 1 int boundary_r = !isalnum((unsigned char)m[kl]);
495 1 ▶ if (boundary_l && boundary_r) return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (boundary_l && boundary_r) return 1; 1 0 1
if (boundary_l && boundary_r) return 1; 1 0 1
496 0 p = m + 1;
497 }
498 }
499 0 return 0;
500 }
501  
502 /* Advance failover ring + fire on_failover callback (if set). Caller is
503 * responsible for callback_depth bookkeeping. */
504 40 static void failover_advance(ev_clickhouse_t *self, const char *msg) {
505 40 ▶ if (!self->failover_hosts || self->failover_n <= 0) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!self->failover_hosts || self->failover_n <= 0) return; 1 39 40
if (!self->failover_hosts || self->failover_n <= 0) return; 0 1 1
506 1 ▶ if (!failover_msg_match(msg)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!failover_msg_match(msg)) return; 0 1 1
507 1 ▶ char *old_host = self->host ? safe_strdup(self->host) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
char *old_host = self->host ? safe_strdup(self->host) : NULL; 1 0 1
508 1 unsigned int old_port = self->port;
509 1 self->failover_idx = (self->failover_idx + 1) % self->failover_n;
510 1 ▶ CLEAR_STR(self->host);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->host); 1 0 1
511 1 self->host = safe_strdup(self->failover_hosts[self->failover_idx]);
512 1 self->port = self->failover_ports[self->failover_idx];
513 1 ▶ if (self->on_failover) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_failover) { 1 0 1
514 1 dSP;
515 1 ENTER; SAVETMPS;
516 1 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 1 1
517 1 ▶ XPUSHs(old_host ? sv_2mortal(newSVpv(old_host, 0)) : &PL_sv_undef);
Branch: 2 branches
BranchTrueFalseTotal
XPUSHs(old_host ? sv_2mortal(newSVpv(old_host, 0)) : &PL_sv_undef); 0 1 1
XPUSHs(old_host ? sv_2mortal(newSVpv(old_host, 0)) : &PL_sv_undef); 1 0 1
518 1 ▶ mXPUSHu(old_port);
Branch: 1 branch
BranchTrueFalseTotal
mXPUSHu(old_port); 0 1 1
519 1 ▶ XPUSHs(sv_2mortal(newSVpv(self->host, 0)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpv(self->host, 0))); 0 1 1
520 1 ▶ mXPUSHu(self->port);
Branch: 1 branch
BranchTrueFalseTotal
mXPUSHu(self->port); 0 1 1
521 1 ▶ XPUSHs(sv_2mortal(newSVpv(msg ? msg : "", 0)));
Branch: 2 branches
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpv(msg ? msg : "", 0))); 0 1 1
XPUSHs(sv_2mortal(newSVpv(msg ? msg : "", 0))); 1 0 1
522 1 PUTBACK;
523 1 PINNED_CALL_SV(self->on_failover, G_DISCARD | G_EVAL);
524 1 ▶ WARN_AND_CLEAR_ERRSV("on_failover");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("on_failover"); 1 0 1
WARN_AND_CLEAR_ERRSV("on_failover"); 0 1 1
WARN_AND_CLEAR_ERRSV("on_failover"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_failover"); 0 0 0
525 1 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 1 0 1
526 }
527 1 ▶ if (old_host) Safefree(old_host);
Branch: 1 branch
BranchTrueFalseTotal
if (old_host) Safefree(old_host); 1 0 1
528 }
529  
530 40 static void emit_error(ev_clickhouse_t *self, const char *msg) {
531 /* Guard callback_depth across BOTH dispatches: failover_advance can
532 * fire on_failover, and a user reset/finish from there must not
533 * cause Safefree(self) before emit_error finishes its own work.
534 * Caller must invoke check_destroyed() afterwards. */
535 40 self->callback_depth++;
536 40 failover_advance(self, msg);
537 40 ▶ if (!self->on_error) goto done;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->on_error) goto done; 0 40 40
538 {
539 40 dSP;
540 40 ENTER;
541 40 SAVETMPS;
542 40 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 40 40
543 40 ▶ XPUSHs(sv_2mortal(newSVpv(msg, 0)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpv(msg, 0))); 0 40 40
544 40 PUTBACK;
545  
546 40 PINNED_CALL_SV(self->on_error, G_DISCARD | G_EVAL);
547 40 ▶ WARN_AND_CLEAR_ERRSV("error handler");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("error handler"); 40 0 40
WARN_AND_CLEAR_ERRSV("error handler"); 0 40 40
WARN_AND_CLEAR_ERRSV("error handler"); 0 0 0
WARN_AND_CLEAR_ERRSV("error handler"); 0 0 0
548  
549 40 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 40 0 40
550 40 LEAVE;
551 }
552 40 done:
553 40 self->callback_depth--;
554 40 }
555  
556 /* emit_error + cancel_pending + cleanup_connection. Returns 1 if self was
557 * freed; on 0 the connection is still gone, so caller should return either way.
558 * Re-checks connect_gen after BOTH emit_error and cancel_pending so a user
559 * reset() from on_error OR from any error-callback dispatched by
560 * cancel_pending wins over our teardown. */
561 11 static int teardown_io_error(ev_clickhouse_t *self, const char *emit_msg,
562 const char *cancel_msg) {
563 11 int gen = self->connect_gen;
564 11 emit_error(self, emit_msg);
565 11 ▶ if (check_destroyed(self)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (check_destroyed(self)) return 1; 0 11 11
566 11 ▶ if (self->connect_gen != gen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return 0; 1 10 11
567 10 ▶ if (cancel_or_preserve(self, cancel_msg)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_or_preserve(self, cancel_msg)) return 1; 0 10 10
568 10 ▶ if (self->connect_gen != gen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return 0; 0 10 10
569 10 return cleanup_connection(self, 0); /* 1 if on_disconnect freed self */
570 }
571  
572 9 static int fail_connection(ev_clickhouse_t *self, const char *msg) {
573 9 int gen = self->connect_gen;
574 9 ▶ if (teardown_io_error(self, msg, msg)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (teardown_io_error(self, msg, msg)) return 1; 0 9 9
575 /* gen mismatch means user reset() inside a callback — don't override
576 * their new connect with an auto-reconnect. */
577 9 ▶ if (self->connect_gen == gen && self->auto_reconnect && self->host)
Branch: 3 branches
BranchTrueFalseTotal
if (self->connect_gen == gen && self->auto_reconnect && self->host) 8 1 9
if (self->connect_gen == gen && self->auto_reconnect && self->host) 5 3 8
if (self->connect_gen == gen && self->auto_reconnect && self->host) 5 0 5
578 5 schedule_reconnect(self);
579 9 return 0;
580 }
581  
582 /* teardown_io_error that also re-arms auto_reconnect. cancel_or_preserve
583 * keeps the send queue on a connected auto_reconnect handle, so a bare
584 * teardown strands those entries (never dispatched, never failed). */
585 1 static int teardown_io_error_reconnect(ev_clickhouse_t *self,
586 const char *emit_msg,
587 const char *cancel_msg) {
588 1 int gen = self->connect_gen;
589 1 ▶ if (teardown_io_error(self, emit_msg, cancel_msg)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (teardown_io_error(self, emit_msg, cancel_msg)) return 1; 0 1 1
590 1 ▶ if (self->connect_gen == gen && self->auto_reconnect && self->host)
Branch: 3 branches
BranchTrueFalseTotal
if (self->connect_gen == gen && self->auto_reconnect && self->host) 1 0 1
if (self->connect_gen == gen && self->auto_reconnect && self->host) 0 1 1
if (self->connect_gen == gen && self->auto_reconnect && self->host) 0 0 0
591 0 schedule_reconnect(self);
592 1 return 0;
593 }
594  
595 /* Invoke a zero-argument callback (on_connect, on_disconnect, on_drain).
596 * Self-guards callback_depth and consumes ERRSV; caller decides whether to
597 * SvREFCNT_dec the captured cb. Returns 1 if self was freed. */
598 100 static int fire_zero_arg_cb(ev_clickhouse_t *self, SV *cb, const char *what) {
599 100 self->callback_depth++;
600 {
601 100 dSP;
602 100 ENTER;
603 100 SAVETMPS;
604 100 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 100 100
605 100 PUTBACK;
606 100 PINNED_CALL_SV(cb, G_DISCARD | G_EVAL);
607 100 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 100 0 100
if (SvTRUE(ERRSV)) { 0 100 100
608 0 ▶ warn("EV::ClickHouse: exception in %s handler: %s",
Branch: 1 branch
BranchTrueFalseTotal
warn("EV::ClickHouse: exception in %s handler: %s", 0 0 0
609 what, SvPV_nolen(ERRSV));
610 0 ▶ sv_setsv(ERRSV, &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
sv_setsv(ERRSV, &PL_sv_undef); 0 0 0
611 }
612 100 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 0 100 100
613 100 LEAVE;
614 }
615 100 self->callback_depth--;
616 100 return check_destroyed(self);
617 }
618  
619 192 static void emit_trace(ev_clickhouse_t *self, const char *fmt, ...) {
620 char buf[512];
621 va_list ap;
622 194 ▶ if (!self->on_trace) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!self->on_trace) return; 187 5 192
623 5 ▶ if (self->in_trace) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->in_trace) return; 2 3 5
624 3 va_start(ap, fmt);
625 3 vsnprintf(buf, sizeof(buf), fmt, ap);
626 3 va_end(ap);
627  
628 /* Guard callback_depth; deliberately skip check_destroyed because most
629 * callers continue to use self after emit_trace — outer check_destroyed
630 * picks up the EV_CH_FREED state on the next opportunity. */
631 3 self->in_trace = 1;
632 3 self->callback_depth++;
633 {
634 3 dSP;
635 3 ENTER;
636 3 SAVETMPS;
637 3 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 3 3
638 3 ▶ XPUSHs(sv_2mortal(newSVpv(buf, 0)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newSVpv(buf, 0))); 0 3 3
639 3 PUTBACK;
640 3 PINNED_CALL_SV(self->on_trace, G_DISCARD | G_EVAL);
641 3 ▶ WARN_AND_CLEAR_ERRSV("trace handler");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("trace handler"); 3 0 3
WARN_AND_CLEAR_ERRSV("trace handler"); 0 3 3
WARN_AND_CLEAR_ERRSV("trace handler"); 0 0 0
WARN_AND_CLEAR_ERRSV("trace handler"); 0 0 0
642 3 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 3 0 3
643 3 LEAVE;
644 }
645 3 self->callback_depth--;
646 3 self->in_trace = 0;
647 }
648  
649 /* Pop the head cb_queue entry. If `out_on_complete` is non-NULL, the
650 * per-query on_query_complete override (if any) is moved into *out_on_complete
651 * with ownership transferred to the caller (caller must SvREFCNT_dec). */
652 49 static SV* pop_cb_ex(ev_clickhouse_t *self, SV **out_on_complete) {
653 ngx_queue_t *q;
654 ev_ch_cb_t *cbt;
655 SV *cb;
656  
657 49 ▶ if (out_on_complete) *out_on_complete = NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (out_on_complete) *out_on_complete = NULL; 49 0 49
658 49 ▶ if (ngx_queue_empty(&self->cb_queue)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return NULL; 0 49 49
659  
660 49 q = ngx_queue_head(&self->cb_queue);
661 49 cbt = ngx_queue_data(q, ev_ch_cb_t, queue);
662  
663 49 cb = cbt->cb;
664 49 ▶ CLEAR_SV(cbt->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(cbt->on_data); 0 49 49
665 49 ▶ if (out_on_complete) {
Branch: 1 branch
BranchTrueFalseTotal
if (out_on_complete) { 49 0 49
666 49 *out_on_complete = cbt->on_complete; /* transfer ownership */
667 49 cbt->on_complete = NULL;
668 } else {
669 0 ▶ CLEAR_SV(cbt->on_complete);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(cbt->on_complete); 0 0 0
670 }
671 49 ngx_queue_remove(q);
672 49 self->pending_count--;
673 49 release_cbt(cbt);
674  
675 49 return cb;
676 }
677  
678 /* Peek the on_data callback from front of cb_queue (NULL if none) */
679 0 static SV* peek_cb_on_data(ev_clickhouse_t *self) {
680 ngx_queue_t *q;
681 ev_ch_cb_t *cbt;
682 0 ▶ if (ngx_queue_empty(&self->cb_queue)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return NULL; 0 0 0
683 0 q = ngx_queue_head(&self->cb_queue);
684 0 cbt = ngx_queue_data(q, ev_ch_cb_t, queue);
685 0 return cbt->on_data;
686 }
687  
688 1 static int peek_cb_raw(ev_clickhouse_t *self) {
689 ngx_queue_t *q;
690 ev_ch_cb_t *cbt;
691 1 ▶ if (ngx_queue_empty(&self->cb_queue)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (ngx_queue_empty(&self->cb_queue)) return 0; 0 1 1
692 1 q = ngx_queue_head(&self->cb_queue);
693 1 cbt = ngx_queue_data(q, ev_ch_cb_t, queue);
694 1 return cbt->raw;
695 }
696  
697 55 static void invoke_cb(SV *cb) {
698 55 call_sv(cb, G_DISCARD | G_EVAL);
699 55 ▶ WARN_AND_CLEAR_ERRSV("callback");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("callback"); 55 0 55
WARN_AND_CLEAR_ERRSV("callback"); 0 55 55
WARN_AND_CLEAR_ERRSV("callback"); 0 0 0
WARN_AND_CLEAR_ERRSV("callback"); 0 0 0
700 55 SvREFCNT_dec(cb);
701 55 }
702  
703 /* Invoke `cb` with (undef, errmsg). Caller manages callback_depth. */
704 52 static void invoke_err_cb(SV *cb, const char *errmsg) {
705 52 dSP;
706 52 ENTER;
707 52 SAVETMPS;
708 52 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 52 52
709 52 PUSHs(&PL_sv_undef);
710 52 PUSHs(sv_2mortal(newSVpv(errmsg, 0)));
711 52 PUTBACK;
712 52 invoke_cb(cb);
713 52 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 52 0 52
714 52 LEAVE;
715 52 }
716  
717 /* Fire on_query_complete with (query_id, rows, bytes, error_code, duration_s, errmsg).
718 * Caller must guard callback_depth around any invoke that follows. Safe to
719 * call when on_query_complete is unset. `override` (when non-NULL) is the
720 * per-query override hook from the settings hashref; it REPLACES the
721 * connection-level handler for this query so per-query instrumentation
722 * doesn't double-count against global metrics. */
723 51 static void fire_on_query_complete_ex(ev_clickhouse_t *self, const char *errmsg,
724 SV *override) {
725 51 ▶ SV *target = override ? override : self->on_query_complete;
Branch: 1 branch
BranchTrueFalseTotal
SV *target = override ? override : self->on_query_complete; 51 0 51
726 51 ▶ if (!target) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!target) return; 51 0 51
727 0 double dur = self->force_zero_dur ? 0.0
728 0 ▶ : self->query_start_time > 0
Branch: 1 branch
BranchTrueFalseTotal
: self->query_start_time > 0 0 0 0
729 0 ▶ ? ev_now(self->loop) - self->query_start_time : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
? ev_now(self->loop) - self->query_start_time : 0.0; 0 0 0
730 /* Consumed by this fire: a nested teardown during the handler must
731 * see the real start time, not a leaked zero. */
732 0 self->force_zero_dur = 0;
733 0 unsigned seq0 = self->dispatch_seq;
734 0 self->callback_depth++;
735 {
736 0 dSP;
737 0 ENTER; SAVETMPS;
738 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
739 0 ▶ EXTEND(SP, 6);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 6); 0 0 0
740 0 ▶ PUSHs(self->last_query_id
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(self->last_query_id 0 0 0
741 ? sv_2mortal(newSVpv(self->last_query_id, 0)) : &PL_sv_undef);
742 0 PUSHs(sv_2mortal(newSVuv(self->profile_rows)));
743 0 PUSHs(sv_2mortal(newSVuv(self->profile_bytes)));
744 0 PUSHs(sv_2mortal(newSViv(self->last_error_code)));
745 0 PUSHs(sv_2mortal(newSVnv(dur)));
746 0 ▶ PUSHs(errmsg ? sv_2mortal(newSVpv(errmsg, 0)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(errmsg ? sv_2mortal(newSVpv(errmsg, 0)) : &PL_sv_undef); 0 0 0
747 0 PUTBACK;
748 0 PINNED_CALL_SV(target, G_DISCARD | G_EVAL);
749 0 ▶ WARN_AND_CLEAR_ERRSV("on_query_complete");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("on_query_complete"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_query_complete"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_query_complete"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_query_complete"); 0 0 0
750 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
751 }
752 0 self->callback_depth--;
753 /* Reset the start time only when nothing remains in flight: a queued
754 * entry's fire must not consume the live start time a nested teardown
755 * during its handler still needs (queued fires report dur 0.0 via
756 * force_zero_dur instead). Skip the reset when the handler dispatched
757 * a nested query (seq bumped) — the start time is the nested query's. */
758 0 ▶ if (self->dispatch_seq == seq0 && ngx_queue_empty(&self->cb_queue))
Branch: 2 branches
BranchTrueFalseTotal
if (self->dispatch_seq == seq0 && ngx_queue_empty(&self->cb_queue)) 0 0 0
if (self->dispatch_seq == seq0 && ngx_queue_empty(&self->cb_queue)) 0 0 0
759 0 self->query_start_time = 0;
760 }
761  
762 /* IS_KEEPALIVE_CB is defined in xs/macros.h; keepalive_noop_cb is the
763 * sentinel that backs it (declared below this comment). */
764  
765 15 static int deliver_error(ev_clickhouse_t *self, const char *errmsg) {
766 15 SV *oqc = NULL;
767 15 SV *cb = pop_cb_ex(self, &oqc);
768 15 ▶ if (cb == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb == NULL) { 0 15 15
769 0 fire_on_query_complete_ex(self, errmsg, oqc);
770 0 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 0 0
771 0 return check_destroyed(self);
772 }
773  
774 15 self->callback_depth++;
775 15 ▶ if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, errmsg, oqc);
Branch: 2 branches
BranchTrueFalseTotal
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, errmsg, oqc); 15 0 15
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, errmsg, oqc); 12 3 15
776 15 invoke_err_cb(cb, errmsg);
777 15 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 15 15
778 15 self->callback_depth--;
779 15 return check_destroyed(self);
780 }
781  
782 /* Returns 1 if self was freed. */
783 3 static int deliver_rows(ev_clickhouse_t *self, AV *rows) {
784 3 SV *oqc = NULL;
785 3 SV *cb = pop_cb_ex(self, &oqc);
786 3 ▶ if (cb == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb == NULL) { 0 3 3
787 0 ▶ if (rows) SvREFCNT_dec((SV*)rows);
Branch: 1 branch
BranchTrueFalseTotal
if (rows) SvREFCNT_dec((SV*)rows); 0 0 0
788 0 fire_on_query_complete_ex(self, NULL, oqc);
789 0 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 0 0
790 0 return check_destroyed(self);
791 }
792  
793 3 self->callback_depth++;
794 3 ▶ if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc);
Branch: 2 branches
BranchTrueFalseTotal
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc); 3 0 3
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc); 3 0 3
795 {
796 3 dSP;
797 3 ENTER;
798 3 SAVETMPS;
799 3 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 3 3
800 3 ▶ PUSHs(rows ? sv_2mortal(newRV_noinc((SV*)rows)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(rows ? sv_2mortal(newRV_noinc((SV*)rows)) : &PL_sv_undef); 1 2 3
801 3 PUTBACK;
802 3 invoke_cb(cb);
803 3 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 1 2 3
804 3 LEAVE;
805 }
806 3 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 3 3
807 3 self->callback_depth--;
808 3 return check_destroyed(self);
809 }
810  
811 /* Deliver raw response body as scalar string. Returns 1 if self was freed. */
812 0 static int deliver_raw_body(ev_clickhouse_t *self, const char *data, size_t len) {
813 0 SV *oqc = NULL;
814 0 SV *cb = pop_cb_ex(self, &oqc);
815 0 ▶ if (cb == NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if (cb == NULL) { 0 0 0
816 0 fire_on_query_complete_ex(self, NULL, oqc);
817 0 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 0 0
818 0 return check_destroyed(self);
819 }
820  
821 0 self->callback_depth++;
822 0 ▶ if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc);
Branch: 2 branches
BranchTrueFalseTotal
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc); 0 0 0
if (!IS_KEEPALIVE_CB(cb)) fire_on_query_complete_ex(self, NULL, oqc); 0 0 0
823 {
824 0 dSP;
825 0 ENTER;
826 0 SAVETMPS;
827 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
828 0 PUSHs(sv_2mortal(newSVpvn(data, len)));
829 0 PUTBACK;
830 0 invoke_cb(cb);
831 0 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 0 0 0
832 0 LEAVE;
833 }
834 0 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 0 0
835 0 self->callback_depth--;
836 0 return check_destroyed(self);
837 }
838  
839 /* deliver_error + cancel_pending + cleanup_connection. Mirrors
840 * teardown_io_error but for paths that consume the in-flight callback
841 * (via deliver_error) rather than firing on_error. Returns 1 if self
842 * was freed; on 0 the connection is gone — caller must return either
843 * way. Re-checks connect_gen after BOTH dispatches so a user reset()
844 * from the delivered error-cb OR from any error-cb dispatched by
845 * cancel_pending wins over our teardown. */
846 3 static int teardown_after_deliver(ev_clickhouse_t *self,
847 const char *deliver_msg,
848 const char *cancel_msg) {
849 3 int gen = self->connect_gen;
850 3 ▶ if (deliver_error(self, deliver_msg)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (deliver_error(self, deliver_msg)) return 1; 0 3 3
851 3 ▶ if (self->connect_gen != gen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return 0; 0 3 3
852 3 ▶ if (cancel_or_preserve(self, cancel_msg)) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_or_preserve(self, cancel_msg)) return 1; 0 3 3
853 3 ▶ if (self->connect_gen != gen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return 0; 0 3 3
854 3 return cleanup_connection(self, 0); /* 1 if on_disconnect freed self */
855 }
856  
857 /* on_complete refcount: caller transfers an already-owned ref (or NULL).
858 * Mirror semantics: the send entry held its own SvREFCNT_inc; we adopt
859 * that ref here and clear send->on_complete in the call site. */
860 49 static void push_cb_owned_ex(ev_clickhouse_t *self, SV *cb, int raw,
861 SV *on_data, SV *on_complete,
862 double query_timeout) {
863 49 ev_ch_cb_t *cbt = alloc_cbt();
864 49 cbt->cb = cb;
865 49 cbt->raw = raw;
866 49 ▶ cbt->on_data = on_data ? SvREFCNT_inc(on_data) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
cbt->on_data = on_data ? SvREFCNT_inc(on_data) : NULL; 0 49 49
867 49 cbt->on_complete = on_complete; /* ownership adopted */
868 49 cbt->query_timeout = query_timeout;
869 49 ngx_queue_insert_tail(&self->cb_queue, &cbt->queue);
870 49 }
871  
872 107 static SV* handler_accessor(SV **slot, SV *handler, int has_arg) {
873 107 ▶ if (has_arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (has_arg) { 105 2 107
874 105 ▶ if (handler && SvOK(handler)
Branch: 2 branches
BranchTrueFalseTotal
if (handler && SvOK(handler) 105 0 105
if (handler && SvOK(handler) 104 1 105
875 104 ▶ && !(SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
&& !(SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV)) 103 1 104
&& !(SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV)) 0 103 103
876 1 croak("handler must be a CODE reference or undef");
877 104 ▶ CLEAR_SV(*slot);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(*slot); 1 103 104
878 104 ▶ if (handler && SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV) {
Branch: 3 branches
BranchTrueFalseTotal
if (handler && SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV) { 104 0 104
if (handler && SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV) { 103 1 104
if (handler && SvROK(handler) && SvTYPE(SvRV(handler)) == SVt_PVCV) { 103 0 103
879 103 *slot = SvREFCNT_inc(handler);
880 }
881 }
882 106 ▶ return *slot ? SvREFCNT_inc(*slot) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
return *slot ? SvREFCNT_inc(*slot) : &PL_sv_undef; 104 2 106
883 }
884  
885 222 static char* safe_strdup(const char *s) {
886 char *d;
887 size_t len;
888 222 ▶ if (!s) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!s) return NULL; 18 204 222
889 204 len = strlen(s);
890 204 Newx(d, len + 1, char);
891 204 Copy(s, d, len + 1, char);
892 204 return d;
893 }
894  
895 /* Write a SQL block comment "<slashstar> <cmt> <starslash> " to buf.
896 * Returns bytes written, or 0 if cmt is NULL. Both call sites reserve
897 * strlen(cmt) + 7 bytes for the comment plus the 7 framing bytes. */
898 18 static size_t qlc_emit_prefix(char *buf, const char *cmt) {
899 18 size_t cl, off = 0;
900 18 ▶ if (!cmt) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!cmt) return 0; 18 0 18
901 0 cl = strlen(cmt);
902 0 memcpy(buf + off, "/* ", 3); off += 3;
903 0 memcpy(buf + off, cmt, cl); off += cl;
904 0 memcpy(buf + off, " */ ", 4); off += 4;
905 0 return off;
906 }
907  
908 192 static int has_http_unsafe_chars(const char *s) {
909 /* XS gives us NUL-terminated C strings, so only reject CR/LF. */
910 192 ▶ if (!s) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!s) return 0; 0 192 192
911 1296 ▶ for (; *s; s++)
Branch: 1 branch
BranchTrueFalseTotal
for (; *s; s++) 1104 192 1296
912 1104 ▶ if (*s == '\r' || *s == '\n') return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (*s == '\r' || *s == '\n') return 1; 1104 0 1104
if (*s == '\r' || *s == '\n') return 1; 0 1104 1104
913 192 return 0;
914 }
915  
916 /* Drop the first `n` bytes from recv_buf, shifting any remaining bytes left. */
917 49 static inline void recv_consume(struct ev_clickhouse_s *self, size_t n) {
918 /* Saturating: a user callback fired from inside the parser may
919 * call reset() which zeroes recv_len; an unguarded subtract would
920 * underflow size_t to a huge value and the next ch_read would write
921 * past the buffer. */
922 49 ▶ if (n >= self->recv_len) { self->recv_len = 0; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (n >= self->recv_len) { self->recv_len = 0; return; } 49 0 49
923 0 memmove(self->recv_buf, self->recv_buf + n, self->recv_len - n);
924 0 self->recv_len -= n;
925 }
926  
927 static void ensure_send_cap(struct ev_clickhouse_s *self, size_t need);
928  
929 /* Replace send_buf content with `src` (heap-allocated, freed here). */
930 61 static inline void send_replace(struct ev_clickhouse_s *self, char *src, size_t len) {
931 61 ensure_send_cap(self, len);
932 61 Copy(src, self->send_buf, len, char);
933 61 self->send_len = len;
934 61 self->send_pos = 0;
935 61 Safefree(src);
936 61 }
937  
938 1 static int is_ip_literal(const char *s) {
939 struct in_addr a4;
940 struct in6_addr a6;
941 1 return (inet_pton(AF_INET, s, &a4) == 1 ||
942 0 inet_pton(AF_INET6, s, &a6) == 1);
943 }
944  
945 /* Tears down the socket + per-connection state, then fires on_disconnect.
946 * Returns 1 if on_disconnect freed self (caller must not touch self), else 0. */
947 193 static void stop_reconnect(ev_clickhouse_t *self) {
948 193 ▶ if (self->reconnect_timing) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->reconnect_timing) { 0 193 193
949 0 ev_timer_stop(self->loop, &self->reconnect_timer);
950 0 self->reconnect_timing = 0;
951 }
952 193 }
953  
954 /* OpenSSL teardown as file-scope helpers: preprocessor conditionals are
955 * not allowed inside braced XSUB bodies (xsubpp mangles them), so the
956 * DESTROY arms and dump_state call these instead of #ifdef inline. */
957 3 static void ch_ssl_free(ev_clickhouse_t *self) {
958 #ifdef HAVE_OPENSSL
959 3 ▶ if (self->ssl) { SSL_free(self->ssl); self->ssl = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { SSL_free(self->ssl); self->ssl = NULL; } 0 3 3
960 3 ▶ if (self->ssl_ctx) { SSL_CTX_free(self->ssl_ctx); self->ssl_ctx = NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_ctx) { SSL_CTX_free(self->ssl_ctx); self->ssl_ctx = NULL; } 0 3 3
961 #else
962 (void)self;
963 #endif
964 3 }
965  
966 145 static void ch_ssl_shutdown_free(ev_clickhouse_t *self) {
967 #ifdef HAVE_OPENSSL
968 145 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 1 144 145
969 1 SSL_shutdown(self->ssl);
970 1 SSL_free(self->ssl);
971 1 self->ssl = NULL;
972 }
973 145 ▶ if (self->ssl_ctx) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl_ctx) { 1 144 145
974 1 SSL_CTX_free(self->ssl_ctx);
975 1 self->ssl_ctx = NULL;
976 }
977 #else
978 (void)self;
979 #endif
980 145 }
981  
982 0 static int ch_tls_active(ev_clickhouse_t *self) {
983 #ifdef HAVE_OPENSSL
984 0 return self->ssl ? 1 : 0;
985 #else
986 (void)self;
987 return 0;
988 #endif
989 }
990  
991 101 static int cleanup_connection(ev_clickhouse_t *self, int reconnecting) {
992 101 int was_connected = self->connected;
993  
994 101 ▶ if (was_connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (was_connected) { 63 38 101
995 63 int gen = self->connect_gen;
996 63 emit_trace(self, "disconnect");
997 /* The handler may have reset()/finished (or dropped $ch): a
998 * nested reset already tore down and reconnected — continuing
999 * would destroy the new connection. */
1000 63 ▶ if (self->magic != EV_CH_MAGIC) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) return 1; 0 63 63
1001 63 ▶ if (self->connect_gen != gen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return 0; 1 62 63
1002 }
1003 100 stop_reading(self);
1004 100 stop_writing(self);
1005 100 stop_keepalive(self);
1006 100 stop_timing(self);
1007 100 stop_reconnect(self);
1008  
1009 100 ch_ssl_shutdown_free(self);
1010  
1011 100 ▶ if (self->fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { 78 22 100
1012 78 close(self->fd);
1013 78 self->fd = -1;
1014 }
1015  
1016 100 self->connected = 0;
1017 100 self->connecting = 0;
1018 100 self->handshaking = 0;
1019 100 self->dns_pending = 0; /* finish/reset interrupts async DNS */
1020 100 self->send_len = 0;
1021 100 self->send_pos = 0;
1022 100 self->recv_len = 0;
1023 100 ▶ if (self->http_decoded) Safefree(self->http_decoded);
Branch: 1 branch
BranchTrueFalseTotal
if (self->http_decoded) Safefree(self->http_decoded); 0 100 100
1024 100 self->http_decoded = NULL;
1025 100 self->http_decoded_len = 0;
1026 100 self->http_decoded_cap = 0;
1027 100 self->http_chunk_off = 0;
1028 100 self->http_chunk_active = 0;
1029 100 self->send_count = 0;
1030 100 self->pending_addendum_finish = 0;
1031 100 self->cancel_after_meta = 0;
1032 100 self->dispatch_cancelled = 0;
1033 100 self->cancelled = 0;
1034 100 self->native_state = NATIVE_IDLE;
1035 100 ▶ CLEAR_SV(self->native_rows);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_rows); 0 100 100
1036 100 ▶ CLEAR_SV(self->native_col_names);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_names); 0 100 100
1037 100 ▶ CLEAR_SV(self->native_col_types);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_col_types); 0 100 100
1038 100 ▶ CLEAR_SV(self->native_totals);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_totals); 0 100 100
1039 100 ▶ CLEAR_SV(self->native_extremes);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_extremes); 0 100 100
1040 100 lc_free_dicts(self);
1041 100 ▶ CLEAR_INSERT(self); free_insert_default_state(self);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(self); free_insert_default_state(self); 0 100 100
CLEAR_INSERT(self); free_insert_default_state(self); 0 100 100
1042 100 ▶ CLEAR_STR(self->insert_err);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->insert_err); 0 100 100
1043  
1044 /* Fire on_disconnect AFTER state is reset, so a handler that queues
1045 * new queries or calls reconnect sees clean state. The handler can
1046 * drop the last $ch ref (-> DESTROY); propagate that so callers
1047 * don't touch a freed self. */
1048 100 ▶ if (was_connected && self->on_disconnect) {
Branch: 2 branches
BranchTrueFalseTotal
if (was_connected && self->on_disconnect) { 62 38 100
if (was_connected && self->on_disconnect) { 38 24 62
1049 int rc;
1050 38 self->in_disconnect = 1;
1051 38 rc = fire_zero_arg_cb(self, self->on_disconnect, "disconnect");
1052 38 ▶ if (!rc) {
Branch: 1 branch
BranchTrueFalseTotal
if (!rc) { 38 0 38
1053 38 self->in_disconnect = 0;
1054 38 ▶ if (!reconnecting && !self->auto_reconnect && !self->connected && !self->connecting &&
Branch: 4 branches
BranchTrueFalseTotal
if (!reconnecting && !self->auto_reconnect && !self->connected && !self->connecting && 38 0 38
if (!reconnecting && !self->auto_reconnect && !self->connected && !self->connecting && 1 37 38
if (!reconnecting && !self->auto_reconnect && !self->connected && !self->connecting && 1 0 1
if (!reconnecting && !self->auto_reconnect && !self->connected && !self->connecting && 1 0 1
1055 1 ▶ !self->handshaking && !self->dns_pending && !self->reconnect_timing)
Branch: 3 branches
BranchTrueFalseTotal
!self->handshaking && !self->dns_pending && !self->reconnect_timing) 1 0 1
!self->handshaking && !self->dns_pending && !self->reconnect_timing) 1 0 1
!self->handshaking && !self->dns_pending && !self->reconnect_timing) 1 0 1
1056 1 return cancel_pending(self, "connection closed", 0);
1057 }
1058 37 return rc;
1059 }
1060 62 return 0;
1061 }
1062  
1063 /* Fire user error callback + on_query_complete (per-query override or
1064 * connection-level — fire_on_query_complete_ex falls back). Honors the
1065 * documented "fires after every query (success or error)" contract for
1066 * cancelled queries. oqc is consumed (refcount-dec'd) here.
1067 * HTTP keepalive PINGs are suppressed to match the success-path behavior:
1068 * users instrumenting via on_query_complete shouldn't see spurious zero-
1069 * row completions for pings they didn't initiate. */
1070 31 static void fire_err_and_complete(ev_clickhouse_t *self, SV *cb,
1071 const char *errmsg, SV *oqc) {
1072 /* Fire on_query_complete BEFORE the user cb to match the order
1073 * used by deliver_error / deliver_rows on the normal path —
1074 * instrumentation observers expect the global hook to run first.
1075 * Keepalive PINGs are suppressed to match the success-path
1076 * behavior so observers don't see spurious zero-row completions. */
1077 31 ▶ if (!IS_KEEPALIVE_CB(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (!IS_KEEPALIVE_CB(cb)) 31 0 31
if (!IS_KEEPALIVE_CB(cb)) 30 1 31
1078 30 fire_on_query_complete_ex(self, errmsg, oqc);
1079 31 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 31 31
1080 /* A user error callback may drop the last ref to $ch (DESTROY runs
1081 * deferred while callback_depth > 0). invoke_err_cb itself is safe
1082 * either way — caller's outer magic check handles the next loop. */
1083 31 invoke_err_cb(cb, errmsg);
1084 31 }
1085  
1086 /* Drain in-flight cb_queue, delivering errmsg to each callback and resetting
1087 * send_count. Caller manages callback_depth. Aborts if a callback
1088 * reconnected (reset()/connect() bumps connect_gen): the remaining
1089 * entries belong to the new generation — firing them with the old
1090 * teardown error would deliver a phantom error to a live query, and
1091 * zeroing send_count would desync the new generation's in-flight
1092 * accounting. */
1093 195 static void drain_cb_queue(ev_clickhouse_t *self, const char *errmsg) {
1094 195 int gen = self->connect_gen;
1095 225 ▶ while (!ngx_queue_empty(&self->cb_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->cb_queue)) { 30 195 225
1096 30 SV *oqc = NULL;
1097 30 SV *cb = pop_cb_ex(self, &oqc);
1098 30 ▶ if (cb == NULL) break;
Branch: 1 branch
BranchTrueFalseTotal
if (cb == NULL) break; 0 30 30
1099 30 fire_err_and_complete(self, cb, errmsg, oqc);
1100 30 ▶ if (self->magic != EV_CH_MAGIC) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) break; 0 30 30
1101 30 ▶ if (self->connect_gen != gen) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) break; 0 30 30
1102 }
1103 195 ▶ if (self->connect_gen == gen)
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen == gen) 195 0 195
1104 195 self->send_count = 0;
1105 195 }
1106  
1107 /* Returns 1 if self was freed. Abandons the drain if a callback
1108 * reconnected (connect_gen changed): an inner reset()/connect() already
1109 * settled the old generation's queues, and anything queued since
1110 * belongs to the live connection — firing it with the stale teardown
1111 * error would deliver phantom errors to live queries. */
1112 195 static int cancel_pending(ev_clickhouse_t *self, const char *errmsg,
1113 int fail_requeues) {
1114 195 int gen = self->connect_gen;
1115 195 self->callback_depth++;
1116  
1117 /* Entries queued during the cb phase below: fail them right away
1118 * when the connection is going away (they could never dispatch),
1119 * else leave them queued for the reconnect/dispatch that follows. */
1120 195 again:
1121 201 ▶ while (!ngx_queue_empty(&self->send_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->send_queue)) { 6 195 201
1122 6 ngx_queue_t *q = ngx_queue_head(&self->send_queue);
1123 6 ev_ch_send_t *send = ngx_queue_data(q, ev_ch_send_t, queue);
1124 6 SV *cb = send->cb;
1125 6 SV *oqc = send->on_complete; /* transfer ownership for fire below */
1126 6 char *qid = send->query_id; /* adopted for the fire below */
1127 6 send->on_complete = NULL;
1128 6 send->query_id = NULL;
1129 6 ngx_queue_remove(q);
1130 6 Safefree(send->data);
1131 6 ▶ CLEAR_INSERT(send);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(send); 2 4 6
CLEAR_INSERT(send); 0 6 6
1132 6 ▶ CLEAR_SV(send->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(send->on_data); 0 6 6
1133 6 release_send(send);
1134 6 self->pending_count--;
1135  
1136 /* Never-dispatched entries report dur 0.0 via the one-shot
1137 * flag; the shared query_start_time stays live throughout (a
1138 * nested teardown during the handler still measures the
1139 * in-flight query correctly). The entry's own query_id is
1140 * adopted for the fire; last_query_id still names an older
1141 * (possibly in-flight) query and must not leak across. */
1142 6 unsigned seq0 = self->dispatch_seq;
1143 6 char *qid0 = self->last_query_id;
1144 6 self->last_query_id = qid;
1145 6 self->force_zero_dur = 1;
1146 /* Inline fire_err_and_complete: the adopted id must be restored
1147 * BEFORE any user code runs, so nested teardown/dispatch during
1148 * the handlers sees the live id (and a nested CLEAR frees only
1149 * what is current then). */
1150 6 ▶ if (!IS_KEEPALIVE_CB(cb))
Branch: 2 branches
BranchTrueFalseTotal
if (!IS_KEEPALIVE_CB(cb)) 6 0 6
if (!IS_KEEPALIVE_CB(cb)) 6 0 6
1151 6 fire_on_query_complete_ex(self, errmsg, oqc);
1152 6 self->force_zero_dur = 0;
1153 6 ▶ if (self->dispatch_seq == seq0 && self->connect_gen == gen) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->dispatch_seq == seq0 && self->connect_gen == gen) { 6 0 6
if (self->dispatch_seq == seq0 && self->connect_gen == gen) { 6 0 6
1154 6 ▶ CLEAR_STR(self->last_query_id);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->last_query_id); 0 6 6
1155 6 self->last_query_id = qid0;
1156 0 ▶ } else if (qid0) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (qid0) { 0 0 0
1157 /* Nested teardown/dispatch already replaced (and freed)
1158 * our adopted id; the pre-fire id it displaced is ours. */
1159 0 Safefree(qid0);
1160 }
1161 6 ▶ if (oqc) SvREFCNT_dec(oqc);
Branch: 1 branch
BranchTrueFalseTotal
if (oqc) SvREFCNT_dec(oqc); 0 6 6
1162 /* A user error callback may drop the last ref to $ch (DESTROY
1163 * runs deferred while callback_depth > 0). invoke_err_cb itself
1164 * is safe either way — the magic check below handles the rest. */
1165 6 invoke_err_cb(cb, errmsg);
1166 6 ▶ if (self->magic != EV_CH_MAGIC) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) break; 0 6 6
1167 6 ▶ if (self->connect_gen != gen) break;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) break; 0 6 6
1168 }
1169  
1170 195 ▶ if (self->magic == EV_CH_MAGIC && self->connect_gen == gen) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->magic == EV_CH_MAGIC && self->connect_gen == gen) { 195 0 195
if (self->magic == EV_CH_MAGIC && self->connect_gen == gen) { 195 0 195
1171 195 drain_cb_queue(self, errmsg);
1172 195 ▶ if (fail_requeues && self->magic == EV_CH_MAGIC
Branch: 2 branches
BranchTrueFalseTotal
if (fail_requeues && self->magic == EV_CH_MAGIC 148 47 195
if (fail_requeues && self->magic == EV_CH_MAGIC 148 0 148
1173 148 ▶ && self->connect_gen == gen
Branch: 1 branch
BranchTrueFalseTotal
&& self->connect_gen == gen 148 0 148
1174 148 ▶ && !ngx_queue_empty(&self->send_queue))
Branch: 1 branch
BranchTrueFalseTotal
&& !ngx_queue_empty(&self->send_queue)) 0 148 148
1175 0 goto again;
1176  
1177 /* A registered drain waiter must not hang: every queue is drained,
1178 * so pending work is settled (with errors) — release the waiter.
1179 * Skip when a callback re-queued work or dropped the last $ch ref. */
1180 195 ▶ if (self->magic == EV_CH_MAGIC && self->on_drain
Branch: 2 branches
BranchTrueFalseTotal
if (self->magic == EV_CH_MAGIC && self->on_drain 195 0 195
if (self->magic == EV_CH_MAGIC && self->on_drain 0 195 195
1181 0 ▶ && ngx_queue_empty(&self->send_queue)
Branch: 1 branch
BranchTrueFalseTotal
&& ngx_queue_empty(&self->send_queue) 0 0 0
1182 0 ▶ && ngx_queue_empty(&self->cb_queue)
Branch: 1 branch
BranchTrueFalseTotal
&& ngx_queue_empty(&self->cb_queue) 0 0 0
1183 0 ▶ && self->pending_count == 0) {
Branch: 1 branch
BranchTrueFalseTotal
&& self->pending_count == 0) { 0 0 0
1184 0 SV *drain_cb = self->on_drain;
1185 0 self->on_drain = NULL;
1186 0 (void)fire_zero_arg_cb(self, drain_cb, "drain");
1187 0 SvREFCNT_dec(drain_cb);
1188 }
1189 }
1190  
1191 195 self->callback_depth--;
1192 195 return check_destroyed(self);
1193 }
1194  
1195 /* Teardown variant for a live (connected==1) link: entries still in
1196 * send_queue were never sent, so with auto_reconnect they are preserved
1197 * for redispatch after the reconnect instead of failing. In-flight
1198 * cb_queue entries are irrecoverable and fire the error. Without
1199 * auto_reconnect, or with nothing queued, everything fails. Connect-phase
1200 * failures (connected==0) always fail fast: queries must not hang
1201 * silently across backoff before the first byte flows. Exhaustion and
1202 * finish()/reset() drain preserved entries, so nothing strands.
1203 * Returns 1 if self was freed. */
1204 13 static int cancel_or_preserve(ev_clickhouse_t *self, const char *errmsg) {
1205 13 ▶ if (!self->connected || !self->auto_reconnect
Branch: 2 branches
BranchTrueFalseTotal
if (!self->connected || !self->auto_reconnect 5 8 13
if (!self->connected || !self->auto_reconnect 4 1 5
1206 4 ▶ || ngx_queue_empty(&self->send_queue))
Branch: 1 branch
BranchTrueFalseTotal
|| ngx_queue_empty(&self->send_queue)) 4 0 4
1207 13 return cancel_pending(self, errmsg,
1208 13 ▶ !(self->auto_reconnect && self->host));
Branch: 2 branches
BranchTrueFalseTotal
!(self->auto_reconnect && self->host)); 9 4 13
!(self->auto_reconnect && self->host)); 0 9 9
1209 0 self->callback_depth++;
1210 0 drain_cb_queue(self, errmsg);
1211 0 self->callback_depth--;
1212 0 return check_destroyed(self);
1213 }
1214  
1215 /* --- I/O helpers (with optional TLS) --- */
1216  
1217 80 static ssize_t ch_read(ev_clickhouse_t *self, void *buf, size_t len) {
1218 #ifdef HAVE_OPENSSL
1219 80 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 0 80 80
1220 0 ▶ int ssl_len = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
Branch: 1 branch
BranchTrueFalseTotal
int ssl_len = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; 0 0 0
1221 0 int ret = SSL_read(self->ssl, buf, ssl_len);
1222 0 ▶ if (ret <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret <= 0) { 0 0 0
1223 0 int err = SSL_get_error(self->ssl, ret);
1224 0 ▶ if (err == SSL_ERROR_WANT_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ) { 0 0 0
1225 0 errno = EAGAIN;
1226 0 return -1;
1227 }
1228 0 ▶ if (err == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_WRITE) { 0 0 0
1229 0 start_writing(self);
1230 0 errno = EAGAIN;
1231 0 return -1;
1232 }
1233 0 ▶ if (err == SSL_ERROR_ZERO_RETURN) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_ZERO_RETURN) return 0; 0 0 0
1234 0 capture_tls_error(self);
1235 0 errno = EIO;
1236 0 return -1;
1237 }
1238 0 return ret;
1239 }
1240 #endif
1241 80 return read(self->fd, buf, len);
1242 }
1243  
1244 109 static ssize_t ch_write(ev_clickhouse_t *self, const void *buf, size_t len) {
1245 #ifdef HAVE_OPENSSL
1246 109 ▶ if (self->ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->ssl) { 0 109 109
1247 0 ▶ int ssl_len = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
Branch: 1 branch
BranchTrueFalseTotal
int ssl_len = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; 0 0 0
1248 0 int ret = SSL_write(self->ssl, buf, ssl_len);
1249 0 ▶ if (ret <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (ret <= 0) { 0 0 0
1250 0 int err = SSL_get_error(self->ssl, ret);
1251 0 ▶ if (err == SSL_ERROR_WANT_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_WRITE) { 0 0 0
1252 0 errno = EAGAIN;
1253 0 return -1;
1254 }
1255 0 ▶ if (err == SSL_ERROR_WANT_READ) {
Branch: 1 branch
BranchTrueFalseTotal
if (err == SSL_ERROR_WANT_READ) { 0 0 0
1256 0 start_reading(self);
1257 0 errno = EAGAIN;
1258 0 return -1;
1259 }
1260 0 capture_tls_error(self);
1261 0 errno = EIO;
1262 0 return -1;
1263 }
1264 0 return ret;
1265 }
1266 #endif
1267 109 return write(self->fd, buf, len);
1268 }
1269  
1270 /* --- Buffer management --- */
1271  
1272 80 static void ensure_recv_cap(ev_clickhouse_t *self, size_t need) {
1273 80 ▶ if (self->recv_cap >= need) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->recv_cap >= need) return; 80 0 80
1274 0 ▶ if (need > SIZE_MAX / 2) croak("recv buffer overflow");
Branch: 1 branch
BranchTrueFalseTotal
if (need > SIZE_MAX / 2) croak("recv buffer overflow"); 0 0 0
1275 0 size_t newcap = self->recv_cap * 2;
1276 0 ▶ if (newcap < need) newcap = need;
Branch: 1 branch
BranchTrueFalseTotal
if (newcap < need) newcap = need; 0 0 0
1277 0 Renew(self->recv_buf, newcap, char);
1278 0 self->recv_cap = newcap;
1279 }
1280  
1281 110 static void ensure_send_cap(ev_clickhouse_t *self, size_t need) {
1282 110 ▶ if (self->send_cap >= need) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->send_cap >= need) return; 110 0 110
1283 0 ▶ if (need > SIZE_MAX / 2) croak("send buffer overflow");
Branch: 1 branch
BranchTrueFalseTotal
if (need > SIZE_MAX / 2) croak("send buffer overflow"); 0 0 0
1284 0 size_t newcap = self->send_cap * 2;
1285 0 ▶ if (newcap < need) newcap = need;
Branch: 1 branch
BranchTrueFalseTotal
if (newcap < need) newcap = need; 0 0 0
1286 0 Renew(self->send_buf, newcap, char);
1287 0 self->send_cap = newcap;
1288 }
1289  
1290 /* --- Native protocol buffer (for building packets) --- */
1291  
1292 typedef struct {
1293 char *data;
1294 size_t len;
1295 size_t cap;
1296 } native_buf_t;
1297  
1298 166 static void nbuf_init(native_buf_t *b) {
1299 166 b->cap = 256;
1300 166 b->len = 0;
1301 166 Newx(b->data, b->cap, char);
1302 166 }
1303  
1304 1807 static void nbuf_grow(native_buf_t *b, size_t need) {
1305 /* Guard the b->len + need sum itself: a wraparound would make the
1306 * loop condition false and let nbuf_append memcpy past the buffer. */
1307 1807 ▶ if (need > SIZE_MAX - b->len) croak("native buffer overflow");
Branch: 1 branch
BranchTrueFalseTotal
if (need > SIZE_MAX - b->len) croak("native buffer overflow"); 0 1807 1807
1308 1807 ▶ if (b->len + need > b->cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (b->len + need > b->cap) { 0 1807 1807
1309 0 ▶ while (b->len + need > b->cap) {
Branch: 1 branch
BranchTrueFalseTotal
while (b->len + need > b->cap) { 0 0 0
1310 0 ▶ if (b->cap > SIZE_MAX / 2) croak("native buffer overflow");
Branch: 1 branch
BranchTrueFalseTotal
if (b->cap > SIZE_MAX / 2) croak("native buffer overflow"); 0 0 0
1311 0 b->cap *= 2;
1312 }
1313 0 Renew(b->data, b->cap, char);
1314 }
1315 1807 }
1316  
1317 573 static void nbuf_append(native_buf_t *b, const char *data, size_t len) {
1318 573 nbuf_grow(b, len);
1319 /* len==0 with data==NULL is memcpy(dst, NULL, 0) — strict UB */
1320 573 ▶ if (len) memcpy(b->data + b->len, data, len);
Branch: 1 branch
BranchTrueFalseTotal
if (len) memcpy(b->data + b->len, data, len); 318 255 573
1321 573 b->len += len;
1322 573 }
1323  
1324 928 static void nbuf_varuint(native_buf_t *b, uint64_t n) {
1325 928 nbuf_grow(b, 10);
1326 1020 ▶ while (n >= 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
while (n >= 0x80) { 92 928 1020
1327 92 b->data[b->len++] = (char)((n & 0x7F) | 0x80);
1328 92 n >>= 7;
1329 }
1330 928 b->data[b->len++] = (char)n;
1331 928 }
1332  
1333 399 static void nbuf_string(native_buf_t *b, const char *s, size_t len) {
1334 399 nbuf_varuint(b, (uint64_t)len);
1335 399 nbuf_append(b, s, len);
1336 399 }
1337  
1338 353 static void nbuf_cstring(native_buf_t *b, const char *s) {
1339 353 ▶ nbuf_string(b, s, s ? strlen(s) : 0);
Branch: 1 branch
BranchTrueFalseTotal
nbuf_string(b, s, s ? strlen(s) : 0); 353 0 353
1340 353 }
1341  
1342 254 static void nbuf_u8(native_buf_t *b, uint8_t v) {
1343 254 nbuf_grow(b, 1);
1344 254 b->data[b->len++] = (char)v;
1345 254 }
1346  
1347 0 static void nbuf_le64(native_buf_t *b, uint64_t v) {
1348 0 nbuf_grow(b, 8);
1349 0 Copy(&v, b->data + b->len, 8, char);
1350 0 b->len += 8;
1351 0 }
1352  
1353 0 static void nbuf_ledouble(native_buf_t *b, double d) {
1354 uint64_t v;
1355 0 Copy(&d, &v, 8, char);
1356 0 nbuf_le64(b, v);
1357 0 }
1358  
1359 /* Write a parameter value as a Field::dump-format quoted string.
1360 * ClickHouse's Field::restoreFromDump for String parses a single-quoted token
1361 * with backslash escaping for ' and \. Without escaping, embedded single
1362 * quotes truncate the value silently. */
1363 0 static void nbuf_quoted_param(native_buf_t *b, const char *s, size_t len) {
1364 0 size_t i, esc = 0;
1365 0 ▶ for (i = 0; i < len; i++) if (s[i] == '\'' || s[i] == '\\') esc++;
Branch: 3 branches
BranchTrueFalseTotal
for (i = 0; i < len; i++) if (s[i] == '\'' || s[i] == '\\') esc++; 0 0 0
for (i = 0; i < len; i++) if (s[i] == '\'' || s[i] == '\\') esc++; 0 0 0
for (i = 0; i < len; i++) if (s[i] == '\'' || s[i] == '\\') esc++; 0 0 0
1366 0 nbuf_varuint(b, (uint64_t)(len + esc + 2));
1367 0 nbuf_grow(b, len + esc + 2);
1368 0 b->data[b->len++] = '\'';
1369 0 ▶ if (esc == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (esc == 0) { 0 0 0
1370 0 memcpy(b->data + b->len, s, len);
1371 0 b->len += len;
1372 } else {
1373 0 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 0 0 0
1374 0 ▶ if (s[i] == '\'' || s[i] == '\\') b->data[b->len++] = '\\';
Branch: 2 branches
BranchTrueFalseTotal
if (s[i] == '\'' || s[i] == '\\') b->data[b->len++] = '\\'; 0 0 0
if (s[i] == '\'' || s[i] == '\\') b->data[b->len++] = '\\'; 0 0 0
1375 0 b->data[b->len++] = s[i];
1376 }
1377 }
1378 0 b->data[b->len++] = '\'';
1379 0 }
1380  
1381 /* --- Native protocol read helpers (from recv_buf) --- */
1382  
1383 /* Returns 1=success, 0=need more data, -1=overflow */
1384 284 static int read_varuint(const char *buf, size_t len, size_t *pos, uint64_t *out) {
1385 284 uint64_t val = 0;
1386 284 unsigned shift = 0;
1387 284 size_t p = *pos;
1388 326 ▶ while (p < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < len) { 326 0 326
1389 326 uint8_t byte = (uint8_t)buf[p++];
1390 326 val |= (uint64_t)(byte & 0x7F) << shift;
1391 326 ▶ if (!(byte & 0x80)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!(byte & 0x80)) { 284 42 326
1392 284 *out = val;
1393 284 *pos = p;
1394 284 return 1;
1395 }
1396 42 shift += 7;
1397 42 ▶ if (shift >= 64) return -1;
Branch: 1 branch
BranchTrueFalseTotal
if (shift >= 64) return -1; 0 42 42
1398 }
1399 0 return 0;
1400 }
1401  
1402 61 static int read_native_string_alloc(const char *buf, size_t len, size_t *pos,
1403 char **out, size_t *out_len) {
1404 uint64_t slen;
1405 61 size_t saved = *pos;
1406 61 int rc = read_varuint(buf, len, pos, &slen);
1407 61 ▶ if (rc <= 0) { *pos = saved; return rc; }
Branch: 1 branch
BranchTrueFalseTotal
if (rc <= 0) { *pos = saved; return rc; } 0 61 61
1408 61 ▶ if (slen > len - *pos) { *pos = saved; return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (slen > len - *pos) { *pos = saved; return 0; } 0 61 61
1409 61 Newx(*out, slen + 1, char);
1410 61 Copy(buf + *pos, *out, slen, char);
1411 61 (*out)[slen] = '\0';
1412 61 ▶ if (out_len) *out_len = (size_t)slen;
Branch: 1 branch
BranchTrueFalseTotal
if (out_len) *out_len = (size_t)slen; 0 61 61
1413 61 *pos += slen;
1414 61 return 1;
1415 }
1416  
1417 /* Read a string without allocating — returns pointer into buf */
1418 34 static int read_native_string_ref(const char *buf, size_t len, size_t *pos,
1419 const char **out, size_t *out_len) {
1420 uint64_t slen;
1421 34 size_t saved = *pos;
1422 34 int rc = read_varuint(buf, len, pos, &slen);
1423 34 ▶ if (rc <= 0) { *pos = saved; return rc; }
Branch: 1 branch
BranchTrueFalseTotal
if (rc <= 0) { *pos = saved; return rc; } 0 34 34
1424 34 ▶ if (slen > len - *pos) { *pos = saved; return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (slen > len - *pos) { *pos = saved; return 0; } 0 34 34
1425 34 *out = buf + *pos;
1426 34 *out_len = (size_t)slen;
1427 34 *pos += slen;
1428 34 return 1;
1429 }
1430  
1431 2 static int read_u8(const char *buf, size_t len, size_t *pos, uint8_t *out) {
1432 2 ▶ if (*pos + 1 > len) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (*pos + 1 > len) return 0; 0 2 2
1433 2 *out = (uint8_t)buf[*pos];
1434 2 (*pos)++;
1435 2 return 1;
1436 }
1437  
1438 2 static int read_i32(const char *buf, size_t len, size_t *pos, int32_t *out) {
1439 2 ▶ if (*pos + 4 > len) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (*pos + 4 > len) return 0; 0 2 2
1440 2 memcpy(out, buf + *pos, 4);
1441 2 *pos += 4;
1442 2 return 1;
1443 }
1444  
1445 /* Skip native string */
1446 14 static int skip_native_string(const char *buf, size_t len, size_t *pos) {
1447 uint64_t slen;
1448 14 size_t saved = *pos;
1449 14 int rc = read_varuint(buf, len, pos, &slen);
1450 14 ▶ if (rc <= 0) { *pos = saved; return rc; }
Branch: 1 branch
BranchTrueFalseTotal
if (rc <= 0) { *pos = saved; return rc; } 0 14 14
1451 14 ▶ if (slen > len - *pos) { *pos = saved; return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (slen > len - *pos) { *pos = saved; return 0; } 0 14 14
1452 14 *pos += slen;
1453 14 return 1;
1454 }
1455  
1456 /* --- URL encoding --- */
1457  
1458 26 static size_t url_encode(const char *src, size_t src_len, char *dst) {
1459 static const char hex[] = "0123456789ABCDEF";
1460 26 size_t j = 0;
1461 size_t i;
1462 208 ▶ for (i = 0; i < src_len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < src_len; i++) { 182 26 208
1463 182 unsigned char c = (unsigned char)src[i];
1464 182 ▶ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
Branch: 5 branches
BranchTrueFalseTotal
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || 182 0 182
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || 182 0 182
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || 182 0 182
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || 0 182 182
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || 0 0 0
1465 0 ▶ (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') {
Branch: 5 branches
BranchTrueFalseTotal
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { 0 0 0
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { 0 0 0
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { 0 0 0
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { 0 0 0
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { 0 0 0
1466 182 dst[j++] = c;
1467 } else {
1468 0 dst[j++] = '%';
1469 0 dst[j++] = hex[c >> 4];
1470 0 dst[j++] = hex[c & 0x0F];
1471 }
1472 }
1473 26 return j;
1474 }
1475  
1476 /* --- Per-query settings helpers --- */
1477  
1478 /* Settings keys consumed by the client and never sent to the server. */
1479 2 static int is_client_only_key(const char *key, I32 klen) {
1480 0 ▶ return (klen == 3 && memcmp(key, "raw", 3) == 0)
Branch: 1 branch
BranchTrueFalseTotal
return (klen == 3 && memcmp(key, "raw", 3) == 0) 0 0 0
1481 2 ▶ || (klen == 8 && memcmp(key, "query_id", 8) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 8 && memcmp(key, "query_id", 8) == 0) 2 0 2
|| (klen == 8 && memcmp(key, "query_id", 8) == 0) 0 2 2
1482 0 ▶ || (klen == 7 && memcmp(key, "on_data", 7) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 7 && memcmp(key, "on_data", 7) == 0) 0 0 0
|| (klen == 7 && memcmp(key, "on_data", 7) == 0) 0 0 0
1483 0 ▶ || (klen == 13 && memcmp(key, "query_timeout", 13) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 13 && memcmp(key, "query_timeout", 13) == 0) 0 0 0
|| (klen == 13 && memcmp(key, "query_timeout", 13) == 0) 0 0 0
1484 0 ▶ || (klen == 6 && memcmp(key, "params", 6) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 6 && memcmp(key, "params", 6) == 0) 0 0 0
|| (klen == 6 && memcmp(key, "params", 6) == 0) 0 0 0
1485 0 ▶ || (klen == 8 && memcmp(key, "external", 8) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 8 && memcmp(key, "external", 8) == 0) 0 0 0
|| (klen == 8 && memcmp(key, "external", 8) == 0) 0 0 0
1486 0 ▶ || (klen == 10 && memcmp(key, "idempotent", 10) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 10 && memcmp(key, "idempotent", 10) == 0) 0 0 0
|| (klen == 10 && memcmp(key, "idempotent", 10) == 0) 0 0 0
1487 0 ▶ || (klen == 11 && memcmp(key, "data_format", 11) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 11 && memcmp(key, "data_format", 11) == 0) 0 0 0
|| (klen == 11 && memcmp(key, "data_format", 11) == 0) 0 0 0
1488 0 ▶ || (klen == 10 && memcmp(key, "columns_at", 10) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 10 && memcmp(key, "columns_at", 10) == 0) 0 0 0
|| (klen == 10 && memcmp(key, "columns_at", 10) == 0) 0 0 0
1489 0 ▶ || (klen == 16 && memcmp(key, "empty_as_default", 16) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 16 && memcmp(key, "empty_as_default", 16) == 0) 0 0 0
|| (klen == 16 && memcmp(key, "empty_as_default", 16) == 0) 0 0 0
1490 0 ▶ || (klen == 8 && memcmp(key, "defaults", 8) == 0)
Branch: 2 branches
BranchTrueFalseTotal
|| (klen == 8 && memcmp(key, "defaults", 8) == 0) 0 0 0
|| (klen == 8 && memcmp(key, "defaults", 8) == 0) 0 0 0
1491 4 ▶ || (klen == 17 && memcmp(key, "on_query_complete", 17) == 0);
Branch: 3 branches
BranchTrueFalseTotal
|| (klen == 17 && memcmp(key, "on_query_complete", 17) == 0); 0 2 2
|| (klen == 17 && memcmp(key, "on_query_complete", 17) == 0); 0 0 0
|| (klen == 17 && memcmp(key, "on_query_complete", 17) == 0); 0 0 0
1492 }
1493  
1494 /* Append one "&key=encoded_value" pair, growing the buffer. */
1495 0 static void append_url_param(native_buf_t *b, const char *key, size_t klen,
1496 const char *val, size_t vlen) {
1497 /* Guard the *3 arithmetic itself against size_t wraparound. */
1498 0 ▶ if (klen > (SIZE_MAX - 64) / 3 || vlen > (SIZE_MAX - 64) / 3)
Branch: 2 branches
BranchTrueFalseTotal
if (klen > (SIZE_MAX - 64) / 3 || vlen > (SIZE_MAX - 64) / 3) 0 0 0
if (klen > (SIZE_MAX - 64) / 3 || vlen > (SIZE_MAX - 64) / 3) 0 0 0
1499 0 croak("URL parameter too large");
1500 0 nbuf_grow(b, 2 + klen * 3 + vlen * 3);
1501 0 b->data[b->len++] = '&';
1502 0 b->len += url_encode(key, klen, b->data + b->len);
1503 0 b->data[b->len++] = '=';
1504 0 b->len += url_encode(val, vlen, b->data + b->len);
1505 0 }
1506  
1507 /* Append merged settings as URL params (&key=encoded_value).
1508 * Extracts query_id into *query_id_out (caller must not free — points into HV).
1509 * Per-query overrides take precedence over connection defaults.
1510 * Single pass: each value is SvPV'd exactly once, so tied/magic values
1511 * cannot change size between a sizing pass and the fill. */
1512 26 static void append_settings_url_params(native_buf_t *b,
1513 HV *defaults, HV *overrides,
1514 const char **query_id_out, STRLEN *query_id_len_out) {
1515 HE *entry;
1516 26 *query_id_out = NULL;
1517 26 *query_id_len_out = 0;
1518  
1519 /* Write overrides first */
1520 26 ▶ if (overrides) {
Branch: 1 branch
BranchTrueFalseTotal
if (overrides) { 0 26 26
1521 0 hv_iterinit(overrides);
1522 0 ▶ while ((entry = hv_iternext(overrides))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(overrides))) { 0 0 0
1523 I32 klen;
1524 STRLEN vlen;
1525 0 char *key = hv_iterkey(entry, &klen);
1526 0 SV *sv = hv_iterval(overrides, entry);
1527 char *val;
1528 0 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 0 0
1529 0 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 0 0
1530 0 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1531 0 ▶ if (klen == 8 && memcmp(key, "query_id", 8) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (klen == 8 && memcmp(key, "query_id", 8) == 0) { 0 0 0
if (klen == 8 && memcmp(key, "query_id", 8) == 0) { 0 0 0
1532 0 *query_id_out = val;
1533 0 *query_id_len_out = vlen;
1534 0 continue;
1535 }
1536 0 ▶ if (is_client_only_key(key, klen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (is_client_only_key(key, klen)) continue; 0 0 0
1537 0 append_url_param(b, key, (size_t)klen, val, vlen);
1538 }
1539 }
1540 /* Write defaults, skipping keys present in overrides */
1541 26 ▶ if (defaults) {
Branch: 1 branch
BranchTrueFalseTotal
if (defaults) { 0 26 26
1542 0 hv_iterinit(defaults);
1543 0 ▶ while ((entry = hv_iternext(defaults))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(defaults))) { 0 0 0
1544 I32 klen;
1545 STRLEN vlen;
1546 0 char *key = hv_iterkey(entry, &klen);
1547 0 SV *sv = hv_iterval(defaults, entry);
1548 char *val;
1549 0 ▶ if (overrides && hv_exists(overrides, key, klen))
Branch: 2 branches
BranchTrueFalseTotal
if (overrides && hv_exists(overrides, key, klen)) 0 0 0
if (overrides && hv_exists(overrides, key, klen)) 0 0 0
1550 0 continue;
1551 0 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 0 0
1552 0 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 0 0
1553 0 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1554 0 ▶ if (klen == 8 && memcmp(key, "query_id", 8) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (klen == 8 && memcmp(key, "query_id", 8) == 0) { 0 0 0
if (klen == 8 && memcmp(key, "query_id", 8) == 0) { 0 0 0
1555 0 ▶ if (!*query_id_out) {
Branch: 1 branch
BranchTrueFalseTotal
if (!*query_id_out) { 0 0 0
1556 0 *query_id_out = val;
1557 0 *query_id_len_out = vlen;
1558 }
1559 0 continue;
1560 }
1561 0 ▶ if (is_client_only_key(key, klen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (is_client_only_key(key, klen)) continue; 0 0 0
1562 0 append_url_param(b, key, (size_t)klen, val, vlen);
1563 }
1564 }
1565 26 }
1566  
1567 /* Write merged param_* entries as native parameters block.
1568 * Format: (String name, VarUInt flags=2, String quoted-value)* — name is the
1569 * portion after the "param_" prefix. Caller writes the empty-name terminator.
1570 * Returns the number of entries written. */
1571 19 static int write_native_params(native_buf_t *b, HV *defaults, HV *overrides) {
1572 HE *entry;
1573 19 int count = 0;
1574 19 ▶ if (overrides) {
Branch: 1 branch
BranchTrueFalseTotal
if (overrides) { 2 17 19
1575 2 hv_iterinit(overrides);
1576 4 ▶ while ((entry = hv_iternext(overrides))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(overrides))) { 2 2 4
1577 I32 klen;
1578 STRLEN vlen;
1579 2 char *key = hv_iterkey(entry, &klen);
1580 2 SV *sv = hv_iterval(overrides, entry);
1581 char *val;
1582 2 ▶ if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue; 2 0 2
if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue; 2 0 2
1583 0 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 0 0
1584 0 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 0 0
1585 0 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1586 0 nbuf_varuint(b, (uint64_t)(klen - 6));
1587 0 nbuf_append(b, key + 6, (size_t)(klen - 6));
1588 0 nbuf_varuint(b, 2); /* flags: CUSTOM */
1589 0 nbuf_quoted_param(b, val, vlen);
1590 0 count++;
1591 }
1592 }
1593 19 ▶ if (defaults) {
Branch: 1 branch
BranchTrueFalseTotal
if (defaults) { 0 19 19
1594 0 hv_iterinit(defaults);
1595 0 ▶ while ((entry = hv_iternext(defaults))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(defaults))) { 0 0 0
1596 I32 klen;
1597 STRLEN vlen;
1598 0 char *key = hv_iterkey(entry, &klen);
1599 0 SV *sv = hv_iterval(defaults, entry);
1600 char *val;
1601 0 ▶ if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue; 0 0 0
if (klen <= 6 || memcmp(key, "param_", 6) != 0) continue; 0 0 0
1602 0 ▶ if (overrides && hv_exists(overrides, key, klen)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (overrides && hv_exists(overrides, key, klen)) continue; 0 0 0
if (overrides && hv_exists(overrides, key, klen)) continue; 0 0 0
1603 0 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 0 0
1604 0 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 0 0
1605 0 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1606 0 nbuf_varuint(b, (uint64_t)(klen - 6));
1607 0 nbuf_append(b, key + 6, (size_t)(klen - 6));
1608 0 nbuf_varuint(b, 2); /* flags: CUSTOM */
1609 0 nbuf_quoted_param(b, val, vlen);
1610 0 count++;
1611 }
1612 }
1613 19 return count;
1614 }
1615  
1616 /* Write merged settings in native protocol wire format.
1617 * Format per setting: String name, UInt8 is_important(0), String value.
1618 * Terminated by empty name string (written by caller). */
1619 19 static void write_native_settings(native_buf_t *b, HV *defaults, HV *overrides) {
1620 HE *entry;
1621  
1622 19 ▶ if (overrides) {
Branch: 1 branch
BranchTrueFalseTotal
if (overrides) { 2 17 19
1623 2 hv_iterinit(overrides);
1624 4 ▶ while ((entry = hv_iternext(overrides))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(overrides))) { 2 2 4
1625 I32 klen;
1626 STRLEN vlen;
1627 2 char *key = hv_iterkey(entry, &klen);
1628 2 SV *sv = hv_iterval(overrides, entry);
1629 char *val;
1630 2 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 2 2
1631 4 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 2 2
1632 2 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1633 2 ▶ if (is_client_only_key(key, klen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (is_client_only_key(key, klen)) continue; 2 0 2
1634 /* param_* keys go in the parameters block, not settings */
1635 0 ▶ if (klen > 6 && memcmp(key, "param_", 6) == 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (klen > 6 && memcmp(key, "param_", 6) == 0) continue; 0 0 0
if (klen > 6 && memcmp(key, "param_", 6) == 0) continue; 0 0 0
1636 0 nbuf_varuint(b, (uint64_t)klen);
1637 0 nbuf_append(b, key, (size_t)klen);
1638 0 nbuf_u8(b, 0); /* is_important = 0 */
1639 0 nbuf_varuint(b, (uint64_t)vlen);
1640 0 nbuf_append(b, val, vlen);
1641 }
1642 }
1643 19 ▶ if (defaults) {
Branch: 1 branch
BranchTrueFalseTotal
if (defaults) { 0 19 19
1644 0 hv_iterinit(defaults);
1645 0 ▶ while ((entry = hv_iternext(defaults))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((entry = hv_iternext(defaults))) { 0 0 0
1646 I32 klen;
1647 STRLEN vlen;
1648 0 char *key = hv_iterkey(entry, &klen);
1649 0 SV *sv = hv_iterval(defaults, entry);
1650 char *val;
1651 0 ▶ if (overrides && hv_exists(overrides, key, klen))
Branch: 2 branches
BranchTrueFalseTotal
if (overrides && hv_exists(overrides, key, klen)) 0 0 0
if (overrides && hv_exists(overrides, key, klen)) 0 0 0
1652 0 continue;
1653 0 ▶ if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */
Branch: 1 branch
BranchTrueFalseTotal
if (SvGMAGICAL(sv)) mg_get(sv); /* tied settings: FETCH */ 0 0 0
1654 0 ▶ if (!SvOK(sv)) continue; /* undef value means absent */
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(sv)) continue; /* undef value means absent */ 0 0 0
1655 0 val = SvPV_nomg(sv, vlen); /* already FETCHed above */
1656 0 ▶ if (is_client_only_key(key, klen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (is_client_only_key(key, klen)) continue; 0 0 0
1657 0 ▶ if (klen > 6 && memcmp(key, "param_", 6) == 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (klen > 6 && memcmp(key, "param_", 6) == 0) continue; 0 0 0
if (klen > 6 && memcmp(key, "param_", 6) == 0) continue; 0 0 0
1658 0 nbuf_varuint(b, (uint64_t)klen);
1659 0 nbuf_append(b, key, (size_t)klen);
1660 0 nbuf_u8(b, 0); /* is_important = 0 */
1661 0 nbuf_varuint(b, (uint64_t)vlen);
1662 0 nbuf_append(b, val, vlen);
1663 }
1664 }
1665 19 }
1666  
1667 /* Textually included so all helpers stay file-local statics and the
1668 * compiler sees one translation unit. Order matters: each file may
1669 * call into helpers defined above it, but not below. xs/io.c must
1670 * come last because it's the only file that reaches into every other
1671 * subsystem (TCP/TLS, HTTP, native, types). */
1672 #include "xs/codecs.c"
1673 #include "xs/proto_http.c"
1674 #include "xs/proto_native_build.c"
1675 #include "xs/types.c"
1676 #include "xs/proto_native_parse.c"
1677 #include "xs/io.c"
1678  
1679 /* --- XS interface --- */
1680  
1681 MODULE = EV::ClickHouse PACKAGE = EV::ClickHouse
1682  
1683 BOOT:
1684 {
1685 74 ▶ I_EV_API("EV::ClickHouse");
Branch: 3 branches
BranchTrueFalseTotal
I_EV_API("EV::ClickHouse"); 0 74 74
I_EV_API("EV::ClickHouse"); 74 0 74
I_EV_API("EV::ClickHouse"); 0 74 74
1686 /* A reset peer must surface as EPIPE errors, not kill the process:
1687 * ignore SIGPIPE, but only when the app left it at SIG_DFL (an
1688 * explicit app handler or EV::signal watcher is respected). Same
1689 * stance as the Go and Python runtimes. */
1690 {
1691 struct sigaction sa, old;
1692 74 memset(&sa, 0, sizeof(sa));
1693 74 sa.sa_handler = SIG_IGN;
1694 74 sigemptyset(&sa.sa_mask);
1695 74 ▶ if (sigaction(SIGPIPE, NULL, &old) == 0 && old.sa_handler == SIG_DFL)
Branch: 2 branches
BranchTrueFalseTotal
if (sigaction(SIGPIPE, NULL, &old) == 0 && old.sa_handler == SIG_DFL) 74 0 74
if (sigaction(SIGPIPE, NULL, &old) == 0 && old.sa_handler == SIG_DFL) 74 0 74
1696 74 sigaction(SIGPIPE, &sa, NULL);
1697 }
1698 74 ch_openssl_init();
1699 /* Permanent no-op CV used for internal callbacks (HTTP keepalive ping). */
1700 74 keepalive_noop_cb = newRV_inc((SV*)get_cv("EV::ClickHouse::__keepalive_noop", GV_ADD));
1701 74 ch_guard_cv = newXS(NULL, ch_guard_xs, __FILE__);
1702 /* Per-process rand() seed so reconnect_jitter desynchronises forks
1703 * (otherwise every worker generates the same sequence and the
1704 * jitter is uniform across the herd, defeating its purpose). */
1705 74 srand((unsigned)time(NULL) ^ (unsigned)getpid());
1706 }
1707  
1708 void
1709 __keepalive_noop(...)
1710 CODE:
1711 {
1712 /* Internal no-op invoked for keepalive ping completions. A real
1713 * empty XSUB, registered before the BOOT block runs, so
1714 * keepalive_noop_cb binds to a callable CV instead of an
1715 * undefined stub that would die. */
1716 PERL_UNUSED_VAR(items);
1717 }
1718  
1719 EV::ClickHouse
1720 _new(char *class, SV *loop_sv)
1721 CODE:
1722 {
1723 PERL_UNUSED_VAR(class);
1724 48 ▶ if (!SvROK(loop_sv) || !SvIOK(SvRV(loop_sv)))
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(loop_sv) || !SvIOK(SvRV(loop_sv))) 48 0 48
if (!SvROK(loop_sv) || !SvIOK(SvRV(loop_sv))) 0 48 48
1725 0 croak("loop must be an EV::Loop object");
1726 48 Newxz(RETVAL, 1, ev_clickhouse_t);
1727 48 RETVAL->magic = EV_CH_MAGIC;
1728 48 RETVAL->loop = INT2PTR(struct ev_loop *, SvIVX(SvRV(loop_sv)));
1729 48 RETVAL->loop_sv = SvREFCNT_inc(SvRV(loop_sv));
1730 48 RETVAL->fd = -1;
1731 48 RETVAL->protocol = PROTO_HTTP;
1732 48 ngx_queue_init(&RETVAL->cb_queue);
1733 48 ngx_queue_init(&RETVAL->send_queue);
1734  
1735 48 Newx(RETVAL->recv_buf, RECV_BUF_INIT, char);
1736 48 RETVAL->recv_cap = RECV_BUF_INIT;
1737 48 Newx(RETVAL->send_buf, SEND_BUF_INIT, char);
1738 48 RETVAL->send_cap = SEND_BUF_INIT;
1739  
1740 48 ev_init(&RETVAL->timer, timer_cb);
1741 48 RETVAL->timer.data = (void *)RETVAL;
1742 }
1743 OUTPUT:
1744 RETVAL
1745  
1746 void
1747 DESTROY(EV::ClickHouse self)
1748 CODE:
1749 {
1750 48 ▶ if (self->magic != EV_CH_MAGIC) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->magic != EV_CH_MAGIC) return; 0 48 48
1751  
1752 48 stop_reading(self);
1753 48 stop_writing(self);
1754 48 stop_timing(self);
1755 48 stop_keepalive(self);
1756 48 stop_reconnect(self);
1757  
1758 48 ▶ if (PL_dirty) {
Branch: 1 branch
BranchTrueFalseTotal
if (PL_dirty) { 3 45 48
1759 3 self->magic = EV_CH_FREED;
1760 3 ▶ while (!ngx_queue_empty(&self->send_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->send_queue)) { 0 3 3
1761 0 ngx_queue_t *q = ngx_queue_head(&self->send_queue);
1762 0 ev_ch_send_t *send = ngx_queue_data(q, ev_ch_send_t, queue);
1763 0 ngx_queue_remove(q);
1764 0 Safefree(send->data);
1765 0 ▶ CLEAR_INSERT(send);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(send); 0 0 0
CLEAR_INSERT(send); 0 0 0
1766 0 ▶ CLEAR_SV(send->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(send->on_data); 0 0 0
1767 0 ▶ CLEAR_SV(send->on_complete);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(send->on_complete); 0 0 0
1768 0 SvREFCNT_dec(send->cb);
1769 0 release_send(send);
1770 }
1771 3 ▶ while (!ngx_queue_empty(&self->cb_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
while (!ngx_queue_empty(&self->cb_queue)) { 0 3 3
1772 0 ngx_queue_t *q = ngx_queue_head(&self->cb_queue);
1773 0 ev_ch_cb_t *cbt = ngx_queue_data(q, ev_ch_cb_t, queue);
1774 0 ngx_queue_remove(q);
1775 0 ▶ CLEAR_SV(cbt->on_data);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(cbt->on_data); 0 0 0
1776 0 ▶ CLEAR_SV(cbt->on_complete);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(cbt->on_complete); 0 0 0
1777 0 SvREFCNT_dec(cbt->cb);
1778 0 release_cbt(cbt);
1779 }
1780  
1781 3 ch_ssl_free(self);
1782 3 ▶ if (self->fd >= 0) close(self->fd);
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) close(self->fd); 0 3 3
1783 3 ▶ CLEAR_SV(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->loop_sv); 3 0 3
1784 3 ▶ CLEAR_CONNECTION_HANDLERS(self);
Branch: 9 branches
BranchTrueFalseTotal
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
CLEAR_CONNECTION_HANDLERS(self); 0 3 3
1785 3 ▶ CLEAR_PERSISTENT_STATE(self);
Branch: 25 branches
BranchTrueFalseTotal
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 2 1 3
CLEAR_PERSISTENT_STATE(self); 2 1 3
CLEAR_PERSISTENT_STATE(self); 2 1 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 3 0 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
CLEAR_PERSISTENT_STATE(self); 0 3 3
1786 3 failover_free(self);
1787 3 ▶ CLEAR_INSERT(self);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(self); 0 3 3
CLEAR_INSERT(self); 0 3 3
1788 3 free_insert_default_state(self);
1789 3 lc_free_dicts(self);
1790 3 Safefree(self);
1791 3 return;
1792 }
1793  
1794 45 ▶ if (cancel_pending(self, "object destroyed", 1))
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_pending(self, "object destroyed", 1)) 0 45 45
1795 0 return; /* inner DESTROY already freed self */
1796  
1797 /* A user callback fired from cancel_pending may have called
1798 * $ch->reset() which re-arms watchers / opens a fresh fd.
1799 * Stop everything again before tearing the struct down so the
1800 * EV loop can't dispatch into freed memory. */
1801 45 stop_reading(self);
1802 45 stop_writing(self);
1803 45 stop_timing(self);
1804 45 stop_keepalive(self);
1805 45 stop_reconnect(self);
1806  
1807 45 ch_ssl_shutdown_free(self);
1808  
1809 45 ▶ if (self->fd >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->fd >= 0) { 2 43 45
1810 2 close(self->fd);
1811 2 self->fd = -1;
1812 }
1813  
1814 45 self->loop = NULL;
1815 45 ▶ CLEAR_SV(self->loop_sv);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->loop_sv); 45 0 45
1816 45 self->connected = 0;
1817  
1818 45 ▶ CLEAR_CONNECTION_HANDLERS(self);
Branch: 9 branches
BranchTrueFalseTotal
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 2 43 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
CLEAR_CONNECTION_HANDLERS(self); 0 45 45
1819 {
1820 /* The parser in a callback frame still points into recv_buf
1821 * (column names, types); check_destroyed frees it with self. */
1822 45 char *keep_recv = NULL;
1823 45 ▶ if (self->callback_depth > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->callback_depth > 0) { 0 45 45
1824 0 keep_recv = self->recv_buf;
1825 0 self->recv_buf = NULL;
1826 }
1827 45 ▶ CLEAR_PERSISTENT_STATE(self);
Branch: 25 branches
BranchTrueFalseTotal
CLEAR_PERSISTENT_STATE(self); 1 44 45
CLEAR_PERSISTENT_STATE(self); 1 44 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 18 27 45
CLEAR_PERSISTENT_STATE(self); 17 28 45
CLEAR_PERSISTENT_STATE(self); 17 28 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 45 0 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
CLEAR_PERSISTENT_STATE(self); 0 45 45
1828 45 self->recv_buf = keep_recv;
1829 }
1830 45 failover_free(self);
1831 45 lc_free_dicts(self);
1832 45 ▶ CLEAR_INSERT(self); free_insert_default_state(self);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(self); free_insert_default_state(self); 0 45 45
CLEAR_INSERT(self); free_insert_default_state(self); 0 45 45
1833  
1834 45 self->magic = EV_CH_FREED;
1835 45 ▶ if (self->callback_depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->callback_depth == 0) { 45 0 45
1836 45 Safefree(self);
1837 }
1838 /* else: check_destroyed() will Safefree when callback_depth reaches 0 */
1839 }
1840  
1841 void
1842 _set_tls_ca_file(EV::ClickHouse self, const char *path)
1843 CODE:
1844 {
1845 0 ▶ CLEAR_STR(self->tls_ca_file);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->tls_ca_file); 0 0 0
1846 0 self->tls_ca_file = safe_strdup(path);
1847 }
1848  
1849 void
1850 _set_tls_cert_file(EV::ClickHouse self, const char *path)
1851 CODE:
1852 {
1853 0 ▶ CLEAR_STR(self->tls_cert_file);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->tls_cert_file); 0 0 0
1854 0 self->tls_cert_file = safe_strdup(path);
1855 }
1856  
1857 void
1858 _set_tls_key_file(EV::ClickHouse self, const char *path)
1859 CODE:
1860 {
1861 0 ▶ CLEAR_STR(self->tls_key_file);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->tls_key_file); 0 0 0
1862 0 self->tls_key_file = safe_strdup(path);
1863 }
1864  
1865 void
1866 connect(EV::ClickHouse self, const char *host, unsigned int port, const char *user, const char *password, const char *database)
1867 CODE:
1868 {
1869 /* An explicit connect supersedes outstanding async DNS: without
1870 * this the stale resolver callback tears the new link down. */
1871 48 self->dns_pending = 0;
1872 48 ▶ if (self->connected || self->connecting || self->handshaking)
Branch: 3 branches
BranchTrueFalseTotal
if (self->connected || self->connecting || self->handshaking) 48 0 48
if (self->connected || self->connecting || self->handshaking) 48 0 48
if (self->connected || self->connecting || self->handshaking) 0 48 48
1873 0 croak("already connected");
1874 96 ▶ if (has_http_unsafe_chars(host) || has_http_unsafe_chars(user) ||
Branch: 1 branch
BranchTrueFalseTotal
if (has_http_unsafe_chars(host) || has_http_unsafe_chars(user) || 48 0 48
1875 96 ▶ has_http_unsafe_chars(password) || has_http_unsafe_chars(database))
Branch: 1 branch
BranchTrueFalseTotal
has_http_unsafe_chars(password) || has_http_unsafe_chars(database)) 0 48 48
1876 0 croak("connection parameters must not contain CR or LF");
1877  
1878 48 store_conn_params(self, host, port, user, password, database);
1879  
1880 48 start_connect(self);
1881 }
1882  
1883 void
1884 reset(EV::ClickHouse self)
1885 CODE:
1886 {
1887 int gen;
1888 13 ▶ if (!self->host) croak("no previous connection to reset");
Branch: 1 branch
BranchTrueFalseTotal
if (!self->host) croak("no previous connection to reset"); 0 13 13
1889 13 gen = self->connect_gen;
1890 13 ▶ if (cancel_pending(self, "connection reset", 0)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_pending(self, "connection reset", 0)) return; 0 13 13
1891 /* An inner reset()/connect() from a callback already reconnected; a
1892 * query issued from a callback afterwards was enqueued at
1893 * callback_depth > 0 (so undispatched) and would strand on the
1894 * live connection — advance it. pipeline_advance may free self;
1895 * return immediately without touching self afterwards. */
1896 13 ▶ if (self->connect_gen != gen) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) { 0 13 13
1897 0 ▶ if (self->connected && !ngx_queue_empty(&self->send_queue))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
1898 0 pipeline_advance(self);
1899 0 return;
1900 }
1901 13 ▶ if (cleanup_connection(self, 1)) return; /* on_disconnect freed self */
Branch: 1 branch
BranchTrueFalseTotal
if (cleanup_connection(self, 1)) return; /* on_disconnect freed self */ 0 13 13
1902 13 ▶ if (self->connect_gen != gen) { /* reset()/connect() from on_disconnect won */
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) { /* reset()/connect() from on_disconnect won */ 0 13 13
1903 0 ▶ if (self->connected && !ngx_queue_empty(&self->send_queue))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
1904 0 pipeline_advance(self);
1905 0 return;
1906 }
1907 13 start_connect(self);
1908 }
1909  
1910 void
1911 finish(EV::ClickHouse self)
1912 CODE:
1913 {
1914 /* Rotate the generation so an enclosing fail_connection (user called
1915 * finish from on_error) does not schedule a reconnect afterwards. */
1916 47 self->connect_gen++;
1917 47 ▶ if (cancel_pending(self, "connection finished", 1)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_pending(self, "connection finished", 1)) return; 0 47 47
1918 47 ▶ if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */
Branch: 1 branch
BranchTrueFalseTotal
if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */ 0 47 47
1919 94 ▶ if (!self->connected && !self->connecting && !self->dns_pending &&
Branch: 2 branches
BranchTrueFalseTotal
if (!self->connected && !self->connecting && !self->dns_pending && 47 0 47
if (!self->connected && !self->connecting && !self->dns_pending && 47 0 47
1920 47 cancel_pending(self, "connection finished", 1)) return;
1921 /* Terminal call: drop handler refs so closures capturing $ch don't
1922 * pin the struct (fd, watchers) past the last user ref. */
1923 47 ▶ CLEAR_CONNECTION_HANDLERS(self);
Branch: 9 branches
BranchTrueFalseTotal
CLEAR_CONNECTION_HANDLERS(self); 38 9 47
CLEAR_CONNECTION_HANDLERS(self); 45 2 47
CLEAR_CONNECTION_HANDLERS(self); 0 47 47
CLEAR_CONNECTION_HANDLERS(self); 14 33 47
CLEAR_CONNECTION_HANDLERS(self); 0 47 47
CLEAR_CONNECTION_HANDLERS(self); 1 46 47
CLEAR_CONNECTION_HANDLERS(self); 0 47 47
CLEAR_CONNECTION_HANDLERS(self); 0 47 47
CLEAR_CONNECTION_HANDLERS(self); 1 46 47
1924 47 ▶ if (self->on_failover) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_failover) { 1 46 47
1925 1 SvREFCNT_dec(self->on_failover);
1926 1 self->on_failover = NULL;
1927 }
1928 }
1929  
1930 void
1931 query(EV::ClickHouse self, SV *sql_sv, ...)
1932 CODE:
1933 {
1934 /* Pin the invocant: stringify/FETCH below runs user code that may
1935 * drop the last $ch ref (DESTROY frees self when depth is 0). */
1936 33 sv_2mortal(SvREFCNT_inc(ST(0)));
1937 STRLEN sql_len;
1938 const char *sql;
1939 ev_ch_send_t *s;
1940 char *req;
1941 size_t req_len;
1942 SV *cb;
1943 33 HV *settings = NULL;
1944 33 int raw = 0;
1945  
1946 33 ▶ if (items == 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (items == 3) { 31 2 33
1947 31 cb = ST(2);
1948 2 ▶ } else if (items == 4) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (items == 4) { 2 0 2
1949 2 ▶ if (!(SvROK(ST(2)) && SvTYPE(SvRV(ST(2))) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(ST(2)) && SvTYPE(SvRV(ST(2))) == SVt_PVHV)) 2 0 2
if (!(SvROK(ST(2)) && SvTYPE(SvRV(ST(2))) == SVt_PVHV)) 0 2 2
1950 0 croak("settings must be a HASH reference");
1951 2 settings = (HV *)SvRV(ST(2));
1952 2 cb = ST(3);
1953 } else {
1954 0 croak("Usage: $ch->query($sql, [\\%%settings], $cb)");
1955 }
1956  
1957 33 ▶ if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending &&
Branch: 4 branches
BranchTrueFalseTotal
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 29 33
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
1958 4 ▶ !self->reconnect_timing && !self->in_disconnect) croak("not connected");
Branch: 2 branches
BranchTrueFalseTotal
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 4 0 4
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 2 2 4
1959 31 ▶ if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 31 0 31
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 31 31
1960 0 croak("callback must be a CODE reference");
1961  
1962 31 ▶ if (self->protocol == PROTO_NATIVE && (self->insert_data || self->insert_av))
Branch: 3 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && (self->insert_data || self->insert_av)) 5 26 31
if (self->protocol == PROTO_NATIVE && (self->insert_data || self->insert_av)) 5 0 5
if (self->protocol == PROTO_NATIVE && (self->insert_data || self->insert_av)) 0 5 5
1963 0 croak("cannot queue native query while INSERT is pending");
1964  
1965 /* Stringify SQL before owning anything: a dying tie must not
1966 * longjmp over settings_copy. */
1967 31 sql = SvPV(sql_sv, sql_len);
1968  
1969 /* Extract client-side options from settings */
1970 31 SV *on_data_sv = NULL;
1971 31 SV *on_complete_sv = NULL;
1972 31 HV *external = NULL; /* per-query external tables (native only) */
1973 31 HV *settings_copy = NULL; /* owned copy if we need to expand params */
1974 31 ▶ if (settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (settings) { 2 29 31
1975 2 settings_copy = expand_params(aTHX_ settings);
1976 2 ▶ if (settings_copy) settings = settings_copy;
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) settings = settings_copy; 0 2 2
1977 2 SV **svp = hv_fetch(settings, "raw", 3, 0);
1978 2 ▶ if (svp) raw = SvTRUE(*svp) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
if (svp) raw = SvTRUE(*svp) ? 1 : 0; 0 2 2
1979 /* hv_fetch on a tie returns a lazy FETCH proxy: materialize
1980 * before the SvROK test, and wrap the referent (the send
1981 * entry outlives the mortal proxy). */
1982 2 svp = hv_fetch(settings, "on_data", 7, 0);
1983 2 ▶ if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp);
Branch: 3 branches
BranchTrueFalseTotal
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 2 2
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
1984 2 ▶ if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV)
Branch: 3 branches
BranchTrueFalseTotal
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 2 2
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
1985 0 on_data_sv = SvMAGICAL(*svp) ? sv_2mortal(newRV_inc(SvRV(*svp)))
1986 0 ▶ : *svp;
Branch: 1 branch
BranchTrueFalseTotal
: *svp; 0 0 0
1987 2 svp = hv_fetch(settings, "on_query_complete", 17, 0);
1988 2 ▶ if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp);
Branch: 3 branches
BranchTrueFalseTotal
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 2 2
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
1989 2 ▶ if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV)
Branch: 3 branches
BranchTrueFalseTotal
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 2 2
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
1990 0 on_complete_sv = SvMAGICAL(*svp) ? sv_2mortal(newRV_inc(SvRV(*svp)))
1991 0 ▶ : *svp;
Branch: 1 branch
BranchTrueFalseTotal
: *svp; 0 0 0
1992 2 svp = hv_fetch(settings, "external", 8, 0);
1993 2 ▶ if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp);
Branch: 3 branches
BranchTrueFalseTotal
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 2 2
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
1994 2 ▶ if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVHV
Branch: 3 branches
BranchTrueFalseTotal
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVHV 0 2 2
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVHV 0 0 0
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVHV 0 0 0
1995 0 ▶ && HvKEYS((HV *)SvRV(*svp)) > 0)
Branch: 2 branches
BranchTrueFalseTotal
&& HvKEYS((HV *)SvRV(*svp)) > 0) 0 0 0
&& HvKEYS((HV *)SvRV(*svp)) > 0) 0 0 0
1996 0 external = (HV *)SvRV(*svp);
1997 }
1998  
1999 31 ▶ if (self->max_query_size > 0 && sql_len > self->max_query_size) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->max_query_size > 0 && sql_len > self->max_query_size) { 0 31 31
if (self->max_query_size > 0 && sql_len > self->max_query_size) { 0 0 0
2000 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2001 0 croak("query size %lu exceeds max_query_size %lu",
2002 (unsigned long)sql_len, (unsigned long)self->max_query_size);
2003 }
2004  
2005 31 ▶ if (raw && self->protocol == PROTO_NATIVE) {
Branch: 2 branches
BranchTrueFalseTotal
if (raw && self->protocol == PROTO_NATIVE) { 0 31 31
if (raw && self->protocol == PROTO_NATIVE) { 0 0 0
2006 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2007 0 croak("raw mode is only supported with the HTTP protocol");
2008 }
2009  
2010 31 ▶ if (on_data_sv && self->protocol == PROTO_HTTP) {
Branch: 2 branches
BranchTrueFalseTotal
if (on_data_sv && self->protocol == PROTO_HTTP) { 0 31 31
if (on_data_sv && self->protocol == PROTO_HTTP) { 0 0 0
2011 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2012 0 croak("on_data is only supported with the native protocol");
2013 }
2014  
2015 31 ▶ if (external && self->protocol == PROTO_HTTP) {
Branch: 2 branches
BranchTrueFalseTotal
if (external && self->protocol == PROTO_HTTP) { 0 31 31
if (external && self->protocol == PROTO_HTTP) { 0 0 0
2016 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2017 0 croak("external tables are only supported with the native protocol");
2018 }
2019  
2020 /* Optionally prepend a SQL block comment carrying query_log_comment
2021 * for system.query_log traceability. Connection-level setting; the
2022 * prefix lives for the query call only. */
2023 31 char *qlc_sql = NULL;
2024 31 ▶ if (self->query_log_comment) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->query_log_comment) { 0 31 31
2025 0 size_t qlc_sql_len = strlen(self->query_log_comment) + sql_len + 7;
2026 0 Newx(qlc_sql, qlc_sql_len + 1, char);
2027 0 size_t off = qlc_emit_prefix(qlc_sql, self->query_log_comment);
2028 0 memcpy(qlc_sql + off, sql, sql_len);
2029 0 qlc_sql[qlc_sql_len] = '\0';
2030 0 sql = qlc_sql;
2031 0 sql_len = qlc_sql_len;
2032 }
2033  
2034 31 char *ext_data = NULL;
2035 31 size_t ext_len = 0;
2036 31 int defer_build = 0;
2037 31 ▶ if (self->protocol == PROTO_HTTP) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) { 26 5 31
2038 26 req = build_http_post_request(self, NULL, 0, sql, sql_len,
2039 self->default_settings, settings,
2040 &req_len);
2041 } else {
2042 5 ▶ if (external) {
Branch: 1 branch
BranchTrueFalseTotal
if (external) { 0 5 5
2043 char ext_errbuf[640];
2044 0 ext_errbuf[0] = '\0';
2045 0 char *ext_tz = query_session_tz(aTHX_ self, settings);
2046 0 ▶ if (ext_tz) SAVEFREEPV(ext_tz);
Branch: 1 branch
BranchTrueFalseTotal
if (ext_tz) SAVEFREEPV(ext_tz); 0 0 0
2047 0 ext_data = build_external_tables(aTHX_ self, external,
2048 effective_tz(self, ext_tz),
2049 &ext_len, ext_errbuf, sizeof(ext_errbuf));
2050 0 ▶ if (!ext_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ext_data) { 0 0 0
2051 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2052 0 ▶ if (qlc_sql) Safefree(qlc_sql);
Branch: 1 branch
BranchTrueFalseTotal
if (qlc_sql) Safefree(qlc_sql); 0 0 0
2053 0 croak("%s", ext_errbuf);
2054 }
2055 }
2056 5 ▶ if (!self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if (!self->connected) { 2 3 5
2057 /* server_revision unknown: stash inputs, build at dispatch */
2058 2 defer_build = 1;
2059 2 req = NULL;
2060 2 req_len = 0;
2061 } else {
2062 3 req = build_native_query(self, sql, sql_len,
2063 self->default_settings, settings,
2064 ext_data, ext_len, &req_len);
2065 3 ▶ if (ext_data) Safefree(ext_data);
Branch: 1 branch
BranchTrueFalseTotal
if (ext_data) Safefree(ext_data); 0 3 3
2066 3 ext_data = NULL;
2067 3 ▶ if (!req) {
Branch: 1 branch
BranchTrueFalseTotal
if (!req) { 0 3 3
2068 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2069 0 ▶ if (qlc_sql) Safefree(qlc_sql);
Branch: 1 branch
BranchTrueFalseTotal
if (qlc_sql) Safefree(qlc_sql); 0 0 0
2070 0 croak("query parameters require server revision >= %d",
2071 DBMS_MIN_REVISION_WITH_PARAMETERS);
2072 }
2073 }
2074 }
2075 31 s = alloc_send();
2076 31 ▶ if (defer_build) {
Branch: 1 branch
BranchTrueFalseTotal
if (defer_build) { 2 29 31
2077 2 stash_send_deferred(aTHX_ s, sql, sql_len,
2078 self->default_settings, settings, &settings_copy,
2079 ext_data, ext_len);
2080 } else {
2081 29 s->data = req;
2082 29 s->data_len = req_len;
2083 }
2084 31 ▶ if (qlc_sql) Safefree(qlc_sql);
Branch: 1 branch
BranchTrueFalseTotal
if (qlc_sql) Safefree(qlc_sql); 0 31 31
2085 31 s->raw = raw;
2086 31 ▶ if (on_data_sv) s->on_data = SvREFCNT_inc(on_data_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (on_data_sv) s->on_data = SvREFCNT_inc(on_data_sv); 0 31 31
2087 31 ▶ if (on_complete_sv) s->on_complete = SvREFCNT_inc(on_complete_sv);
Branch: 1 branch
BranchTrueFalseTotal
if (on_complete_sv) s->on_complete = SvREFCNT_inc(on_complete_sv); 0 31 31
2088 31 ▶ if (settings) send_apply_settings(s, settings);
Branch: 1 branch
BranchTrueFalseTotal
if (settings) send_apply_settings(s, settings); 2 29 31
2089 31 s->session_tz = query_session_tz(aTHX_ self, settings);
2090 31 s->cb = SvREFCNT_inc(cb);
2091 31 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 31 31
2092 31 enqueue_send(self, s);
2093 }
2094  
2095 void
2096 insert(EV::ClickHouse self, SV *table_sv, SV *data_sv, ...)
2097 CODE:
2098 {
2099 /* Pin the invocant: stringify/FETCH below runs user code that may
2100 * drop the last $ch ref (DESTROY frees self when depth is 0). */
2101 18 sv_2mortal(SvREFCNT_inc(ST(0)));
2102 STRLEN table_len;
2103 const char *table;
2104 ev_ch_send_t *s;
2105 char *req;
2106 size_t req_len;
2107 SV *cb;
2108 18 HV *settings = NULL;
2109 18 int data_is_av = 0;
2110 18 AV *data_av = NULL;
2111  
2112 18 ▶ if (items == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (items == 4) { 18 0 18
2113 18 cb = ST(3);
2114 0 ▶ } else if (items == 5) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (items == 5) { 0 0 0
2115 0 ▶ if (!(SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV)) 0 0 0
if (!(SvROK(ST(3)) && SvTYPE(SvRV(ST(3))) == SVt_PVHV)) 0 0 0
2116 0 croak("settings must be a HASH reference");
2117 0 settings = (HV *)SvRV(ST(3));
2118 0 cb = ST(4);
2119 } else {
2120 0 croak("Usage: $ch->insert($table, $data, [\\%%settings], $cb)");
2121 }
2122  
2123 18 ▶ if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending &&
Branch: 4 branches
BranchTrueFalseTotal
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 2 16 18
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 2 0 2
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 2 0 2
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 2 0 2
2124 2 ▶ !self->reconnect_timing && !self->in_disconnect) croak("not connected");
Branch: 2 branches
BranchTrueFalseTotal
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 2 0 2
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 0 2 2
2125 18 ▶ if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 18 0 18
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 18 18
2126 0 croak("callback must be a CODE reference");
2127  
2128 18 table = SvPV(table_sv, table_len);
2129  
2130 /* Detect arrayref-of-arrayrefs vs TSV string */
2131 18 ▶ if (SvROK(data_sv) && SvTYPE(SvRV(data_sv)) == SVt_PVAV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(data_sv) && SvTYPE(SvRV(data_sv)) == SVt_PVAV) { 16 2 18
if (SvROK(data_sv) && SvTYPE(SvRV(data_sv)) == SVt_PVAV) { 16 0 16
2132 16 data_is_av = 1;
2133 16 data_av = (AV *)SvRV(data_sv);
2134 }
2135  
2136 char data_format[65];
2137 18 STRLEN data_format_len = 0;
2138 18 ▶ if (settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (settings) { 0 18 18
2139 0 SV **fmt = hv_fetchs(settings, "data_format", 0);
2140 0 ▶ if (fmt) SvGETMAGIC(*fmt);
Branch: 1 branch
BranchTrueFalseTotal
if (fmt) SvGETMAGIC(*fmt); 0 0 0
2141 0 ▶ if (fmt && SvOK(*fmt)) {
Branch: 2 branches
BranchTrueFalseTotal
if (fmt && SvOK(*fmt)) { 0 0 0
if (fmt && SvOK(*fmt)) { 0 0 0
2142 STRLEN i;
2143 0 const char *f = SvPV_nomg(*fmt, data_format_len);
2144 0 ▶ if (data_format_len == 0 || data_format_len >= sizeof(data_format))
Branch: 2 branches
BranchTrueFalseTotal
if (data_format_len == 0 || data_format_len >= sizeof(data_format)) 0 0 0
if (data_format_len == 0 || data_format_len >= sizeof(data_format)) 0 0 0
2145 0 croak("data_format must be a ClickHouse format name");
2146 0 ▶ for (i = 0; i < data_format_len; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < data_format_len; i++) 0 0 0
2147 0 ▶ if (!isALNUM(f[i]))
Branch: 1 branch
BranchTrueFalseTotal
if (!isALNUM(f[i])) 0 0 0
2148 0 croak("data_format must be a ClickHouse format name");
2149 0 ▶ if (data_is_av)
Branch: 1 branch
BranchTrueFalseTotal
if (data_is_av) 0 0 0
2150 0 croak("data_format needs the data as one pre-formatted string");
2151 0 Copy(f, data_format, data_format_len, char);
2152 }
2153 }
2154 18 data_format[data_format_len] = '\0';
2155  
2156 SSize_t ncols_at;
2157 18 SSize_t *cols_at = insert_columns_at(aTHX_ settings, &ncols_at);
2158 18 ▶ if (cols_at && !data_is_av)
Branch: 2 branches
BranchTrueFalseTotal
if (cols_at && !data_is_av) 0 18 18
if (cols_at && !data_is_av) 0 0 0
2159 0 croak("columns_at needs the data as an array of rows");
2160  
2161 /* Client-side defaults for empty values: validated here, snapshotted
2162 * onto the send entry after alloc_send. Native only; with data_format
2163 * the data rides pre-formatted and the server applies its own rules. */
2164 18 int want_empty_default = 0;
2165 18 int have_user_defaults = 0;
2166 18 HV *user_defaults = NULL;
2167 18 ▶ if (settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (settings) { 0 18 18
2168 0 SV **esv = hv_fetch(settings, "empty_as_default", 16, 0);
2169 0 SV **dsv = hv_fetch(settings, "defaults", 8, 0);
2170 0 ▶ if (esv && *esv && SvGMAGICAL(*esv)) mg_get(*esv);
Branch: 3 branches
BranchTrueFalseTotal
if (esv && *esv && SvGMAGICAL(*esv)) mg_get(*esv); 0 0 0
if (esv && *esv && SvGMAGICAL(*esv)) mg_get(*esv); 0 0 0
if (esv && *esv && SvGMAGICAL(*esv)) mg_get(*esv); 0 0 0
2171 0 ▶ if (esv && *esv && SvTRUE(*esv)) want_empty_default = 1;
Branch: 3 branches
BranchTrueFalseTotal
if (esv && *esv && SvTRUE(*esv)) want_empty_default = 1; 0 0 0
if (esv && *esv && SvTRUE(*esv)) want_empty_default = 1; 0 0 0
if (esv && *esv && SvTRUE(*esv)) want_empty_default = 1; 0 0 0
2172 0 ▶ if (dsv && *dsv && SvGMAGICAL(*dsv)) mg_get(*dsv);
Branch: 3 branches
BranchTrueFalseTotal
if (dsv && *dsv && SvGMAGICAL(*dsv)) mg_get(*dsv); 0 0 0
if (dsv && *dsv && SvGMAGICAL(*dsv)) mg_get(*dsv); 0 0 0
if (dsv && *dsv && SvGMAGICAL(*dsv)) mg_get(*dsv); 0 0 0
2173 0 ▶ if (dsv && *dsv && SvOK(*dsv)) {
Branch: 3 branches
BranchTrueFalseTotal
if (dsv && *dsv && SvOK(*dsv)) { 0 0 0
if (dsv && *dsv && SvOK(*dsv)) { 0 0 0
if (dsv && *dsv && SvOK(*dsv)) { 0 0 0
2174 HV *dhv;
2175 0 ▶ if (!SvROK(*dsv) || SvTYPE(SvRV(*dsv)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(*dsv) || SvTYPE(SvRV(*dsv)) != SVt_PVHV) 0 0 0
if (!SvROK(*dsv) || SvTYPE(SvRV(*dsv)) != SVt_PVHV) 0 0 0
2176 0 croak("defaults must be a HASH reference");
2177 0 dhv = (HV *)SvRV(*dsv);
2178 0 hv_iterinit(dhv);
2179 0 ▶ if (hv_iternext(dhv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hv_iternext(dhv)) { 0 0 0
2180 HE *he;
2181 0 have_user_defaults = 1;
2182 /* copied now: `settings` may become settings_copy, freed
2183 * before the send entry is filled */
2184 0 user_defaults = (HV *)sv_2mortal((SV *)newHV());
2185 0 hv_iterinit(dhv);
2186 0 ▶ while ((he = hv_iternext(dhv))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(dhv))) { 0 0 0
2187 I32 klen;
2188 0 char *key = hv_iterkey(he, &klen);
2189 0 (void)hv_store(user_defaults, key, klen,
2190 newSVsv(hv_iterval(dhv, he)), 0);
2191 }
2192 }
2193 }
2194 0 ▶ if (want_empty_default || have_user_defaults) {
Branch: 2 branches
BranchTrueFalseTotal
if (want_empty_default || have_user_defaults) { 0 0 0
if (want_empty_default || have_user_defaults) { 0 0 0
2195 0 ▶ if (self->protocol == PROTO_HTTP)
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) 0 0 0
2196 0 croak("empty_as_default and defaults require the native protocol");
2197 0 ▶ if (data_format_len)
Branch: 1 branch
BranchTrueFalseTotal
if (data_format_len) 0 0 0
2198 0 croak("empty_as_default and defaults cannot be combined with data_format");
2199 }
2200 }
2201  
2202 /* Native two-phase INSERT can only have one in flight at a time */
2203 18 ▶ if (self->protocol == PROTO_NATIVE && !data_format_len
Branch: 2 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && !data_format_len 18 0 18
if (self->protocol == PROTO_NATIVE && !data_format_len 18 0 18
2204 18 ▶ && (self->insert_data || self->insert_av))
Branch: 2 branches
BranchTrueFalseTotal
&& (self->insert_data || self->insert_av)) 18 0 18
&& (self->insert_data || self->insert_av)) 0 18 18
2205 0 croak("cannot pipeline native INSERT: previous INSERT still pending");
2206  
2207 /* Validate/serialize HTTP TSV data first — serialize_av_to_tsv can croak,
2208 * and we don't want to leak settings_copy or insert_sql via longjmp. */
2209 18 char *tsv_buf = NULL;
2210 18 STRLEN tsv_len = 0;
2211 18 const char *http_data = NULL;
2212 18 SV *snap = NULL;
2213 18 ▶ if (self->protocol == PROTO_NATIVE && !data_format_len && data_is_av)
Branch: 3 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && !data_format_len && data_is_av) 18 0 18
if (self->protocol == PROTO_NATIVE && !data_format_len && data_is_av) 18 0 18
if (self->protocol == PROTO_NATIVE && !data_format_len && data_is_av) 16 2 18
2214 16 snap = sv_2mortal(snapshot_insert_av(aTHX_ data_av, cols_at, ncols_at));
2215 18 ▶ if (self->protocol == PROTO_HTTP) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) { 0 18 18
2216 0 ▶ if (data_is_av) {
Branch: 1 branch
BranchTrueFalseTotal
if (data_is_av) { 0 0 0
2217 0 tsv_buf = serialize_av_to_tsv(aTHX_ data_av, cols_at, ncols_at,
2218 &tsv_len);
2219 0 http_data = tsv_buf;
2220 } else {
2221 0 http_data = SvPV(data_sv, tsv_len);
2222 }
2223 }
2224 18 const char *inline_data = NULL;
2225 18 STRLEN inline_len = 0;
2226 18 ▶ if (self->protocol == PROTO_NATIVE && data_format_len)
Branch: 2 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && data_format_len) 18 0 18
if (self->protocol == PROTO_NATIVE && data_format_len) 0 18 18
2227 0 inline_data = SvPV(data_sv, inline_len);
2228  
2229 /* Expand params => { x => 1 } to param_x => '1' AND idempotent => 1|$tok
2230 * to insert_deduplication_token in a single owned settings copy. */
2231 18 HV *settings_copy = NULL;
2232 18 ▶ if (settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (settings) { 0 18 18
2233 0 SV **idem = hv_fetch(settings, "idempotent", 10, 0);
2234 0 settings_copy = expand_params(aTHX_ settings);
2235 /* `idempotent => 1` (true scalar) auto-mints a token;
2236 * `idempotent => "any-other-string"` is used as the literal token;
2237 * a falsy value (0 / "" / undef / not present) is a no-op. */
2238 0 ▶ if (idem && SvTRUE(*idem)) {
Branch: 2 branches
BranchTrueFalseTotal
if (idem && SvTRUE(*idem)) { 0 0 0
if (idem && SvTRUE(*idem)) { 0 0 0
2239 0 ▶ if (!settings_copy) {
Branch: 1 branch
BranchTrueFalseTotal
if (!settings_copy) { 0 0 0
2240 0 settings_copy = newHVhv(settings);
2241 }
2242 0 (void)hv_delete(settings_copy, "idempotent", 10, G_DISCARD);
2243 0 STRLEN tlen = 0;
2244 0 const char *tstr = NULL;
2245 char tbuf[48];
2246 0 int generate = 1;
2247 0 ▶ if (SvPOK(*idem) || SvIOK(*idem) || SvNOK(*idem)) {
Branch: 3 branches
BranchTrueFalseTotal
if (SvPOK(*idem) || SvIOK(*idem) || SvNOK(*idem)) { 0 0 0
if (SvPOK(*idem) || SvIOK(*idem) || SvNOK(*idem)) { 0 0 0
if (SvPOK(*idem) || SvIOK(*idem) || SvNOK(*idem)) { 0 0 0
2248 0 tstr = SvPV(*idem, tlen);
2249 /* Only the literal "1" auto-generates; any other truthy
2250 * stringy value is the user's own token. */
2251 0 ▶ if (!(tlen == 1 && tstr[0] == '1')) generate = 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!(tlen == 1 && tstr[0] == '1')) generate = 0; 0 0 0
if (!(tlen == 1 && tstr[0] == '1')) generate = 0; 0 0 0
2252 }
2253 0 ▶ if (generate) {
Branch: 1 branch
BranchTrueFalseTotal
if (generate) { 0 0 0
2254 static uint64_t idem_seq = 0;
2255 0 idem_seq++;
2256 0 tlen = (size_t)snprintf(tbuf, sizeof(tbuf),
2257 "ev-ch-%lld-%d-%llu",
2258 0 (long long)time(NULL), (int)getpid(),
2259 (unsigned long long)idem_seq);
2260 0 tstr = tbuf;
2261 }
2262 0 (void)hv_store(settings_copy, "insert_deduplication_token", 26,
2263 newSVpvn(tstr, tlen), 0);
2264 }
2265 /* `async_insert => 1` toggles ClickHouse server-side INSERT batching;
2266 * fills in wait_for_async_insert=0 unless the caller overrode it. */
2267 0 SV **async = hv_fetch(settings, "async_insert", 12, 0);
2268 0 ▶ if (async && SvTRUE(*async)) {
Branch: 2 branches
BranchTrueFalseTotal
if (async && SvTRUE(*async)) { 0 0 0
if (async && SvTRUE(*async)) { 0 0 0
2269 0 ▶ if (!settings_copy) settings_copy = newHVhv(settings);
Branch: 1 branch
BranchTrueFalseTotal
if (!settings_copy) settings_copy = newHVhv(settings); 0 0 0
2270 0 (void)hv_store(settings_copy, "async_insert", 12, newSViv(1), 0);
2271 0 ▶ if (!hv_exists(settings_copy, "wait_for_async_insert", 21))
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_exists(settings_copy, "wait_for_async_insert", 21)) 0 0 0
2272 0 (void)hv_store(settings_copy, "wait_for_async_insert", 21,
2273 newSViv(0), 0);
2274 }
2275 0 ▶ if (settings_copy) settings = settings_copy;
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) settings = settings_copy; 0 0 0
2276 }
2277  
2278 /* "insert into table format F", optionally prefixed with the
2279 * connection's query_log_comment so the server's system.query_log
2280 * shows the same tag for selects and inserts. With data_format on
2281 * native the data rides inline in the query (one round trip, parsed
2282 * by the server's input format); otherwise it follows in phase 2. */
2283 36 size_t qlc_extra = self->query_log_comment
2284 0 ? strlen(self->query_log_comment) + 7
2285 18 ▶ : 0;
Branch: 1 branch
BranchTrueFalseTotal
: 0; 0 18 18
2286 char *insert_sql;
2287 18 ▶ if (inline_len > SIZE_MAX - table_len - qlc_extra - 128)
Branch: 1 branch
BranchTrueFalseTotal
if (inline_len > SIZE_MAX - table_len - qlc_extra - 128) 0 18 18
2288 0 croak("insert data too large");
2289 18 Newx(insert_sql, table_len + qlc_extra + 128 + inline_len, char);
2290 18 size_t off = qlc_emit_prefix(insert_sql, self->query_log_comment);
2291 18 size_t insert_sql_len = off + (size_t)snprintf(insert_sql + off,
2292 table_len + 128,
2293 "insert into %.*s format %s",
2294 (int)table_len, table,
2295 18 ▶ data_format_len ? data_format : "TabSeparated");
Branch: 1 branch
BranchTrueFalseTotal
data_format_len ? data_format : "TabSeparated"); 0 18 18
2296 18 ▶ if (inline_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (inline_data) { 0 18 18
2297 0 insert_sql[insert_sql_len++] = '\n';
2298 0 Copy(inline_data, insert_sql + insert_sql_len, inline_len, char);
2299 0 insert_sql_len += inline_len;
2300 }
2301  
2302 18 int defer_build = 0;
2303 18 ▶ if (self->protocol == PROTO_HTTP) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) { 0 18 18
2304 0 req = build_http_post_request(self, insert_sql, insert_sql_len,
2305 http_data, tsv_len,
2306 self->default_settings, settings,
2307 &req_len);
2308 0 ▶ if (tsv_buf) Safefree(tsv_buf);
Branch: 1 branch
BranchTrueFalseTotal
if (tsv_buf) Safefree(tsv_buf); 0 0 0
2309 18 ▶ } else if (!self->connected) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!self->connected) { 2 16 18
2310 /* server_revision unknown: stash inputs, build at dispatch.
2311 * INSERT carries no external tables. */
2312 2 defer_build = 1;
2313 2 req = NULL;
2314 2 req_len = 0;
2315 } else {
2316 /* Two-phase unless inline: phase 1 sends the query, phase 2 the
2317 * binary Data block once we have the sample block. */
2318 16 req = build_native_query(self, insert_sql, insert_sql_len,
2319 self->default_settings, settings,
2320 NULL, 0, &req_len);
2321 16 ▶ if (!req) {
Branch: 1 branch
BranchTrueFalseTotal
if (!req) { 0 16 16
2322 0 Safefree(insert_sql);
2323 0 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 0 0
2324 0 croak("query parameters require server revision >= %d",
2325 DBMS_MIN_REVISION_WITH_PARAMETERS);
2326 }
2327 }
2328  
2329 18 s = alloc_send();
2330 18 ▶ if (defer_build) {
Branch: 1 branch
BranchTrueFalseTotal
if (defer_build) { 2 16 18
2331 2 stash_send_deferred(aTHX_ s, insert_sql, insert_sql_len,
2332 self->default_settings, settings, &settings_copy,
2333 NULL, 0);
2334 } else {
2335 16 s->data = req;
2336 16 s->data_len = req_len;
2337 }
2338 18 Safefree(insert_sql);
2339 18 ▶ if (settings) send_apply_settings(s, settings);
Branch: 1 branch
BranchTrueFalseTotal
if (settings) send_apply_settings(s, settings); 0 18 18
2340 18 s->session_tz = query_session_tz(aTHX_ self, settings);
2341 /* Per-query on_query_complete override: extract BEFORE freeing
2342 * settings_copy (matches query() XSUB pattern; otherwise the
2343 * hv_fetch below would read a freed HV). */
2344 18 ▶ if (settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (settings) { 0 18 18
2345 0 SV **svp = hv_fetch(settings, "on_query_complete", 17, 0);
2346 0 ▶ if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp);
Branch: 3 branches
BranchTrueFalseTotal
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
if (svp && *svp && SvGMAGICAL(*svp)) mg_get(*svp); 0 0 0
2347 0 ▶ if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV)
Branch: 3 branches
BranchTrueFalseTotal
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
if (svp && SvROK(*svp) && SvTYPE(SvRV(*svp)) == SVt_PVCV) 0 0 0
2348 0 s->on_complete = SvMAGICAL(*svp) ? newRV_inc(SvRV(*svp))
2349 0 ▶ : SvREFCNT_inc(*svp);
Branch: 1 branch
BranchTrueFalseTotal
: SvREFCNT_inc(*svp); 0 0 0
2350 }
2351 18 ▶ if (settings_copy) SvREFCNT_dec((SV*)settings_copy);
Branch: 1 branch
BranchTrueFalseTotal
if (settings_copy) SvREFCNT_dec((SV*)settings_copy); 0 18 18
2352  
2353 /* For native INSERT, store data in the send entry (deferred to dispatch).
2354 * Even empty data needs the two-phase INSERT protocol to send an empty
2355 * DATA block. */
2356 18 ▶ if (self->protocol == PROTO_NATIVE && !data_format_len) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && !data_format_len) { 18 0 18
if (self->protocol == PROTO_NATIVE && !data_format_len) { 18 0 18
2357 18 ▶ if (data_is_av) {
Branch: 1 branch
BranchTrueFalseTotal
if (data_is_av) { 16 2 18
2358 16 s->insert_av = SvREFCNT_inc(snap);
2359 } else {
2360 STRLEN data_len;
2361 2 const char *data = SvPV(data_sv, data_len);
2362 2 Newx(s->insert_data, data_len + 1, char);
2363 2 ▶ if (data_len > 0)
Branch: 1 branch
BranchTrueFalseTotal
if (data_len > 0) 2 0 2
2364 2 Copy(data, s->insert_data, data_len, char);
2365 2 s->insert_data[data_len] = '\0';
2366 2 s->insert_data_len = data_len;
2367 }
2368 18 s->insert_empty_as_default = want_empty_default;
2369 18 ▶ if (have_user_defaults)
Branch: 1 branch
BranchTrueFalseTotal
if (have_user_defaults) 0 18 18
2370 0 s->insert_defaults = (HV *)SvREFCNT_inc((SV *)user_defaults);
2371 }
2372  
2373 18 s->cb = SvREFCNT_inc(cb);
2374 18 enqueue_send(self, s);
2375 }
2376  
2377 void
2378 ping(EV::ClickHouse self, SV *cb)
2379 CODE:
2380 {
2381 ev_ch_send_t *s;
2382 char *req;
2383 size_t req_len;
2384  
2385 4 ▶ if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending &&
Branch: 4 branches
BranchTrueFalseTotal
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
if (!self->connected && !self->connecting && !self->handshaking && !self->dns_pending && 4 0 4
2386 4 ▶ !self->reconnect_timing && !self->in_disconnect) croak("not connected");
Branch: 2 branches
BranchTrueFalseTotal
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 4 0 4
!self->reconnect_timing && !self->in_disconnect) croak("not connected"); 2 2 4
2387 2 ▶ if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 2 0 2
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 2 2
2388 0 croak("callback must be a CODE reference");
2389  
2390 2 ▶ if (self->protocol == PROTO_HTTP) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->protocol == PROTO_HTTP) { 0 2 2
2391 0 req = build_http_ping_request(self, &req_len);
2392 } else {
2393 2 req = build_native_ping(&req_len);
2394 }
2395  
2396 2 s = alloc_send();
2397 2 s->data = req;
2398 2 s->data_len = req_len;
2399 2 s->cb = SvREFCNT_inc(cb);
2400 2 enqueue_send(self, s);
2401 }
2402  
2403 SV*
2404 on_connect(EV::ClickHouse self, SV *handler = NULL)
2405 CODE:
2406 {
2407 38 RETVAL = handler_accessor(&self->on_connect, handler, items > 1);
2408 }
2409 OUTPUT:
2410 RETVAL
2411  
2412 SV*
2413 on_error(EV::ClickHouse self, SV *handler = NULL)
2414 CODE:
2415 {
2416 52 RETVAL = handler_accessor(&self->on_error, handler, items > 1);
2417 }
2418 OUTPUT:
2419 RETVAL
2420  
2421 SV*
2422 on_progress(EV::ClickHouse self, SV *handler = NULL)
2423 CODE:
2424 {
2425 0 RETVAL = handler_accessor(&self->on_progress, handler, items > 1);
2426 }
2427 OUTPUT:
2428 RETVAL
2429  
2430 int
2431 is_connected(EV::ClickHouse self)
2432 CODE:
2433 {
2434 1 ▶ RETVAL = self->connected ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->connected ? 1 : 0; 0 1 1
2435 }
2436 OUTPUT:
2437 RETVAL
2438  
2439 int
2440 pending_count(EV::ClickHouse self)
2441 CODE:
2442 {
2443 2 ▶ RETVAL = self->pending_count;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->pending_count; 1 1 2
2444 }
2445 OUTPUT:
2446 RETVAL
2447  
2448 # Snapshot of pending queries: returns arrayref of hashrefs. The
2449 # in-flight head (if any) appears first with state => 'in_flight',
2450 # query_id => last_query_id, age => seconds since dispatch. Queued
2451 # entries follow in dispatch order with state => 'queued' and the
2452 # query_id from settings (or undef if none was supplied). We only
2453 # expose what is cheaply reachable from struct state — full SQL or
2454 # settings hashes aren't retained after enqueue.
2455 SV*
2456 pending_queries(EV::ClickHouse self)
2457 CODE:
2458 {
2459 0 AV *out = newAV();
2460 0 ▶ if (!ngx_queue_empty(&self->cb_queue)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ngx_queue_empty(&self->cb_queue)) { 0 0 0
2461 0 HV *h = newHV();
2462 0 (void)hv_stores(h, "state", newSVpvs("in_flight"));
2463 0 ▶ (void)hv_stores(h, "query_id",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(h, "query_id", 0 0 0
2464 self->last_query_id
2465 ? newSVpv(self->last_query_id, 0)
2466 : newSV(0));
2467 0 double age = self->query_start_time > 0
2468 0 ▶ ? ev_now(self->loop) - self->query_start_time : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
? ev_now(self->loop) - self->query_start_time : 0.0; 0 0 0
2469 0 (void)hv_stores(h, "age", newSVnv(age));
2470 0 av_push(out, newRV_noinc((SV *)h));
2471 }
2472 ngx_queue_t *q;
2473 0 for (q = ngx_queue_head(&self->send_queue);
2474 0 ▶ q != ngx_queue_sentinel(&self->send_queue);
Branch: 1 branch
BranchTrueFalseTotal
q != ngx_queue_sentinel(&self->send_queue); 0 0 0
2475 0 q = ngx_queue_next(q)) {
2476 0 ev_ch_send_t *s = ngx_queue_data(q, ev_ch_send_t, queue);
2477 0 HV *h = newHV();
2478 0 (void)hv_stores(h, "state", newSVpvs("queued"));
2479 0 ▶ (void)hv_stores(h, "query_id",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(h, "query_id", 0 0 0
2480 s->query_id ? newSVpv(s->query_id, 0) : newSV(0));
2481 0 (void)hv_stores(h, "age", newSVnv(0.0));
2482 0 av_push(out, newRV_noinc((SV *)h));
2483 }
2484 0 RETVAL = newRV_noinc((SV *)out);
2485 }
2486 OUTPUT:
2487 RETVAL
2488  
2489 # Diagnostic snapshot of internal struct state — useful for debugging
2490 # stuck connections / leaks. Returns a hashref with a small fixed set
2491 # of fields; do NOT script against this in production (the shape may
2492 # change between versions).
2493 SV*
2494 dump_state(EV::ClickHouse self)
2495 CODE:
2496 {
2497 0 HV *h = newHV();
2498 0 (void)hv_stores(h, "connected", newSViv(self->connected ? 1 : 0));
2499 0 ▶ (void)hv_stores(h, "connecting", newSViv((self->connecting || self->handshaking) ? 1 : 0));
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_stores(h, "connecting", newSViv((self->connecting || self->handshaking) ? 1 : 0)); 0 0 0
(void)hv_stores(h, "connecting", newSViv((self->connecting || self->handshaking) ? 1 : 0)); 0 0 0
2500 0 (void)hv_stores(h, "dns_pending", newSViv(self->dns_pending ? 1 : 0));
2501 0 (void)hv_stores(h, "pending_count", newSViv(self->pending_count));
2502 0 (void)hv_stores(h, "callback_depth", newSViv(self->callback_depth));
2503 0 (void)hv_stores(h, "send_len", newSVuv((UV)self->send_len));
2504 0 (void)hv_stores(h, "send_pos", newSVuv((UV)self->send_pos));
2505 0 (void)hv_stores(h, "send_cap", newSVuv((UV)self->send_cap));
2506 0 (void)hv_stores(h, "recv_len", newSVuv((UV)self->recv_len));
2507 0 (void)hv_stores(h, "recv_cap", newSVuv((UV)self->recv_cap));
2508 0 (void)hv_stores(h, "fd", newSViv(self->fd));
2509 0 ▶ (void)hv_stores(h, "protocol", newSVpv(self->protocol == PROTO_NATIVE ? "native" : "http", 0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(h, "protocol", newSVpv(self->protocol == PROTO_NATIVE ? "native" : "http", 0)); 0 0 0
2510 0 (void)hv_stores(h, "server_revision", newSViv(self->server_revision));
2511 0 (void)hv_stores(h, "reconnect_attempts", newSViv(self->reconnect_attempts));
2512 0 ▶ (void)hv_stores(h, "host",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(h, "host", 0 0 0
2513 self->host ? newSVpv(self->host, 0) : newSV(0));
2514 0 (void)hv_stores(h, "port", newSVuv(self->port));
2515 0 (void)hv_stores(h, "send_count", newSVuv((UV)self->send_count));
2516 0 (void)hv_stores(h, "compress", newSViv(self->compress ? 1 : 0));
2517 0 (void)hv_stores(h, "tls", newSViv(ch_tls_active(self)));
2518 0 RETVAL = newRV_noinc((SV *)h);
2519 }
2520 OUTPUT:
2521 RETVAL
2522  
2523 SV *
2524 current_host(EV::ClickHouse self)
2525 CODE:
2526 {
2527 0 ▶ RETVAL = self->host ? newSVpv(self->host, 0) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->host ? newSVpv(self->host, 0) : &PL_sv_undef; 0 0 0
2528 }
2529 OUTPUT:
2530 RETVAL
2531  
2532 unsigned int
2533 current_port(EV::ClickHouse self)
2534 CODE:
2535 {
2536 1 ▶ RETVAL = self->port;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->port; 0 1 1
2537 }
2538 OUTPUT:
2539 RETVAL
2540  
2541 SV *
2542 server_info(EV::ClickHouse self)
2543 CODE:
2544 {
2545 0 ▶ if (self->server_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->server_name) { 0 0 0
2546 char buf[256];
2547 0 int n = snprintf(buf, sizeof(buf), "%s %u.%u.%u (revision %u)",
2548 self->server_name,
2549 self->server_version_major,
2550 self->server_version_minor,
2551 self->server_version_patch,
2552 self->server_revision);
2553 0 ▶ if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1; 0 0 0
2554 0 RETVAL = newSVpvn(buf, n);
2555 } else {
2556 0 RETVAL = &PL_sv_undef;
2557 }
2558 }
2559 OUTPUT:
2560 RETVAL
2561  
2562 SV *
2563 server_version(EV::ClickHouse self)
2564 CODE:
2565 {
2566 0 ▶ if (self->server_revision) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->server_revision) { 0 0 0
2567 char buf[64];
2568 0 int n = snprintf(buf, sizeof(buf), "%u.%u.%u",
2569 self->server_version_major,
2570 self->server_version_minor,
2571 self->server_version_patch);
2572 0 ▶ if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1; 0 0 0
2573 0 RETVAL = newSVpvn(buf, n);
2574 } else {
2575 0 RETVAL = &PL_sv_undef;
2576 }
2577 }
2578 OUTPUT:
2579 RETVAL
2580  
2581 UV
2582 server_revision(EV::ClickHouse self)
2583 CODE:
2584 {
2585 0 ▶ RETVAL = (UV)self->server_revision;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (UV)self->server_revision; 0 0 0
2586 }
2587 OUTPUT:
2588 RETVAL
2589  
2590 void
2591 skip_pending(EV::ClickHouse self)
2592 CODE:
2593 {
2594 /* Cancel queued + in-flight callbacks first (delivers errors), then
2595 * tear down the socket if a request was on the wire — capture the
2596 * had_inflight state up front because cancel_pending zeroes send_count. */
2597 0 int gen = self->connect_gen;
2598 0 int had_inflight = self->send_count > 0;
2599 0 ▶ if (cancel_pending(self, "skipped", 0)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_pending(self, "skipped", 0)) return; 0 0 0
2600 /* From on_query_start the staged entry is dequeued with its bytes in
2601 * send_buf; without this the dispatch guard (gen/connected
2602 * unchanged, nothing torn down) would send the skipped query and
2603 * its orphan response would corrupt the next query's accounting. */
2604 0 ▶ if (self->in_dispatch)
Branch: 1 branch
BranchTrueFalseTotal
if (self->in_dispatch) 0 0 0
2605 0 self->dispatch_cancelled = 1;
2606 /* A reset()/connect() from a callback already settled the old
2607 * generation — tearing down now would kill the live connection,
2608 * and work queued at depth > 0 would strand (same shape as
2609 * reset(); pipeline_advance may free self, so return after it). */
2610 0 ▶ if (self->connect_gen != gen) {
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) { 0 0 0
2611 0 ▶ if (self->connected && !ngx_queue_empty(&self->send_queue))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
2612 0 pipeline_advance(self);
2613 0 return;
2614 }
2615 0 ▶ CLEAR_INSERT(self); free_insert_default_state(self);
Branch: 2 branches
BranchTrueFalseTotal
CLEAR_INSERT(self); free_insert_default_state(self); 0 0 0
CLEAR_INSERT(self); free_insert_default_state(self); 0 0 0
2616 0 ▶ CLEAR_STR(self->insert_err);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->insert_err); 0 0 0
2617 0 ▶ if (had_inflight) {
Branch: 1 branch
BranchTrueFalseTotal
if (had_inflight) { 0 0 0
2618 0 ▶ if (cleanup_connection(self, 0)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (cleanup_connection(self, 0)) return; 0 0 0
2619 0 ▶ if (self->connect_gen != gen) return; /* reset() from on_disconnect won */
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; /* reset() from on_disconnect won */ 0 0 0
2620 0 ▶ if (self->auto_reconnect && self->host)
Branch: 2 branches
BranchTrueFalseTotal
if (self->auto_reconnect && self->host) 0 0 0
if (self->auto_reconnect && self->host) 0 0 0
2621 0 schedule_reconnect(self);
2622 }
2623 0 ▶ else if (self->connected && !ngx_queue_empty(&self->send_queue))
Branch: 2 branches
BranchTrueFalseTotal
else if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
else if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
2624 0 pipeline_advance(self); /* dispatch entries queued from skip callbacks */
2625 }
2626  
2627 void
2628 _set_protocol(EV::ClickHouse self, int proto)
2629 CODE:
2630 {
2631 48 self->protocol = proto;
2632 }
2633  
2634 void
2635 _set_compress(EV::ClickHouse self, int val)
2636 CODE:
2637 {
2638 14 self->compress = val;
2639 }
2640  
2641 void
2642 _set_session_id(EV::ClickHouse self, const char *sid)
2643 CODE:
2644 {
2645 0 ▶ CLEAR_STR(self->session_id);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->session_id); 0 0 0
2646 0 self->session_id = safe_strdup(sid);
2647 }
2648  
2649 void
2650 _set_query_log_comment(EV::ClickHouse self, const char *cmt)
2651 CODE:
2652 {
2653 0 ▶ CLEAR_STR(self->query_log_comment);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->query_log_comment); 0 0 0
2654 0 self->query_log_comment = safe_strdup(cmt);
2655 }
2656  
2657 void
2658 _set_host(EV::ClickHouse self, const char *host, unsigned int port)
2659 CODE:
2660 {
2661 0 ▶ CLEAR_STR(self->host);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_STR(self->host); 0 0 0
2662 0 self->host = safe_strdup(host);
2663 0 self->port = port;
2664 /* Don't reset reconnect_attempts here — that would defeat
2665 * reconnect_max_attempts for failover (every host advance would
2666 * restart the budget). Backoff naturally widens across the rotation,
2667 * which is what we want when every server is unreachable. */
2668 }
2669  
2670 void
2671 _set_dns_pending(EV::ClickHouse self, int v)
2672 CODE:
2673 {
2674 0 self->dns_pending = v ? 1 : 0;
2675 }
2676  
2677 int
2678 _take_dns_pending(EV::ClickHouse self)
2679 CODE:
2680 {
2681 /* Atomically read-and-clear. Returns 1 only on the first call after
2682 * dns_pending was set, so the Perl DNS callback can detect a finish
2683 * that ran during resolution and skip the post-DNS connect. */
2684 0 RETVAL = self->dns_pending;
2685 0 ▶ self->dns_pending = 0;
Branch: 1 branch
BranchTrueFalseTotal
self->dns_pending = 0; 0 0 0
2686 }
2687 OUTPUT:
2688 RETVAL
2689  
2690 void
2691 _set_conn_params(EV::ClickHouse self, const char *host, unsigned int port, const char *user, const char *password, const char *database)
2692 CODE:
2693 {
2694 /* Stash parameters without connecting, so the async-DNS path has a
2695 * reconnect/failover target when resolution fails. */
2696 0 store_conn_params(self, host, port, user, password, database);
2697 }
2698  
2699 void
2700 _dns_failed(EV::ClickHouse self, char *msg)
2701 CODE:
2702 {
2703 /* Async-DNS failure takes the same path as a blocking getaddrinfo
2704 * failure (failover rotation + auto_reconnect) instead of a bare
2705 * on_error. Must not touch self afterwards: user callbacks may
2706 * have freed it. */
2707 0 fail_connection(self, msg);
2708 }
2709  
2710 void
2711 _set_connect_timeout(EV::ClickHouse self, NV val)
2712 CODE:
2713 {
2714 3 self->connect_timeout = val;
2715 }
2716  
2717 void
2718 _set_tls(EV::ClickHouse self, int val)
2719 CODE:
2720 #ifdef HAVE_OPENSSL
2721 2 self->tls_enabled = val;
2722 #else
2723 if (val) croak("TLS support not compiled in (OpenSSL not found)");
2724 #endif
2725  
2726 void
2727 _set_settings(EV::ClickHouse self, SV *href)
2728 CODE:
2729 {
2730 0 ▶ if (!(SvROK(href) && SvTYPE(SvRV(href)) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(href) && SvTYPE(SvRV(href)) == SVt_PVHV)) 0 0 0
if (!(SvROK(href) && SvTYPE(SvRV(href)) == SVt_PVHV)) 0 0 0
2731 0 croak("settings must be a HASH reference");
2732 0 ▶ CLEAR_SV(self->default_settings);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->default_settings); 0 0 0
2733 0 self->default_settings = (HV *)SvREFCNT_inc(SvRV(href));
2734 }
2735  
2736 SV*
2737 on_disconnect(EV::ClickHouse self, SV *handler = NULL)
2738 CODE:
2739 {
2740 14 RETVAL = handler_accessor(&self->on_disconnect, handler, items > 1);
2741 }
2742 OUTPUT:
2743 RETVAL
2744  
2745 SV*
2746 on_query_complete(EV::ClickHouse self, SV *handler = NULL)
2747 CODE:
2748 {
2749 0 RETVAL = handler_accessor(&self->on_query_complete, handler, items > 1);
2750 }
2751 OUTPUT:
2752 RETVAL
2753  
2754 SV*
2755 on_query_start(EV::ClickHouse self, SV *handler = NULL)
2756 CODE:
2757 {
2758 1 RETVAL = handler_accessor(&self->on_query_start, handler, items > 1);
2759 }
2760 OUTPUT:
2761 RETVAL
2762  
2763 SV*
2764 on_log(EV::ClickHouse self, SV *handler = NULL)
2765 CODE:
2766 {
2767 0 RETVAL = handler_accessor(&self->on_log, handler, items > 1);
2768 }
2769 OUTPUT:
2770 RETVAL
2771  
2772 SV*
2773 last_tls_error(EV::ClickHouse self)
2774 CODE:
2775 {
2776 1 ▶ RETVAL = self->last_tls_error ? newSVpv(self->last_tls_error, 0) : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = self->last_tls_error ? newSVpv(self->last_tls_error, 0) : &PL_sv_undef; 1 0 1
2777 }
2778 OUTPUT:
2779 RETVAL
2780  
2781 SV*
2782 on_failover(EV::ClickHouse self, SV *handler = NULL)
2783 CODE:
2784 {
2785 1 RETVAL = handler_accessor(&self->on_failover, handler, items > 1);
2786 }
2787 OUTPUT:
2788 RETVAL
2789  
2790 void
2791 _set_failover(EV::ClickHouse self, SV *hosts_av_ref, unsigned int default_port, unsigned int explicit_port = 0)
2792 CODE:
2793 {
2794 /* Validate before freeing so a bad call keeps the old config. */
2795 2 ▶ if (!SvOK(hosts_av_ref)) { failover_free_hosts(self); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(hosts_av_ref)) { failover_free_hosts(self); return; } 0 2 2
2796 2 ▶ if (!(SvROK(hosts_av_ref) && SvTYPE(SvRV(hosts_av_ref)) == SVt_PVAV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(hosts_av_ref) && SvTYPE(SvRV(hosts_av_ref)) == SVt_PVAV)) 1 1 2
if (!(SvROK(hosts_av_ref) && SvTYPE(SvRV(hosts_av_ref)) == SVt_PVAV)) 0 1 1
2797 1 croak("_set_failover: hosts must be an arrayref");
2798 1 AV *hosts = (AV*)SvRV(hosts_av_ref);
2799 1 SSize_t n = av_top_index(hosts) + 1;
2800 1 ▶ if (n <= 0) { failover_free_hosts(self); return; }
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) { failover_free_hosts(self); return; } 0 1 1
2801 1 failover_free_hosts(self);
2802 1 ▶ Newx(self->failover_hosts, n, char *);
Branch: 1 branch
BranchTrueFalseTotal
Newx(self->failover_hosts, n, char *); 0 1 1
2803 1 ▶ Newx(self->failover_ports, n, unsigned int);
Branch: 1 branch
BranchTrueFalseTotal
Newx(self->failover_ports, n, unsigned int); 0 1 1
2804 1 self->failover_n = (int)n;
2805 1 self->failover_idx = 0;
2806 1 self->failover_default_port = default_port;
2807 /* Each entry is "host" or "host:port" or "[ipv6]:port". Parse here so
2808 * the hot emit_error path doesn't have to. */
2809 3 ▶ for (SSize_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i < n; i++) { 2 1 3
2810 2 SV **e = av_fetch(hosts, i, 0);
2811 2 ▶ if (!e || !SvOK(*e)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!e || !SvOK(*e)) { 2 0 2
if (!e || !SvOK(*e)) { 0 2 2
2812 0 self->failover_hosts[i] = safe_strdup("");
2813 0 self->failover_ports[i] = default_port;
2814 0 continue;
2815 }
2816 STRLEN sl;
2817 2 const char *s = SvPV(*e, sl);
2818 /* An explicit port => wins over embedded entry ports, matching
2819 * the initial-connect precedence in new(). */
2820 2 ▶ unsigned int port = explicit_port ? explicit_port : default_port;
Branch: 1 branch
BranchTrueFalseTotal
unsigned int port = explicit_port ? explicit_port : default_port; 0 2 2
2821 2 char *host = NULL;
2822 const char *colon;
2823 2 ▶ if (sl > 0 && s[0] == '[') {
Branch: 2 branches
BranchTrueFalseTotal
if (sl > 0 && s[0] == '[') { 2 0 2
if (sl > 0 && s[0] == '[') { 0 2 2
2824 0 const char *close = (const char *)memchr(s, ']', sl);
2825 0 ▶ if (close) {
Branch: 1 branch
BranchTrueFalseTotal
if (close) { 0 0 0
2826 0 Newx(host, close - s, char);
2827 0 memcpy(host, s + 1, close - s - 1);
2828 0 host[close - s - 1] = '\0';
2829 0 ▶ if (!explicit_port && close + 1 < s + sl && close[1] == ':')
Branch: 3 branches
BranchTrueFalseTotal
if (!explicit_port && close + 1 < s + sl && close[1] == ':') 0 0 0
if (!explicit_port && close + 1 < s + sl && close[1] == ':') 0 0 0
if (!explicit_port && close + 1 < s + sl && close[1] == ':') 0 0 0
2830 0 port = (unsigned int)atoi(close + 2);
2831 }
2832 }
2833 2 ▶ if (!host && (colon = (const char *)memchr(s, ':', sl))) {
Branch: 2 branches
BranchTrueFalseTotal
if (!host && (colon = (const char *)memchr(s, ':', sl))) { 2 0 2
if (!host && (colon = (const char *)memchr(s, ':', sl))) { 2 0 2
2834 2 size_t hl = colon - s;
2835 2 Newx(host, hl + 1, char);
2836 2 memcpy(host, s, hl);
2837 2 host[hl] = '\0';
2838 2 ▶ if (!explicit_port)
Branch: 1 branch
BranchTrueFalseTotal
if (!explicit_port) 2 0 2
2839 2 port = (unsigned int)atoi(colon + 1);
2840 }
2841 2 ▶ if (!host) host = safe_strdup(s);
Branch: 1 branch
BranchTrueFalseTotal
if (!host) host = safe_strdup(s); 0 2 2
2842 2 self->failover_hosts[i] = host;
2843 2 self->failover_ports[i] = port;
2844 }
2845 }
2846  
2847 SV *
2848 server_timezone(EV::ClickHouse self)
2849 CODE:
2850 {
2851 0 RETVAL = self->server_timezone ? newSVpv(self->server_timezone, 0)
2852 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2853 }
2854 OUTPUT:
2855 RETVAL
2856  
2857 void
2858 _set_tls_skip_verify(EV::ClickHouse self, int val)
2859 CODE:
2860 {
2861 1 self->tls_skip_verify = val;
2862 }
2863  
2864 void
2865 _set_query_timeout(EV::ClickHouse self, NV val)
2866 CODE:
2867 {
2868 0 self->query_timeout = val;
2869 }
2870  
2871 void
2872 _set_max_recv_buffer(EV::ClickHouse self, UV val)
2873 CODE:
2874 {
2875 0 self->max_recv_buffer = (size_t)val;
2876 }
2877  
2878 void
2879 _set_http_basic_auth(EV::ClickHouse self, int v)
2880 CODE:
2881 {
2882 0 self->http_basic_auth = v ? 1 : 0;
2883 }
2884  
2885 void
2886 _set_max_query_size(EV::ClickHouse self, UV val)
2887 CODE:
2888 {
2889 0 self->max_query_size = (size_t)val;
2890 }
2891  
2892 void
2893 _set_auto_reconnect(EV::ClickHouse self, int val)
2894 CODE:
2895 {
2896 20 self->auto_reconnect = val;
2897 }
2898  
2899 void
2900 _set_decode_flags(EV::ClickHouse self, unsigned int flags)
2901 CODE:
2902 {
2903 0 self->decode_flags = (uint32_t)flags;
2904 }
2905  
2906 SV *
2907 column_names(EV::ClickHouse self)
2908 CODE:
2909 {
2910 0 RETVAL = self->native_col_names ? newRV_inc((SV*)self->native_col_names)
2911 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2912 }
2913 OUTPUT:
2914 RETVAL
2915  
2916 SV *
2917 last_query_id(EV::ClickHouse self)
2918 CODE:
2919 {
2920 0 RETVAL = self->last_query_id ? newSVpv(self->last_query_id, 0)
2921 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2922 }
2923 OUTPUT:
2924 RETVAL
2925  
2926 SV *
2927 last_error_code(EV::ClickHouse self)
2928 CODE:
2929 {
2930 0 RETVAL = newSViv(self->last_error_code);
2931 }
2932 OUTPUT:
2933 RETVAL
2934  
2935 SV *
2936 column_types(EV::ClickHouse self)
2937 CODE:
2938 {
2939 0 RETVAL = self->native_col_types ? newRV_inc((SV*)self->native_col_types)
2940 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2941 }
2942 OUTPUT:
2943 RETVAL
2944  
2945 SV *
2946 last_totals(EV::ClickHouse self)
2947 CODE:
2948 {
2949 0 RETVAL = self->native_totals ? newRV_inc((SV*)self->native_totals)
2950 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2951 }
2952 OUTPUT:
2953 RETVAL
2954  
2955 SV *
2956 last_extremes(EV::ClickHouse self)
2957 CODE:
2958 {
2959 0 RETVAL = self->native_extremes ? newRV_inc((SV*)self->native_extremes)
2960 0 ▶ : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
: &PL_sv_undef; 0 0 0
2961 }
2962 OUTPUT:
2963 RETVAL
2964  
2965 SV *
2966 profile_rows_before_limit(EV::ClickHouse self)
2967 CODE:
2968 {
2969 0 RETVAL = newSVuv(self->profile_rows_before_limit);
2970 }
2971 OUTPUT:
2972 RETVAL
2973  
2974 SV *
2975 profile_rows(EV::ClickHouse self)
2976 CODE:
2977 {
2978 0 RETVAL = newSVuv(self->profile_rows);
2979 }
2980 OUTPUT:
2981 RETVAL
2982  
2983 SV *
2984 profile_bytes(EV::ClickHouse self)
2985 CODE:
2986 {
2987 0 RETVAL = newSVuv(self->profile_bytes);
2988 }
2989 OUTPUT:
2990 RETVAL
2991  
2992 SV*
2993 on_trace(EV::ClickHouse self, SV *handler = NULL)
2994 CODE:
2995 {
2996 1 RETVAL = handler_accessor(&self->on_trace, handler, items > 1);
2997 }
2998 OUTPUT:
2999 RETVAL
3000  
3001 void
3002 _set_keepalive(EV::ClickHouse self, double val)
3003 CODE:
3004 {
3005 1 self->keepalive = val;
3006 }
3007  
3008 void
3009 _set_reconnect_delay(EV::ClickHouse self, double val)
3010 CODE:
3011 {
3012 16 self->reconnect_delay = val;
3013 }
3014  
3015 void
3016 _set_reconnect_max_delay(EV::ClickHouse self, double val)
3017 CODE:
3018 {
3019 0 self->reconnect_max_delay = val;
3020 }
3021  
3022 void
3023 _set_reconnect_jitter(EV::ClickHouse self, double val)
3024 CODE:
3025 {
3026 0 ▶ self->reconnect_jitter = val < 0 ? 0 : val;
Branch: 1 branch
BranchTrueFalseTotal
self->reconnect_jitter = val < 0 ? 0 : val; 0 0 0
3027 }
3028  
3029 void
3030 _set_reconnect_max_attempts(EV::ClickHouse self, int val)
3031 CODE:
3032 {
3033 13 self->reconnect_max_attempts = val;
3034 }
3035  
3036 void
3037 _set_progress_period(EV::ClickHouse self, double val)
3038 CODE:
3039 {
3040 0 self->progress_period = val;
3041 }
3042  
3043 void
3044 drain(EV::ClickHouse self, SV *cb)
3045 CODE:
3046 {
3047 0 ▶ if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 0 0
if (!(SvROK(cb) && SvTYPE(SvRV(cb)) == SVt_PVCV)) 0 0 0
3048 0 croak("drain callback must be a CODE reference");
3049 0 ▶ if (self->on_drain)
Branch: 1 branch
BranchTrueFalseTotal
if (self->on_drain) 0 0 0
3050 0 croak("drain already pending");
3051 0 ▶ CLEAR_SV(self->on_drain);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->on_drain); 0 0 0
3052 0 ▶ if (self->pending_count == 0 && ngx_queue_empty(&self->send_queue)) {
Branch: 2 branches
BranchTrueFalseTotal
if (self->pending_count == 0 && ngx_queue_empty(&self->send_queue)) { 0 0 0
if (self->pending_count == 0 && ngx_queue_empty(&self->send_queue)) { 0 0 0
3053 /* Nothing pending — fire immediately. The handler runs at
3054 * callback_depth > 0, so a query it issues is enqueued
3055 * undispatched — advance afterwards or it strands until the
3056 * next event (forever with keepalive off). */
3057 0 ▶ if (fire_zero_arg_cb(self, cb, "drain")) return;
Branch: 1 branch
BranchTrueFalseTotal
if (fire_zero_arg_cb(self, cb, "drain")) return; 0 0 0
3058 0 ▶ if (self->connected && !ngx_queue_empty(&self->send_queue))
Branch: 2 branches
BranchTrueFalseTotal
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
if (self->connected && !ngx_queue_empty(&self->send_queue)) 0 0 0
3059 0 pipeline_advance(self);
3060 } else {
3061 0 self->on_drain = SvREFCNT_inc(cb);
3062 }
3063 }
3064  
3065 void
3066 cancel(EV::ClickHouse self)
3067 CODE:
3068 {
3069 5 ▶ if (self->protocol == PROTO_NATIVE && self->send_count > 0
Branch: 2 branches
BranchTrueFalseTotal
if (self->protocol == PROTO_NATIVE && self->send_count > 0 5 0 5
if (self->protocol == PROTO_NATIVE && self->send_count > 0 4 1 5
3070 4 ▶ && self->native_state == NATIVE_WAIT_INSERT_META) {
Branch: 1 branch
BranchTrueFalseTotal
&& self->native_state == NATIVE_WAIT_INSERT_META) { 4 0 4
3071 /* Answer the pending sample block with Cancel instead of data. */
3072 4 self->cancel_after_meta = 1;
3073 4 self->cancelled = 1;
3074 1 ▶ } else if (self->protocol == PROTO_NATIVE && self->in_dispatch) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (self->protocol == PROTO_NATIVE && self->in_dispatch) { 1 0 1
} else if (self->protocol == PROTO_NATIVE && self->in_dispatch) { 1 0 1
3075 /* From on_query_start the entry is dequeued but nothing is on
3076 * the wire yet — abort the dispatch itself instead of sending
3077 * a query plus a racing CANCEL. The cb_queue holds exactly
3078 * this entry (send_count is 0 at dispatch, so nothing else is
3079 * in flight); a nested second cancel finds it empty and just
3080 * re-arms the flag. */
3081 1 SV *oqc = NULL;
3082 1 SV *cb = pop_cb_ex(self, &oqc);
3083 1 ▶ if (cb != NULL)
Branch: 1 branch
BranchTrueFalseTotal
if (cb != NULL) 1 0 1
3084 1 fire_err_and_complete(self, cb, "query cancelled", oqc);
3085 1 self->dispatch_cancelled = 1;
3086 0 ▶ } else if (self->protocol == PROTO_NATIVE && self->send_count > 0) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (self->protocol == PROTO_NATIVE && self->send_count > 0) { 0 0 0
} else if (self->protocol == PROTO_NATIVE && self->send_count > 0) { 0 0 0
3087 /* Send CLIENT_CANCEL packet */
3088 native_buf_t pkt;
3089 0 nbuf_init(&pkt);
3090 0 nbuf_varuint(&pkt, CLIENT_CANCEL);
3091 0 ensure_send_cap(self, self->send_len + pkt.len);
3092 0 Copy(pkt.data, self->send_buf + self->send_len, pkt.len, char);
3093 0 self->send_len += pkt.len;
3094 0 Safefree(pkt.data);
3095 0 start_writing(self);
3096 0 self->cancelled = 1;
3097 /* We still need to wait for EndOfStream or Exception from server */
3098 0 ▶ } else if (self->protocol == PROTO_HTTP && (self->send_count > 0 || self->in_dispatch)) {
Branch: 3 branches
BranchTrueFalseTotal
} else if (self->protocol == PROTO_HTTP && (self->send_count > 0 || self->in_dispatch)) { 0 0 0
} else if (self->protocol == PROTO_HTTP && (self->send_count > 0 || self->in_dispatch)) { 0 0 0
} else if (self->protocol == PROTO_HTTP && (self->send_count > 0 || self->in_dispatch)) { 0 0 0
3099 /* HTTP: close connection to cancel. From on_query_start the
3100 * dispatch guard sees !connected and drops the staged entry.
3101 * Never-sent queued entries survive for the reconnect. */
3102 0 ▶ CLEAR_SV(self->native_rows);
Branch: 1 branch
BranchTrueFalseTotal
CLEAR_SV(self->native_rows); 0 0 0
3103 0 int gen = self->connect_gen;
3104 0 ▶ if (cancel_or_preserve(self, "query cancelled")) return;
Branch: 1 branch
BranchTrueFalseTotal
if (cancel_or_preserve(self, "query cancelled")) return; 0 0 0
3105 0 ▶ if (self->connect_gen != gen) return;
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; 0 0 0
3106 0 ▶ if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */
Branch: 1 branch
BranchTrueFalseTotal
if (cleanup_connection(self, 0)) return; /* on_disconnect freed self */ 0 0 0
3107 0 ▶ if (self->connect_gen != gen) return; /* reset() from on_disconnect won */
Branch: 1 branch
BranchTrueFalseTotal
if (self->connect_gen != gen) return; /* reset() from on_disconnect won */ 0 0 0
3108 0 ▶ if (self->auto_reconnect && self->host)
Branch: 2 branches
BranchTrueFalseTotal
if (self->auto_reconnect && self->host) 0 0 0
if (self->auto_reconnect && self->host) 0 0 0
3109 0 schedule_reconnect(self);
3110 }
3111 }
3112  
3113 # --- XS-resident hot-path helpers (Streamer, Pool, Iterator, breaker) ---
3114 # Each takes the Perl object hash directly; they read/write hash slots
3115 # from C and call back into Perl only for the cold paths (_flush,
3116 # on_high_water; EV::run is invoked via the C API).
3117  
3118 SV *
3119 _streamer_push_row(SV *self_sv, SV *row)
3120 CODE:
3121 {
3122 /* Pin the streamer: _flush / on_high_water below run user code
3123 * that may drop the last ref while HV *self is still in use. */
3124 0 sv_2mortal(SvREFCNT_inc(self_sv));
3125 0 ▶ if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV)) 0 0 0
if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV)) 0 0 0
3126 0 croak("_streamer_push_row: self must be a hash ref");
3127 0 HV *self = (HV*)SvRV(self_sv);
3128  
3129 0 SV **buf_p = hv_fetchs(self, "buffer", 0);
3130 0 ▶ if (!buf_p || !SvROK(*buf_p) || SvTYPE(SvRV(*buf_p)) != SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (!buf_p || !SvROK(*buf_p) || SvTYPE(SvRV(*buf_p)) != SVt_PVAV) 0 0 0
if (!buf_p || !SvROK(*buf_p) || SvTYPE(SvRV(*buf_p)) != SVt_PVAV) 0 0 0
if (!buf_p || !SvROK(*buf_p) || SvTYPE(SvRV(*buf_p)) != SVt_PVAV) 0 0 0
3131 0 croak("_streamer_push_row: buffer slot missing");
3132 0 AV *buffer = (AV*)SvRV(*buf_p);
3133  
3134 SV *to_push;
3135 0 ▶ if (SvROK(row) && SvTYPE(SvRV(row)) == SVt_PVHV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(row) && SvTYPE(SvRV(row)) == SVt_PVHV) { 0 0 0
if (SvROK(row) && SvTYPE(SvRV(row)) == SVt_PVHV) { 0 0 0
3136 0 SV **cols_p = hv_fetchs(self, "columns", 0);
3137 0 ▶ if (!cols_p || !SvROK(*cols_p) || SvTYPE(SvRV(*cols_p)) != SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (!cols_p || !SvROK(*cols_p) || SvTYPE(SvRV(*cols_p)) != SVt_PVAV) 0 0 0
if (!cols_p || !SvROK(*cols_p) || SvTYPE(SvRV(*cols_p)) != SVt_PVAV) 0 0 0
if (!cols_p || !SvROK(*cols_p) || SvTYPE(SvRV(*cols_p)) != SVt_PVAV) 0 0 0
3138 0 croak("push_row(\\%%hash) requires columns => [...] at insert_streamer creation");
3139 0 AV *cols = (AV*)SvRV(*cols_p);
3140 0 HV *h = (HV*)SvRV(row);
3141 0 SSize_t n = av_top_index(cols) + 1;
3142 0 AV *out = newAV();
3143 0 av_extend(out, n - 1);
3144 0 ▶ for (SSize_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i < n; i++) { 0 0 0
3145 0 SV **col = av_fetch(cols, i, 0);
3146 0 ▶ if (!col) { av_push(out, newSV(0)); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (!col) { av_push(out, newSV(0)); continue; } 0 0 0
3147 STRLEN cl;
3148 0 const char *cp = SvPV(*col, cl);
3149 0 SV **vp = hv_fetch(h, cp, cl, 0);
3150 0 ▶ av_push(out, vp ? newSVsv(*vp) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(out, vp ? newSVsv(*vp) : newSV(0)); 0 0 0
3151 }
3152 0 to_push = newRV_noinc((SV*)out);
3153 } else {
3154 0 to_push = newSVsv(row);
3155 }
3156 0 av_push(buffer, to_push);
3157 0 SSize_t buf_n = av_top_index(buffer) + 1;
3158  
3159 0 SV **bs_p = hv_fetchs(self, "batch_size", 0);
3160 0 ▶ SSize_t batch = bs_p ? SvIV(*bs_p) : 10000;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t batch = bs_p ? SvIV(*bs_p) : 10000; 0 0 0
3161 0 int need_flush = buf_n >= batch;
3162  
3163 0 int need_hw = 0;
3164 0 SV **hw_p = hv_fetchs(self, "high_water", 0);
3165 0 ▶ SSize_t hw = hw_p ? SvIV(*hw_p) : 0;
Branch: 1 branch
BranchTrueFalseTotal
SSize_t hw = hw_p ? SvIV(*hw_p) : 0; 0 0 0
3166 0 ▶ if (hw && buf_n >= hw) {
Branch: 2 branches
BranchTrueFalseTotal
if (hw && buf_n >= hw) { 0 0 0
if (hw && buf_n >= hw) { 0 0 0
3167 0 SV **act_p = hv_fetchs(self, "high_water_active", 0);
3168 0 ▶ if (!act_p || !SvTRUE(*act_p)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!act_p || !SvTRUE(*act_p)) { 0 0 0
if (!act_p || !SvTRUE(*act_p)) { 0 0 0
3169 0 (void)hv_stores(self, "high_water_active", newSViv(1));
3170 0 need_hw = 1;
3171 }
3172 }
3173  
3174 /* G_EVAL on both dispatches: insert() reachable from _flush can
3175 * croak ("not connected" etc.); the user's on_high_water is also
3176 * untrusted. Match the rest of the codebase's exception policy. */
3177 0 ▶ if (need_flush) {
Branch: 1 branch
BranchTrueFalseTotal
if (need_flush) { 0 0 0
3178 0 dSP;
3179 0 ENTER; SAVETMPS;
3180 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
3181 0 ▶ XPUSHs(self_sv);
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(self_sv); 0 0 0
3182 0 PUTBACK;
3183 0 call_method("_flush", G_DISCARD | G_EVAL);
3184 0 ▶ WARN_AND_CLEAR_ERRSV("Streamer _flush");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("Streamer _flush"); 0 0 0
WARN_AND_CLEAR_ERRSV("Streamer _flush"); 0 0 0
WARN_AND_CLEAR_ERRSV("Streamer _flush"); 0 0 0
WARN_AND_CLEAR_ERRSV("Streamer _flush"); 0 0 0
3185 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
3186 }
3187  
3188 0 ▶ if (need_hw) {
Branch: 1 branch
BranchTrueFalseTotal
if (need_hw) { 0 0 0
3189 0 SV **cb_p = hv_fetchs(self, "on_high_water", 0);
3190 0 ▶ if (cb_p && SvROK(*cb_p) && SvTYPE(SvRV(*cb_p)) == SVt_PVCV) {
Branch: 3 branches
BranchTrueFalseTotal
if (cb_p && SvROK(*cb_p) && SvTYPE(SvRV(*cb_p)) == SVt_PVCV) { 0 0 0
if (cb_p && SvROK(*cb_p) && SvTYPE(SvRV(*cb_p)) == SVt_PVCV) { 0 0 0
if (cb_p && SvROK(*cb_p) && SvTYPE(SvRV(*cb_p)) == SVt_PVCV) { 0 0 0
3191 0 SV **inflight_p = hv_fetchs(self, "in_flight", 0);
3192 0 ▶ IV inflight = inflight_p ? SvIV(*inflight_p) : 0;
Branch: 1 branch
BranchTrueFalseTotal
IV inflight = inflight_p ? SvIV(*inflight_p) : 0; 0 0 0
3193 0 dSP;
3194 0 ENTER; SAVETMPS;
3195 0 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 0 0
3196 0 ▶ mXPUSHi(buf_n);
Branch: 1 branch
BranchTrueFalseTotal
mXPUSHi(buf_n); 0 0 0
3197 0 ▶ mXPUSHi(inflight);
Branch: 1 branch
BranchTrueFalseTotal
mXPUSHi(inflight); 0 0 0
3198 0 PUTBACK;
3199 0 PINNED_CALL_SV(*cb_p, G_DISCARD | G_EVAL);
3200 0 ▶ WARN_AND_CLEAR_ERRSV("on_high_water");
Branch: 4 branches
BranchTrueFalseTotal
WARN_AND_CLEAR_ERRSV("on_high_water"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_high_water"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_high_water"); 0 0 0
WARN_AND_CLEAR_ERRSV("on_high_water"); 0 0 0
3201 0 ▶ FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; LEAVE; 0 0 0
3202 }
3203 }
3204  
3205 /* Return self to allow chaining ($s->push_row(...)->push_row(...))
3206 * without allocating a fresh RV per call. */
3207 0 RETVAL = SvREFCNT_inc(self_sv);
3208 }
3209 OUTPUT:
3210 RETVAL
3211  
3212 SV *
3213 _pool_pick(SV *pool_sv)
3214 CODE:
3215 {
3216 0 ▶ if (!(SvROK(pool_sv) && SvTYPE(SvRV(pool_sv)) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(pool_sv) && SvTYPE(SvRV(pool_sv)) == SVt_PVHV)) 0 0 0
if (!(SvROK(pool_sv) && SvTYPE(SvRV(pool_sv)) == SVt_PVHV)) 0 0 0
3217 0 croak("_pool_pick: pool must be a hash ref");
3218 0 HV *pool = (HV*)SvRV(pool_sv);
3219  
3220 0 SV **conns_p = hv_fetchs(pool, "conns", 0);
3221 0 ▶ if (!conns_p || !SvROK(*conns_p) || SvTYPE(SvRV(*conns_p)) != SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (!conns_p || !SvROK(*conns_p) || SvTYPE(SvRV(*conns_p)) != SVt_PVAV) 0 0 0
if (!conns_p || !SvROK(*conns_p) || SvTYPE(SvRV(*conns_p)) != SVt_PVAV) 0 0 0
if (!conns_p || !SvROK(*conns_p) || SvTYPE(SvRV(*conns_p)) != SVt_PVAV) 0 0 0
3222 0 croak("_pool_pick: conns slot missing");
3223 0 AV *conns = (AV*)SvRV(*conns_p);
3224 0 SSize_t n = av_top_index(conns) + 1;
3225 0 ▶ if (n <= 0) croak("_pool_pick: empty pool");
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 0) croak("_pool_pick: empty pool"); 0 0 0
3226  
3227 0 SV **thresh_p = hv_fetchs(pool, "cb_thresh", 0);
3228 0 ▶ IV thresh = thresh_p ? SvIV(*thresh_p) : 0;
Branch: 1 branch
BranchTrueFalseTotal
IV thresh = thresh_p ? SvIV(*thresh_p) : 0; 0 0 0
3229 0 AV *cb_state = NULL;
3230 0 double now = 0;
3231 0 ▶ if (thresh > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (thresh > 0) { 0 0 0
3232 0 SV **cs_p = hv_fetchs(pool, "cb_state", 0);
3233 0 ▶ if (cs_p && SvROK(*cs_p) && SvTYPE(SvRV(*cs_p)) == SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (cs_p && SvROK(*cs_p) && SvTYPE(SvRV(*cs_p)) == SVt_PVAV) 0 0 0
if (cs_p && SvROK(*cs_p) && SvTYPE(SvRV(*cs_p)) == SVt_PVAV) 0 0 0
if (cs_p && SvROK(*cs_p) && SvTYPE(SvRV(*cs_p)) == SVt_PVAV) 0 0 0
3234 0 cb_state = (AV*)SvRV(*cs_p);
3235 0 now = ev_time();
3236 }
3237 /* with_session "pinned" members get round-robined LAST — they're
3238 * still selectable but only as a fallback. _pinned is a refaddr-
3239 * keyed hash maintained by Pool::with_session in the .pm. */
3240 0 HV *pinned = NULL;
3241 {
3242 0 SV **p_p = hv_fetchs(pool, "_pinned", 0);
3243 0 ▶ if (p_p && SvROK(*p_p) && SvTYPE(SvRV(*p_p)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (p_p && SvROK(*p_p) && SvTYPE(SvRV(*p_p)) == SVt_PVHV) 0 0 0
if (p_p && SvROK(*p_p) && SvTYPE(SvRV(*p_p)) == SVt_PVHV) 0 0 0
if (p_p && SvROK(*p_p) && SvTYPE(SvRV(*p_p)) == SVt_PVHV) 0 0 0
3244 0 pinned = (HV*)SvRV(*p_p);
3245 }
3246  
3247 int stack_ties[64];
3248 0 int *ties = stack_ties;
3249 0 int ties_cap = 64;
3250 0 ▶ if (n > ties_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > ties_cap) { 0 0 0
3251 0 ▶ Newx(ties, n, int);
Branch: 1 branch
BranchTrueFalseTotal
Newx(ties, n, int); 0 0 0
3252 0 ties_cap = (int)n;
3253 }
3254  
3255 0 int best = -1;
3256 0 int best_n = 0;
3257 0 int n_ties = 0;
3258 /* 3 passes: live+unpinned, live (incl pinned), all members (fallback). */
3259 0 ▶ for (int pass = 0; pass < 3; pass++) {
Branch: 1 branch
BranchTrueFalseTotal
for (int pass = 0; pass < 3; pass++) { 0 0 0
3260 0 ▶ for (SSize_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i < n; i++) { 0 0 0
3261 0 ▶ if (pass < 2 && cb_state) {
Branch: 2 branches
BranchTrueFalseTotal
if (pass < 2 && cb_state) { 0 0 0
if (pass < 2 && cb_state) { 0 0 0
3262 0 SV **slot_sv = av_fetch(cb_state, i, 0);
3263 0 ▶ if (slot_sv && SvROK(*slot_sv) && SvTYPE(SvRV(*slot_sv)) == SVt_PVHV) {
Branch: 3 branches
BranchTrueFalseTotal
if (slot_sv && SvROK(*slot_sv) && SvTYPE(SvRV(*slot_sv)) == SVt_PVHV) { 0 0 0
if (slot_sv && SvROK(*slot_sv) && SvTYPE(SvRV(*slot_sv)) == SVt_PVHV) { 0 0 0
if (slot_sv && SvROK(*slot_sv) && SvTYPE(SvRV(*slot_sv)) == SVt_PVHV) { 0 0 0
3264 0 HV *slot = (HV*)SvRV(*slot_sv);
3265 0 SV **du_p = hv_fetchs(slot, "dead_until", 0);
3266 0 ▶ if (du_p && SvNV(*du_p) > now) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (du_p && SvNV(*du_p) > now) continue; 0 0 0
if (du_p && SvNV(*du_p) > now) continue; 0 0 0
3267 }
3268 }
3269 0 SV **csv = av_fetch(conns, i, 0);
3270 0 ▶ if (!csv || !SvROK(*csv) || !sv_isa(*csv, "EV::ClickHouse")) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!csv || !SvROK(*csv) || !sv_isa(*csv, "EV::ClickHouse")) continue; 0 0 0
if (!csv || !SvROK(*csv) || !sv_isa(*csv, "EV::ClickHouse")) continue; 0 0 0
if (!csv || !SvROK(*csv) || !sv_isa(*csv, "EV::ClickHouse")) continue; 0 0 0
3271 0 ev_clickhouse_t *ch = INT2PTR(ev_clickhouse_t*, SvIV(SvRV(*csv)));
3272 0 ▶ if (ch->magic != EV_CH_MAGIC) continue; /* freed mid-callback */
Branch: 1 branch
BranchTrueFalseTotal
if (ch->magic != EV_CH_MAGIC) continue; /* freed mid-callback */ 0 0 0
3273 0 ▶ if (pass == 0 && pinned) {
Branch: 2 branches
BranchTrueFalseTotal
if (pass == 0 && pinned) { 0 0 0
if (pass == 0 && pinned) { 0 0 0
3274 /* Match Pool::with_session's `refaddr($conn)` key —
3275 * that's the address of the referent SV (SvRV(*csv)),
3276 * not the struct pointer. */
3277 char key[32];
3278 0 int klen = snprintf(key, sizeof(key), "%lu",
3279 0 (unsigned long)(uintptr_t)SvRV(*csv));
3280 0 ▶ if (hv_exists(pinned, key, klen)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(pinned, key, klen)) continue; 0 0 0
3281 }
3282 0 int pc = ch->pending_count;
3283 0 ▶ if (best < 0 || pc < best_n) {
Branch: 2 branches
BranchTrueFalseTotal
if (best < 0 || pc < best_n) { 0 0 0
if (best < 0 || pc < best_n) { 0 0 0
3284 0 best_n = pc;
3285 0 best = (int)i;
3286 0 ties[0] = (int)i;
3287 0 n_ties = 1;
3288 0 ▶ } else if (pc == best_n) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (pc == best_n) { 0 0 0
3289 0 ▶ if (n_ties < ties_cap) ties[n_ties++] = (int)i;
Branch: 1 branch
BranchTrueFalseTotal
if (n_ties < ties_cap) ties[n_ties++] = (int)i; 0 0 0
3290 }
3291 }
3292 0 ▶ if (best >= 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (best >= 0) break; 0 0 0
3293 }
3294  
3295 /* Defensive: if every entry was filtered out (sv_isa mismatch /
3296 * magic mismatch / external corruption) all three passes leave
3297 * best=-1. Free the heap ties array before croaking. */
3298 0 ▶ if (best < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (best < 0) { 0 0 0
3299 0 ▶ if (ties != stack_ties) Safefree(ties);
Branch: 1 branch
BranchTrueFalseTotal
if (ties != stack_ties) Safefree(ties); 0 0 0
3300 0 croak("_pool_pick: no valid EV::ClickHouse entries in pool");
3301 }
3302  
3303 int picked;
3304 0 ▶ if (n_ties == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (n_ties == 1) { 0 0 0
3305 0 picked = ties[0];
3306 } else {
3307 0 SV **idx_p = hv_fetchs(pool, "idx", 0);
3308 0 ▶ IV idx = idx_p ? SvIV(*idx_p) : 0;
Branch: 1 branch
BranchTrueFalseTotal
IV idx = idx_p ? SvIV(*idx_p) : 0; 0 0 0
3309 0 ▶ if (idx < 0) idx = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (idx < 0) idx = 0; 0 0 0
3310 0 picked = ties[idx % n_ties];
3311 /* Store a monotonic counter, not (idx+1) % n_ties: n_ties varies
3312 * per call, so a mod-n_ties write would pin idx into the smallest
3313 * recent tie-set and starve higher tie indices under fluctuating
3314 * load. The mod is applied at read time above. */
3315 0 (void)hv_stores(pool, "idx", newSViv(idx + 1));
3316 }
3317 0 ▶ if (ties != stack_ties) Safefree(ties);
Branch: 1 branch
BranchTrueFalseTotal
if (ties != stack_ties) Safefree(ties); 0 0 0
3318  
3319 0 SV **csv = av_fetch(conns, picked, 0);
3320 0 ▶ if (!csv || !*csv)
Branch: 2 branches
BranchTrueFalseTotal
if (!csv || !*csv) 0 0 0
if (!csv || !*csv) 0 0 0
3321 0 croak("_pool_pick: connection slot %d missing", picked);
3322 0 RETVAL = SvREFCNT_inc(*csv);
3323 }
3324 OUTPUT:
3325 RETVAL
3326  
3327 SV *
3328 _iterator_next(SV *self_sv, SV *timeout_sv = &PL_sv_undef)
3329 CODE:
3330 {
3331 /* Pin the iterator: timeout stringify / ev_run below run user
3332 * code that may drop the last ref while HV *self is in use. */
3333 0 sv_2mortal(SvREFCNT_inc(self_sv));
3334 0 ▶ if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV))
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV)) 0 0 0
if (!(SvROK(self_sv) && SvTYPE(SvRV(self_sv)) == SVt_PVHV)) 0 0 0
3335 0 croak("_iterator_next: self must be a hash ref");
3336 0 HV *self = (HV*)SvRV(self_sv);
3337 0 SV **ch_p = hv_fetchs(self, "ch", 0);
3338 0 ▶ if (!ch_p || !SvROK(*ch_p) || !sv_isa(*ch_p, "EV::ClickHouse"))
Branch: 3 branches
BranchTrueFalseTotal
if (!ch_p || !SvROK(*ch_p) || !sv_isa(*ch_p, "EV::ClickHouse")) 0 0 0
if (!ch_p || !SvROK(*ch_p) || !sv_isa(*ch_p, "EV::ClickHouse")) 0 0 0
if (!ch_p || !SvROK(*ch_p) || !sv_isa(*ch_p, "EV::ClickHouse")) 0 0 0
3339 0 croak("_iterator_next: ch slot is not an EV::ClickHouse");
3340 0 ev_clickhouse_t *ch = INT2PTR(ev_clickhouse_t*, SvIV(SvRV(*ch_p)));
3341 0 ▶ struct ev_loop *loop = ch->loop ? ch->loop : EV_DEFAULT;
Branch: 1 branch
BranchTrueFalseTotal
struct ev_loop *loop = ch->loop ? ch->loop : EV_DEFAULT; 0 0 0
3342  
3343 0 SV **batches_p = hv_fetchs(self, "batches", 0);
3344 0 ▶ if (!batches_p || !SvROK(*batches_p) || SvTYPE(SvRV(*batches_p)) != SVt_PVAV)
Branch: 3 branches
BranchTrueFalseTotal
if (!batches_p || !SvROK(*batches_p) || SvTYPE(SvRV(*batches_p)) != SVt_PVAV) 0 0 0
if (!batches_p || !SvROK(*batches_p) || SvTYPE(SvRV(*batches_p)) != SVt_PVAV) 0 0 0
if (!batches_p || !SvROK(*batches_p) || SvTYPE(SvRV(*batches_p)) != SVt_PVAV) 0 0 0
3345 0 croak("_iterator_next: batches slot missing");
3346 0 AV *batches = (AV*)SvRV(*batches_p);
3347  
3348 0 double timeout = 0;
3349 0 ▶ if (SvOK(timeout_sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(timeout_sv)) { 0 0 0
3350 0 double t = SvNV(timeout_sv);
3351 0 ▶ if (t > 0) timeout = t;
Branch: 1 branch
BranchTrueFalseTotal
if (t > 0) timeout = t; 0 0 0
3352 }
3353 0 ev_now_update(loop);
3354 0 ▶ double expires = timeout > 0 ? ev_now(loop) + timeout : 0;
Branch: 1 branch
BranchTrueFalseTotal
double expires = timeout > 0 ? ev_now(loop) + timeout : 0; 0 0 0
3355  
3356 ev_timer to;
3357 0 int armed = 0;
3358  
3359 0 ▶ while (av_top_index(batches) < 0) {
Branch: 1 branch
BranchTrueFalseTotal
while (av_top_index(batches) < 0) { 0 0 0
3360 0 SV **done_p = hv_fetchs(self, "done", 0);
3361 0 ▶ if (done_p && SvTRUE(*done_p)) break;
Branch: 2 branches
BranchTrueFalseTotal
if (done_p && SvTRUE(*done_p)) break; 0 0 0
if (done_p && SvTRUE(*done_p)) break; 0 0 0
3362 0 ▶ if (expires) {
Branch: 1 branch
BranchTrueFalseTotal
if (expires) { 0 0 0
3363 0 double left = expires - ev_now(loop);
3364 0 ▶ if (left <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (left <= 0) { 0 0 0
3365 0 ▶ if (armed) { ev_timer_stop(loop, &to); armed = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (armed) { ev_timer_stop(loop, &to); armed = 0; } 0 0 0
3366 0 RETVAL = &PL_sv_undef;
3367 0 goto out;
3368 }
3369 0 ev_timer_init(&to, iter_timeout_cb, left, 0);
3370 0 ev_timer_start(loop, &to);
3371 0 armed = 1;
3372 }
3373 0 ev_run(loop, 0);
3374 0 ▶ if (armed) { ev_timer_stop(loop, &to); armed = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (armed) { ev_timer_stop(loop, &to); armed = 0; } 0 0 0
3375 /* ev_run returns for any break on the shared loop, not just
3376 * ours: with no batch, no done flag and no timeout expiry,
3377 * loop and keep waiting instead of truncating the results. */
3378 }
3379  
3380 0 ▶ if (av_top_index(batches) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (av_top_index(batches) >= 0) { 0 0 0
3381 0 SV *b = av_shift(batches);
3382 0 ▶ RETVAL = b ? b : &PL_sv_undef;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = b ? b : &PL_sv_undef; 0 0 0
3383 } else {
3384 0 RETVAL = &PL_sv_undef;
3385 }
3386 0 out:
3387 ;
3388 }
3389 OUTPUT:
3390 RETVAL
3391  
3392 void
3393 _breaker_observe(SV *slot_sv, SV *err_sv, IV threshold, NV cooldown)
3394 CODE:
3395 {
3396 0 ▶ if (!(SvROK(slot_sv) && SvTYPE(SvRV(slot_sv)) == SVt_PVHV)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(slot_sv) && SvTYPE(SvRV(slot_sv)) == SVt_PVHV)) return; 0 0 0
if (!(SvROK(slot_sv) && SvTYPE(SvRV(slot_sv)) == SVt_PVHV)) return; 0 0 0
3397 0 HV *slot = (HV*)SvRV(slot_sv);
3398 0 ▶ if (SvTRUE(err_sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTRUE(err_sv)) { 0 0 0
3399 0 SV **fails_p = hv_fetchs(slot, "fails", 0);
3400 0 ▶ IV fails = (fails_p ? SvIV(*fails_p) : 0) + 1;
Branch: 1 branch
BranchTrueFalseTotal
IV fails = (fails_p ? SvIV(*fails_p) : 0) + 1; 0 0 0
3401 0 (void)hv_stores(slot, "fails", newSViv(fails));
3402 0 ▶ if (threshold > 0 && fails >= threshold) {
Branch: 2 branches
BranchTrueFalseTotal
if (threshold > 0 && fails >= threshold) { 0 0 0
if (threshold > 0 && fails >= threshold) { 0 0 0
3403 0 (void)hv_stores(slot, "dead_until",
3404 newSVnv(ev_time() + cooldown));
3405 }
3406 } else {
3407 0 (void)hv_stores(slot, "fails", newSViv(0));
3408 0 (void)hv_stores(slot, "dead_until", newSViv(0));
3409 }
3410 }
« xs/proto_native_parse.c ↑ Summary xs/proto_http.c »