ClickHouse.xs

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