Add ::Exception, and use throw instead of die.
[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 =head1 NAME 
19
20 DBIx::Class::Table - Basic table methods
21
22 =head1 SYNOPSIS
23
24 =head1 DESCRIPTION
25
26 This class is responsible for defining and doing basic operations on 
27 L<DBIx::Class> objects.
28
29 =head1 METHODS
30
31 =over 4
32
33 =cut
34
35 sub new {
36   my ($class, $attrs) = @_;
37   $class = ref $class if ref $class;
38   my $new = bless({ _column_data => { } }, $class);
39   if ($attrs) {
40     $new->throw("attrs must be a hashref" ) unless ref($attrs) eq 'HASH';
41     while (my ($k, $v) = each %{$attrs}) {
42       $new->store_column($k => $v);
43     }
44   }
45   return $new;
46 }
47
48 sub insert {
49   my ($self) = @_;
50   return if $self->in_database;
51   #use Data::Dumper; warn Dumper($self);
52   my $sth = $self->_get_sth('insert', [ keys %{$self->{_column_data}} ],
53                               $self->_table_name, undef);
54   $sth->execute(values %{$self->{_column_data}});
55   $sth->finish;
56   $self->in_database(1);
57   $self->{_dirty_columns} = {};
58   return $self;
59 }
60
61 sub in_database {
62   my ($self, $val) = @_;
63   $self->{_in_database} = $val if @_ > 1;
64   return $self->{_in_database};
65 }
66
67 sub create {
68   my ($class, $attrs) = @_;
69   $class->throw( "create needs a hashref" ) unless ref $attrs eq 'HASH';
70   return $class->new($attrs)->insert;
71 }
72
73 sub update {
74   my ($self) = @_;
75   $self->throw( "Not in database" ) unless $self->in_database;
76   my @to_update = keys %{$self->{_dirty_columns} || {}};
77   return -1 unless @to_update;
78   my $sth = $self->_get_sth('update', \@to_update,
79                               $self->_table_name, $self->_ident_cond);
80   my $rows = $sth->execute( (map { $self->{_column_data}{$_} } @to_update),
81                   $self->_ident_values );
82   $sth->finish;
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     $sth->finish;
101     $self->in_database(undef);
102   } else {
103     my $attrs = { };
104     if (@_ > 1 && ref $_[$#_] eq 'HASH') {
105       $attrs = { %{ pop(@_) } };
106     }
107     my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
108     my ($cond, @param) = $self->_cond_resolve($query, $attrs);
109     my $sth = $self->_get_sth('delete', undef, $self->_table_name, $cond);
110     $sth->execute(@param);
111     $sth->finish;
112   }
113   return $self;
114 }
115
116 sub get_column {
117   my ($self, $column) = @_;
118   $self->throw( "Can't fetch data as class method" ) unless ref $self;
119   $self->throw( "No such column '${column}'" ) unless $self->_columns->{$column};
120   return $self->{_column_data}{$column}
121     if exists $self->{_column_data}{$column};
122   return undef;
123 }
124
125 sub set_column {
126   my $self = shift;
127   my ($column) = @_;
128   my $ret = $self->store_column(@_);
129   $self->{_dirty_columns}{$column} = 1;
130   return $ret;
131 }
132
133 sub store_column {
134   my ($self, $column, $value) = @_;
135   $self->throw( "No such column '${column}'" ) 
136     unless $self->_columns->{$column};
137   $self->throw( "set_column called for ${column} without value" ) 
138     if @_ < 3;
139   return $self->{_column_data}{$column} = $value;
140 }
141
142 sub _register_columns {
143   my ($class, @cols) = @_;
144   my $names = { %{$class->_columns} };
145   $names->{$_} ||= {} for @cols;
146   $class->_columns($names); 
147 }
148
149 sub _mk_column_accessors {
150   my ($class, @cols) = @_;
151   $class->mk_group_accessors('column' => @cols);
152 }
153
154 sub add_columns {
155   my ($class, @cols) = @_;
156   $class->_register_columns(@cols);
157   $class->_mk_column_accessors(@cols);
158 }
159
160 sub retrieve_from_sql {
161   my ($class, $cond, @vals) = @_;
162   $cond =~ s/^\s*WHERE//i;
163   my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
164   my @cols = $class->_select_columns($attrs);
165   my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
166   #warn "$cond @vals";
167   return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
168 }
169
170 sub sth_to_objects {
171   my ($class, $sth, $args, $cols, $attrs) = @_;
172   my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
173   my $cursor_class = $class->_cursor_class;
174   eval "use $cursor_class;";
175   my $cursor = $cursor_class->new($class, $sth, $args, \@cols, $attrs);
176   return (wantarray ? $cursor->all : $cursor);
177 }
178
179 sub _row_to_object { # WARNING: Destructive to @$row
180   my ($class, $cols, $row) = @_;
181   my $new = $class->new;
182   $new->store_column($_, shift @$row) for @$cols;
183   $new->in_database(1);
184   return $new;
185 }
186
187 sub search {
188   my $class = shift;
189   my $attrs = { };
190   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
191     $attrs = { %{ pop(@_) } };
192   }
193   my $query    = ref $_[0] eq "HASH" ? shift: {@_};
194   my ($cond, @param)  = $class->_cond_resolve($query, $attrs);
195   return $class->retrieve_from_sql($cond, @param, $attrs);
196 }
197
198 sub search_like {
199   my $class    = shift;
200   my $attrs = { };
201   if (@_ > 1 && ref $_[$#_] eq 'HASH') {
202     $attrs = pop(@_);
203   }
204   return $class->search(@_, { %$attrs, cmp => 'LIKE' });
205 }
206
207 sub _select_columns {
208   return keys %{$_[0]->_columns};
209 }
210
211 sub copy {
212   my ($self, $changes) = @_;
213   my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
214   $new->set_column($_ => $changes->{$_}) for keys %$changes;
215   return $new->insert;
216 }
217
218 sub _cond_resolve {
219   my ($self, $query, $attrs) = @_;
220   return '1 = 1' unless keys %$query;
221   my $op = $attrs->{'cmp'} || '=';
222   my $cond = join(' AND ',
223                map { (defined $query->{$_}
224                        ? "$_ $op ?"
225                        : (do { delete $query->{$_}; "$_ IS NULL"; }));
226                    } keys %$query);
227   return ($cond, values %$query);
228 }
229
230 sub table {
231   shift->_table_name(@_);
232 }
233
234 sub find_or_create {
235   my $class    = shift;
236   my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
237   my ($exists) = $class->search($hash);
238   return defined($exists) ? $exists : $class->create($hash);
239 }
240
241 sub retrieve_all {
242   my ($class) = @_;
243   return $class->retrieve_from_sql( '1' );
244 }
245
246 1;
247
248 =back
249
250 =head1 AUTHORS
251
252 Matt S. Trout <perl-stuff@trout.me.uk>
253
254 =head1 LICENSE
255
256 You may distribute this code under the same terms as Perl itself.
257
258 =cut
259