Removed apparently unnecessary finish statements
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Table.pm
1 package DBIx::Class::Table;
2
3 use strict;
4 use warnings;
5
6 use DBIx::Class::Cursor;
7
8 use base qw/Class::Data::Inheritable/;
9
10 __PACKAGE__->mk_classdata('_columns' => {});
11
12 __PACKAGE__->mk_classdata('_table_name');
13
14 __PACKAGE__->mk_classdata('table_alias'); # FIXME: Doesn't actually do anything yet!
15
16 __PACKAGE__->mk_classdata('_cursor_class' => 'DBIx::Class::Cursor');
17
18 sub iterator_class { shift->_cursor_class(@_) }
19
20 =head1 NAME 
21
22 DBIx::Class::Table - Basic table methods
23
24 =head1 SYNOPSIS
25
26 =head1 DESCRIPTION
27
28 This class is responsible for defining and doing basic operations on 
29 L<DBIx::Class> objects.
30
31 =head1 METHODS
32
33 =over 4
34
35 =cut
36
37 sub new {
38   my ($class, $attrs) = @_;
39   $class = ref $class if ref $class;
40   my $new = bless({ _column_data => { } }, $class);
41   if ($attrs) {
42     $new->throw("attrs must be a hashref" ) unless ref($attrs) eq 'HASH';
43     while (my ($k, $v) = each %{$attrs}) {
44       $new->store_column($k => $v);
45     }
46   }
47   return $new;
48 }
49
50 sub insert {
51   my ($self) = @_;
52   return if $self->in_database;
53   #use Data::Dumper; warn Dumper($self);
54   my $sth = $self->_get_sth('insert', [ keys %{$self->{_column_data}} ],
55                               $self->_table_name, undef);
56   $sth->execute(values %{$self->{_column_data}});
57   $self->in_database(1);
58   $self->{_dirty_columns} = {};
59   return $self;
60 }
61
62 sub in_database {
63   my ($self, $val) = @_;
64   $self->{_in_database} = $val if @_ > 1;
65   return $self->{_in_database};
66 }
67
68 sub create {
69   my ($class, $attrs) = @_;
70   $class->throw( "create needs a hashref" ) unless ref $attrs eq 'HASH';
71   return $class->new($attrs)->insert;
72 }
73
74 sub update {
75   my ($self) = @_;
76   $self->throw( "Not in database" ) unless $self->in_database;
77   my @to_update = keys %{$self->{_dirty_columns} || {}};
78   return -1 unless @to_update;
79   my $sth = $self->_get_sth('update', \@to_update,
80                               $self->_table_name, $self->_ident_cond);
81   my $rows = $sth->execute( (map { $self->{_column_data}{$_} } @to_update),
82                   $self->_ident_values );
83   if ($rows == 0) {
84     $self->throw( "Can't update $self: row not found" );
85   } elsif ($rows > 1) {
86     $self->throw("Can't update $self: updated more than one row");
87   }
88   $self->{_dirty_columns} = {};
89   return $self;
90 }
91
92 sub delete {
93   my $self = shift;
94   if (ref $self) {
95     $self->throw( "Not in database" ) unless $self->in_database;
96     #warn $self->_ident_cond.' '.join(', ', $self->_ident_values);
97     my $sth = $self->_get_sth('delete', undef,
98                                 $self->_table_name, $self->_ident_cond);
99     $sth->execute($self->_ident_values);
100     $self->in_database(undef);
101   } else {
102     my $attrs = { };
103     if (@_ > 1 && ref $_[$#_] eq 'HASH') {
104       $attrs = { %{ pop(@_) } };
105     }
106     my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
107     my ($cond, @param) = $self->_cond_resolve($query, $attrs);
108     my $sth = $self->_get_sth('delete', undef, $self->_table_name, $cond);
109     $sth->execute(@param);
110   }
111   return $self;
112 }
113
114 sub get_column {
115   my ($self, $column) = @_;
116   $self->throw( "Can't fetch data as class method" ) unless ref $self;
117   $self->throw( "No such column '${column}'" ) unless $self->_columns->{$column};
118   return $self->{_column_data}{$column}
119     if exists $self->{_column_data}{$column};
120   return undef;
121 }
122
123 sub set_column {
124   my $self = shift;
125   my ($column) = @_;
126   my $old = $self->get_column($column);
127   my $ret = $self->store_column(@_);
128   $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
129   return $ret;
130 }
131
132 sub store_column {
133   my ($self, $column, $value) = @_;
134   $self->throw( "No such column '${column}'" ) 
135     unless $self->_columns->{$column};
136   $self->throw( "set_column called for ${column} without value" ) 
137     if @_ < 3;
138   return $self->{_column_data}{$column} = $value;
139 }
140
141 sub _register_columns {
142   my ($class, @cols) = @_;
143   my $names = { %{$class->_columns} };
144   $names->{$_} ||= {} for @cols;
145   $class->_columns($names); 
146 }
147
148 sub _mk_column_accessors {
149   my ($class, @cols) = @_;
150   $class->mk_group_accessors('column' => @cols);
151 }
152
153 sub add_columns {
154   my ($class, @cols) = @_;
155   $class->_register_columns(@cols);
156   $class->_mk_column_accessors(@cols);
157 }
158
159 sub retrieve_from_sql {
160   my ($class, $cond, @vals) = @_;
161   $cond =~ s/^\s*WHERE//i;
162   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
163   my @cols = $class->_select_columns($attrs);
164   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
165   #warn "$cond @vals";
166   return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
167 }
168
169 sub count_from_sql {
170   my ($class, $cond, @vals) = @_;
171   $cond =~ s/^\s*WHERE//i;
172   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
173   my @cols = 'COUNT(*)';
174   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
175   #warn "$cond @vals";
176   $sth->execute(@vals);
177   my ($count) = $sth->fetchrow_array;
178   return $count;
179 }
180
181 sub count {
182   my $class = shift;
183   my $attrs = { };
184   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
185     $attrs = { %{ pop(@_) } };
186   }
187   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
188   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
189   return $class->count_from_sql($cond, @param, $attrs);
190 }
191
192 sub sth_to_objects {
193   my ($class, $sth, $args, $cols, $attrs) = @_;
194   my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
195   my @args = map { ref $_ ? ''.$_ : $_ } @$args; # Stringify objects
196   my $cursor_class = $class->_cursor_class;
197   eval "use $cursor_class;";
198   my $cursor = $cursor_class->new($class, $sth, \@args, \@cols, $attrs);
199   return (wantarray ? $cursor->all : $cursor);
200 }
201
202 sub _row_to_object { # WARNING: Destructive to @$row
203   my ($class, $cols, $row) = @_;
204   my $new = $class->new;
205   $new->store_column($_, shift @$row) for @$cols;
206   $new->in_database(1);
207   return $new;
208 }
209
210 sub search {
211   my $class = shift;
212   my $attrs = { };
213   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
214     $attrs = { %{ pop(@_) } };
215   }
216   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
217   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
218   return $class->retrieve_from_sql($cond, @param, $attrs);
219 }
220
221 sub search_like {
222   my $class    = shift;
223   my $attrs = { };
224   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
225     $attrs = pop(@_);
226   }
227   return $class->search(@_, { %$attrs, cmp => 'LIKE' });
228 }
229
230 sub _select_columns {
231   return keys %{$_[0]->_columns};
232 }
233
234 sub copy {
235   my ($self, $changes) = @_;
236   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
237   $new->set_column($_ => $changes->{$_}) for keys %$changes;
238   return $new->insert;
239 }
240
241 sub _cond_resolve {
242   my ($self, $query, $attrs) = @_;
243   return '1 = 1' unless keys %$query;
244   my $op = $attrs->{'cmp'} || '=';
245   my $cond = join(' AND ',
246                map { (defined $query->{$_}
247                        ? "$_ $op ?"
248                        : (do { delete $query->{$_}; "$_ IS NULL"; }));
249                    } keys %$query);
250   return ($cond, values %$query);
251 }
252
253 sub table {
254   shift->_table_name(@_);
255 }
256
257 sub find_or_create {
258   my $class    = shift;
259   my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
260   my ($exists) = $class->search($hash);
261   return defined($exists) ? $exists : $class->create($hash);
262 }
263
264 sub insert_or_update {
265   my $self = shift;
266   return ($self->in_database ? $self->update : $self->insert);
267 }
268
269 sub retrieve_all {
270   my ($class) = @_;
271   return $class->retrieve_from_sql( '1' );
272 }
273
274 sub is_changed {
275   return keys %{shift->{_dirty_columns} || {}};
276 }
277
278 1;
279
280 =back
281
282 =head1 AUTHORS
283
284 Matt S. Trout <perl-stuff@trout.me.uk>
285
286 =head1 LICENSE
287
288 You may distribute this code under the same terms as Perl itself.
289
290 =cut
291