b02f071b7ebd262b0c8a003749c9751663a24827
[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   $sth->finish;
58   $self->in_database(1);
59   $self->{_dirty_columns} = {};
60   return $self;
61 }
62
63 sub in_database {
64   my ($self, $val) = @_;
65   $self->{_in_database} = $val if @_ > 1;
66   return $self->{_in_database};
67 }
68
69 sub create {
70   my ($class, $attrs) = @_;
71   $class->throw( "create needs a hashref" ) unless ref $attrs eq 'HASH';
72   return $class->new($attrs)->insert;
73 }
74
75 sub update {
76   my ($self) = @_;
77   $self->throw( "Not in database" ) unless $self->in_database;
78   my @to_update = keys %{$self->{_dirty_columns} || {}};
79   return -1 unless @to_update;
80   my $sth = $self->_get_sth('update', \@to_update,
81                               $self->_table_name, $self->_ident_cond);
82   my $rows = $sth->execute( (map { $self->{_column_data}{$_} } @to_update),
83                   $self->_ident_values );
84   $sth->finish;
85   if ($rows == 0) {
86     $self->throw( "Can't update $self: row not found" );
87   } elsif ($rows > 1) {
88     $self->throw("Can't update $self: updated more than one row");
89   }
90   $self->{_dirty_columns} = {};
91   return $self;
92 }
93
94 sub delete {
95   my $self = shift;
96   if (ref $self) {
97     $self->throw( "Not in database" ) unless $self->in_database;
98     #warn $self->_ident_cond.' '.join(', ', $self->_ident_values);
99     my $sth = $self->_get_sth('delete', undef,
100                                 $self->_table_name, $self->_ident_cond);
101     $sth->execute($self->_ident_values);
102     $sth->finish;
103     $self->in_database(undef);
104   } else {
105     my $attrs = { };
106     if (@_ > 1 && ref $_[$#_] eq 'HASH') {
107       $attrs = { %{ pop(@_) } };
108     }
109     my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
110     my ($cond, @param) = $self->_cond_resolve($query, $attrs);
111     my $sth = $self->_get_sth('delete', undef, $self->_table_name, $cond);
112     $sth->execute(@param);
113     $sth->finish;
114   }
115   return $self;
116 }
117
118 sub get_column {
119   my ($self, $column) = @_;
120   $self->throw( "Can't fetch data as class method" ) unless ref $self;
121   $self->throw( "No such column '${column}'" ) unless $self->_columns->{$column};
122   return $self->{_column_data}{$column}
123     if exists $self->{_column_data}{$column};
124   return undef;
125 }
126
127 sub set_column {
128   my $self = shift;
129   my ($column) = @_;
130   my $old = $self->get_column($column);
131   my $ret = $self->store_column(@_);
132   $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
133   return $ret;
134 }
135
136 sub store_column {
137   my ($self, $column, $value) = @_;
138   $self->throw( "No such column '${column}'" ) 
139     unless $self->_columns->{$column};
140   $self->throw( "set_column called for ${column} without value" ) 
141     if @_ < 3;
142   return $self->{_column_data}{$column} = $value;
143 }
144
145 sub _register_columns {
146   my ($class, @cols) = @_;
147   my $names = { %{$class->_columns} };
148   $names->{$_} ||= {} for @cols;
149   $class->_columns($names); 
150 }
151
152 sub _mk_column_accessors {
153   my ($class, @cols) = @_;
154   $class->mk_group_accessors('column' => @cols);
155 }
156
157 sub add_columns {
158   my ($class, @cols) = @_;
159   $class->_register_columns(@cols);
160   $class->_mk_column_accessors(@cols);
161 }
162
163 sub retrieve_from_sql {
164   my ($class, $cond, @vals) = @_;
165   $cond =~ s/^\s*WHERE//i;
166   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
167   my @cols = $class->_select_columns($attrs);
168   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
169   #warn "$cond @vals";
170   return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
171 }
172
173 sub count_from_sql {
174   my ($class, $cond, @vals) = @_;
175   $cond =~ s/^\s*WHERE//i;
176   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
177   my @cols = 'COUNT(*)';
178   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
179   #warn "$cond @vals";
180   $sth->execute(@vals);
181   my ($count) = $sth->fetchrow_array;
182   $sth->finish;
183   return $count;
184 }
185
186 sub count {
187   my $class = shift;
188   my $attrs = { };
189   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
190     $attrs = { %{ pop(@_) } };
191   }
192   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
193   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
194   return $class->count_from_sql($cond, @param, $attrs);
195 }
196
197 sub sth_to_objects {
198   my ($class, $sth, $args, $cols, $attrs) = @_;
199   my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
200   my @args = map { ref $_ ? ''.$_ : $_ } @$args; # Stringify objects
201   my $cursor_class = $class->_cursor_class;
202   eval "use $cursor_class;";
203   my $cursor = $cursor_class->new($class, $sth, \@args, \@cols, $attrs);
204   return (wantarray ? $cursor->all : $cursor);
205 }
206
207 sub _row_to_object { # WARNING: Destructive to @$row
208   my ($class, $cols, $row) = @_;
209   my $new = $class->new;
210   $new->store_column($_, shift @$row) for @$cols;
211   $new->in_database(1);
212   return $new;
213 }
214
215 sub search {
216   my $class = shift;
217   my $attrs = { };
218   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
219     $attrs = { %{ pop(@_) } };
220   }
221   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
222   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
223   return $class->retrieve_from_sql($cond, @param, $attrs);
224 }
225
226 sub search_like {
227   my $class    = shift;
228   my $attrs = { };
229   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
230     $attrs = pop(@_);
231   }
232   return $class->search(@_, { %$attrs, cmp => 'LIKE' });
233 }
234
235 sub _select_columns {
236   return keys %{$_[0]->_columns};
237 }
238
239 sub copy {
240   my ($self, $changes) = @_;
241   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
242   $new->set_column($_ => $changes->{$_}) for keys %$changes;
243   return $new->insert;
244 }
245
246 sub _cond_resolve {
247   my ($self, $query, $attrs) = @_;
248   return '1 = 1' unless keys %$query;
249   my $op = $attrs->{'cmp'} || '=';
250   my $cond = join(' AND ',
251                map { (defined $query->{$_}
252                        ? "$_ $op ?"
253                        : (do { delete $query->{$_}; "$_ IS NULL"; }));
254                    } keys %$query);
255   return ($cond, values %$query);
256 }
257
258 sub table {
259   shift->_table_name(@_);
260 }
261
262 sub find_or_create {
263   my $class    = shift;
264   my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
265   my ($exists) = $class->search($hash);
266   return defined($exists) ? $exists : $class->create($hash);
267 }
268
269 sub insert_or_update {
270   my $self = shift;
271   return ($self->in_database ? $self->update : $self->insert);
272 }
273
274 sub retrieve_all {
275   my ($class) = @_;
276   return $class->retrieve_from_sql( '1' );
277 }
278
279 sub is_changed {
280   return keys %{shift->{_dirty_columns} || {}};
281 }
282
283 1;
284
285 =back
286
287 =head1 AUTHORS
288
289 Matt S. Trout <perl-stuff@trout.me.uk>
290
291 =head1 LICENSE
292
293 You may distribute this code under the same terms as Perl itself.
294
295 =cut
296