Improve exception text during write operations on uninserted objects
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Row.pm
CommitLineData
7624b19f 1package DBIx::Class::Row;
2
3use strict;
4use warnings;
5
1edd1722 6use base qw/DBIx::Class/;
1a58752c 7
6298a324 8use Scalar::Util 'blessed';
09d2e66a 9use DBIx::Class::_Util qw(
10 dbic_internal_try fail_on_internal_call
11 DUMMY_ALIASPAIR
12);
6dd43920 13use DBIx::Class::Carp;
f6d731aa 14use SQL::Abstract qw( is_literal_value is_plain_value );
1edd1722 15
0d5d1f12 16###
17### Internal method
18### Do not use
19###
e0cdf2cb 20BEGIN {
21 *MULTICREATE_DEBUG =
22 $ENV{DBIC_MULTICREATE_DEBUG}
23 ? sub () { 1 }
24 : sub () { 0 };
25}
26
9c1700e3 27use namespace::clean;
8c49f629 28
4c8ef945 29__PACKAGE__->mk_group_accessors ( simple => [ in_storage => '_in_storage' ] );
30
75d07914 31=head1 NAME
7624b19f 32
33DBIx::Class::Row - Basic row methods
34
35=head1 SYNOPSIS
36
37=head1 DESCRIPTION
38
39This class is responsible for defining and doing basic operations on rows
1ea77c14 40derived from L<DBIx::Class::ResultSource> objects.
7624b19f 41
fb13a49f 42Result objects are returned from L<DBIx::Class::ResultSet>s using the
ea36f4e4 43L<create|DBIx::Class::ResultSet/create>, L<find|DBIx::Class::ResultSet/find>,
44L<next|DBIx::Class::ResultSet/next> and L<all|DBIx::Class::ResultSet/all> methods,
45as well as invocations of 'single' (
46L<belongs_to|DBIx::Class::Relationship/belongs_to>,
47L<has_one|DBIx::Class::Relationship/has_one> or
48L<might_have|DBIx::Class::Relationship/might_have>)
fb13a49f 49relationship accessors of L<Result|DBIx::Class::Manual::ResultClass> objects.
a2531bf2 50
93711422 51=head1 NOTE
52
53All "Row objects" derived from a Schema-attached L<DBIx::Class::ResultSet>
78f7b20c 54object (such as a typical C<< L<search|DBIx::Class::ResultSet/search>->
55L<next|DBIx::Class::ResultSet/next> >> call) are actually Result
93711422 56instances, based on your application's
5529838f 57L<Result Class|DBIx::Class::Manual::Glossary/Result Class>.
93711422 58
59L<DBIx::Class::Row> implements most of the row-based communication with the
60underlying storage, but a Result class B<should not inherit from it directly>.
61Usually, Result classes inherit from L<DBIx::Class::Core>, which in turn
62combines the methods from several classes, one of them being
63L<DBIx::Class::Row>. Therefore, while many of the methods available to a
64L<DBIx::Class::Core>-derived Result class are described in the following
65documentation, it does not detail all of the methods available to Result
fb13a49f 66objects. Refer to L<DBIx::Class::Manual::ResultClass> for more info.
a2531bf2 67
7624b19f 68=head1 METHODS
69
8091aa91 70=head2 new
7624b19f 71
47d7b769 72 my $result = My::Class->new(\%attrs);
a2531bf2 73
47d7b769 74 my $result = $schema->resultset('MySource')->new(\%colsandvalues);
a2531bf2 75
76=over
77
78=item Arguments: \%attrs or \%colsandvalues
79
fb13a49f 80=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
7624b19f 81
a2531bf2 82=back
83
fb13a49f 84While you can create a new result object by calling C<new> directly on
a2531bf2 85this class, you are better off calling it on a
86L<DBIx::Class::ResultSet> object.
87
88When calling it directly, you will not get a complete, usable row
50261284 89object until you pass or set the C<result_source> attribute, to a
a2531bf2 90L<DBIx::Class::ResultSource> instance that is attached to a
91L<DBIx::Class::Schema> with a valid connection.
92
93C<$attrs> is a hashref of column name, value data. It can also contain
50261284 94some other attributes such as the C<result_source>.
7624b19f 95
33dd4e80 96Passing an object, or an arrayref of objects as a value will call
97L<DBIx::Class::Relationship::Base/set_from_related> for you. When
98passed a hashref or an arrayref of hashrefs as the value, these will
99be turned into objects via new_related, and treated as if you had
100passed objects.
101
264f1571 102For a more involved explanation, see L<DBIx::Class::ResultSet/create>.
103
dc5f0ad3 104Please note that if a value is not passed to new, no value will be sent
105in the SQL INSERT call, and the column will therefore assume whatever
106default value was specified in your database. While DBIC will retrieve the
107value of autoincrement columns, it will never make an explicit database
108trip to retrieve default values assigned by the RDBMS. You can explicitly
109request that all values be fetched back from the database by calling
110L</discard_changes>, or you can supply an explicit C<undef> to columns
111with NULL as the default, and save yourself a SELECT.
112
113 CAVEAT:
114
115 The behavior described above will backfire if you use a foreign key column
116 with a database-defined default. If you call the relationship accessor on
117 an object that doesn't have a set value for the FK column, DBIC will throw
118 an exception, as it has no way of knowing the PK of the related object (if
119 there is one).
120
7624b19f 121=cut
122
33dd4e80 123## It needs to store the new objects somewhere, and call insert on that list later when insert is called on this object. We may need an accessor for these so the user can retrieve them, if just doing ->new().
4a0eed52 124## This only works because DBIC doesn't yet care to check whether the new_related objects have been passed all their mandatory columns
33dd4e80 125## When doing the later insert, we need to make sure the PKs are set.
126## using _relationship_data in new and funky ways..
127## check Relationship::CascadeActions and Relationship::Accessor for compat
128## tests!
129
370f2ba2 130sub __new_related_find_or_new_helper {
a5f5e470 131 my ($self, $rel_name, $values) = @_;
68888c09 132
b7ded743 133 my $rsrc = $self->result_source;
134
68888c09 135 # create a mock-object so all new/set_column component overrides will run:
a5f5e470 136 my $rel_rs = $rsrc->related_source($rel_name)->resultset;
72c2540d 137 my $new_rel_obj = $rel_rs->new_result($values);
68888c09 138 my $proc_data = { $new_rel_obj->get_columns };
139
a5f5e470 140 if ($self->__their_pk_needs_us($rel_name)) {
141 MULTICREATE_DEBUG and print STDERR "MC $self constructing $rel_name via new_result\n";
68888c09 142 return $new_rel_obj;
370f2ba2 143 }
a5f5e470 144 elsif ($rsrc->_pk_depends_on($rel_name, $proc_data )) {
68888c09 145 if (! keys %$proc_data) {
146 # there is nothing to search for - blind create
a5f5e470 147 MULTICREATE_DEBUG and print STDERR "MC $self constructing default-insert $rel_name\n";
68888c09 148 }
149 else {
a5f5e470 150 MULTICREATE_DEBUG and print STDERR "MC $self constructing $rel_name via find_or_new\n";
68888c09 151 # this is not *really* find or new, as we don't want to double-new the
152 # data (thus potentially double encoding or whatever)
153 my $exists = $rel_rs->find ($proc_data);
154 return $exists if $exists;
155 }
156 return $new_rel_obj;
370f2ba2 157 }
68888c09 158 else {
b7ded743 159 my $us = $rsrc->source_name;
854929cb 160 $self->throw_exception (
a5f5e470 161 "Unable to determine relationship '$rel_name' direction from '$us', "
162 . "possibly due to a missing reverse-relationship on '$rel_name' to '$us'."
854929cb 163 );
370f2ba2 164 }
370f2ba2 165}
166
167sub __their_pk_needs_us { # this should maybe be in resultsource.
a5f5e470 168 my ($self, $rel_name) = @_;
72c2540d 169 my $rsrc = $self->result_source;
a5f5e470 170 my $reverse = $rsrc->reverse_relationship_info($rel_name);
171 my $rel_source = $rsrc->related_source($rel_name);
370f2ba2 172 my $us = { $self->get_columns };
173 foreach my $key (keys %$reverse) {
174 # if their primary key depends on us, then we have to
175 # just create a result and we'll fill it out afterwards
6d0ee587 176 return 1 if $rel_source->_pk_depends_on($key, $us);
370f2ba2 177 }
178 return 0;
179}
180
7624b19f 181sub new {
448f820f 182 my ($class, $attrs) = @_;
7624b19f 183 $class = ref $class if ref $class;
04786a4c 184
4c8ef945 185 my $new = bless { _column_data => {}, _in_storage => 0 }, $class;
09e1f723 186
7624b19f 187 if ($attrs) {
27f01d1f 188 $new->throw_exception("attrs must be a hashref")
189 unless ref($attrs) eq 'HASH';
b6d347e0 190
72c2540d 191 my $rsrc = delete $attrs->{-result_source};
4376a157 192 if ( my $h = delete $attrs->{-source_handle} ) {
72c2540d 193 $rsrc ||= $h->resolve;
4376a157 194 }
195
e570488a 196 $new->result_source_instance($rsrc) if $rsrc;
4376a157 197
198 if (my $col_from_rel = delete $attrs->{-cols_from_relations}) {
199 @{$new->{_ignore_at_insert}={}}{@$col_from_rel} = ();
200 }
201
b83736a7 202 my( $related, $inflated, $colinfos );
8222f722 203
61a622ee 204 foreach my $key (keys %$attrs) {
f8193780 205 if (ref $attrs->{$key} and ! is_literal_value($attrs->{$key}) ) {
af2d42c0 206 ## Can we extract this lot to use with update(_or .. ) ?
1a58752c 207 $new->throw_exception("Can't do multi-create without result source")
72c2540d 208 unless $rsrc;
209 my $info = $rsrc->relationship_info($key);
b82c8a28 210 my $acc_type = $info->{attrs}{accessor} || '';
211 if ($acc_type eq 'single') {
de7c7c53 212 my $rel_obj = delete $attrs->{$key};
6298a324 213 if(!blessed $rel_obj) {
370f2ba2 214 $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
33dd4e80 215 }
2bc3c81e 216
e0cdf2cb 217 if ($rel_obj->in_storage) {
d4fe33d0 218 $new->{_rel_in_storage}{$key} = 1;
e0cdf2cb 219 $new->set_from_related($key, $rel_obj);
220 } else {
eed5492f 221 MULTICREATE_DEBUG and print STDERR "MC $new uninserted $key $rel_obj\n";
e0cdf2cb 222 }
2bc3c81e 223
de7c7c53 224 $related->{$key} = $rel_obj;
61a622ee 225 next;
b82c8a28 226 }
227 elsif ($acc_type eq 'multi' && ref $attrs->{$key} eq 'ARRAY' ) {
2ec8e594 228 my $others = delete $attrs->{$key};
e0cdf2cb 229 my $total = @$others;
230 my @objects;
231 foreach my $idx (0 .. $#$others) {
232 my $rel_obj = $others->[$idx];
6298a324 233 if(!blessed $rel_obj) {
370f2ba2 234 $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
33dd4e80 235 }
2bc3c81e 236
e0cdf2cb 237 if ($rel_obj->in_storage) {
d4fe33d0 238 $rel_obj->throw_exception ('A multi relationship can not be pre-existing when doing multicreate. Something went wrong');
e0cdf2cb 239 } else {
e0cdf2cb 240 MULTICREATE_DEBUG and
eed5492f 241 print STDERR "MC $new uninserted $key $rel_obj (${\($idx+1)} of $total)\n";
e0cdf2cb 242 }
e0cdf2cb 243 push(@objects, $rel_obj);
2ec8e594 244 }
e0cdf2cb 245 $related->{$key} = \@objects;
2ec8e594 246 next;
b82c8a28 247 }
248 elsif ($acc_type eq 'filter') {
33dd4e80 249 ## 'filter' should disappear and get merged in with 'single' above!
2ec8e594 250 my $rel_obj = delete $attrs->{$key};
6298a324 251 if(!blessed $rel_obj) {
370f2ba2 252 $rel_obj = $new->__new_related_find_or_new_helper($key, $rel_obj);
33dd4e80 253 }
d4fe33d0 254 if ($rel_obj->in_storage) {
255 $new->{_rel_in_storage}{$key} = 1;
256 }
257 else {
eed5492f 258 MULTICREATE_DEBUG and print STDERR "MC $new uninserted $key $rel_obj\n";
e0cdf2cb 259 }
33dd4e80 260 $inflated->{$key} = $rel_obj;
61a622ee 261 next;
4006691d 262 }
263 elsif (
b83736a7 264 ( $colinfos ||= $rsrc->columns_info )
265 ->{$key}{_inflate_info}
4006691d 266 ) {
61a622ee 267 $inflated->{$key} = $attrs->{$key};
268 next;
269 }
270 }
b6d347e0 271 $new->store_column($key => $attrs->{$key});
7624b19f 272 }
f90375dd 273
61a622ee 274 $new->{_relationship_data} = $related if $related;
275 $new->{_inflated_column} = $inflated if $inflated;
7624b19f 276 }
04786a4c 277
7624b19f 278 return $new;
279}
280
93711422 281=head2 $column_accessor
282
283 # Each pair does the same thing
284
285 # (un-inflated, regular column)
47d7b769 286 my $val = $result->get_column('first_name');
287 my $val = $result->first_name;
93711422 288
47d7b769 289 $result->set_column('first_name' => $val);
290 $result->first_name($val);
93711422 291
292 # (inflated column via DBIx::Class::InflateColumn::DateTime)
47d7b769 293 my $val = $result->get_inflated_column('last_modified');
294 my $val = $result->last_modified;
93711422 295
47d7b769 296 $result->set_inflated_column('last_modified' => $val);
297 $result->last_modified($val);
93711422 298
299=over
300
301=item Arguments: $value?
302
fb13a49f 303=item Return Value: $value
93711422 304
305=back
306
307A column accessor method is created for each column, which is used for
308getting/setting the value for that column.
309
8ed69929 310The actual method name is based on the
311L<accessor|DBIx::Class::ResultSource/accessor> name given during the
312L<Result Class|DBIx::Class::Manual::ResultClass> L<column definition
313|DBIx::Class::ResultSource/add_columns>. Like L</set_column>, this
314will not store the data in the database until L</insert> or L</update>
315is called on the row.
93711422 316
8091aa91 317=head2 insert
7624b19f 318
47d7b769 319 $result->insert;
a2531bf2 320
321=over
7624b19f 322
a2531bf2 323=item Arguments: none
324
fb13a49f 325=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 326
327=back
328
329Inserts an object previously created by L</new> into the database if
5298bbb5 330it isn't already in there. Returns the object itself. To insert an
331entirely new row into the database, use L<DBIx::Class::ResultSet/create>.
7624b19f 332
fb13a49f 333To fetch an uninserted result object, call
69bc5f2b 334L<new_result|DBIx::Class::ResultSet/new_result> on a resultset.
e91e756c 335
264f1571 336This will also insert any uninserted, related objects held inside this
337one, see L<DBIx::Class::ResultSet/create> for more details.
338
7624b19f 339=cut
340
341sub insert {
342 my ($self) = @_;
343 return $self if $self->in_storage;
72c2540d 344 my $rsrc = $self->result_source;
aeb1bf75 345 $self->throw_exception("No result_source set on this object; can't insert")
72c2540d 346 unless $rsrc;
6e399b4f 347
e5053694 348 my $storage = $rsrc->schema->storage;
a85b7ebe 349
9c6d6d93 350 my $rollback_guard;
351
33dd4e80 352 # Check if we stored uninserted relobjs here in new()
b6d347e0 353 my %related_stuff = (%{$self->{_relationship_data} || {}},
33dd4e80 354 %{$self->{_inflated_column} || {}});
9c6d6d93 355
d4fe33d0 356 # insert what needs to be inserted before us
357 my %pre_insert;
a5f5e470 358 for my $rel_name (keys %related_stuff) {
359 my $rel_obj = $related_stuff{$rel_name};
9c6d6d93 360
a5f5e470 361 if (! $self->{_rel_in_storage}{$rel_name}) {
c6ec7900 362 next unless (blessed $rel_obj && $rel_obj->isa(__PACKAGE__));
a8c98174 363
72c2540d 364 next unless $rsrc->_pk_depends_on(
a5f5e470 365 $rel_name, { $rel_obj->get_columns }
d4fe33d0 366 );
a8c98174 367
d4fe33d0 368 # The guard will save us if we blow out of this scope via die
a85b7ebe 369 $rollback_guard ||= $storage->txn_scope_guard;
9c6d6d93 370
a5f5e470 371 MULTICREATE_DEBUG and print STDERR "MC $self pre-reconstructing $rel_name $rel_obj\n";
e0cdf2cb 372
380d34f5 373 my $them = { %{$rel_obj->{_relationship_data} || {} }, $rel_obj->get_columns };
68888c09 374 my $existing;
375
376 # if there are no keys - nothing to search for
5567c8f8 377 if (keys %$them and $existing = $rsrc->related_source($rel_name)
68888c09 378 ->resultset
379 ->find($them)
380 ) {
381 %{$rel_obj} = %{$existing};
382 }
383 else {
384 $rel_obj->insert;
385 }
d4fe33d0 386
a5f5e470 387 $self->{_rel_in_storage}{$rel_name} = 1;
33dd4e80 388 }
d4fe33d0 389
a5f5e470 390 $self->set_from_related($rel_name, $rel_obj);
391 delete $related_stuff{$rel_name};
d4fe33d0 392 }
393
394 # start a transaction here if not started yet and there is more stuff
395 # to insert after us
396 if (keys %related_stuff) {
a85b7ebe 397 $rollback_guard ||= $storage->txn_scope_guard
33dd4e80 398 }
6e399b4f 399
09e1f723 400 MULTICREATE_DEBUG and do {
401 no warnings 'uninitialized';
eed5492f 402 print STDERR "MC $self inserting (".join(', ', $self->get_columns).")\n";
09e1f723 403 };
ac8e89d7 404
8b9473f5 405 # perform the insert - the storage will return everything it is asked to
406 # (autoinc primary columns and any retrieve_on_insert columns)
a85b7ebe 407 my %current_rowdata = $self->get_columns;
a85b7ebe 408 my $returned_cols = $storage->insert(
72c2540d 409 $rsrc,
8b9473f5 410 { %current_rowdata }, # what to insert, copy because the storage *will* change it
1e45aa87 411 );
412
a85b7ebe 413 for (keys %$returned_cols) {
8b9473f5 414 $self->store_column($_, $returned_cols->{$_})
415 # this ensures we fire store_column only once
416 # (some asshats like overriding it)
417 if (
cf6692ad 418 (!exists $current_rowdata{$_})
8b9473f5 419 or
cf6692ad 420 (defined $current_rowdata{$_} xor defined $returned_cols->{$_})
421 or
59d017a0 422 (
423 defined $current_rowdata{$_}
424 and
425 # one of the few spots doing forced-stringification
426 # needed to work around objects with defined stringification
427 # but *without* overloaded comparison (ugh!)
428 "$current_rowdata{$_}" ne "$returned_cols->{$_}"
429 )
8b9473f5 430 );
ac8e89d7 431 }
33dd4e80 432
5ef76b8b 433 delete $self->{_column_data_in_storage};
434 $self->in_storage(1);
e0cdf2cb 435
370f2ba2 436 $self->{_dirty_columns} = {};
437 $self->{related_resultsets} = {};
438
a5f5e470 439 foreach my $rel_name (keys %related_stuff) {
440 next unless $rsrc->has_relationship ($rel_name);
31c3800e 441
a5f5e470 442 my @cands = ref $related_stuff{$rel_name} eq 'ARRAY'
443 ? @{$related_stuff{$rel_name}}
444 : $related_stuff{$rel_name}
31c3800e 445 ;
d4fe33d0 446
c6ec7900 447 if (@cands && blessed $cands[0] && $cands[0]->isa(__PACKAGE__)
31c3800e 448 ) {
a5f5e470 449 my $reverse = $rsrc->reverse_relationship_info($rel_name);
d4fe33d0 450 foreach my $obj (@cands) {
451 $obj->set_from_related($_, $self) for keys %$reverse;
a5f5e470 452 if ($self->__their_pk_needs_us($rel_name)) {
453 if (exists $self->{_ignore_at_insert}{$rel_name}) {
454 MULTICREATE_DEBUG and print STDERR "MC $self skipping post-insert on $rel_name\n";
65ee2b31 455 }
456 else {
a5f5e470 457 MULTICREATE_DEBUG and print STDERR "MC $self inserting $rel_name $obj\n";
65ee2b31 458 $obj->insert;
370f2ba2 459 }
d4fe33d0 460 } else {
eed5492f 461 MULTICREATE_DEBUG and print STDERR "MC $self post-inserting $obj\n";
d4fe33d0 462 $obj->insert();
8222f722 463 }
33dd4e80 464 }
465 }
466 }
33dd4e80 467
d4fe33d0 468 delete $self->{_ignore_at_insert};
5ef76b8b 469
d4fe33d0 470 $rollback_guard->commit if $rollback_guard;
471
7624b19f 472 return $self;
473}
474
8091aa91 475=head2 in_storage
7624b19f 476
47d7b769 477 $result->in_storage; # Get value
478 $result->in_storage(1); # Set value
a2531bf2 479
480=over
481
482=item Arguments: none or 1|0
483
fb13a49f 484=item Return Value: 1|0
a2531bf2 485
486=back
7624b19f 487
e91e756c 488Indicates whether the object exists as a row in the database or
489not. This is set to true when L<DBIx::Class::ResultSet/find>,
5529838f 490L<DBIx::Class::ResultSet/create> or L<DBIx::Class::Row/insert>
491are invoked.
e91e756c 492
69bc5f2b 493Creating a result object using L<DBIx::Class::ResultSet/new_result>, or
494calling L</delete> on one, sets it to false.
7624b19f 495
7624b19f 496
8091aa91 497=head2 update
7624b19f 498
47d7b769 499 $result->update(\%columns?)
a2531bf2 500
501=over
7624b19f 502
a2531bf2 503=item Arguments: none or a hashref
7624b19f 504
fb13a49f 505=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 506
507=back
508
fb13a49f 509Throws an exception if the result object is not yet in the database,
47d7b769 510according to L</in_storage>. Returns the object itself.
a2531bf2 511
512This method issues an SQL UPDATE query to commit any changes to the
d6988be8 513object to the database if required (see L</get_dirty_columns>).
514It throws an exception if a proper WHERE clause uniquely identifying
515the database row can not be constructed (see
516L<significance of primary keys|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
517for more details).
a2531bf2 518
0d0fcdbf 519Also takes an optional hashref of C<< column_name => value >> pairs
a2531bf2 520to update on the object first. Be aware that the hashref will be
521passed to C<set_inflated_columns>, which might edit it in place, so
522don't rely on it being the same after a call to C<update>. If you
523need to preserve the hashref, it is sufficient to pass a shallow copy
524to C<update>, e.g. ( { %{ $href } } )
d5d833d9 525
05d1bc9c 526If the values passed or any of the column values set on the object
48580715 527contain scalar references, e.g.:
05d1bc9c 528
47d7b769 529 $result->last_modified(\'NOW()')->update();
05d1bc9c 530 # OR
47d7b769 531 $result->update({ last_modified => \'NOW()' });
05d1bc9c 532
533The update will pass the values verbatim into SQL. (See
fb13a49f 534L<SQL::Abstract> docs). The values in your Result object will NOT change
05d1bc9c 535as a result of the update call, if you want the object to be updated
536with the actual values from the database, call L</discard_changes>
537after the update.
538
47d7b769 539 $result->update()->discard_changes();
a2531bf2 540
541To determine before calling this method, which column values have
542changed and will be updated, call L</get_dirty_columns>.
543
544To check if any columns will be updated, call L</is_changed>.
545
546To force a column to be updated, call L</make_column_dirty> before
547this method.
05d1bc9c 548
7624b19f 549=cut
550
551sub update {
552 my ($self, $upd) = @_;
6e399b4f 553
bacf6f12 554 $self->set_inflated_columns($upd) if $upd;
de5ce481 555
014789be 556 my %to_update = $self->get_dirty_columns
557 or return $self;
558
84bf5d8c 559 $self->throw_exception(
560 'Result object not marked in_storage: an update() operation is not possible'
561 ) unless $self->in_storage;
de5ce481 562
e5053694 563 my $rows = $self->result_source->schema->storage->update(
867f1b28 564 $self->result_source, \%to_update, $self->_storage_ident_condition
cf856357 565 );
7624b19f 566 if ($rows == 0) {
701da8c4 567 $self->throw_exception( "Can't update ${self}: row not found" );
7624b19f 568 } elsif ($rows > 1) {
701da8c4 569 $self->throw_exception("Can't update ${self}: updated more than one row");
7624b19f 570 }
571 $self->{_dirty_columns} = {};
64acc2bc 572 $self->{related_resultsets} = {};
5ef76b8b 573 delete $self->{_column_data_in_storage};
7624b19f 574 return $self;
575}
576
8091aa91 577=head2 delete
7624b19f 578
47d7b769 579 $result->delete
a2531bf2 580
581=over
582
583=item Arguments: none
7624b19f 584
fb13a49f 585=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 586
587=back
588
589Throws an exception if the object is not in the database according to
d6988be8 590L</in_storage>. Also throws an exception if a proper WHERE clause
591uniquely identifying the database row can not be constructed (see
592L<significance of primary keys|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
593for more details).
a2531bf2 594
595The object is still perfectly usable, but L</in_storage> will
ea36f4e4 596now return 0 and the object must be reinserted using L</insert>
b6d347e0 597before it can be used to L</update> the row again.
a2531bf2 598
599If you delete an object in a class with a C<has_many> relationship, an
600attempt is made to delete all the related objects as well. To turn
601this behaviour off, pass C<< cascade_delete => 0 >> in the C<$attr>
602hashref of the relationship, see L<DBIx::Class::Relationship>. Any
603database-level cascade or restrict will take precedence over a
281e677e 604DBIx-Class-based cascading delete, since DBIx-Class B<deletes the
605main row first> and only then attempts to delete any remaining related
606rows.
a2531bf2 607
b1d16ffd 608If you delete an object within a txn_do() (see L<DBIx::Class::Storage/txn_do>)
fb13a49f 609and the transaction subsequently fails, the result object will remain marked as
b1d16ffd 610not being in storage. If you know for a fact that the object is still in
611storage (i.e. by inspecting the cause of the transaction's failure), you can
612use C<< $obj->in_storage(1) >> to restore consistency between the object and
613the database. This would allow a subsequent C<< $obj->delete >> to work
614as expected.
615
a2531bf2 616See also L<DBIx::Class::ResultSet/delete>.
7624b19f 617
618=cut
619
620sub delete {
621 my $self = shift;
622 if (ref $self) {
84bf5d8c 623 $self->throw_exception(
624 'Result object not marked in_storage: a delete() operation is not possible'
625 ) unless $self->in_storage;
cf856357 626
e5053694 627 $self->result_source->schema->storage->delete(
867f1b28 628 $self->result_source, $self->_storage_ident_condition
cf856357 629 );
630
5ef76b8b 631 delete $self->{_column_data_in_storage};
4c8ef945 632 $self->in_storage(0);
cf856357 633 }
634 else {
4a27d168 635 my $attrs = @_ > 1 && ref $_[-1] eq 'HASH' ? { %{pop(@_)} } : {};
aeb1bf75 636 my $query = ref $_[0] eq 'HASH' ? $_[0] : {@_};
e570488a 637 $self->result_source->resultset->search_rs(@_)->delete;
7624b19f 638 }
639 return $self;
640}
641
8091aa91 642=head2 get_column
7624b19f 643
47d7b769 644 my $val = $result->get_column($col);
a2531bf2 645
646=over
647
648=item Arguments: $columnname
649
fb13a49f 650=item Return Value: The value of the column
a2531bf2 651
652=back
653
654Throws an exception if the column name given doesn't exist according
16667b3a 655to L<has_column|DBIx::Class::ResultSource/has_column>.
7624b19f 656
fb13a49f 657Returns a raw column value from the result object, if it has already
e91e756c 658been fetched from the database or set by an accessor.
659
660If an L<inflated value|DBIx::Class::InflateColumn> has been set, it
661will be deflated and returned.
7624b19f 662
ea36f4e4 663Note that if you used the C<columns> or the C<select/as>
664L<search attributes|DBIx::Class::ResultSet/ATTRIBUTES> on the resultset from
47d7b769 665which C<$result> was derived, and B<did not include> C<$columnname> in the list,
ea36f4e4 666this method will return C<undef> even if the database contains some value.
667
a2531bf2 668To retrieve all loaded column values as a hash, use L</get_columns>.
669
7624b19f 670=cut
671
672sub get_column {
673 my ($self, $column) = @_;
701da8c4 674 $self->throw_exception( "Can't fetch data as class method" ) unless ref $self;
5ae153d7 675
676 return $self->{_column_data}{$column}
677 if exists $self->{_column_data}{$column};
678
61a622ee 679 if (exists $self->{_inflated_column}{$column}) {
5ae153d7 680 # deflate+return cycle
681 return $self->store_column($column, $self->_deflated_column(
682 $column, $self->{_inflated_column}{$column}
683 ));
61a622ee 684 }
5ae153d7 685
75ef16a7 686 $self->throw_exception( "No such column '${column}' on " . ref $self )
4006691d 687 unless $self->result_source->has_column($column);
5ae153d7 688
7624b19f 689 return undef;
690}
691
9b83fccd 692=head2 has_column_loaded
693
47d7b769 694 if ( $result->has_column_loaded($col) ) {
9b83fccd 695 print "$col has been loaded from db";
696 }
697
a2531bf2 698=over
699
700=item Arguments: $columnname
701
fb13a49f 702=item Return Value: 0|1
a2531bf2 703
704=back
705
9b83fccd 706Returns a true value if the column value has been loaded from the
707database (or set locally).
708
709=cut
710
def81720 711sub has_column_loaded {
712 my ($self, $column) = @_;
713 $self->throw_exception( "Can't call has_column data as class method" ) unless ref $self;
5ae153d7 714
715 return (
716 exists $self->{_inflated_column}{$column}
717 or
718 exists $self->{_column_data}{$column}
719 ) ? 1 : 0;
def81720 720}
721
8091aa91 722=head2 get_columns
076a6864 723
47d7b769 724 my %data = $result->get_columns;
a2531bf2 725
726=over
727
728=item Arguments: none
076a6864 729
fb13a49f 730=item Return Value: A hash of columnname, value pairs.
a2531bf2 731
732=back
733
734Returns all loaded column data as a hash, containing raw values. To
735get just one value for a particular column, use L</get_column>.
076a6864 736
c0a171bf 737See L</get_inflated_columns> to get the inflated values.
738
076a6864 739=cut
740
741sub get_columns {
742 my $self = shift;
61a622ee 743 if (exists $self->{_inflated_column}) {
5ae153d7 744 # deflate cycle for each inflation, including filter rels
61a622ee 745 foreach my $col (keys %{$self->{_inflated_column}}) {
6dd43920 746 unless (exists $self->{_column_data}{$col}) {
747
748 # if cached related_resultset is present assume this was a prefetch
749 carp_unique(
750 "Returning primary keys of prefetched 'filter' rels as part of get_columns() is deprecated and will "
751 . 'eventually be removed entirely (set DBIC_COLUMNS_INCLUDE_FILTER_RELS to disable this warning)'
752 ) if (
753 ! $ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS}
754 and
755 defined $self->{related_resultsets}{$col}
756 and
757 defined $self->{related_resultsets}{$col}->get_cache
758 );
759
760 $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col}));
761 }
61a622ee 762 }
763 }
cb5f2eea 764 return %{$self->{_column_data}};
d7156e50 765}
766
767=head2 get_dirty_columns
768
47d7b769 769 my %data = $result->get_dirty_columns;
a2531bf2 770
771=over
772
773=item Arguments: none
d7156e50 774
fb13a49f 775=item Return Value: A hash of column, value pairs
a2531bf2 776
777=back
778
779Only returns the column, value pairs for those columns that have been
780changed on this object since the last L</update> or L</insert> call.
781
782See L</get_columns> to fetch all column/value pairs.
d7156e50 783
784=cut
785
786sub get_dirty_columns {
787 my $self = shift;
788 return map { $_ => $self->{_column_data}{$_} }
789 keys %{$self->{_dirty_columns}};
076a6864 790}
791
6dbea98e 792=head2 make_column_dirty
793
47d7b769 794 $result->make_column_dirty($col)
a2531bf2 795
796=over
797
798=item Arguments: $columnname
799
fb13a49f 800=item Return Value: not defined
a2531bf2 801
802=back
803
804Throws an exception if the column does not exist.
805
806Marks a column as having been changed regardless of whether it has
b6d347e0 807really changed.
6dbea98e 808
809=cut
4c8ef945 810
6dbea98e 811sub make_column_dirty {
812 my ($self, $column) = @_;
813
75ef16a7 814 $self->throw_exception( "No such column '${column}' on " . ref $self )
4006691d 815 unless exists $self->{_column_data}{$column} || $self->result_source->has_column($column);
497d874a 816
b6d347e0 817 # the entire clean/dirty code relies on exists, not on true/false
497d874a 818 return 1 if exists $self->{_dirty_columns}{$column};
819
6dbea98e 820 $self->{_dirty_columns}{$column} = 1;
497d874a 821
822 # if we are just now making the column dirty, and if there is an inflated
823 # value, force it over the deflated one
824 if (exists $self->{_inflated_column}{$column}) {
825 $self->store_column($column,
826 $self->_deflated_column(
827 $column, $self->{_inflated_column}{$column}
828 )
829 );
830 }
6dbea98e 831}
832
ba4a6453 833=head2 get_inflated_columns
834
e91e756c 835 my %inflated_data = $obj->get_inflated_columns;
ba4a6453 836
a2531bf2 837=over
838
839=item Arguments: none
840
fb13a49f 841=item Return Value: A hash of column, object|value pairs
a2531bf2 842
843=back
844
845Returns a hash of all column keys and associated values. Values for any
846columns set to use inflation will be inflated and returns as objects.
847
848See L</get_columns> to get the uninflated values.
849
850See L<DBIx::Class::InflateColumn> for how to setup inflation.
ba4a6453 851
852=cut
853
854sub get_inflated_columns {
855 my $self = shift;
d61b2132 856
4006691d 857 my $loaded_colinfo = $self->result_source->columns_info;
858 $self->has_column_loaded($_) or delete $loaded_colinfo->{$_}
859 for keys %$loaded_colinfo;
d61b2132 860
6dd43920 861 my %cols_to_return = ( %{$self->{_column_data}}, %$loaded_colinfo );
862
863 unless ($ENV{DBIC_COLUMNS_INCLUDE_FILTER_RELS}) {
864 for (keys %$loaded_colinfo) {
865 # if cached related_resultset is present assume this was a prefetch
866 if (
867 $loaded_colinfo->{$_}{_inflate_info}
868 and
869 defined $self->{related_resultsets}{$_}
870 and
871 defined $self->{related_resultsets}{$_}->get_cache
872 ) {
873 carp_unique(
874 "Returning prefetched 'filter' rels as part of get_inflated_columns() is deprecated and will "
875 . 'eventually be removed entirely (set DBIC_COLUMNS_INCLUDE_FILTER_RELS to disable this warning)'
876 );
877 last;
878 }
d61b2132 879 }
880 }
881
6dd43920 882 map { $_ => (
883 (
884 ! exists $loaded_colinfo->{$_}
885 or
886 (
887 exists $loaded_colinfo->{$_}{accessor}
888 and
889 ! defined $loaded_colinfo->{$_}{accessor}
890 )
891 ) ? $self->get_column($_)
892 : $self->${ \(
893 defined $loaded_colinfo->{$_}{accessor}
894 ? $loaded_colinfo->{$_}{accessor}
895 : $_
896 )}
897 )} keys %cols_to_return;
ba4a6453 898}
899
ca8a1270 900sub _is_column_numeric {
57e9c142 901 my ($self, $column) = @_;
902
5567c8f8 903 my $rsrc;
57e9c142 904
5567c8f8 905 return undef
906 unless ( $rsrc = $self->result_source )->has_column($column);
907
b83736a7 908 my $colinfo = $rsrc->columns_info->{$column};
0bb1a52f 909
910 # cache for speed (the object may *not* have a resultsource instance)
50261284 911 if (
912 ! defined $colinfo->{is_numeric}
913 and
5567c8f8 914 my $storage = dbic_internal_try { $rsrc->schema->storage }
50261284 915 ) {
0bb1a52f 916 $colinfo->{is_numeric} =
50261284 917 $storage->is_datatype_numeric ($colinfo->{data_type})
0bb1a52f 918 ? 1
919 : 0
920 ;
921 }
922
923 return $colinfo->{is_numeric};
924}
925
8091aa91 926=head2 set_column
7624b19f 927
47d7b769 928 $result->set_column($col => $val);
a2531bf2 929
930=over
931
932=item Arguments: $columnname, $value
933
fb13a49f 934=item Return Value: $value
a2531bf2 935
936=back
7624b19f 937
e91e756c 938Sets a raw column value. If the new value is different from the old one,
a2531bf2 939the column is marked as dirty for when you next call L</update>.
7624b19f 940
ea36f4e4 941If passed an object or reference as a value, this method will happily
942attempt to store it, and a later L</insert> or L</update> will try and
a2531bf2 943stringify/numify as appropriate. To set an object to be deflated
93711422 944instead, see L</set_inflated_columns>, or better yet, use L</$column_accessor>.
e91e756c 945
7624b19f 946=cut
947
948sub set_column {
1d0057bd 949 my ($self, $column, $new_value) = @_;
950
5ef76b8b 951 my $had_value = $self->has_column_loaded($column);
5ae153d7 952 my $old_value = $self->get_column($column);
1d0057bd 953
b236052f 954 $new_value = $self->store_column($column, $new_value);
8f9eff75 955
cde96798 956 my $dirty =
957 $self->{_dirty_columns}{$column}
958 ||
57e9c142 959 ( $self->in_storage # no point tracking dirtyness on uninserted data
cde96798 960 ? ! $self->_eq_column_values ($column, $old_value, $new_value)
961 : 1
57e9c142 962 )
cde96798 963 ;
8f9eff75 964
35f5c265 965 if ($dirty) {
966 # FIXME sadly the update code just checks for keys, not for their value
967 $self->{_dirty_columns}{$column} = 1;
968
969 # Clear out the relation/inflation cache related to this column
970 #
971 # FIXME - this is a quick *largely incorrect* hack, pending a more
972 # serious rework during the merge of single and filter rels
a5f5e470 973 my $rel_names = $self->result_source->{_relationships};
974 for my $rel_name (keys %$rel_names) {
35f5c265 975
a5f5e470 976 my $acc = $rel_names->{$rel_name}{attrs}{accessor} || '';
35f5c265 977
a5f5e470 978 if ( $acc eq 'single' and $rel_names->{$rel_name}{attrs}{fk_columns}{$column} ) {
979 delete $self->{related_resultsets}{$rel_name};
980 delete $self->{_relationship_data}{$rel_name};
981 #delete $self->{_inflated_column}{$rel_name};
35f5c265 982 }
a5f5e470 983 elsif ( $acc eq 'filter' and $rel_name eq $column) {
984 delete $self->{related_resultsets}{$rel_name};
985 #delete $self->{_relationship_data}{$rel_name};
986 delete $self->{_inflated_column}{$rel_name};
35f5c265 987 }
8f9eff75 988 }
5ef76b8b 989
990 if (
991 # value change from something (even if NULL)
992 $had_value
993 and
994 # no storage - no storage-value
5ae153d7 995 $self->in_storage
5ef76b8b 996 and
997 # no value already stored (multiple changes before commit to storage)
998 ! exists $self->{_column_data_in_storage}{$column}
999 and
1000 $self->_track_storage_value($column)
1001 ) {
1002 $self->{_column_data_in_storage}{$column} = $old_value;
8f9eff75 1003 }
1004 }
1005
1d0057bd 1006 return $new_value;
7624b19f 1007}
e60dc79f 1008
cde96798 1009sub _eq_column_values {
1010 my ($self, $col, $old, $new) = @_;
e60dc79f 1011
cde96798 1012 if (defined $old xor defined $new) {
1013 return 0;
1014 }
1015 elsif (not defined $old) { # both undef
1016 return 1;
1017 }
3705e3b2 1018 elsif (
1019 is_literal_value $old
1020 or
1021 is_literal_value $new
1022 ) {
1023 return 0;
1024 }
cde96798 1025 elsif ($old eq $new) {
1026 return 1;
1027 }
1028 elsif ($self->_is_column_numeric($col)) { # do a numeric comparison if datatype allows it
1029 return $old == $new;
1030 }
1031 else {
1032 return 0;
1033 }
1034}
1035
5ef76b8b 1036# returns a boolean indicating if the passed column should have its original
1037# value tracked between column changes and commitment to storage
1038sub _track_storage_value {
1039 my ($self, $col) = @_;
87b12551 1040 return scalar grep
1041 { $col eq $_ }
1042 $self->result_source->primary_columns
1043 ;
7624b19f 1044}
1045
8091aa91 1046=head2 set_columns
076a6864 1047
47d7b769 1048 $result->set_columns({ $col => $val, ... });
a2531bf2 1049
b6d347e0 1050=over
076a6864 1051
a2531bf2 1052=item Arguments: \%columndata
1053
fb13a49f 1054=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 1055
1056=back
1057
1058Sets multiple column, raw value pairs at once.
1059
1060Works as L</set_column>.
076a6864 1061
1062=cut
1063
1064sub set_columns {
72c2540d 1065 my ($self, $values) = @_;
1066 $self->set_column( $_, $values->{$_} ) for keys %$values;
c01ab172 1067 return $self;
076a6864 1068}
1069
bacf6f12 1070=head2 set_inflated_columns
1071
a5f5e470 1072 $result->set_inflated_columns({ $col => $val, $rel_name => $obj, ... });
a2531bf2 1073
1074=over
1075
1076=item Arguments: \%columndata
1077
fb13a49f 1078=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 1079
1080=back
1081
1082Sets more than one column value at once. Any inflated values are
b6d347e0 1083deflated and the raw values stored.
bacf6f12 1084
fb13a49f 1085Any related values passed as Result objects, using the relation name as a
a2531bf2 1086key, are reduced to the appropriate foreign key values and stored. If
fb13a49f 1087instead of related result objects, a hashref of column, value data is
a2531bf2 1088passed, will create the related object first then store.
1089
1090Will even accept arrayrefs of data as a value to a
1091L<DBIx::Class::Relationship/has_many> key, and create the related
1092objects if necessary.
1093
c1300297 1094Be aware that the input hashref might be edited in place, so don't rely
a2531bf2 1095on it being the same after a call to C<set_inflated_columns>. If you
1096need to preserve the hashref, it is sufficient to pass a shallow copy
1097to C<set_inflated_columns>, e.g. ( { %{ $href } } )
1098
1099See also L<DBIx::Class::Relationship::Base/set_from_related>.
bacf6f12 1100
1101=cut
1102
1103sub set_inflated_columns {
1104 my ( $self, $upd ) = @_;
b83736a7 1105
1106 my ($rsrc, $colinfos);
1107
bacf6f12 1108 foreach my $key (keys %$upd) {
1109 if (ref $upd->{$key}) {
4006691d 1110 $rsrc ||= $self->result_source;
1111 my $info = $rsrc->relationship_info($key);
b82c8a28 1112 my $acc_type = $info->{attrs}{accessor} || '';
5ae153d7 1113
b82c8a28 1114 if ($acc_type eq 'single') {
72c2540d 1115 my $rel_obj = delete $upd->{$key};
1116 $self->set_from_related($key => $rel_obj);
1117 $self->{_relationship_data}{$key} = $rel_obj;
bacf6f12 1118 }
b82c8a28 1119 elsif ($acc_type eq 'multi') {
1120 $self->throw_exception(
1121 "Recursive update is not supported over relationships of type '$acc_type' ($key)"
1122 );
1123 }
4006691d 1124 elsif (
b83736a7 1125 exists( (
1126 ( $colinfos ||= $rsrc->columns_info )->{$key}
1127 ||
1128 {}
1129 )->{_inflate_info} )
4006691d 1130 ) {
a7be8807 1131 $self->set_inflated_column($key, delete $upd->{$key});
bacf6f12 1132 }
1133 }
1134 }
b6d347e0 1135 $self->set_columns($upd);
bacf6f12 1136}
1137
8091aa91 1138=head2 copy
076a6864 1139
1140 my $copy = $orig->copy({ change => $to, ... });
1141
a2531bf2 1142=over
1143
1144=item Arguments: \%replacementdata
1145
fb13a49f 1146=item Return Value: L<$result|DBIx::Class::Manual::ResultClass> copy
a2531bf2 1147
1148=back
1149
1150Inserts a new row into the database, as a copy of the original
1151object. If a hashref of replacement data is supplied, these will take
ce0893e0 1152precedence over data in the original. Also any columns which have
1153the L<column info attribute|DBIx::Class::ResultSource/add_columns>
1154C<< is_auto_increment => 1 >> are explicitly removed before the copy,
1155so that the database can insert its own autoincremented values into
1156the new object.
a2531bf2 1157
f928c965 1158Relationships will be followed by the copy procedure B<only> if the
48580715 1159relationship specifies a true value for its
f928c965 1160L<cascade_copy|DBIx::Class::Relationship::Base> attribute. C<cascade_copy>
1161is set by default on C<has_many> relationships and unset on all others.
076a6864 1162
1163=cut
1164
c01ab172 1165sub copy {
1166 my ($self, $changes) = @_;
333cce60 1167 $changes ||= {};
cc506f8b 1168 my $col_data = { $self->get_columns };
52416317 1169
4006691d 1170 my $rsrc = $self->result_source;
1171
cc506f8b 1172 my $colinfo = $rsrc->columns_info;
fde6e28e 1173 foreach my $col (keys %$col_data) {
1174 delete $col_data->{$col}
cc506f8b 1175 if ( ! $colinfo->{$col} or $colinfo->{$col}{is_auto_increment} );
fde6e28e 1176 }
04786a4c 1177
1178 my $new = { _column_data => $col_data };
1179 bless $new, ref $self;
1180
e570488a 1181 $new->result_source_instance($rsrc);
bacf6f12 1182 $new->set_inflated_columns($changes);
333cce60 1183 $new->insert;
35688220 1184
b6d347e0 1185 # Its possible we'll have 2 relations to the same Source. We need to make
48580715 1186 # sure we don't try to insert the same row twice else we'll violate unique
35688220 1187 # constraints
a5f5e470 1188 my $rel_names_copied = {};
35688220 1189
4006691d 1190 foreach my $rel_name ($rsrc->relationships) {
1191 my $rel_info = $rsrc->relationship_info($rel_name);
35688220 1192
1193 next unless $rel_info->{attrs}{cascade_copy};
b6d347e0 1194
a4e58b18 1195 my $foreign_vals;
a5f5e470 1196 my $copied = $rel_names_copied->{ $rel_info->{source} } ||= {};
b6d347e0 1197
a4e58b18 1198 $copied->{$_->ID}++ or $_->copy(
1199
7293955e 1200 $foreign_vals ||= $rsrc->resolve_relationship_condition(
1bd54f3d 1201 require_join_free_values => 1,
a4e58b18 1202 rel_name => $rel_name,
1203 self_result_object => $new,
1204
09d2e66a 1205 # an API where these are optional would be too cumbersome,
1206 # instead always pass in some dummy values
1207 DUMMY_ALIASPAIR,
1bd54f3d 1208 )->{join_free_values}
a4e58b18 1209
e5053694 1210 ) for $self->related_resultset($rel_name)->all;
333cce60 1211 }
2c4c67b6 1212 return $new;
c01ab172 1213}
1214
8091aa91 1215=head2 store_column
7624b19f 1216
47d7b769 1217 $result->store_column($col => $val);
7624b19f 1218
a2531bf2 1219=over
1220
1221=item Arguments: $columnname, $value
1222
fb13a49f 1223=item Return Value: The value sent to storage
a2531bf2 1224
1225=back
1226
1227Set a raw value for a column without marking it as changed. This
1228method is used internally by L</set_column> which you should probably
1229be using.
1230
fb13a49f 1231This is the lowest level at which data is set on a result object,
a2531bf2 1232extend this method to catch all data setting methods.
7624b19f 1233
1234=cut
1235
1236sub store_column {
1237 my ($self, $column, $value) = @_;
75ef16a7 1238 $self->throw_exception( "No such column '${column}' on " . ref $self )
4006691d 1239 unless exists $self->{_column_data}{$column} || $self->result_source->has_column($column);
75d07914 1240 $self->throw_exception( "set_column called for ${column} without value" )
7624b19f 1241 if @_ < 3;
f6d731aa 1242
59d017a0 1243 my $vref;
1244 $self->{_column_data}{$column} = (
1245 # unpack potential { -value => "foo" }
1246 ( length ref $value and $vref = is_plain_value( $value ) )
1247 ? $$vref
1248 : $value
1249 );
7624b19f 1250}
1251
b52e9bf8 1252=head2 inflate_result
1253
c01ab172 1254 Class->inflate_result($result_source, \%me, \%prefetch?)
b52e9bf8 1255
a2531bf2 1256=over
1257
fb13a49f 1258=item Arguments: L<$result_source|DBIx::Class::ResultSource>, \%columndata, \%prefetcheddata
a2531bf2 1259
fb13a49f 1260=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
a2531bf2 1261
1262=back
1263
1264All L<DBIx::Class::ResultSet> methods that retrieve data from the
fb13a49f 1265database and turn it into result objects call this method.
a2531bf2 1266
1267Extend this method in your Result classes to hook into this process,
1268for example to rebless the result into a different class.
1269
1270Reblessing can also be done more easily by setting C<result_class> in
1271your Result class. See L<DBIx::Class::ResultSource/result_class>.
b52e9bf8 1272
db2b2eb6 1273Different types of results can also be created from a particular
1274L<DBIx::Class::ResultSet>, see L<DBIx::Class::ResultSet/result_class>.
1275
b52e9bf8 1276=cut
1277
1278sub inflate_result {
72c2540d 1279 my ($class, $rsrc, $me, $prefetch) = @_;
aec3eff1 1280
50261284 1281 my $new = bless
72c2540d 1282 { _column_data => $me, _result_source => $rsrc },
50261284 1283 ref $class || $class
1284 ;
04786a4c 1285
ce556881 1286 if ($prefetch) {
a5f5e470 1287 for my $rel_name ( keys %$prefetch ) {
35c77aa3 1288
a5f5e470 1289 my $relinfo = $rsrc->relationship_info($rel_name) or do {
3b4c4d72 1290 my $err = sprintf
1291 "Inflation into non-existent relationship '%s' of '%s' requested",
a5f5e470 1292 $rel_name,
3b4c4d72 1293 $rsrc->source_name,
1294 ;
a5f5e470 1295 if (my ($colname) = sort { length($a) <=> length ($b) } keys %{$prefetch->{$rel_name}[0] || {}} ) {
3b4c4d72 1296 $err .= sprintf ", check the inflation specification (columns/as) ending in '...%s.%s'",
a5f5e470 1297 $rel_name,
3b4c4d72 1298 $colname,
1299 }
1300
1301 $rsrc->throw_exception($err);
1302 };
1303
a5f5e470 1304 $class->throw_exception("No accessor type declared for prefetched relationship '$rel_name'")
3b4c4d72 1305 unless $relinfo->{attrs}{accessor};
1306
a5f5e470 1307 my $rel_rs = $new->related_resultset($rel_name);
93b306f0 1308
72c2540d 1309 my @rel_objects;
52864fbd 1310 if (
a5f5e470 1311 @{ $prefetch->{$rel_name} || [] }
52864fbd 1312 and
a5f5e470 1313 ref($prefetch->{$rel_name}) ne $DBIx::Class::ResultSource::RowParser::Util::null_branch_class
52864fbd 1314 ) {
25a942fa 1315
a5f5e470 1316 if (ref $prefetch->{$rel_name}[0] eq 'ARRAY') {
3b4c4d72 1317 my $rel_rsrc = $rel_rs->result_source;
1318 my $rel_class = $rel_rs->result_class;
1319 my $rel_inflator = $rel_class->can('inflate_result');
1320 @rel_objects = map
1321 { $rel_class->$rel_inflator ( $rel_rsrc, @$_ ) }
a5f5e470 1322 @{$prefetch->{$rel_name}}
3b4c4d72 1323 ;
1324 }
1325 else {
1326 @rel_objects = $rel_rs->result_class->inflate_result(
a5f5e470 1327 $rel_rs->result_source, @{$prefetch->{$rel_name}}
3b4c4d72 1328 );
1329 }
ce556881 1330 }
908aa1bb 1331
3b4c4d72 1332 if ($relinfo->{attrs}{accessor} eq 'single') {
a5f5e470 1333 $new->{_relationship_data}{$rel_name} = $rel_objects[0];
ce556881 1334 }
3b4c4d72 1335 elsif ($relinfo->{attrs}{accessor} eq 'filter') {
a5f5e470 1336 $new->{_inflated_column}{$rel_name} = $rel_objects[0];
ce556881 1337 }
b82c8a28 1338
93b306f0 1339 $rel_rs->set_cache(\@rel_objects);
b52e9bf8 1340 }
1341 }
35c77aa3 1342
1343 $new->in_storage (1);
7624b19f 1344 return $new;
1345}
1346
9b465d00 1347=head2 update_or_insert
7624b19f 1348
47d7b769 1349 $result->update_or_insert
a2531bf2 1350
1351=over
7624b19f 1352
a2531bf2 1353=item Arguments: none
1354
fb13a49f 1355=item Return Value: Result of update or insert operation
a2531bf2 1356
1357=back
1358
5529838f 1359L</update>s the object if it's already in the database, according to
a2531bf2 1360L</in_storage>, else L</insert>s it.
7624b19f 1361
9b83fccd 1362=head2 insert_or_update
1363
1364 $obj->insert_or_update
1365
1366Alias for L</update_or_insert>
1367
7624b19f 1368=cut
1369
1b822bd3 1370sub insert_or_update :DBIC_method_is_indirect_sugar {
e5053694 1371 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
1372 shift->update_or_insert(@_);
1373}
370f2ba2 1374
9b465d00 1375sub update_or_insert {
7624b19f 1376 my $self = shift;
1377 return ($self->in_storage ? $self->update : $self->insert);
1378}
1379
8091aa91 1380=head2 is_changed
7624b19f 1381
47d7b769 1382 my @changed_col_names = $result->is_changed();
1383 if ($result->is_changed()) { ... }
a2531bf2 1384
1385=over
7624b19f 1386
a2531bf2 1387=item Arguments: none
1388
fb13a49f 1389=item Return Value: 0|1 or @columnnames
a2531bf2 1390
1391=back
1392
1393In list context returns a list of columns with uncommited changes, or
9b83fccd 1394in scalar context returns a true value if there are uncommitted
1395changes.
1396
7624b19f 1397=cut
1398
1399sub is_changed {
1400 return keys %{shift->{_dirty_columns} || {}};
1401}
228dbcb4 1402
1403=head2 is_column_changed
1404
47d7b769 1405 if ($result->is_column_changed('col')) { ... }
a2531bf2 1406
1407=over
1408
1409=item Arguments: $columname
1410
fb13a49f 1411=item Return Value: 0|1
a2531bf2 1412
1413=back
228dbcb4 1414
9b83fccd 1415Returns a true value if the column has uncommitted changes.
1416
228dbcb4 1417=cut
1418
1419sub is_column_changed {
1420 my( $self, $col ) = @_;
1421 return exists $self->{_dirty_columns}->{$col};
1422}
7624b19f 1423
097d3227 1424=head2 result_source
1425
47d7b769 1426 my $resultsource = $result->result_source;
a2531bf2 1427
1428=over
1429
fb13a49f 1430=item Arguments: L<$result_source?|DBIx::Class::ResultSource>
097d3227 1431
fb13a49f 1432=item Return Value: L<$result_source|DBIx::Class::ResultSource>
a2531bf2 1433
1434=back
1435
1436Accessor to the L<DBIx::Class::ResultSource> this object was created from.
87c4e602 1437
aec3eff1 1438=cut
1439
1b822bd3 1440sub result_source :DBIC_method_is_indirect_sugar {
e570488a 1441 # While getter calls are routed through here for sensible exception text
1442 # it makes no sense to have setters do the same thing
1443 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS
1444 and
1445 @_ > 1
1446 and
1447 fail_on_internal_call;
1448
f064a2ab 1449 # this is essentially a `shift->result_source_instance(@_)` with handholding
1450 &{
1451 $_[0]->can('result_source_instance')
1452 ||
1453 $_[0]->throw_exception(
e570488a 1454 "No ResultSource instance registered for '@{[ $_[0] ]}', did you forget to call @{[ ref $_[0] || $_[0] ]}->table(...) ?"
f064a2ab 1455 )
1456 };
aec3eff1 1457}
1458
9b83fccd 1459=head2 register_column
27f01d1f 1460
9b83fccd 1461 $column_info = { .... };
1462 $class->register_column($column_name, $column_info);
27f01d1f 1463
a2531bf2 1464=over
1465
1466=item Arguments: $columnname, \%columninfo
1467
fb13a49f 1468=item Return Value: not defined
a2531bf2 1469
1470=back
1471
9b83fccd 1472Registers a column on the class. If the column_info has an 'accessor'
1473key, creates an accessor named after the value if defined; if there is
1474no such key, creates an accessor with the same name as the column
1f23a877 1475
9b83fccd 1476The column_info attributes are described in
1477L<DBIx::Class::ResultSource/add_columns>
1f23a877 1478
097d3227 1479=cut
1480
1f23a877 1481sub register_column {
1482 my ($class, $col, $info) = @_;
91b0fbd7 1483 my $acc = $col;
1484 if (exists $info->{accessor}) {
1485 return unless defined $info->{accessor};
1486 $acc = [ $info->{accessor}, $col ];
1487 }
1488 $class->mk_group_accessors('column' => $acc);
1f23a877 1489}
1490
a2531bf2 1491=head2 get_from_storage
1492
47d7b769 1493 my $copy = $result->get_from_storage($attrs)
a2531bf2 1494
1495=over
b9b4e52f 1496
a2531bf2 1497=item Arguments: \%attrs
b9b4e52f 1498
fb13a49f 1499=item Return Value: A Result object
a2531bf2 1500
1501=back
1502
fb13a49f 1503Fetches a fresh copy of the Result object from the database and returns it.
d6988be8 1504Throws an exception if a proper WHERE clause identifying the database row
1505can not be constructed (i.e. if the original object does not contain its
1506entire
1507 L<primary key|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
1508). If passed the \%attrs argument, will first apply these attributes to
a2531bf2 1509the resultset used to find the row.
1510
fb13a49f 1511This copy can then be used to compare to an existing result object, to
a2531bf2 1512determine if any changes have been made in the database since it was
1513created.
1514
fb13a49f 1515To just update your Result object with any latest changes from the
a2531bf2 1516database, use L</discard_changes> instead.
1517
1518The \%attrs argument should be compatible with
1519L<DBIx::Class::ResultSet/ATTRIBUTES>.
7e38d850 1520
b9b4e52f 1521=cut
1522
a737512c 1523sub get_from_storage {
b9b4e52f 1524 my $self = shift @_;
7e38d850 1525 my $attrs = shift @_;
7e38d850 1526 my $resultset = $self->result_source->resultset;
b6d347e0 1527
7e38d850 1528 if(defined $attrs) {
bbd107cf 1529 $resultset = $resultset->search(undef, $attrs);
7e38d850 1530 }
b6d347e0 1531
867f1b28 1532 return $resultset->find($self->_storage_ident_condition);
b9b4e52f 1533}
701da8c4 1534
93711422 1535=head2 discard_changes
fde05eb9 1536
47d7b769 1537 $result->discard_changes
fde05eb9 1538
1539=over
1540
1541=item Arguments: none or $attrs
1542
fb13a49f 1543=item Return Value: self (updates object in-place)
fde05eb9 1544
1545=back
bbd107cf 1546
1547Re-selects the row from the database, losing any changes that had
fde05eb9 1548been made. Throws an exception if a proper C<WHERE> clause identifying
d6988be8 1549the database row can not be constructed (i.e. if the original object
1550does not contain its entire
fde05eb9 1551L<primary key|DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>).
bbd107cf 1552
1553This method can also be used to refresh from storage, retrieving any
1554changes made since the row was last read from storage.
1555
fde05eb9 1556$attrs, if supplied, is expected to be a hashref of attributes suitable for passing as the
1557second argument to C<< $resultset->search($cond, $attrs) >>;
1558
1559Note: If you are using L<DBIx::Class::Storage::DBI::Replicated> as your
3dd506b8 1560storage, a default of
1561L<< C<< { force_pool => 'master' } >>
1562|DBIx::Class::Storage::DBI::Replicated/SYNOPSIS >> is automatically set for
1563you. Prior to C<< DBIx::Class 0.08109 >> (before 2010) one would have been
1564required to explicitly wrap the entire operation in a transaction to guarantee
1565that up-to-date results are read from the master database.
bbd107cf 1566
1567=cut
1568
1569sub discard_changes {
1570 my ($self, $attrs) = @_;
bbd107cf 1571 return unless $self->in_storage; # Don't reload if we aren't real!
1572
1573 # add a replication default to read from the master only
1574 $attrs = { force_pool => 'master', %{$attrs||{}} };
1575
1576 if( my $current_storage = $self->get_from_storage($attrs)) {
1577
1578 # Set $self to the current.
1579 %$self = %$current_storage;
1580
1581 # Avoid a possible infinite loop with
1582 # sub DESTROY { $_[0]->discard_changes }
1583 bless $current_storage, 'Do::Not::Exist';
1584
1585 return $self;
1586 }
1587 else {
1588 $self->in_storage(0);
1589 return $self;
1590 }
1591}
1592
5160b401 1593=head2 throw_exception
701da8c4 1594
a2531bf2 1595See L<DBIx::Class::Schema/throw_exception>.
701da8c4 1596
1597=cut
1598
1599sub throw_exception {
1600 my $self=shift;
1a58752c 1601
ddcc02d1 1602 if (
78de6edd 1603 ! DBIx::Class::_Util::in_internal_try
ddcc02d1 1604 and
e570488a 1605 # FIXME - the try is 99% superfluous, but just in case
1606 my $rsrc = dbic_internal_try { $self->result_source_instance }
ddcc02d1 1607 ) {
4f52479b 1608 $rsrc->throw_exception(@_)
1a58752c 1609 }
1610 else {
1611 DBIx::Class::Exception->throw(@_);
701da8c4 1612 }
1613}
1614
33cf6616 1615=head2 id
1616
47d7b769 1617 my @pk = $result->id;
a2531bf2 1618
1619=over
1620
1621=item Arguments: none
1622
1623=item Returns: A list of primary key values
1624
1625=back
1626
33cf6616 1627Returns the primary key(s) for a row. Can't be called as a class method.
f7043881 1628Actually implemented in L<DBIx::Class::PK>
33cf6616 1629
a2bd3796 1630=head1 FURTHER QUESTIONS?
7624b19f 1631
a2bd3796 1632Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
7624b19f 1633
a2bd3796 1634=head1 COPYRIGHT AND LICENSE
7624b19f 1635
a2bd3796 1636This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1637by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1638redistribute it and/or modify it under the same terms as the
1639L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
7624b19f 1640
1641=cut
fde05eb9 1642
16431;