Valiant.pm untested

filter: Statementstmt 0.0% 0 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 2 Podpod n/a totaltotal 0.0% 0 / 10 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package DBIx::Class::Valiant;
2  
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.001001';
7 $VERSION = eval $VERSION;
8  
9 # Placeholder for now, not sure if there's going to be code here or not :)
10  
11 1;
12  
13 =head1 NAME
14  
15 DBIx::Class::Valiant - Glue Valiant validations into DBIx::Class
16  
17 =head1 SYNOPSIS
18  
19 You need to add the components L<DBIx::Class::Valiant::Result> and L<DBIx::Class::Valiant::ResultSet>
20 to your result and result classes:
21  
22 package Example::Schema::Result::Person;
23  
24 use base 'DBIx::Class::Core';
25  
26 __PACKAGE__->load_components('Valiant::Result');
27  
28 package Example::Schema::ResultSet::Person;
29  
30 use base 'DBIx::Class::ResultSet';
31  
32 __PACKAGE__->load_components('Valiant::ResultSet');
33  
34 Alternatively (and likely easier if you wish to use this across your entire DBIC schema) you can set these
35 on your base result / resultset classes:
36  
37 package Example::Schema::Result;
38  
39 use strict;
40 use warnings;
41 use base 'DBIx::Class';
42  
43 __PACKAGE__->load_components(qw/
44 Valiant::Result
45 Core
46 /);
47  
48 package Example::Schema::ResultSet;
49  
50 use strict;
51 use warnings;
52 use base 'DBIx::Class::ResultSet';
53  
54 __PACKAGE__->load_components(qw/
55 Valiant::ResultSet
56 /);
57  
58 There's an example schema under C<t/lib/Schema> in the distribution (exercised by the
59 test suite in C<t/dbic>) to give you some hints.
60  
61 B<NOTE> If you are using more than one component, you need to add these first. Hopefully
62 that is a restriction we can figure out how to remove (patches welcomed).
63  
64 =head1 DESCRIPTION
65  
66 B<NOTE> This is beta software: it works as in 'it passed my existing tests'. Feel free
67 to use it if you are willing to get into the code, review / submit test cases, etc.
68 Support for validations at the single result level is pretty firm and I can't imagine
69 significant changes. Support for validating nested results (results that have has_many
70 or similar relationships) is likely to evolve as bugs are reported, and I will feel free
71 to break backward compatibility on the nested support until it seems stable.
72  
73 B<NOTE> Update: I consider this code to be beta stage and will now only break things if
74 its absolutely necessary to fix critical bugs or security matters.
75  
76 This provides a base result component and resultset component that when added to your
77 classes glue L<Valiant> into L<DBIx::Class>. You can set filters and validations on
78 your result source classes very similarily to how you would use L<Valiant> with L<Moo>
79 or L<Moose>. Validations then run when you try to persist a change to the database; if
80 validations fail then we will not complete persisting the change (typically via insert
81 or update SQL). Errors can be read via the C<errors> method just as on L<Moo> or L<Moose>
82 based validations.
83  
84 Additionally we support nested creates and updates; validations follow any nested changes
85 and errors can be aggregated. Errors at any point in the nested create or update (or as
86 is often the cases a mixed situation) will cancel the entire changeset (issuing a rollback
87 if necessary). Please note that as stated above nested support is still considered a beta
88 feature and bug reports / test cases (or patches) welcomed.
89  
90 Documentation in this package only covers how L<Valiant> is glued into your result sources
91 and any local differences in behavior. If you need a comprehensive overview of how
92 L<Valiant> works you should refer to that package. Additionally if you are looking for how
93 to generate HTML forms you should refer to L<Valiant::HTML::Util::Form>,
94 L<Valiant::HTML::Util::FormTags> and L<Valiant::HTML::FormBuilder>.
95  
96 =head2 Adding validations and filters
97  
98 Assuming a base result and resultset as described above, you can add L<Valiant> style
99 validations to the result source columns or on the object as a whole. The helpers described
100 in the L<Valiant> core documentations all work the same on your DBIC result source fields; the
101 main difference is that you must call these helpers as class/package methods:
102  
103 package Example::Schema::Result::Profile;
104  
105 use warnings;
106 use strict;
107 use base 'Example::Schema::Result';
108  
109 __PACKAGE__->table("profile");
110 __PACKAGE__->add_columns(
111 id => { data_type => 'bigint', is_nullable => 0, is_auto_increment => 1 },
112 person_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
113 state_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
114 address => { data_type => 'varchar', is_nullable => 0, size => 48 },
115 city => { data_type => 'varchar', is_nullable => 0, size => 32 },
116 zip => { data_type => 'varchar', is_nullable => 0, size => 5 },
117 birthday => { data_type => 'date', is_nullable => 1, datetime_undef_if_invalid => 1 },
118 phone_number => { data_type => 'varchar', is_nullable => 1, size => 32 },
119 );
120  
121 __PACKAGE__->set_primary_key("id");
122 __PACKAGE__->add_unique_constraint(['id','person_id']);
123  
124 __PACKAGE__->belongs_to(
125 state =>
126 'Example::Schema::Result::State',
127 { 'foreign.id' => 'self.state_id' }
128 );
129  
130 __PACKAGE__->belongs_to(
131 person =>
132 'Example::Schema::Result::Person',
133 { 'foreign.id' => 'self.person_id' }
134 );
135  
136 __PACKAGE__->validates(address => (presence=>1, length=>[2,48]));
137 __PACKAGE__->validates(city => (presence=>1, length=>[2,32]));
138 __PACKAGE__->validates(zip => (presence=>1, format=>'zip'));
139 __PACKAGE__->validates(phone_number => (presence=>1, length=>[10,32]));
140 __PACKAGE__->validates(state_id => (presence=>1));
141 __PACKAGE__->validates(birthday => (
142 date => {
143 max => sub { pop->now->subtract(days=>1) }, # can't be born yesterday
144 min => sub { pop->years_ago(30) }, # Don't trust anyone over 30
145 }
146 )
147 );
148  
149 1;
150  
151 Besides the requirement of calling C<validates>, C<validates_with> and C<filters> as class
152 methods there are a few other changes from the core L<Valiant> behavior.
153  
154 First C<validate> is automatically run for you when you attempt to C<create> or C<insert>
155 a record (or use related methods such as C<find_or_create>). If validation fails the database
156 operation will not occur but you will get a DBIC result with the records in cache along
157 with any validation results. This makes it easier to round trip things like form validation
158 since you can use the database result in your form response logic. For example:
159  
160 my $person = $schema->resultset('Person')->first;
161 my $state = $schema->resultset('State')->first;
162  
163 my $profile = $person->create_related('profile', +{
164 zip => "78621",
165 city => 'E',
166 address => '15604 Harry Lind Road',
167 birthday => DateTime->now->subtract(years=>55)->ymd,
168 phone_number => '2123879509',
169 state_id => $state->id,
170 });
171  
172 $profile->invalid; # TRUE, so the record was NOT created!
173  
174 But the record does have the attempted values cached as expected, even if its not in
175 the storage DB:
176  
177 print $profile->zip; # 78621
178 print $profile->city; # E
179  
180 And you can query for errors:
181
182 Dumper $person_profile->errors->to_hash(full_messages=>1);
183  
184 Returns:
185  
186 city => [
187 "city is too short (minimum is 2 characters)",
188 ],
189 birthday => [
190 "Birthday chosen date can't be before @{[ DateTime->now->subtract(years=>30)->ymd ]}",
191 ],
192  
193 It might seem strange to have a C<$profile> object with invalid data, but it greatly simplifies
194 your UI layer since you can use the same model for both valid and invalid data (and to query for
195 errors.
196  
197 =head2 validation context
198  
199 By default when creating a new record we add a validation context 'create', and for updating we
200 add a 'update' context. This way you can specify different validation rules for create and update
201 very easily. If you want to add a custom context youc an do so with the C<context> method which
202 is part of your result API.
203  
204 $person->context('registration')->update(\%records);
205  
206 Or you can add the context directly to your C<update> or C<create> call:
207  
208 $person->update(+{ __context=>'registration', %records});
209  
210 See the core L<Valiant> documentation for more on validation contexts.
211  
212 =head2 Combining validations into column definitions
213  
214 If you are hand writing your table source definitions you can add validations directly
215 onto a column definition. You might prefer this if you think it looks neater and adds
216 fewer lines of code.
217  
218 package Example::Schema::Result::CreditCard;
219  
220 use strict;
221 use warnings;
222  
223 use base 'Example::Schema::Result';
224  
225 __PACKAGE__->table("credit_card");
226 __PACKAGE__->load_components(qw/Valiant::Result/);
227 __PACKAGE__->set_primary_key("id");
228  
229 __PACKAGE__->add_columns(
230 id => { data_type => 'integer', is_nullable => 0, is_auto_increment => 1 },
231 person_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
232 card_number => {
233 data_type => 'varchar',
234 is_nullable => 0,
235 size => '20',
236 validates => [ presence=>1, length=>[13,20], with=>'looks_like_a_cc' ],
237 filters => [trim => 1],
238 },
239 expiration => {
240 data_type => 'date',
241 is_nullable => 0,
242 validates => [ presence=>1, with=>'looks_like_a_datetime', with=>'is_future' ],
243 },
244 );
245  
246 As in the example above you can define filters this way as well.
247  
248 =head2 DBIC Candy
249  
250 This has L<DBIx::Class::Candy> integration if you use that and prefer it:
251  
252 package Schema::Create::Result::Person;
253  
254 use DBIx::Class::Candy -base => 'Schema::Result';
255  
256 table "person";
257  
258 column id => { data_type => 'bigint', is_nullable => 0, is_auto_increment => 1 };
259 column username => { data_type => 'varchar', is_nullable => 0, size => 48 };
260 column first_name => { data_type => 'varchar', is_nullable => 0, size => 24 };
261 column last_name => { data_type => 'varchar', is_nullable => 0, size => 48 };
262 column password => { data_type => 'varchar', is_nullable => 0, size => 64 };
263  
264 primary_key "id";
265 unique_constraint ['username'];
266  
267 might_have profile => (
268 'Schema::Create::Result::Profile',
269 { 'foreign.person_id' => 'self.id' }
270 );
271  
272 filters username => (trim => 1);
273  
274 validates profile => (result=>+{validations=>1} );
275 validates username => (presence=>1, length=>[3,24], format=>'alpha_numeric', unique=>1);
276 validates first_name => (presence=>1, length=>[2,24]);
277 validates last_name => (presence=>1, length=>[2,48]);
278 validates password => (presence=>1, length=>[8,24]);
279 validates password => (confirmation => { on=>'create' } );
280 validates password => (confirmation => {
281 on => 'update',
282 if => 'is_column_changed', # This method defined by DBIx::Class::Row
283 });
284
285 accept_nested_for 'profile', {update_only=>1};
286  
287 1;
288  
289 When using this with L<DBIx::Class::Candy> the following class methods are available as exports:
290  
291 'filters', 'validates', 'filters_with', 'validates_with', 'accept_nested_for',
292 'auto_validation'
293  
294 =head1 EXAMPLE
295  
296 Assuming you have a base result class C<Example::Schema::Result> which uses the L<DBIx::Class::Valiant::Result>
297 component and a default resultset class which uses the L<Example::Schema::ResultSet> component:
298  
299 package Example::Schema::Result::Person;
300  
301 use warnings;
302 use strict;
303 use base 'Example::Schema::Result';
304  
305 __PACKAGE__->table("person");
306  
307 __PACKAGE__->add_columns(
308 id => { data_type => 'bigint', is_nullable => 0, is_auto_increment => 1 },
309 username => { data_type => 'varchar', is_nullable => 0, size => 48 },
310 first_name => { data_type => 'varchar', is_nullable => 0, size => 24 },
311 last_name => { data_type => 'varchar', is_nullable => 0, size => 48 },
312 );
313  
314 __PACKAGE__->validates(username => presence=>1, length=>[3,24], format=>'alpha_numeric', unique=>1);
315 __PACKAGE__->validates(first_name => (presence=>1, length=>[2,24]));
316 __PACKAGE__->validates(last_name => (presence=>1, length=>[2,48]));
317  
318 We now have L<Valiant> validations wrapping any method which mutates the database.
319  
320 my $person = $schema->resultset('Person')
321 ->create({
322 username => 'jjn', # for this example we'll say this username is taken in the DB
323 first_name => 'j', # too short
324 last_name => 'n', # too short
325 });
326  
327 In this case since we tried to create a record that is not valid the create will be aborted (not saved
328 to the DB and an object will be returned with errors:
329  
330 $person->invalid; # true;
331 $person->errors->size; # 3
332 person->errors->full_messages_for('username'); # ['Username is not unique']
333 person->errors->full_messages_for('first_name'); # ['First Name is too short']
334 person->errors->full_messages_for('last_name'); # ['Last Name is too short']
335  
336 The object will have the invalid values properly populated:
337  
338 $person->get_column('username'); # jjn
339  
340 You might find this useful for building error message responses in for example html forms or other types
341 or error responses.
342  
343 See the test suite in C<t/dbic> for worked examples of this.
344  
345 =head1 NESTED VALIDATIONS
346  
347 With a properly setup schema you can propagate creates/updates down into related result sources. Because
348 this can be a security issue you must configure your result source classes to allow it. For example, let's
349 say you have a C<Person> result source that has a C<Profile> (via 'might_have'), some C<Roles> via a
350 'has_many' bridge result class called C<PersonRoles> and finally a list of C<CreditCards> directly via
351 a 'has_many'. For the purposes of this example assume the base result and result set classes are setup
352 to consume the Valiant components as in the L</SYNOPSIS>.
353  
354 package Example::Schema::Result::Person;
355  
356 use warnings;
357 use strict;
358 use base 'Example::Schema::Result';
359  
360 # This first part is just the normal DBIC class data you assign to a result class
361 # in order to read and update tables as well as follow relationships:
362  
363 __PACKAGE__->table("person");
364  
365 __PACKAGE__->add_columns(
366 id => { data_type => 'bigint', is_nullable => 0, is_auto_increment => 1 },
367 username => { data_type => 'varchar', is_nullable => 0, size => 48 },
368 first_name => { data_type => 'varchar', is_nullable => 0, size => 24 },
369 last_name => { data_type => 'varchar', is_nullable => 0, size => 48 },
370 );
371  
372 __PACKAGE__->set_primary_key("id");
373 __PACKAGE__->add_unique_constraint(['username']);
374  
375 __PACKAGE__->might_have(
376 profile =>
377 'Example::Schema::Result::Profile',
378 { 'foreign.person_id' => 'self.id' }
379 );
380  
381 __PACKAGE__->has_many(
382 credit_cards =>
383 'Example::Schema::Result::CreditCard',
384 { 'foreign.person_id' => 'self.id' }
385 );
386  
387 __PACKAGE__->has_many(
388 person_roles =>
389 'Example::Schema::Result::PersonRole',
390 { 'foreign.person_id' => 'self.id' }
391 );
392  
393 __PACKAGE__->many_to_many('roles' => 'person_roles', 'role');
394  
395 # In this next part we annotate this class with additional meta data which Valiant will
396 # use to performance validations as well as allow you to follow relationships at create / update
397 # time:
398  
399 __PACKAGE__->validates(username => presence=>1, length=>[3,24], format=>'alpha_numeric', unique=>1);
400 __PACKAGE__->validates(first_name => (presence=>1, length=>[2,24]));
401 __PACKAGE__->validates(last_name => (presence=>1, length=>[2,48]));
402  
403 __PACKAGE__->validates(credit_cards => (set_size=>+{min=>2, max=>4}));
404 __PACKAGE__->accept_nested_for('credit_cards', +{allow_destroy=>1});
405  
406 __PACKAGE__->validates(person_roles => (set_size=>+{min=>1}));
407 __PACKAGE__->accept_nested_for('person_roles', {allow_destroy=>1});
408  
409 __PACKAGE__->validates(profile => (presence=>1));
410 __PACKAGE__->accept_nested_for('profile');
411  
412 So in brief we add some simple validations on fields in the C<Person> result class to validate
413 things like the length of text fields and we added things like requiring a person to have at least
414 one C<person_role> and two C<credit_cards>; we also specify that we want to follow those nested
415 relationships and aggregate errors into the C<Persons> result class (we'll see the validation
416 definitions for those classes below). Also we allow that we can delete C<credit_cards> as well
417 as C<person_roles>.
418  
419 Here's how we setup these related classes. Please note that we in general avoid using the 'many_to_many'
420 pseudo relationship. DBIC does not define enough internal meta data for m2m to work reliably and we had
421 other issues around caching. As a result I recommend avoiding m2m for using with L<Valiant> although it
422 seems to work ok for simple use cases. Test cases and patches to improve this are welcomed (you can see
423 there's quite a few m2m test cases already but I was never able to get the type of consistency I felt
424 needed for a data storage layer where integrity is most important).
425  
426 package Example::Schema::Result::Profile;
427  
428 use warnings;
429 use strict;
430 use base 'Example::Schema::Result';
431  
432 __PACKAGE__->table("profile");
433 __PACKAGE__->load_components(qw/Valiant::Result/);
434  
435 __PACKAGE__->add_columns(
436 id => { data_type => 'bigint', is_nullable => 0, is_auto_increment => 1 },
437 person_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
438 address => { data_type => 'varchar', is_nullable => 0, size => 48 },
439 city => { data_type => 'varchar', is_nullable => 0, size => 32 },
440 zip => { data_type => 'varchar', is_nullable => 0, size => 5 },
441 birthday => { data_type => 'date', is_nullable => 1 },
442 phone_number => { data_type => 'varchar', is_nullable => 1, size => 32 },
443 );
444  
445 __PACKAGE__->validates(address => (presence=>1, length=>[2,48]));
446 __PACKAGE__->validates(city => (presence=>1, length=>[2,32]));
447 __PACKAGE__->validates(zip => (presence=>1, format=>'zip'));
448 __PACKAGE__->validates(phone_number => (presence=>1, length=>[10,32]));
449 __PACKAGE__->validates(birthday => (
450 date => {
451 max => sub { pop->now->subtract(days=>1) }, # Can't be born yesterday :)
452 min => sub { pop->years_ago(30) }, # Don't trust anyone over 30
453 }
454 )
455 );
456  
457 __PACKAGE__->set_primary_key("id");
458 __PACKAGE__->add_unique_constraint(['id','person_id']);
459  
460 __PACKAGE__->belongs_to(
461 person =>
462 'Example::Schema::Result::Person',
463 { 'foreign.id' => 'self.person_id' }
464 );
465  
466 package Example::Schema::Result::CreditCard;
467  
468 use strict;
469 use warnings;
470 use DateTime;
471 use DateTime::Format::Strptime;
472  
473 use base 'Example::Schema::Result';
474  
475 __PACKAGE__->table("credit_card");
476 __PACKAGE__->load_components(qw/Valiant::Result/);
477  
478 __PACKAGE__->add_columns(
479 id => { data_type => 'integer', is_nullable => 0, is_auto_increment => 1 },
480 person_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
481 card_number => { data_type => 'varchar', is_nullable => 0, size => '20' },
482 expiration => { data_type => 'date', is_nullable => 0 },
483 );
484  
485 __PACKAGE__->set_primary_key("id");
486  
487 __PACKAGE__->validates(card_number => (presence=>1, length=>[13,20], with=>'looks_like_a_cc' ));
488 __PACKAGE__->validates(expiration => (presence=>1, with=>'looks_like_a_datetime', with=>'is_future' ));
489  
490 __PACKAGE__->belongs_to(
491 person =>
492 'Example::Schema::Result::Person',
493 { 'foreign.id' => 'self.person_id' }
494 );
495  
496 sub looks_like_a_cc {
497 my ($self, $attribute_name, $value) = @_;
498 return if $value =~/^\d{13,20}$/;
499 $self->errors->add($attribute_name, 'does not look like a credit card');
500 }
501  
502 my $strp = DateTime::Format::Strptime->new(pattern => '%Y-%m-%d');
503  
504 sub looks_like_a_datetime {
505 my ($self, $attribute_name, $value) = @_;
506 my $dt = $strp->parse_datetime($value);
507 $self->errors->add($attribute_name, 'does not look like a datetime value') unless $dt;
508 }
509  
510 sub is_future {
511 my ($self, $attribute_name, $value) = @_;
512 my $dt = $strp->parse_datetime($value);
513 return unless $dt; # Skip this validation if the user didn't give us a date time
514 # format (that's caught by ->looks_like_a_datetime).
515 $self->errors->add($attribute_name, 'must be in the future') unless $dt > DateTime->now;
516 }
517  
518 package Example::Schema::Result::PersonRole;
519  
520 use strict;
521 use warnings;
522 use base 'Example::Schema::Result';
523  
524 __PACKAGE__->table("person_role");
525 __PACKAGE__->load_components(qw/Valiant::Result/);
526  
527 __PACKAGE__->add_columns(
528 person_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
529 role_id => { data_type => 'integer', is_nullable => 0, is_foreign_key => 1 },
530 );
531  
532 __PACKAGE__->set_primary_key("person_id", "role_id");
533  
534 __PACKAGE__->belongs_to(
535 person =>
536 'Example::Schema::Result::Person',
537 { 'foreign.id' => 'self.person_id' }
538 );
539  
540 __PACKAGE__->belongs_to(
541 role =>
542 'Example::Schema::Result::Role',
543 { 'foreign.id' => 'self.role_id' }
544 );
545  
546 package Example::Schema::Result::Role;
547  
548 use strict;
549 use warnings;
550  
551 use base 'Example::Schema::Result';
552  
553 __PACKAGE__->table("role");
554 __PACKAGE__->load_components(qw/Valiant::Result/);
555  
556 __PACKAGE__->add_columns(
557 id => { data_type => 'integer', is_nullable => 0, is_auto_increment => 1 },
558 label => { data_type => 'varchar', is_nullable => 0, size => '24' },
559 );
560  
561 __PACKAGE__->set_primary_key("id");
562 __PACKAGE__->add_unique_constraint(['label']);
563  
564 __PACKAGE__->has_many(
565 person_roles =>
566 'Example::Schema::Result::PersonRole',
567 { 'foreign.role_id' => 'self.id' }
568 );
569  
570 With this setup you could deeply validate / create a Person and its permitted relationships:
571  
572 my $person = $schema
573 ->resultset('Person')
574 ->create({
575 first_name => "john",
576 last_name => "nap",
577 username => "jjn1",
578 profile => {
579 address => "15604 Harry Lind Road",
580 birthday => "2000-02-13",
581 city => "Elgin",
582 phone_number => "16467081837",
583 zip => '10000'
584 },
585 person_roles => [
586 { role_id => 1 },
587 { role_id => 2 },
588 { role_id => 4 },
589 ],
590 credit_cards => [
591 {
592 card_number => "3423423423423423",
593 expiration => "2222-02-02",
594 },
595 {
596 card_number => "1111222233334444",
597 expiration => "2333-02-02",
598 },
599 ],
600 });
601  
602 If the proposed data fails validation then you won't create any records, but the errors can
603 be viewed via the C<errors> collection.
604  
605 For doing validation on nested updates you need to do a bit more work to make sure you caches
606 are properly populated from the database. You need to use 'prefetch' to locally cache all the
607 results you are trying to validate:
608  
609 my $person = Schema->resultset('Person')->find(
610 { 'me.id'=>$pid },
611 { prefetch => ['profile', 'credit_cards', {person_roles => 'role' }] }
612 );
613 $person->build_related_if_empty('profile');
614  
615 Then you can do an update:
616  
617 $person->update({
618 username => 'jjn2',
619 profile => {
620 city => 'NYC'
621 },
622 });
623  
624 As before if there's a valiation issue the update won't happen.
625  
626 B<NOTE> Recursion warning! You cannot currently C<accept_nested_for> for a relationship
627 whose target result source is setting C<accept_nested_for> into yourself. This is probably
628 fixable, patches and use cases welcomed!
629  
630 =head2 Deleting
631  
632 If a nested relationship permits deleting (via the 'allow_destroy' flag) you can mark a row for deletion
633 directly using the C<_delete> flag:
634  
635 $person->update({
636 username => 'jjn2',
637 person_roles => [
638 { role_id => 1 },
639 { role_id => 2, _delete => 1 },
640 { role_id => 4, _delete => 1 },
641 ],
642 });
643  
644 This works for C<has_many> relationships as shown above, and also for single relationships
645 (C<might_have> / C<belongs_to>) declared with C<accept_nested_for>:
646  
647 $artist->update({ bio => { id => $bio_id, _delete => 1 } });
648  
649 B<Replace-set updates>: By default, rows omitted from a C<has_many> update are left alone -- matching
650 Rails' C<accepts_nested_attributes_for>, the only way to delete a related row is the explicit
651 C<_delete> flag shown above. If you want the old "replace the whole set" behavior, where any
652 existing related row not mentioned in the update gets deleted, set the C<delete_omitted>
653 C<accept_nested_for> option to true. This fires whenever the relationship key is present in the
654 update on an already-in-storage parent (whether or not the relationship was prefetched), and
655 passing C<< [] >> deletes the entire collection. See
656 L<DBIx::Class::Valiant::Result/delete_omitted> for details, including its coderef form.
657  
658 The full set of C<accept_nested_for> options (C<allow_destroy>, C<delete_omitted>,
659 C<reject_if>, C<limit>, C<update_only>, C<find_with_uniques>) is documented in
660 L<DBIx::Class::Valiant::Result>.
661  
662 This example is far from complete, for now see the many worked examples in the C<t/dbic>
663 tests directory. In particular this example doesn't really cover all the
664 ins and outs of deleting. An overall tutorial is in the works but example submission or questions
665 (that could eventually lead to a FAQ) are very welcomed.
666  
667 =head1 WARNINGS & GOTCHAs
668  
669 You must be careful with how you expose a deeply nested interface. If you simply pass fields
670 from a web form you are potentially opening yourself to SQL injection and similar types of attacks. I
671 recommend being very careful to sanitize incoming parameters, especially any related keys.
672  
673 B<NOTE>Be careful when reusing a result that has deeply nested values after you create or update.
674 In order to keep data consistent, DBIC will blow away any prefetch caches after create or update.
675 So that means if you try to reuse a result you may encounter errors that cause following
676 creates or inserts to fails, especially if you have constraints on the related data, such as SetSize.
677  
678 =head2 Many to Many
679  
680 Many to Many type relationships are supported to the best of my ability but since these types of
681 fake relationships have lots of known issues you are more likely to run into edge cases. In
682 particular its a bad idea to have validations on both a m2m relations and also on the one to many
683 relation that it bridges. This is likely to result in false positive validation errors due to the
684 way the resultset cache works (and doesn't work) for m2m.
685  
686 Happy to take patches for improvements to anyone that feels strongly about it. FWIW the core DBIC
687 development team recommends staying away fron using the many to many code.
688  
689 =head1 SEE ALSO
690  
691 L<Valiant>, L<DBIx::Class::Valiant::Result>, L<DBIx::Class::Valiant::ResultSet>, L<DBIx::Class>.
692  
693 L<DBIO::Valiant> is the port of this distribution to DBIO, the asynchronous fork of
694 L<DBIx::Class>.
695  
696 =head1 AUTHOR
697  
698 John Napiorkowski L<email:jjnapiork@cpan.org>
699  
700 =head1 COPYRIGHT & LICENSE
701  
702 Copyright 2026, John Napiorkowski L<email:jjnapiork@cpan.org>
703  
704 This library is free software; you can redistribute it and/or modify it under
705 the same terms as Perl itself.
706  
707 =cut