1 package DBIx::Class::Table;
6 use DBIx::Class::ResultSet;
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('_resultset_class' => 'DBIx::Class::ResultSet');
18 sub iterator_class { shift->_resultset_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_storage;
68 #use Data::Dumper; warn Dumper($self);
70 $in{$_} = $self->get_column($_)
71 for grep { defined $self->get_column($_) } $self->columns;
72 my %out = %{ $self->storage->insert($self->_table_name, \%in) };
73 $self->store_column($_, $out{$_})
74 for grep { $self->get_column($_) ne $out{$_} } keys %out;
76 $self->{_dirty_columns} = {};
82 $obj->in_storage; # Get value
83 $obj->in_storage(1); # Set value
85 Indicated whether the object exists as a row in the database or not
90 my ($self, $val) = @_;
91 $self->{_in_storage} = $val if @_ > 1;
92 return $self->{_in_storage};
97 my $new = My::Class->create($attrs);
99 A shortcut for My::Class->new($attrs)->insert;
104 my ($class, $attrs) = @_;
105 $class->throw( "create needs a hashref" ) unless ref $attrs eq 'HASH';
106 return $class->new($attrs)->insert;
113 Must be run on an object that is already in the database; issues an SQL
114 UPDATE query to commit any changes to the object to the db if required.
119 my ($self, $upd) = @_;
120 $self->throw( "Not in database" ) unless $self->in_storage;
121 my %to_update = %{$upd || {}};
122 $to_update{$_} = $self->get_column($_) for $self->is_changed;
123 return -1 unless keys %to_update;
124 my $rows = $self->storage->update($self->_table_name, \%to_update,
125 $self->ident_condition);
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} = {};
135 sub ident_condition {
138 $cond{$_} = $self->get_column($_) for keys %{$self->_primaries};
146 Deletes the object from the database. The object is still perfectly usable
147 accessor-wise etc. but ->in_storage will now return 0 and the object must
148 be re ->insert'ed before it can be ->update'ed
155 $self->throw( "Not in database" ) unless $self->in_storage;
156 #warn $self->_ident_cond.' '.join(', ', $self->_ident_values);
157 $self->storage->delete($self->_table_name, $self->ident_condition);
158 $self->in_storage(undef);
159 #$self->store_column($_ => undef) for $self->primary_columns;
160 # Should probably also arrange to trash PK if auto
161 # but if we do, post-delete cascade triggers fail :/
164 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
165 $attrs = { %{ pop(@_) } };
167 my $query = (ref $_[0] eq 'HASH' ? $_[0] : {@_});
168 $self->storage->delete($self->_table_name, $query);
175 my $val = $obj->get_column($col);
177 Fetches a column value
182 my ($self, $column) = @_;
183 $self->throw( "Can't fetch data as class method" ) unless ref $self;
184 $self->throw( "No such column '${column}'" ) unless $self->_columns->{$column};
185 return $self->{_column_data}{$column}
186 if exists $self->{_column_data}{$column};
192 $obj->set_column($col => $val);
194 Sets a column value; if the new value is different to the old the column
195 is marked as dirty for when you next call $obj->update
202 my $old = $self->get_column($column);
203 my $ret = $self->store_column(@_);
204 $self->{_dirty_columns}{$column} = 1 unless defined $old && $old eq $ret;
210 $obj->store_column($col => $val);
212 Sets a column value without marking it as dirty
217 my ($self, $column, $value) = @_;
218 $self->throw( "No such column '${column}'" )
219 unless $self->_columns->{$column};
220 $self->throw( "set_column called for ${column} without value" )
222 return $self->{_column_data}{$column} = $value;
225 sub _register_columns {
226 my ($class, @cols) = @_;
227 my $names = { %{$class->_columns} };
228 $names->{$_} ||= {} for @cols;
229 $class->_columns($names);
232 sub _mk_column_accessors {
233 my ($class, @cols) = @_;
234 $class->mk_group_accessors('column' => @cols);
239 __PACKAGE__->add_columns(qw/col1 col2 col3/);
241 Adds columns to the current package, and creates accessors for them
246 my ($class, @cols) = @_;
247 $class->_register_columns(@cols);
248 $class->_mk_column_accessors(@cols);
253 my @obj = $class->search_literal($literal_where_cond, @bind);
254 my $cursor = $class->search_literal($literal_where_cond, @bind);
259 my ($class, $cond, @vals) = @_;
260 $cond =~ s/^\s*WHERE//i;
261 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
262 $attrs->{bind} = \@vals;
263 return $class->search(\$cond, $attrs);
268 my $count = $class->count_literal($literal_where_cond);
273 my ($class, $cond, @vals) = @_;
274 $cond =~ s/^\s*WHERE//i;
275 my $attrs = (ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
276 $attrs->{bind} = [ @vals ];
277 return $class->count($cond, $attrs);
282 my $count = $class->count({ foo => 3 });
289 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
290 $attrs = { %{ pop(@_) } };
292 my $query = ref $_[0] eq "HASH" || (@_ == 1) ? shift: {@_};
293 my @cols = 'COUNT(*)';
294 my $cursor = $class->storage->select($class->_table_name, \@cols,
296 return ($cursor->next)[0];
299 sub cursor_to_resultset {
300 my ($class, $sth, $args, $cols, $attrs) = @_;
301 my $rs_class = $class->_resultset_class;
302 eval "use $rs_class;";
303 my $rs = $rs_class->new($class, $sth, $args, $cols, $attrs);
304 return (wantarray ? $rs->all : $rs);
307 sub _row_to_object { # WARNING: Destructive to @$row
308 my ($class, $cols, $row) = @_;
309 my $new = $class->new;
310 $new->store_column($_, shift @$row) for @$cols;
317 my @obj = $class->search({ foo => 3 });
318 my $cursor = $class->search({ foo => 3 });
326 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
327 $attrs = { %{ pop(@_) } };
329 my $query = (@_ == 1 || ref $_[0] eq "HASH" ? shift: {@_});
330 my @cols = $class->_select_columns;
331 return $class->cursor_to_resultset(undef, $attrs->{bind}, \@cols,
332 { where => $query, %$attrs });
337 Identical to search except defaults to 'LIKE' instead of '=' in condition
344 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
347 my $query = ref $_[0] eq "HASH" ? { %{shift()} }: {@_};
348 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
349 return $class->search($query, { %$attrs });
352 sub _select_columns {
353 return keys %{$_[0]->_columns};
358 my $copy = $orig->copy({ change => $to, ... });
363 my ($self, $changes) = @_;
364 my $new = bless({ _column_data => { %{$self->{_column_data}}} }, ref $self);
365 $new->set_column($_ => $changes->{$_}) for keys %$changes;
370 # my ($self, $query, $attrs) = @_;
371 # return '1 = 1' unless keys %$query;
372 # my $op = $attrs->{'cmp'} || '=';
373 # my $cond = join(' AND ',
374 # map { (defined $query->{$_}
376 # : (do { delete $query->{$_}; "$_ IS NULL"; }));
378 # return ($cond, values %$query);
383 __PACKAGE__->table('tbl_name');
388 shift->_table_name(@_);
393 $class->find_or_create({ key => $val, ... });
395 Searches for a record matching the search condition; if it doesn't find one,
396 creates one and returns that instead
402 my $hash = ref $_[0] eq "HASH" ? shift: {@_};
403 my ($exists) = $class->search($hash);
404 return defined($exists) ? $exists : $class->create($hash);
407 =item insert_or_update
409 $obj->insert_or_update
411 Updates the object if it's already in the db, else inserts it
415 sub insert_or_update {
417 return ($self->in_storage ? $self->update : $self->insert);
422 my @changed_col_names = $obj->is_changed
427 return keys %{shift->{_dirty_columns} || {}};
430 sub columns { return keys %{shift->_columns}; }
438 Matt S. Trout <perl-stuff@trout.me.uk>
442 You may distribute this code under the same terms as Perl itself.