ClickHouse.xs

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