1 package DBIx::Class::Table;
6 use DBIx::Class::Cursor;
8 use base qw/Class::Data::Inheritable/;
10 __PACKAGE__->mk_classdata('_columns' => {});
12 __PACKAGE__->mk_classdata('_table_name');
14 __PACKAGE__->mk_classdata('table_alias'); # FIXME: Doesn't actually do anything yet!
16 __PACKAGE__->mk_classdata('_cursor_class' => 'DBIx::Class::Cursor');
18 sub iterator_class { shift->_cursor_class(@_) }
22 DBIx::Class::Table - Basic table methods
28 This class is responsible for defining and doing basic operations on
29 L<DBIx::Class> objects.
37 my $obj = My::Class->new($attrs);
39 Creates a new object from column => value mappings passed as a hash ref
44 my ($class, $attrs) = @_;
45 $class = ref $class if ref $class;
46 my $new = bless({ _column_data => { } }, $class);
48 $new->throw("attrs must be a hashref" ) unless ref($attrs) eq 'HASH';
49 while (my ($k, $v) = each %{$attrs}) {
50 $new->store_column($k => $v);
60 Inserts an object into the database if it isn't already in there. Returns
67 return $self if $self->in_database;
68 #use Data::Dumper; warn Dumper($self);
69 my $sth = $self->_get_sth('insert', [ keys %{$self->{_column_data}} ],
70 $self->_table_name, undef);
71 $sth->execute(values %{$self->{_column_data}});
73 $self->in_database(1);
74 $self->{_dirty_columns} = {};
80 $obj->in_database; # Get value
81 $obj->in_database(1); # Set value
83 Indicated whether the object exists as a row in the database or not
88 my ($self, $val) = @_;
89 $self->{_in_database} = $val if @_ > 1;
90 return $self->{_in_database};
95 my $new = My::Class->create($attrs);
97 A shortcut for My::Class->new($attrs)->insert;
102 my ($class, $attrs) = @_;
103 $class->throw( "create needs a hashref" ) unless ref $attrs eq 'HASH';
104 return $class->new($attrs)->insert;
111 Must be run on an object that is already in the database; issues an SQL
112 UPDATE query to commit any changes to the object to the db if required.
118 $self->throw( "Not in database" ) unless $self->in_database;
119 my @to_update = keys %{$self->{_dirty_columns} || {}};
120 return -1 unless @to_update;
121 my $sth = $self->_get_sth('update', \@to_update,
122 $self->_table_name, $self->_ident_cond);
123 my $rows = $sth->execute( (map { $self->{_column_data}{$_} } @to_update),
124 $self->_ident_values );
127 $self->throw( "Can't update $self: row not found" );
128 } elsif ($rows > 1) {
129 $self->throw("Can't update $self: updated more than one row");
131 $self->{_dirty_columns} = {};
139 Deletes the object from the database. The object is still perfectly usable
140 accessor-wise etc. but ->in_database will now return 0 and the object must
141 be re ->insert'ed before it can be ->update'ed
148 $self->throw( "Not in database" ) unless $self->in_database;
149 #warn $self->_ident_cond.' '.join(', ', $self->_ident_values);
150 my $sth = $self->_get_sth('delete', undef,
151 $self->_table_name, $self->_ident_cond);
152 $sth->execute($self->_ident_values);
154 $self->in_database(undef);
155 # Should probably also arrange to trash PK if auto
158 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
159 $attrs = { %{ pop(@_) } };
161 my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
162 my ($cond, @param) = $self->_cond_resolve($query, $attrs);
163 my $sth = $self->_get_sth('delete', undef, $self->_table_name, $cond);
164 $sth->execute(@param);
172 my $val = $obj->get_column($col);
174 Fetches a column value
179 my ($self, $column) = @_;
180 $self->throw( "Can't fetch data as class method" ) unless ref $self;
181 $self->throw( "No such column '${column}'" ) unless $self->_columns->{$column};
182 return $self->{_column_data}{$column}
183 if exists $self->{_column_data}{$column};
189 $obj->set_column($col => $val);
191 Sets a column value; if the new value is different to the old the column
192 is marked as dirty for when you next call $obj->update
199 my $old = $self->get_column($column);
200 my $ret = $self->store_column(@_);
201 $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
207 $obj->store_column($col => $val);
209 Sets a column value without marking it as dirty
214 my ($self, $column, $value) = @_;
215 $self->throw( "No such column '${column}'" )
216 unless $self->_columns->{$column};
217 $self->throw( "set_column called for ${column} without value" )
219 return $self->{_column_data}{$column} = $value;
222 sub _register_columns {
223 my ($class, @cols) = @_;
224 my $names = { %{$class->_columns} };
225 $names->{$_} ||= {} for @cols;
226 $class->_columns($names);
229 sub _mk_column_accessors {
230 my ($class, @cols) = @_;
231 $class->mk_group_accessors('column' => @cols);
236 __PACKAGE__->add_columns(qw/col1 col2 col3/);
238 Adds columns to the current package, and creates accessors for them
243 my ($class, @cols) = @_;
244 $class->_register_columns(@cols);
245 $class->_mk_column_accessors(@cols);
248 =item retrieve_from_sql
250 my @obj = $class->retrieve_from_sql($sql_where_cond, @bind);
251 my $cursor = $class->retrieve_from_sql($sql_where_cond, @bind);
255 sub retrieve_from_sql {
256 my ($class, $cond, @vals) = @_;
257 $cond =~ s/^\s*WHERE//i;
258 my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
259 my @cols = $class->_select_columns($attrs);
260 my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
262 return $class->sth_to_objects($sth, \@vals, \@cols, { where => $cond });
267 my $count = $class->count($sql_where_cond);
272 my ($class, $cond, @vals) = @_;
273 $cond =~ s/^\s*WHERE//i;
274 my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
275 my @cols = 'COUNT(*)';
276 my $sth = $class->_get_sth( 'select', \@cols, $class->_table_name, $cond);
278 $sth->execute(@vals);
279 my ($count) = $sth->fetchrow_array;
286 my $count = $class->count({ foo => 3 });
293 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
294 $attrs = { %{ pop(@_) } };
296 my $query = ref $_[0] eq "HASH" ? shift: {@_};
297 my ($cond, @param) = $class->_cond_resolve($query, $attrs);
298 return $class->count_from_sql($cond, @param, $attrs);
303 my @obj = $class->sth_to_objects($sth, \@bind, \@columns, $attrs);
304 my $cursor = $class->sth_to_objects($sth, \@bind, \@columns, $attrs);
309 my ($class, $sth, $args, $cols, $attrs) = @_;
310 my @cols = ((ref $cols eq 'ARRAY') ? @$cols : @{$sth->{NAME_lc}} );
311 my @args = map { ref $_ ? ''.$_ : $_ } @$args; # Stringify objects
312 my $cursor_class = $class->_cursor_class;
313 eval "use $cursor_class;";
314 my $cursor = $cursor_class->new($class, $sth, \@args, \@cols, $attrs);
315 return (wantarray ? $cursor->all : $cursor);
318 sub _row_to_object { # WARNING: Destructive to @$row
319 my ($class, $cols, $row) = @_;
320 my $new = $class->new;
321 $new->store_column($_, shift @$row) for @$cols;
322 $new->in_database(1);
328 my @obj = $class->search({ foo => 3 });
329 my $cursor = $class->search({ foo => 3 });
336 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
337 $attrs = { %{ pop(@_) } };
339 my $query = ref $_[0] eq "HASH" ? shift: {@_};
340 my ($cond, @param) = $class->_cond_resolve($query, $attrs);
341 return $class->retrieve_from_sql($cond, @param, $attrs);
346 Identical to search except defaults to 'LIKE' instead of '=' in condition
353 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
356 return $class->search(@_, { %$attrs, cmp => 'LIKE' });
359 sub _select_columns {
360 return keys %{$_[0]->_columns};
365 my $copy = $orig->copy({ change => $to, ... });
370 my ($self, $changes) = @_;
371 my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
372 $new->set_column($_ => $changes->{$_}) for keys %$changes;
377 my ($self, $query, $attrs) = @_;
378 return '1 = 1' unless keys %$query;
379 my $op = $attrs->{'cmp'} || '=';
380 my $cond = join(' AND ',
381 map { (defined $query->{$_}
383 : (do { delete $query->{$_}; "$_ IS NULL"; }));
385 return ($cond, values %$query);
390 __PACKAGE__->table('tbl_name');
395 shift->_table_name(@_);
400 $class->find_or_create({ key => $val, ... });
402 Searches for a record matching the search condition; if it doesn't find one,
403 creates one and returns that instead
409 my $hash = ref $_[0] eq "HASH" ? shift: {@_};
410 my ($exists) = $class->search($hash);
411 return defined($exists) ? $exists : $class->create($hash);
414 =item insert_or_update
416 $obj->insert_or_update
418 Updates the object if it's already in the db, else inserts it
422 sub insert_or_update {
424 return ($self->in_database ? $self->update : $self->insert);
429 my @all = $class->retrieve_all;
435 return $class->retrieve_from_sql( '1' );
440 my @changed_col_names = $obj->is_changed
445 return keys %{shift->{_dirty_columns} || {}};
454 Matt S. Trout <perl-stuff@trout.me.uk>
458 You may distribute this code under the same terms as Perl itself.