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