| 1 | package Data::Model::Mixin::FindOrCreate; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | use Carp (); | ||
| 6 | |||
| 7 | sub register_method { | ||
| 8 | +{ | ||
| 9 | find_or_create => \&find_or_create, | ||
| 10 | }; | ||
| 11 | } | ||
| 12 | |||
| 13 | sub find_or_create { | ||
| 14 | my($self, $model, $key, $columns) = @_; | ||
| 15 | my $row; | ||
| 16 | if (ref($key) eq 'HASH') { | ||
| 17 | # use on unique index | ||
| 18 | my($index, $value) = %{ $key }; | ||
| 19 | Carp::corak('index name is required') unless $index; | ||
| 20 | |||
| 21 | my $schema = $self->get_schema($model); | ||
| 22 | Carp::croak("'$index' is not unique index") unless $schema->unique->{$index}; | ||
| 23 | |||
| 24 | ($row) = $self->get($model, { index => { $index => $value } }); | ||
| 25 | return $row if $row; | ||
| 26 | $self->set( $model => $columns ); | ||
| 27 | } else { | ||
| 28 | # primary key | ||
| 29 | |||
| 30 | $row = $self->lookup( $model => $key ); | ||
| 31 | return $row if $row; | ||
| 32 | $self->set( $model => $key => $columns ); | ||
| 33 | } | ||
| 34 | |||
| 35 | } | ||
| 36 | |||
| 37 | 1; | ||
| 38 | |||
| 39 | =head1 NAME | ||
| 40 | |||
| 41 | Data::Model::Mixin::FindOrCreate - add find_or_create method | ||
| 42 | |||
| 43 | =head1 SYNOPSIS | ||
| 44 | |||
| 45 | use Data::Model::Mixin modules => ['FindOrCreate']; | ||
| 46 | |||
| 47 | $model->find_or_create( | ||
| 48 | tablename => key => { | ||
| 49 | field1 => 'value', | ||
| 50 | field2 => 'value', | ||
| 51 | } | ||
| 52 | ); | ||
| 53 | |||
| 54 | $model->find_or_create( | ||
| 55 | tablename => [qw/ key1 key2 /] => { | ||
| 56 | field1 => 'value', | ||
| 57 | field2 => 'value', | ||
| 58 | } | ||
| 59 | ); | ||
| 60 | |||
| 61 | # using unique index, but not use normal index | ||
| 62 | $model->find_or_create( | ||
| 63 | tablename => { unique_idx => 'key' } => { | ||
| 64 | field1 => 'value', | ||
| 65 | field2 => 'value', | ||
| 66 | } | ||
| 67 | ); | ||
| 68 | |||
| 69 | $model->find_or_create( | ||
| 70 | tablename => { unique_idx => [qw/ key1 key2 /] } => { | ||
| 71 | field1 => 'value', | ||
| 72 | field2 => 'value', | ||
| 73 | } | ||
| 74 | ); | ||
| 75 | |||
| 76 | =head1 SEE ALSO | ||
| 77 | |||
| 78 | L<Data::Model::Mixin> | ||
| 79 | |||
| 80 | =head1 AUTHOR | ||
| 81 | |||
| 82 | Kazuhiro Osawa E<lt>yappo <at> shibuya <döt> plE<gt> | ||
| 83 | |||
| 84 | =head1 LICENSE | ||
| 85 | |||
| 86 | This library is free software; you can redistribute it and/or modify | ||
| 87 | it under the same terms as Perl itself. | ||
| 88 | |||
| 89 | =cut | ||
| 90 |