734e1d943cdadcd6e7c4a21f0555e5213d37558c
[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 $ret = $self->store_column(@_);
131   $self->{_dirty_columns}{$column} = 1;
132   return $ret;
133 }
134
135 sub store_column {
136   my ($self, $column, $value) = @_;
137   $self->throw( "No such column '${column}'" ) 
138     unless $self->_columns->{$column};
139   $self->throw( "set_column called for ${column} without value" ) 
140     if @_ < 3;
141   return $self->{_column_data}{$column} = $value;
142 }
143
144 sub _register_columns {
145   my ($class, @cols) = @_;
146   my $names = { %{$class->_columns} };
147   $names->{$_} ||= {} for @cols;
148   $class->_columns($names); 
149 }
150
151 sub _mk_column_accessors {
152   my ($class, @cols) = @_;
153   $class->mk_group_accessors('column' => @cols);
154 }
155
156 sub add_columns {
157   my ($class, @cols) = @_;
158   $class->_register_columns(@cols);
159   $class->_mk_column_accessors(@cols);
160 }
161
162 sub retrieve_from_sql {
163   my ($class, $cond, @vals) = @_;
164   $cond =~ s/^\s*WHERE//i;
165   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
166   my @cols = $class->_select_columns($attrs);
167   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
168   #warn "$cond @vals";
169   return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
170 }
171
172 sub sth_to_objects {
173   my ($class, $sth, $args, $cols, $attrs) = @_;
174   my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
175   my @args = map { ref $_ ? ''.$_ : $_ } @$args; # Stringify objects
176   my $cursor_class = $class->_cursor_class;
177   eval "use $cursor_class;";
178   my $cursor = $cursor_class->new($class, $sth, \@args, \@cols, $attrs);
179   return (wantarray ? $cursor->all : $cursor);
180 }
181
182 sub _row_to_object { # WARNING: Destructive to @$row
183   my ($class, $cols, $row) = @_;
184   my $new = $class->new;
185   $new->store_column($_, shift @$row) for @$cols;
186   $new->in_database(1);
187   return $new;
188 }
189
190 sub search {
191   my $class = shift;
192   my $attrs = { };
193   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
194     $attrs = { %{ pop(@_) } };
195   }
196   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
197   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
198   return $class->retrieve_from_sql($cond, @param, $attrs);
199 }
200
201 sub search_like {
202   my $class    = shift;
203   my $attrs = { };
204   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
205     $attrs = pop(@_);
206   }
207   return $class->search(@_, { %$attrs, cmp => 'LIKE' });
208 }
209
210 sub _select_columns {
211   return keys %{$_[0]->_columns};
212 }
213
214 sub copy {
215   my ($self, $changes) = @_;
216   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
217   $new->set_column($_ => $changes->{$_}) for keys %$changes;
218   return $new->insert;
219 }
220
221 sub _cond_resolve {
222   my ($self, $query, $attrs) = @_;
223   return '1 = 1' unless keys %$query;
224   my $op = $attrs->{'cmp'} || '=';
225   my $cond = join(' AND ',
226                map { (defined $query->{$_}
227                        ? "$_ $op ?"
228                        : (do { delete $query->{$_}; "$_ IS NULL"; }));
229                    } keys %$query);
230   return ($cond, values %$query);
231 }
232
233 sub table {
234   shift->_table_name(@_);
235 }
236
237 sub find_or_create {
238   my $class    = shift;
239   my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
240   my ($exists) = $class->search($hash);
241   return defined($exists) ? $exists : $class->create($hash);
242 }
243
244 sub retrieve_all {
245   my ($class) = @_;
246   return $class->retrieve_from_sql( '1' );
247 }
248
249 1;
250
251 =back
252
253 =head1 AUTHORS
254
255 Matt S. Trout <perl-stuff@trout.me.uk>
256
257 =head1 LICENSE
258
259 You may distribute this code under the same terms as Perl itself.
260
261 =cut
262