MySQL/Storage/Async.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Shortcut/mysql.pm ↑ Summary
1 package DBIO::MySQL::Storage::Async;
2 # ABSTRACT: future_io async MySQL transport over the DBD driver's native async binding
3  
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use base 'DBIO::Async::Storage';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 use Carp 'croak';
9 use Scalar::Util ();
10 use DBI;
11 use Future::IO;
12 use DBIO::MySQL::SQLMaker;
13 use namespace::clean;
14  
15  
16 # --- SQL shaping seams ------------------------------------------------------
17  
18  
19 sub sql_maker_class { 'DBIO::MySQL::SQLMaker' }
20  
21  
22 sub _sql_maker_args {
23 return (
24 quote_char => '`',
25 name_sep => '.',
26 );
27 }
28  
29  
30 sub _transform_sql { $_[1] }
31  
32  
33 sub _post_insert_sql { '' }
34  
35 # --- INSERT returned-columns (last_insert_id, no RETURNING) ------------------
36  
37  
38 sub _insert_returned_columns {
39 my ($self, $source, $to_insert, $affected) = @_;
40  
41 my %returned = %{ $to_insert || {} };
42  
43 my $id = $self->{_last_insert_id};
44 return \%returned unless defined $id && $id;
45  
46 my $col = $self->_auto_increment_column($source, $to_insert);
47 return \%returned unless defined $col;
48  
49 $returned{$col} = $id;
50 return \%returned;
51 }
52  
53 # Find the column the auto-increment id belongs in, matching the sync
54 # DBIO::Storage::DBI heuristic:
55 # - the first column flagged is_auto_increment, OR
56 # - the first PK column that was not supplied in $to_insert (no
57 # is_auto_increment flag on the schema, but MySQL still hands back an id
58 # because the PK is auto_increment server-side).
59 # Returns undef when neither applies (e.g. a table with no PK), leaving the
60 # hashref as the supplied insert data only.
61 sub _auto_increment_column {
62 my ($self, $source, $to_insert) = @_;
63 return unless Scalar::Util::blessed($source) && $source->can('columns');
64  
65 my $col_infos = eval { $source->columns_info } || {};
66 my @pks = $source->can('primary_columns') ? $source->primary_columns : ();
67 my %is_pk = map { $_ => 1 } @pks;
68  
69 my $first_autoinc;
70 my $first_pk_unsupplied;
71 for my $col ($source->columns) {
72 if (!defined $first_autoinc
73 && ($col_infos->{$col}{is_auto_increment} // 0)) {
74 $first_autoinc = $col;
75 }
76 if ($is_pk{$col}
77 && !defined $first_pk_unsupplied
78 && !exists $to_insert->{$col}) {
79 $first_pk_unsupplied = $col;
80 }
81 }
82  
83 return $first_autoinc if defined $first_autoinc;
84 return $first_pk_unsupplied;
85 }
86  
87  
88 sub last_insert_id { $_[0]->{_last_insert_id} }
89  
90 # --- Connect-info seam ------------------------------------------------------
91  
92  
93 sub _normalize_conninfo {
94 my ($self, $info) = @_;
95  
96 # DBI-form: [ 'dbi:mysql:...', $user, $pass, \%attrs ] -> our conninfo shape.
97 if (ref $info eq 'ARRAY'
98 && defined $info->[0] && !ref $info->[0] && $info->[0] =~ /^dbi:/i) {
99 my ($dsn, $user, $pass, $attrs) = @$info;
100 $attrs = {} unless ref $attrs eq 'HASH';
101 my %dbd_attrs = %$attrs;
102 # DBIO-private connect attributes (async, ignore_version, SQLMaker options) are
103 # already stripped centrally by core DBIO::Storage::Async::connect_info before
104 # this seam runs (core #66), so they never reach %dbd_attrs here.
105 my %conninfo = (
106 dsn => $dsn,
107 user => $user,
108 password => $pass,
109 attrs => \%dbd_attrs,
110 );
111 $conninfo{pool_size} = delete $conninfo{attrs}{pool_size}
112 if defined $conninfo{attrs}{pool_size};
113 return [ \%conninfo, {} ];
114 }
115  
116 # Broker arrayref [ $broker ], or an already-normalised [ \%conninfo, \%opts ]
117 # pair -- leave for the inherited broker detection / normalisation.
118 return $info;
119 }
120  
121 # --- Pool connection lifecycle ----------------------------------------------
122  
123  
124 sub _create_pool_connection {
125 my ($self, $conninfo) = @_;
126  
127 croak 'MySQL async conninfo must be a hashref with a dsn'
128 unless ref $conninfo eq 'HASH' && defined $conninfo->{dsn};
129  
130 my $dbh = DBI->connect(
131 $conninfo->{dsn},
132 $conninfo->{user},
133 $conninfo->{password},
134 {
135 %{ $conninfo->{attrs} || {} },
136 AutoCommit => 1,
137 RaiseError => 1,
138 PrintError => 0,
139 },
140 ) or croak "DBI connect failed: $DBI::errstr";
141  
142 return { dbh => $dbh };
143 }
144  
145  
146 sub _shutdown_pool_connection {
147 my ($self, $conn) = @_;
148 my $dbh = $conn->{dbh} or return;
149 $dbh->disconnect if $dbh->{Active};
150 }
151  
152 # --- DBD-specific async primitives ------------------------------------------
153 # These five one-liners are the ONLY places the DBD driver's async binding is
154 # named. This class carries the DBD::mysql binding; the convention subclass
155 # DBIO::MySQL::Storage::MariaDB::Async overrides them with DBD::MariaDB's
156 # mariadb_* equivalents. Everything else in the transport (submit / collect
157 # control flow, pooling, txn) is DBD-agnostic and shared.
158  
159  
160 sub _async_prepare_attrs { { async => 1 } }
161  
162  
163 sub _conn_socket_fd { $_[1]->mysql_fd }
164  
165  
166 sub _async_ready { $_[1]->mysql_async_ready }
167  
168  
169 sub _async_result { $_[1]->mysql_async_result }
170  
171  
172 sub _async_insertid { $_[1]->{mysql_insertid} }
173  
174 # --- Readiness / socket seams -----------------------------------------------
175  
176  
177 sub _conn_ready {
178 my ($self, $conn) = @_;
179 return $conn->{dbh} && $conn->{dbh}{Active} ? 1 : 0;
180 }
181  
182  
183 sub _conn_fileno {
184 my ($self, $conn) = @_;
185 return $self->_conn_socket_fd($conn->{dbh});
186 }
187  
188 # --- Query submit / collect -------------------------------------------------
189  
190  
191 sub _submit_query {
192 my ($self, $conn, $sql, $bind) = @_;
193 $bind //= [];
194  
195 my $dbh = $conn->{dbh};
196  
197 delete $conn->{sth};
198  
199 my $sth = $dbh->prepare($sql, $self->_async_prepare_attrs);
200 $sth->execute(@$bind);
201 $conn->{sth} = $sth;
202  
203 return;
204 }
205  
206  
207 sub _collect_result {
208 my ($self, $conn, $sql, $bind) = @_;
209  
210 my $sth = $conn->{sth};
211  
212 # The result may not have fully arrived on the first readable event.
213 # _async_ready reports whether _async_result will not block; if not, wait for
214 # more and re-check rather than blocking.
215 unless ($self->_async_ready($sth)) {
216 return $self->_await_readable($conn)->then(sub {
217 return $self->_collect_result($conn, $sql, $bind);
218 });
219 }
220  
221 my $rv = $self->_async_result($sth); # finalise; dies (RaiseError) on error
222  
223 # Capture the auto-increment id for insert_async's returned-columns hashref
224 # (MySQL has no RETURNING). The insertid is per-sth and 0 for non-INSERTs, so
225 # guarding on truthiness keeps a following statement from clobbering it.
226 if (my $iid = $self->_async_insertid($sth)) {
227 $self->{_last_insert_id} = $iid;
228 }
229  
230 if (($sth->{NUM_OF_FIELDS} || 0) > 0) {
231 my $rows = $sth->fetchall_arrayref;
232 return $self->future_class->done(@$rows);
233 }
234  
235 return $self->future_class->done($rv);
236 }
237  
238 # --- Transaction context seams ----------------------------------------------
239  
240  
241 sub _txn_context_class { 'DBIO::Async::TransactionContext' }
242  
243  
244 sub _txn_conn_accessor { 'txn_conn' }
245  
246 1;
247  
248 __END__
249  
250 =pod
251  
252 =encoding UTF-8
253  
254 =head1 NAME
255  
256 DBIO::MySQL::Storage::Async - future_io async MySQL transport over the DBD driver's native async binding
257  
258 =head1 VERSION
259  
260 version 0.900001
261  
262 =head1 DESCRIPTION
263  
264 The concrete C<future_io> transport adapter for MySQL / MariaDB (core ADR 0030 /
265 0031), the MySQL analogue of L<DBIO::PostgreSQL::Storage::Async>. It is resolved
266 B<by convention> off the sync driver storage: a connection opened with
267  
268 MyApp::Schema->connect($dsn, $user, $pass, { async => 'future_io' });
269  
270 on a L<DBIO::MySQL::Storage> instance derives C<ref($storage) . '::Async'> ==
271 C<DBIO::MySQL::Storage::Async>. No C<register_async_mode> call is needed; the
272 name itself is the registration.
273  
274 =head2 Storage extensions ride on top by composition
275  
276 Under the storage-layer composition model (core karr #70), a MySQL / MariaDB
277 driver extension is B<not> a C<storage_type> subclass and does B<not> ship a
278 shadow C<register_async_mode> / C<< ::Storage::Async >> of its own. It ships a
279 plain storage B<layer> registered with
280 C<< $schema->register_storage_layer('DBIO::MySQL::Ext::Storage') >> and, for
281 async behaviour, a sibling async mirror C<DBIO::MySQL::Ext::Storage::Async> (a
282 plain method package, B<not> a transport). When a layered schema connects
283 C<< { async => 'future_io' } >>, core resolves this transport by convention off
284 the B<composition base> (the driver, not the layers) and then
285 C<< DBIO::Storage::Composed->compose >>s each registered layer's async mirror
286 B<on top of> it. So this class stays the single per-driver future_io transport
287 BASE; extensions add behaviour above it via C3, exactly as their sync layers
288 ride the sync driver storage. MySQL ships no such extension today, but this
289 reference driver honours the mechanism (the offline structural proof is
290 F<t/56-storage-layer-composition.t>, the live one F<t/57-*-live.t>).
291  
292 =head2 One dist, two DBD drivers
293  
294 MySQL is served by two DBI drivers, and DBIO models them as two storage classes:
295 L<DBIO::MySQL::Storage> for a C<dbi:mysql:> DSN (L<DBD::mysql>) and
296 L<DBIO::MySQL::Storage::MariaDB> for a C<dbi:MariaDB:> DSN (L<DBD::MariaDB>). The
297 user picks the DBD by the DSN, so the async transport must drive I<that> DBD's
298 binding, not a fixed one -- the two are really two drivers that happen to ship
299 in one dist.
300  
301 Both bindings share the same shape -- a single async query per connection plus a
302 socket fd for the event loop -- but differ only in the attribute / method names:
303  
304 DBD::mysql async mysql_fd mysql_async_ready
305 mysql_async_result mysql_insertid
306 DBD::MariaDB mariadb_async mariadb_sockfd mariadb_async_ready
307 mariadb_async_result mariadb_insertid
308  
309 This class carries the B<DBD::mysql> binding and all the shared transport control
310 flow. Its convention subclass L<DBIO::MySQL::Storage::MariaDB::Async> (resolved
311 for a C<dbi:MariaDB:> connection) overrides B<only> the five DBD-specific
312 primitives below with their C<mariadb_*> equivalents. So whichever DBD the sync
313 connection used, the matching async binding is driven -- mirroring the sync
314 split, where L<DBIO::MySQL::Storage::MariaDB> reads C<mariadb_insertid> where
315 L<DBIO::MySQL::Storage> reads C<mysql_insertid>. Neither DBD is loaded at compile
316 time here; C<< DBI->connect >> pulls the one the DSN names.
317  
318 The Model-B orchestration -- the CRUD runner (L<DBIO::Storage::Async/_run_crud>
319 with its pooled / pinned runners), INSERT returned-columns mapping,
320 L<DBIO::Storage::Async/txn_do_async> bracketing, the pipeline scaffold, and the
321 sync C<< ->get >> fallbacks -- is inherited unchanged from
322 L<DBIO::Storage::Async>. The L<Future::IO> transport (query execution over the
323 socket-readable watcher, the L<Future> class and the L<DBIO::Async::Pool>) is
324 inherited from L<DBIO::Async::Storage>. This class fills B<only> the DB-specific
325 transport seams over the driver's asynchronous binding:
326  
327 =over 4
328  
329 =item * L</sql_maker_class> / L</_sql_maker_args> -- the MySQL SQLMaker
330  
331 =item * L</_transform_sql> -- identity (MySQL keeps C<?> placeholders)
332  
333 =item * L</_post_insert_sql> -- empty (MySQL has no C<RETURNING>)
334  
335 =item * L</_insert_returned_columns> -- assemble the returned-columns hashref
336 from the auto-increment id (there is no C<RETURNING>), the key divergence from
337 PostgreSQL
338  
339 =item * L</_normalize_conninfo> -- DBI-form connect info into the pool's shape
340  
341 =item * L</_create_pool_connection> / L</_shutdown_pool_connection> -- DBD handle
342 lifecycle
343  
344 =item * L</_conn_ready> / L</_conn_fileno> -- readiness + the socket fd for the
345 L<Future::IO> watcher
346  
347 =item * L</_submit_query> / L</_collect_result> -- send non-blocking, then gather
348 once the wire is readable
349  
350 =item * L</_async_prepare_attrs> / L</_conn_socket_fd> / L</_async_ready> /
351 L</_async_result> / L</_async_insertid> -- the five DBD-specific async primitives
352 the seams above call, overridden in the MariaDB subclass
353  
354 =item * L</_txn_context_class> / L</_txn_conn_accessor> -- the pinned-connection
355 transaction context
356  
357 =back
358  
359 A connection is represented as a small hashref C<< { dbh => $dbh, sth => $sth } >>:
360 the driver's database handle plus the statement handle of the in-flight async
361 query (there is at most one per connection at a time -- MySQL allows a single
362 async query per connection -- guaranteed by the pool / transaction pinning).
363  
364 =head2 Transport capabilities
365  
366 This transport inherits C<transport_capabilities> from
367 L<DBIO::Async::Storage>, which advertises exactly C<on_connect_replay> (the pool
368 replays the owning sync storage's C<on_connect_do> / C<on_connect_call> on every
369 freshly-spawned connection, core karr #68). It declares B<nothing extra>.
370  
371 MySQL and MariaDB have no C<LISTEN>/C<NOTIFY> and no C<COPY> (those are
372 PostgreSQL wire features), so unlike the PostgreSQL transport there is nothing
373 of that kind to carry here. Pipelining
374 (L<DBIO::Storage::Async/pipeline>) is B<not> implemented on this C<future_io>
375 transport either -- neither DBD driver's async binding exposes a batch/pipeline
376 mode -- so the inherited scaffold croaks if C<pipeline> is called. The native
377 C<ev> backend (L<DBIO::MySQL::EV::Storage>, dist C<dbio-mysql-ev>, over
378 C<EV::MariaDB>) is the transport that carries pipelining. An async storage layer
379 that declares C<required_transport_capabilities> for a feature this transport
380 does not advertise will therefore fail loud (core capability gate) when composed
381 over this C<future_io> transport, naming the missing capability -- never a silent
382 feature loss.
383  
384 =head1 METHODS
385  
386 =head2 sql_maker_class
387  
388 The L<DBIO::MySQL::SQLMaker> subclass used to generate SQL.
389  
390 =head2 _sql_maker_args
391  
392 MySQL SQLMaker construction args: backtick identifier quoting and C<.> name
393 separator. The MySQL C<LIMIT offset, rows> dialect is built into
394 L<DBIO::MySQL::SQLMaker/apply_limit>, so no C<limit_dialect> is passed. Matches
395 the sync driver and the C<ev> backend.
396  
397 =head2 _transform_sql
398  
399 Identity: MySQL uses standard C<?> placeholders, so the maker's output is sent to
400 the DBD driver unchanged (unlike PostgreSQL's C<?E<gt>$N> rewrite).
401  
402 =head2 _post_insert_sql
403  
404 Empty string: MySQL has no C<RETURNING> clause, so nothing is appended to an
405 INSERT. The returned-columns hashref is assembled from the auto-increment id
406 instead (see L</_insert_returned_columns>).
407  
408 =head2 _insert_returned_columns
409  
410 $hashref = $storage->_insert_returned_columns($source, \%to_insert, $affected);
411  
412 Assemble the returned-columns hashref (ADR 0031 §3) from the auto-increment id
413 MySQL generated for the INSERT. MySQL has no C<RETURNING>, so the inherited
414 runner hands this method the INSERT's affected-row count (C<$affected>, ignored
415 here); the id itself was captured on C<< $self->{_last_insert_id} >> by
416 L</_collect_result> from the per-statement insertid (L</_async_insertid>) at the
417 moment the INSERT finalised. The hashref is C<< { %$to_insert, $col => $id } >>,
418 where C<$col> is the source's first C<is_auto_increment> column (falling back to
419 the first PK column whose value was not supplied, matching the sync
420 L<DBIO::Storage::DBI/insert> heuristic). When no id was generated (an explicit PK
421 was supplied, or the table has no auto-increment) the supplied data is returned
422 untouched. Overrides the inherited RETURNING-row default.
423  
424 Genuinely-concurrent inserts on one storage instance (outside a transaction) are
425 not supported by this last_insert_id path -- issue them sequentially or inside a
426 C<txn_do_async>. This mirrors MySQL's own "one async query per connection"
427 limit; pipelining is not available on this backend.
428  
429 =head2 last_insert_id
430  
431 my $id = $storage->last_insert_id;
432  
433 The auto-increment value from the last INSERT this storage finalised, captured
434 from the driver's per-statement insertid (L</_async_insertid>). Valid after an
435 C<insert_async> / C<insert> succeeds; provided for legacy callers (scripts,
436 tests). The CRUD path uses L</_insert_returned_columns> instead.
437  
438 =head2 _normalize_conninfo
439  
440 my $info = $storage->_normalize_conninfo([ 'dbi:mysql:...', $user, $pass, \%attrs ]);
441  
442 Convert the sync storage's DBI-form connect info into the C<[ \%conninfo,
443 \%opts ]> pair the pool consumes, carrying the DSN / user / password / attrs
444 straight through for L</_create_pool_connection> to hand to C<< DBI->connect >>.
445 A C<pool_size> attribute, if present, is lifted into the conninfo hash (the
446 inherited normaliser strips it back out to size the pool). Broker-style or
447 already-normalised info is passed through untouched.
448  
449 =head2 _create_pool_connection
450  
451 my $conn = $storage->_create_pool_connection(\%conninfo);
452  
453 Open one DBD handle via C<< DBI->connect >> and wrap it as C<< { dbh => $dbh } >>.
454 C<AutoCommit> is on: the inherited orchestration drives transactions with
455 explicit C<BEGIN> / C<COMMIT> / C<ROLLBACK> on the pinned connection.
456  
457 =head2 _shutdown_pool_connection
458  
459 Disconnect the DBD handle held by C<$conn>.
460  
461 =head2 _async_prepare_attrs
462  
463 The prepare-time attributes that arm a non-blocking query: C<< { async => 1 } >>
464 for DBD::mysql. C<execute> then returns immediately.
465  
466 =head2 _conn_socket_fd
467  
468 my $fd = $storage->_conn_socket_fd($dbh);
469  
470 The connection socket file descriptor for the L<Future::IO> readable watcher --
471 C<< $dbh->mysql_fd >> for DBD::mysql (the MySQL analogue of DBD::Pg's
472 C<pg_socket>).
473  
474 =head2 _async_ready
475  
476 my $bool = $storage->_async_ready($sth);
477  
478 True once L</_async_result> will not block -- DBD::mysql C<mysql_async_ready>.
479  
480 =head2 _async_result
481  
482 my $rv = $storage->_async_result($sth);
483  
484 Finalise the in-flight async statement and return what C<execute> would have --
485 the affected-row count (DBD::mysql C<mysql_async_result>). Dies (RaiseError) on a
486 server-side error.
487  
488 =head2 _async_insertid
489  
490 my $id = $storage->_async_insertid($sth);
491  
492 The per-statement C<AUTO_INCREMENT> id generated by the finalised INSERT, read
493 from C<< $sth->{mysql_insertid} >> -- the per-sth form DBD::mysql recommends over
494 the shared-handle C<< $dbh->{mysql_insertid} >>. Zero / undef for non-INSERTs.
495  
496 =head2 _conn_ready
497  
498 True once the connection can accept queries. C<< DBI->connect >> is a blocking
499 connect, so a handed-out connection is ready immediately -- we only confirm the
500 handle is live.
501  
502 =head2 _conn_fileno
503  
504 The connection socket fd for the L<Future::IO> readable watcher, obtained from
505 the DBD-specific L</_conn_socket_fd> primitive. The transport base
506 (L<DBIO::Async::Storage/_await_readable>) dups this integer fd into a filehandle
507 for C<< Future::IO->poll >>.
508  
509 =head2 _submit_query
510  
511 $storage->_submit_query($conn, $sql, $bind);
512  
513 Send C<$sql> non-blocking via the DBD driver's async binding: prepare with
514 L</_async_prepare_attrs> and execute the bind values. C<execute> returns
515 immediately; the result is gathered later by L</_collect_result>. The statement
516 handle is stashed on C<$conn> so the collector can finalise and fetch it.
517  
518 The previous (already-collected) async statement handle is released B<before>
519 starting the new async query. MySQL allows a single async query per connection;
520 clearing the spent sth first means the new execute owns the connection's async
521 slot uncontested (mirrors the DBD::Pg adapter's fix).
522  
523 =head2 _collect_result
524  
525 my $future = $storage->_collect_result($conn, $sql, $bind);
526  
527 Called once the socket is readable. If the async result has not fully arrived
528 (L</_async_ready> is false) it waits for the socket again and re-checks -- so a
529 large result spanning several reads is handled correctly. Once ready it finalises
530 with L</_async_result> and resolves:
531  
532 =over 4
533  
534 =item * a query that produced a result set (SELECT) -> the list of raw row
535 arrayrefs, exactly the shape the sync cursor's C<< ->all >> yields (ADR 0031 §3);
536  
537 =item * a statement with no result set (INSERT / UPDATE / DELETE, BEGIN /
538 COMMIT / ...) -> the affected-row count from L</_async_result>.
539  
540 =back
541  
542 For an INSERT it also captures the per-statement insertid (L</_async_insertid>)
543 onto C<< $self->{_last_insert_id} >> so L</_insert_returned_columns> can fold the
544 auto-increment id into the returned-columns hashref (MySQL has no C<RETURNING>).
545 The id is captured only when non-zero, so a following non-INSERT statement does
546 not clobber a pending insert's id.
547  
548 The full row list is carried in an explicit C<< future_class->done(@rows) >> so
549 it survives the surrounding C<< ->then >> chain (a bare list return would
550 collapse to its last element).
551  
552 =head2 _txn_context_class
553  
554 The pinned-connection transaction context handed to a C<txn_do_async> coderef:
555 the C<future_io> L<DBIO::Async::TransactionContext>.
556  
557 =head2 _txn_conn_accessor
558  
559 The constructor key the pinned connection is passed under -- C<txn_conn>,
560 matching L<DBIO::Storage::Async::TransactionContext>.
561  
562 =head1 AUTHOR
563  
564 DBIO & DBIx::Class Authors
565  
566 =head1 COPYRIGHT AND LICENSE
567  
568 Copyright (C) 2026 DBIO Authors
569 Portions Copyright (C) 2005-2025 DBIx::Class Authors
570 Based on DBIx::Class, heavily modified.
571  
572 This is free software; you can redistribute it and/or modify it under
573 the same terms as the Perl 5 programming language system itself.
574  
575 =cut
« Shortcut/mysql.pm ↑ Summary