| 1 | package Teng::Plugin::Replace; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use utf8; | ||
| 5 | |||
| 6 | our @EXPORT = qw/replace/; | ||
| 7 | |||
| 8 | sub replace { | ||
| 9 | my ($self, $table_name, $args) = @_; | ||
| 10 | |||
| 11 | my $table = $self->schema->get_table($table_name); | ||
| 12 | if (! $table) { | ||
| 13 | Carp::croak( "Table definition for $table_name does not exist (Did you declare it in our schema?)" ); | ||
| 14 | } | ||
| 15 | |||
| 16 | for my $col (keys %{$args}) { | ||
| 17 | $args->{$col} = $table->call_deflate($col, $args->{$col}); | ||
| 18 | } | ||
| 19 | |||
| 20 | my ($sql, @binds) = $self->sql_builder->insert( $table_name, $args, { prefix => 'REPLACE INTO' } ); | ||
| 21 | $self->_execute($sql, \@binds, $table_name); | ||
| 22 | |||
| 23 | my $pk = $table->primary_keys(); | ||
| 24 | if (scalar(@$pk) == 1 && not defined $args->{$pk->[0]}) { | ||
| 25 | $args->{$pk->[0]} = $self->_last_insert_id($table_name); | ||
| 26 | } | ||
| 27 | |||
| 28 | return $args if $self->suppress_row_objects; | ||
| 29 | |||
| 30 | $table->row_class->new( | ||
| 31 | { | ||
| 32 | row_data => $args, | ||
| 33 | teng => $self, | ||
| 34 | table_name => $table_name, | ||
| 35 | } | ||
| 36 | ); | ||
| 37 | } | ||
| 38 | |||
| 39 | 1; | ||
| 40 | __END__ | ||
| 41 | |||
| 42 | =head1 NAME | ||
| 43 | |||
| 44 | Teng::Plugin::Replace - add replace for Teng | ||
| 45 | |||
| 46 | =head1 PROVIDED METHODS | ||
| 47 | |||
| 48 | =over 4 | ||
| 49 | |||
| 50 | =item $teng->replace($table_name, \%rows_data); | ||
| 51 | |||
| 52 | recoed by replace. | ||
| 53 | |||
| 54 | example: | ||
| 55 | |||
| 56 | Your::Model->replace('user', | ||
| 57 | { | ||
| 58 | id => 3, | ||
| 59 | name => 'walf443', | ||
| 60 | }, | ||
| 61 | ); | ||
| 62 | |||
| 63 | =back | ||
| 64 |