One more output for the resolver - used in next commit
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource.pm
1 package DBIx::Class::ResultSource;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class::ResultSource::RowParser DBIx::Class/;
7
8 use DBIx::Class::ResultSet;
9 use DBIx::Class::ResultSourceHandle;
10
11 use DBIx::Class::Carp;
12 use DBIx::Class::_Util 'UNRESOLVABLE_CONDITION';
13 use SQL::Abstract 'is_literal_value';
14 use Devel::GlobalDestruction;
15 use Try::Tiny;
16 use List::Util 'first';
17 use Scalar::Util qw/blessed weaken isweak/;
18
19 use namespace::clean;
20
21 __PACKAGE__->mk_group_accessors(simple => qw/
22   source_name name source_info
23   _ordered_columns _columns _primaries _unique_constraints
24   _relationships resultset_attributes
25   column_info_from_storage
26 /);
27
28 __PACKAGE__->mk_group_accessors(component_class => qw/
29   resultset_class
30   result_class
31 /);
32
33 __PACKAGE__->mk_classdata( sqlt_deploy_callback => 'default_sqlt_deploy_hook' );
34
35 =head1 NAME
36
37 DBIx::Class::ResultSource - Result source object
38
39 =head1 SYNOPSIS
40
41   # Create a table based result source, in a result class.
42
43   package MyApp::Schema::Result::Artist;
44   use base qw/DBIx::Class::Core/;
45
46   __PACKAGE__->table('artist');
47   __PACKAGE__->add_columns(qw/ artistid name /);
48   __PACKAGE__->set_primary_key('artistid');
49   __PACKAGE__->has_many(cds => 'MyApp::Schema::Result::CD');
50
51   1;
52
53   # Create a query (view) based result source, in a result class
54   package MyApp::Schema::Result::Year2000CDs;
55   use base qw/DBIx::Class::Core/;
56
57   __PACKAGE__->load_components('InflateColumn::DateTime');
58   __PACKAGE__->table_class('DBIx::Class::ResultSource::View');
59
60   __PACKAGE__->table('year2000cds');
61   __PACKAGE__->result_source_instance->is_virtual(1);
62   __PACKAGE__->result_source_instance->view_definition(
63       "SELECT cdid, artist, title FROM cd WHERE year ='2000'"
64       );
65
66
67 =head1 DESCRIPTION
68
69 A ResultSource is an object that represents a source of data for querying.
70
71 This class is a base class for various specialised types of result
72 sources, for example L<DBIx::Class::ResultSource::Table>. Table is the
73 default result source type, so one is created for you when defining a
74 result class as described in the synopsis above.
75
76 More specifically, the L<DBIx::Class::Core> base class pulls in the
77 L<DBIx::Class::ResultSourceProxy::Table> component, which defines
78 the L<table|DBIx::Class::ResultSourceProxy::Table/table> method.
79 When called, C<table> creates and stores an instance of
80 L<DBIx::Class::ResultSoure::Table>. Luckily, to use tables as result
81 sources, you don't need to remember any of this.
82
83 Result sources representing select queries, or views, can also be
84 created, see L<DBIx::Class::ResultSource::View> for full details.
85
86 =head2 Finding result source objects
87
88 As mentioned above, a result source instance is created and stored for
89 you when you define a L<result class|DBIx::Class::Manual::Glossary/Result class>.
90
91 You can retrieve the result source at runtime in the following ways:
92
93 =over
94
95 =item From a Schema object:
96
97    $schema->source($source_name);
98
99 =item From a Result object:
100
101    $result->result_source;
102
103 =item From a ResultSet object:
104
105    $rs->result_source;
106
107 =back
108
109 =head1 METHODS
110
111 =pod
112
113 =cut
114
115 sub new {
116   my ($class, $attrs) = @_;
117   $class = ref $class if ref $class;
118
119   my $new = bless { %{$attrs || {}} }, $class;
120   $new->{resultset_class} ||= 'DBIx::Class::ResultSet';
121   $new->{resultset_attributes} = { %{$new->{resultset_attributes} || {}} };
122   $new->{_ordered_columns} = [ @{$new->{_ordered_columns}||[]}];
123   $new->{_columns} = { %{$new->{_columns}||{}} };
124   $new->{_relationships} = { %{$new->{_relationships}||{}} };
125   $new->{name} ||= "!!NAME NOT SET!!";
126   $new->{_columns_info_loaded} ||= 0;
127   return $new;
128 }
129
130 =pod
131
132 =head2 add_columns
133
134 =over
135
136 =item Arguments: @columns
137
138 =item Return Value: L<$result_source|/new>
139
140 =back
141
142   $source->add_columns(qw/col1 col2 col3/);
143
144   $source->add_columns('col1' => \%col1_info, 'col2' => \%col2_info, ...);
145
146 Adds columns to the result source. If supplied colname => hashref
147 pairs, uses the hashref as the L</column_info> for that column. Repeated
148 calls of this method will add more columns, not replace them.
149
150 The column names given will be created as accessor methods on your
151 L<Result|DBIx::Class::Manual::ResultClass> objects. You can change the name of the accessor
152 by supplying an L</accessor> in the column_info hash.
153
154 If a column name beginning with a plus sign ('+col1') is provided, the
155 attributes provided will be merged with any existing attributes for the
156 column, with the new attributes taking precedence in the case that an
157 attribute already exists. Using this without a hashref
158 (C<< $source->add_columns(qw/+col1 +col2/) >>) is legal, but useless --
159 it does the same thing it would do without the plus.
160
161 The contents of the column_info are not set in stone. The following
162 keys are currently recognised/used by DBIx::Class:
163
164 =over 4
165
166 =item accessor
167
168    { accessor => '_name' }
169
170    # example use, replace standard accessor with one of your own:
171    sub name {
172        my ($self, $value) = @_;
173
174        die "Name cannot contain digits!" if($value =~ /\d/);
175        $self->_name($value);
176
177        return $self->_name();
178    }
179
180 Use this to set the name of the accessor method for this column. If unset,
181 the name of the column will be used.
182
183 =item data_type
184
185    { data_type => 'integer' }
186
187 This contains the column type. It is automatically filled if you use the
188 L<SQL::Translator::Producer::DBIx::Class::File> producer, or the
189 L<DBIx::Class::Schema::Loader> module.
190
191 Currently there is no standard set of values for the data_type. Use
192 whatever your database supports.
193
194 =item size
195
196    { size => 20 }
197
198 The length of your column, if it is a column type that can have a size
199 restriction. This is currently only used to create tables from your
200 schema, see L<DBIx::Class::Schema/deploy>.
201
202 =item is_nullable
203
204    { is_nullable => 1 }
205
206 Set this to a true value for a column that is allowed to contain NULL
207 values, default is false. This is currently only used to create tables
208 from your schema, see L<DBIx::Class::Schema/deploy>.
209
210 =item is_auto_increment
211
212    { is_auto_increment => 1 }
213
214 Set this to a true value for a column whose value is somehow
215 automatically set, defaults to false. This is used to determine which
216 columns to empty when cloning objects using
217 L<DBIx::Class::Row/copy>. It is also used by
218 L<DBIx::Class::Schema/deploy>.
219
220 =item is_numeric
221
222    { is_numeric => 1 }
223
224 Set this to a true or false value (not C<undef>) to explicitly specify
225 if this column contains numeric data. This controls how set_column
226 decides whether to consider a column dirty after an update: if
227 C<is_numeric> is true a numeric comparison C<< != >> will take place
228 instead of the usual C<eq>
229
230 If not specified the storage class will attempt to figure this out on
231 first access to the column, based on the column C<data_type>. The
232 result will be cached in this attribute.
233
234 =item is_foreign_key
235
236    { is_foreign_key => 1 }
237
238 Set this to a true value for a column that contains a key from a
239 foreign table, defaults to false. This is currently only used to
240 create tables from your schema, see L<DBIx::Class::Schema/deploy>.
241
242 =item default_value
243
244    { default_value => \'now()' }
245
246 Set this to the default value which will be inserted into a column by
247 the database. Can contain either a value or a function (use a
248 reference to a scalar e.g. C<\'now()'> if you want a function). This
249 is currently only used to create tables from your schema, see
250 L<DBIx::Class::Schema/deploy>.
251
252 See the note on L<DBIx::Class::Row/new> for more information about possible
253 issues related to db-side default values.
254
255 =item sequence
256
257    { sequence => 'my_table_seq' }
258
259 Set this on a primary key column to the name of the sequence used to
260 generate a new key value. If not specified, L<DBIx::Class::PK::Auto>
261 will attempt to retrieve the name of the sequence from the database
262 automatically.
263
264 =item retrieve_on_insert
265
266   { retrieve_on_insert => 1 }
267
268 For every column where this is set to true, DBIC will retrieve the RDBMS-side
269 value upon a new row insertion (normally only the autoincrement PK is
270 retrieved on insert). C<INSERT ... RETURNING> is used automatically if
271 supported by the underlying storage, otherwise an extra SELECT statement is
272 executed to retrieve the missing data.
273
274 =item auto_nextval
275
276    { auto_nextval => 1 }
277
278 Set this to a true value for a column whose value is retrieved automatically
279 from a sequence or function (if supported by your Storage driver.) For a
280 sequence, if you do not use a trigger to get the nextval, you have to set the
281 L</sequence> value as well.
282
283 Also set this for MSSQL columns with the 'uniqueidentifier'
284 L<data_type|DBIx::Class::ResultSource/data_type> whose values you want to
285 automatically generate using C<NEWID()>, unless they are a primary key in which
286 case this will be done anyway.
287
288 =item extra
289
290 This is used by L<DBIx::Class::Schema/deploy> and L<SQL::Translator>
291 to add extra non-generic data to the column. For example: C<< extra
292 => { unsigned => 1} >> is used by the MySQL producer to set an integer
293 column to unsigned. For more details, see
294 L<SQL::Translator::Producer::MySQL>.
295
296 =back
297
298 =head2 add_column
299
300 =over
301
302 =item Arguments: $colname, \%columninfo?
303
304 =item Return Value: 1/0 (true/false)
305
306 =back
307
308   $source->add_column('col' => \%info);
309
310 Add a single column and optional column info. Uses the same column
311 info keys as L</add_columns>.
312
313 =cut
314
315 sub add_columns {
316   my ($self, @cols) = @_;
317   $self->_ordered_columns(\@cols) unless $self->_ordered_columns;
318
319   my @added;
320   my $columns = $self->_columns;
321   while (my $col = shift @cols) {
322     my $column_info = {};
323     if ($col =~ s/^\+//) {
324       $column_info = $self->column_info($col);
325     }
326
327     # If next entry is { ... } use that for the column info, if not
328     # use an empty hashref
329     if (ref $cols[0]) {
330       my $new_info = shift(@cols);
331       %$column_info = (%$column_info, %$new_info);
332     }
333     push(@added, $col) unless exists $columns->{$col};
334     $columns->{$col} = $column_info;
335   }
336   push @{ $self->_ordered_columns }, @added;
337   return $self;
338 }
339
340 sub add_column { shift->add_columns(@_); } # DO NOT CHANGE THIS TO GLOB
341
342 =head2 has_column
343
344 =over
345
346 =item Arguments: $colname
347
348 =item Return Value: 1/0 (true/false)
349
350 =back
351
352   if ($source->has_column($colname)) { ... }
353
354 Returns true if the source has a column of this name, false otherwise.
355
356 =cut
357
358 sub has_column {
359   my ($self, $column) = @_;
360   return exists $self->_columns->{$column};
361 }
362
363 =head2 column_info
364
365 =over
366
367 =item Arguments: $colname
368
369 =item Return Value: Hashref of info
370
371 =back
372
373   my $info = $source->column_info($col);
374
375 Returns the column metadata hashref for a column, as originally passed
376 to L</add_columns>. See L</add_columns> above for information on the
377 contents of the hashref.
378
379 =cut
380
381 sub column_info {
382   my ($self, $column) = @_;
383   $self->throw_exception("No such column $column")
384     unless exists $self->_columns->{$column};
385
386   if ( ! $self->_columns->{$column}{data_type}
387        and ! $self->{_columns_info_loaded}
388        and $self->column_info_from_storage
389        and my $stor = try { $self->storage } )
390   {
391     $self->{_columns_info_loaded}++;
392
393     # try for the case of storage without table
394     try {
395       my $info = $stor->columns_info_for( $self->from );
396       my $lc_info = { map
397         { (lc $_) => $info->{$_} }
398         ( keys %$info )
399       };
400
401       foreach my $col ( keys %{$self->_columns} ) {
402         $self->_columns->{$col} = {
403           %{ $self->_columns->{$col} },
404           %{ $info->{$col} || $lc_info->{lc $col} || {} }
405         };
406       }
407     };
408   }
409
410   return $self->_columns->{$column};
411 }
412
413 =head2 columns
414
415 =over
416
417 =item Arguments: none
418
419 =item Return Value: Ordered list of column names
420
421 =back
422
423   my @column_names = $source->columns;
424
425 Returns all column names in the order they were declared to L</add_columns>.
426
427 =cut
428
429 sub columns {
430   my $self = shift;
431   $self->throw_exception(
432     "columns() is a read-only accessor, did you mean add_columns()?"
433   ) if @_;
434   return @{$self->{_ordered_columns}||[]};
435 }
436
437 =head2 columns_info
438
439 =over
440
441 =item Arguments: \@colnames ?
442
443 =item Return Value: Hashref of column name/info pairs
444
445 =back
446
447   my $columns_info = $source->columns_info;
448
449 Like L</column_info> but returns information for the requested columns. If
450 the optional column-list arrayref is omitted it returns info on all columns
451 currently defined on the ResultSource via L</add_columns>.
452
453 =cut
454
455 sub columns_info {
456   my ($self, $columns) = @_;
457
458   my $colinfo = $self->_columns;
459
460   if (
461     first { ! $_->{data_type} } values %$colinfo
462       and
463     ! $self->{_columns_info_loaded}
464       and
465     $self->column_info_from_storage
466       and
467     my $stor = try { $self->storage }
468   ) {
469     $self->{_columns_info_loaded}++;
470
471     # try for the case of storage without table
472     try {
473       my $info = $stor->columns_info_for( $self->from );
474       my $lc_info = { map
475         { (lc $_) => $info->{$_} }
476         ( keys %$info )
477       };
478
479       foreach my $col ( keys %$colinfo ) {
480         $colinfo->{$col} = {
481           %{ $colinfo->{$col} },
482           %{ $info->{$col} || $lc_info->{lc $col} || {} }
483         };
484       }
485     };
486   }
487
488   my %ret;
489
490   if ($columns) {
491     for (@$columns) {
492       if (my $inf = $colinfo->{$_}) {
493         $ret{$_} = $inf;
494       }
495       else {
496         $self->throw_exception( sprintf (
497           "No such column '%s' on source '%s'",
498           $_,
499           $self->source_name || $self->name || 'Unknown source...?',
500         ));
501       }
502     }
503   }
504   else {
505     %ret = %$colinfo;
506   }
507
508   return \%ret;
509 }
510
511 =head2 remove_columns
512
513 =over
514
515 =item Arguments: @colnames
516
517 =item Return Value: not defined
518
519 =back
520
521   $source->remove_columns(qw/col1 col2 col3/);
522
523 Removes the given list of columns by name, from the result source.
524
525 B<Warning>: Removing a column that is also used in the sources primary
526 key, or in one of the sources unique constraints, B<will> result in a
527 broken result source.
528
529 =head2 remove_column
530
531 =over
532
533 =item Arguments: $colname
534
535 =item Return Value: not defined
536
537 =back
538
539   $source->remove_column('col');
540
541 Remove a single column by name from the result source, similar to
542 L</remove_columns>.
543
544 B<Warning>: Removing a column that is also used in the sources primary
545 key, or in one of the sources unique constraints, B<will> result in a
546 broken result source.
547
548 =cut
549
550 sub remove_columns {
551   my ($self, @to_remove) = @_;
552
553   my $columns = $self->_columns
554     or return;
555
556   my %to_remove;
557   for (@to_remove) {
558     delete $columns->{$_};
559     ++$to_remove{$_};
560   }
561
562   $self->_ordered_columns([ grep { not $to_remove{$_} } @{$self->_ordered_columns} ]);
563 }
564
565 sub remove_column { shift->remove_columns(@_); } # DO NOT CHANGE THIS TO GLOB
566
567 =head2 set_primary_key
568
569 =over 4
570
571 =item Arguments: @cols
572
573 =item Return Value: not defined
574
575 =back
576
577 Defines one or more columns as primary key for this source. Must be
578 called after L</add_columns>.
579
580 Additionally, defines a L<unique constraint|add_unique_constraint>
581 named C<primary>.
582
583 Note: you normally do want to define a primary key on your sources
584 B<even if the underlying database table does not have a primary key>.
585 See
586 L<DBIx::Class::Manual::Intro/The Significance and Importance of Primary Keys>
587 for more info.
588
589 =cut
590
591 sub set_primary_key {
592   my ($self, @cols) = @_;
593
594   my $colinfo = $self->columns_info(\@cols);
595   for my $col (@cols) {
596     carp_unique(sprintf (
597       "Primary key of source '%s' includes the column '%s' which has its "
598     . "'is_nullable' attribute set to true. This is a mistake and will cause "
599     . 'various Result-object operations to fail',
600       $self->source_name || $self->name || 'Unknown source...?',
601       $col,
602     )) if $colinfo->{$col}{is_nullable};
603   }
604
605   $self->_primaries(\@cols);
606
607   $self->add_unique_constraint(primary => \@cols);
608 }
609
610 =head2 primary_columns
611
612 =over 4
613
614 =item Arguments: none
615
616 =item Return Value: Ordered list of primary column names
617
618 =back
619
620 Read-only accessor which returns the list of primary keys, supplied by
621 L</set_primary_key>.
622
623 =cut
624
625 sub primary_columns {
626   return @{shift->_primaries||[]};
627 }
628
629 # a helper method that will automatically die with a descriptive message if
630 # no pk is defined on the source in question. For internal use to save
631 # on if @pks... boilerplate
632 sub _pri_cols_or_die {
633   my $self = shift;
634   my @pcols = $self->primary_columns
635     or $self->throw_exception (sprintf(
636       "Operation requires a primary key to be declared on '%s' via set_primary_key",
637       # source_name is set only after schema-registration
638       $self->source_name || $self->result_class || $self->name || 'Unknown source...?',
639     ));
640   return @pcols;
641 }
642
643 # same as above but mandating single-column PK (used by relationship condition
644 # inference)
645 sub _single_pri_col_or_die {
646   my $self = shift;
647   my ($pri, @too_many) = $self->_pri_cols_or_die;
648
649   $self->throw_exception( sprintf(
650     "Operation requires a single-column primary key declared on '%s'",
651     $self->source_name || $self->result_class || $self->name || 'Unknown source...?',
652   )) if @too_many;
653   return $pri;
654 }
655
656
657 =head2 sequence
658
659 Manually define the correct sequence for your table, to avoid the overhead
660 associated with looking up the sequence automatically. The supplied sequence
661 will be applied to the L</column_info> of each L<primary_key|/set_primary_key>
662
663 =over 4
664
665 =item Arguments: $sequence_name
666
667 =item Return Value: not defined
668
669 =back
670
671 =cut
672
673 sub sequence {
674   my ($self,$seq) = @_;
675
676   my @pks = $self->primary_columns
677     or return;
678
679   $_->{sequence} = $seq
680     for values %{ $self->columns_info (\@pks) };
681 }
682
683
684 =head2 add_unique_constraint
685
686 =over 4
687
688 =item Arguments: $name?, \@colnames
689
690 =item Return Value: not defined
691
692 =back
693
694 Declare a unique constraint on this source. Call once for each unique
695 constraint.
696
697   # For UNIQUE (column1, column2)
698   __PACKAGE__->add_unique_constraint(
699     constraint_name => [ qw/column1 column2/ ],
700   );
701
702 Alternatively, you can specify only the columns:
703
704   __PACKAGE__->add_unique_constraint([ qw/column1 column2/ ]);
705
706 This will result in a unique constraint named
707 C<table_column1_column2>, where C<table> is replaced with the table
708 name.
709
710 Unique constraints are used, for example, when you pass the constraint
711 name as the C<key> attribute to L<DBIx::Class::ResultSet/find>. Then
712 only columns in the constraint are searched.
713
714 Throws an error if any of the given column names do not yet exist on
715 the result source.
716
717 =cut
718
719 sub add_unique_constraint {
720   my $self = shift;
721
722   if (@_ > 2) {
723     $self->throw_exception(
724         'add_unique_constraint() does not accept multiple constraints, use '
725       . 'add_unique_constraints() instead'
726     );
727   }
728
729   my $cols = pop @_;
730   if (ref $cols ne 'ARRAY') {
731     $self->throw_exception (
732       'Expecting an arrayref of constraint columns, got ' . ($cols||'NOTHING')
733     );
734   }
735
736   my $name = shift @_;
737
738   $name ||= $self->name_unique_constraint($cols);
739
740   foreach my $col (@$cols) {
741     $self->throw_exception("No such column $col on table " . $self->name)
742       unless $self->has_column($col);
743   }
744
745   my %unique_constraints = $self->unique_constraints;
746   $unique_constraints{$name} = $cols;
747   $self->_unique_constraints(\%unique_constraints);
748 }
749
750 =head2 add_unique_constraints
751
752 =over 4
753
754 =item Arguments: @constraints
755
756 =item Return Value: not defined
757
758 =back
759
760 Declare multiple unique constraints on this source.
761
762   __PACKAGE__->add_unique_constraints(
763     constraint_name1 => [ qw/column1 column2/ ],
764     constraint_name2 => [ qw/column2 column3/ ],
765   );
766
767 Alternatively, you can specify only the columns:
768
769   __PACKAGE__->add_unique_constraints(
770     [ qw/column1 column2/ ],
771     [ qw/column3 column4/ ]
772   );
773
774 This will result in unique constraints named C<table_column1_column2> and
775 C<table_column3_column4>, where C<table> is replaced with the table name.
776
777 Throws an error if any of the given column names do not yet exist on
778 the result source.
779
780 See also L</add_unique_constraint>.
781
782 =cut
783
784 sub add_unique_constraints {
785   my $self = shift;
786   my @constraints = @_;
787
788   if ( !(@constraints % 2) && first { ref $_ ne 'ARRAY' } @constraints ) {
789     # with constraint name
790     while (my ($name, $constraint) = splice @constraints, 0, 2) {
791       $self->add_unique_constraint($name => $constraint);
792     }
793   }
794   else {
795     # no constraint name
796     foreach my $constraint (@constraints) {
797       $self->add_unique_constraint($constraint);
798     }
799   }
800 }
801
802 =head2 name_unique_constraint
803
804 =over 4
805
806 =item Arguments: \@colnames
807
808 =item Return Value: Constraint name
809
810 =back
811
812   $source->table('mytable');
813   $source->name_unique_constraint(['col1', 'col2']);
814   # returns
815   'mytable_col1_col2'
816
817 Return a name for a unique constraint containing the specified
818 columns. The name is created by joining the table name and each column
819 name, using an underscore character.
820
821 For example, a constraint on a table named C<cd> containing the columns
822 C<artist> and C<title> would result in a constraint name of C<cd_artist_title>.
823
824 This is used by L</add_unique_constraint> if you do not specify the
825 optional constraint name.
826
827 =cut
828
829 sub name_unique_constraint {
830   my ($self, $cols) = @_;
831
832   my $name = $self->name;
833   $name = $$name if (ref $name eq 'SCALAR');
834
835   return join '_', $name, @$cols;
836 }
837
838 =head2 unique_constraints
839
840 =over 4
841
842 =item Arguments: none
843
844 =item Return Value: Hash of unique constraint data
845
846 =back
847
848   $source->unique_constraints();
849
850 Read-only accessor which returns a hash of unique constraints on this
851 source.
852
853 The hash is keyed by constraint name, and contains an arrayref of
854 column names as values.
855
856 =cut
857
858 sub unique_constraints {
859   return %{shift->_unique_constraints||{}};
860 }
861
862 =head2 unique_constraint_names
863
864 =over 4
865
866 =item Arguments: none
867
868 =item Return Value: Unique constraint names
869
870 =back
871
872   $source->unique_constraint_names();
873
874 Returns the list of unique constraint names defined on this source.
875
876 =cut
877
878 sub unique_constraint_names {
879   my ($self) = @_;
880
881   my %unique_constraints = $self->unique_constraints;
882
883   return keys %unique_constraints;
884 }
885
886 =head2 unique_constraint_columns
887
888 =over 4
889
890 =item Arguments: $constraintname
891
892 =item Return Value: List of constraint columns
893
894 =back
895
896   $source->unique_constraint_columns('myconstraint');
897
898 Returns the list of columns that make up the specified unique constraint.
899
900 =cut
901
902 sub unique_constraint_columns {
903   my ($self, $constraint_name) = @_;
904
905   my %unique_constraints = $self->unique_constraints;
906
907   $self->throw_exception(
908     "Unknown unique constraint $constraint_name on '" . $self->name . "'"
909   ) unless exists $unique_constraints{$constraint_name};
910
911   return @{ $unique_constraints{$constraint_name} };
912 }
913
914 =head2 sqlt_deploy_callback
915
916 =over
917
918 =item Arguments: $callback_name | \&callback_code
919
920 =item Return Value: $callback_name | \&callback_code
921
922 =back
923
924   __PACKAGE__->sqlt_deploy_callback('mycallbackmethod');
925
926    or
927
928   __PACKAGE__->sqlt_deploy_callback(sub {
929     my ($source_instance, $sqlt_table) = @_;
930     ...
931   } );
932
933 An accessor to set a callback to be called during deployment of
934 the schema via L<DBIx::Class::Schema/create_ddl_dir> or
935 L<DBIx::Class::Schema/deploy>.
936
937 The callback can be set as either a code reference or the name of a
938 method in the current result class.
939
940 Defaults to L</default_sqlt_deploy_hook>.
941
942 Your callback will be passed the $source object representing the
943 ResultSource instance being deployed, and the
944 L<SQL::Translator::Schema::Table> object being created from it. The
945 callback can be used to manipulate the table object or add your own
946 customised indexes. If you need to manipulate a non-table object, use
947 the L<DBIx::Class::Schema/sqlt_deploy_hook>.
948
949 See L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To
950 Your SQL> for examples.
951
952 This sqlt deployment callback can only be used to manipulate
953 SQL::Translator objects as they get turned into SQL. To execute
954 post-deploy statements which SQL::Translator does not currently
955 handle, override L<DBIx::Class::Schema/deploy> in your Schema class
956 and call L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
957
958 =head2 default_sqlt_deploy_hook
959
960 This is the default deploy hook implementation which checks if your
961 current Result class has a C<sqlt_deploy_hook> method, and if present
962 invokes it B<on the Result class directly>. This is to preserve the
963 semantics of C<sqlt_deploy_hook> which was originally designed to expect
964 the Result class name and the
965 L<$sqlt_table instance|SQL::Translator::Schema::Table> of the table being
966 deployed.
967
968 =cut
969
970 sub default_sqlt_deploy_hook {
971   my $self = shift;
972
973   my $class = $self->result_class;
974
975   if ($class and $class->can('sqlt_deploy_hook')) {
976     $class->sqlt_deploy_hook(@_);
977   }
978 }
979
980 sub _invoke_sqlt_deploy_hook {
981   my $self = shift;
982   if ( my $hook = $self->sqlt_deploy_callback) {
983     $self->$hook(@_);
984   }
985 }
986
987 =head2 result_class
988
989 =over 4
990
991 =item Arguments: $classname
992
993 =item Return Value: $classname
994
995 =back
996
997  use My::Schema::ResultClass::Inflator;
998  ...
999
1000  use My::Schema::Artist;
1001  ...
1002  __PACKAGE__->result_class('My::Schema::ResultClass::Inflator');
1003
1004 Set the default result class for this source. You can use this to create
1005 and use your own result inflator. See L<DBIx::Class::ResultSet/result_class>
1006 for more details.
1007
1008 Please note that setting this to something like
1009 L<DBIx::Class::ResultClass::HashRefInflator> will make every result unblessed
1010 and make life more difficult.  Inflators like those are better suited to
1011 temporary usage via L<DBIx::Class::ResultSet/result_class>.
1012
1013 =head2 resultset
1014
1015 =over 4
1016
1017 =item Arguments: none
1018
1019 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
1020
1021 =back
1022
1023 Returns a resultset for the given source. This will initially be created
1024 on demand by calling
1025
1026   $self->resultset_class->new($self, $self->resultset_attributes)
1027
1028 but is cached from then on unless resultset_class changes.
1029
1030 =head2 resultset_class
1031
1032 =over 4
1033
1034 =item Arguments: $classname
1035
1036 =item Return Value: $classname
1037
1038 =back
1039
1040   package My::Schema::ResultSet::Artist;
1041   use base 'DBIx::Class::ResultSet';
1042   ...
1043
1044   # In the result class
1045   __PACKAGE__->resultset_class('My::Schema::ResultSet::Artist');
1046
1047   # Or in code
1048   $source->resultset_class('My::Schema::ResultSet::Artist');
1049
1050 Set the class of the resultset. This is useful if you want to create your
1051 own resultset methods. Create your own class derived from
1052 L<DBIx::Class::ResultSet>, and set it here. If called with no arguments,
1053 this method returns the name of the existing resultset class, if one
1054 exists.
1055
1056 =head2 resultset_attributes
1057
1058 =over 4
1059
1060 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
1061
1062 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
1063
1064 =back
1065
1066   # In the result class
1067   __PACKAGE__->resultset_attributes({ order_by => [ 'id' ] });
1068
1069   # Or in code
1070   $source->resultset_attributes({ order_by => [ 'id' ] });
1071
1072 Store a collection of resultset attributes, that will be set on every
1073 L<DBIx::Class::ResultSet> produced from this result source.
1074
1075 B<CAVEAT>: C<resultset_attributes> comes with its own set of issues and
1076 bugs! While C<resultset_attributes> isn't deprecated per se, its usage is
1077 not recommended!
1078
1079 Since relationships use attributes to link tables together, the "default"
1080 attributes you set may cause unpredictable and undesired behavior.  Furthermore,
1081 the defaults cannot be turned off, so you are stuck with them.
1082
1083 In most cases, what you should actually be using are project-specific methods:
1084
1085   package My::Schema::ResultSet::Artist;
1086   use base 'DBIx::Class::ResultSet';
1087   ...
1088
1089   # BAD IDEA!
1090   #__PACKAGE__->resultset_attributes({ prefetch => 'tracks' });
1091
1092   # GOOD IDEA!
1093   sub with_tracks { shift->search({}, { prefetch => 'tracks' }) }
1094
1095   # in your code
1096   $schema->resultset('Artist')->with_tracks->...
1097
1098 This gives you the flexibility of not using it when you don't need it.
1099
1100 For more complex situations, another solution would be to use a virtual view
1101 via L<DBIx::Class::ResultSource::View>.
1102
1103 =cut
1104
1105 sub resultset {
1106   my $self = shift;
1107   $self->throw_exception(
1108     'resultset does not take any arguments. If you want another resultset, '.
1109     'call it on the schema instead.'
1110   ) if scalar @_;
1111
1112   $self->resultset_class->new(
1113     $self,
1114     {
1115       try { %{$self->schema->default_resultset_attributes} },
1116       %{$self->{resultset_attributes}},
1117     },
1118   );
1119 }
1120
1121 =head2 name
1122
1123 =over 4
1124
1125 =item Arguments: none
1126
1127 =item Result value: $name
1128
1129 =back
1130
1131 Returns the name of the result source, which will typically be the table
1132 name. This may be a scalar reference if the result source has a non-standard
1133 name.
1134
1135 =head2 source_name
1136
1137 =over 4
1138
1139 =item Arguments: $source_name
1140
1141 =item Result value: $source_name
1142
1143 =back
1144
1145 Set an alternate name for the result source when it is loaded into a schema.
1146 This is useful if you want to refer to a result source by a name other than
1147 its class name.
1148
1149   package ArchivedBooks;
1150   use base qw/DBIx::Class/;
1151   __PACKAGE__->table('books_archive');
1152   __PACKAGE__->source_name('Books');
1153
1154   # from your schema...
1155   $schema->resultset('Books')->find(1);
1156
1157 =head2 from
1158
1159 =over 4
1160
1161 =item Arguments: none
1162
1163 =item Return Value: FROM clause
1164
1165 =back
1166
1167   my $from_clause = $source->from();
1168
1169 Returns an expression of the source to be supplied to storage to specify
1170 retrieval from this source. In the case of a database, the required FROM
1171 clause contents.
1172
1173 =cut
1174
1175 sub from { die 'Virtual method!' }
1176
1177 =head2 schema
1178
1179 =over 4
1180
1181 =item Arguments: L<$schema?|DBIx::Class::Schema>
1182
1183 =item Return Value: L<$schema|DBIx::Class::Schema>
1184
1185 =back
1186
1187   my $schema = $source->schema();
1188
1189 Sets and/or returns the L<DBIx::Class::Schema> object to which this
1190 result source instance has been attached to.
1191
1192 =cut
1193
1194 sub schema {
1195   if (@_ > 1) {
1196     $_[0]->{schema} = $_[1];
1197   }
1198   else {
1199     $_[0]->{schema} || do {
1200       my $name = $_[0]->{source_name} || '_unnamed_';
1201       my $err = 'Unable to perform storage-dependent operations with a detached result source '
1202               . "(source '$name' is not associated with a schema).";
1203
1204       $err .= ' You need to use $schema->thaw() or manually set'
1205             . ' $DBIx::Class::ResultSourceHandle::thaw_schema while thawing.'
1206         if $_[0]->{_detached_thaw};
1207
1208       DBIx::Class::Exception->throw($err);
1209     };
1210   }
1211 }
1212
1213 =head2 storage
1214
1215 =over 4
1216
1217 =item Arguments: none
1218
1219 =item Return Value: L<$storage|DBIx::Class::Storage>
1220
1221 =back
1222
1223   $source->storage->debug(1);
1224
1225 Returns the L<storage handle|DBIx::Class::Storage> for the current schema.
1226
1227 =cut
1228
1229 sub storage { shift->schema->storage; }
1230
1231 =head2 add_relationship
1232
1233 =over 4
1234
1235 =item Arguments: $rel_name, $related_source_name, \%cond, \%attrs?
1236
1237 =item Return Value: 1/true if it succeeded
1238
1239 =back
1240
1241   $source->add_relationship('rel_name', 'related_source', $cond, $attrs);
1242
1243 L<DBIx::Class::Relationship> describes a series of methods which
1244 create pre-defined useful types of relationships. Look there first
1245 before using this method directly.
1246
1247 The relationship name can be arbitrary, but must be unique for each
1248 relationship attached to this result source. 'related_source' should
1249 be the name with which the related result source was registered with
1250 the current schema. For example:
1251
1252   $schema->source('Book')->add_relationship('reviews', 'Review', {
1253     'foreign.book_id' => 'self.id',
1254   });
1255
1256 The condition C<$cond> needs to be an L<SQL::Abstract>-style
1257 representation of the join between the tables. For example, if you're
1258 creating a relation from Author to Book,
1259
1260   { 'foreign.author_id' => 'self.id' }
1261
1262 will result in the JOIN clause
1263
1264   author me JOIN book foreign ON foreign.author_id = me.id
1265
1266 You can specify as many foreign => self mappings as necessary.
1267
1268 Valid attributes are as follows:
1269
1270 =over 4
1271
1272 =item join_type
1273
1274 Explicitly specifies the type of join to use in the relationship. Any
1275 SQL join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in
1276 the SQL command immediately before C<JOIN>.
1277
1278 =item proxy
1279
1280 An arrayref containing a list of accessors in the foreign class to proxy in
1281 the main class. If, for example, you do the following:
1282
1283   CD->might_have(liner_notes => 'LinerNotes', undef, {
1284     proxy => [ qw/notes/ ],
1285   });
1286
1287 Then, assuming LinerNotes has an accessor named notes, you can do:
1288
1289   my $cd = CD->find(1);
1290   # set notes -- LinerNotes object is created if it doesn't exist
1291   $cd->notes('Notes go here');
1292
1293 =item accessor
1294
1295 Specifies the type of accessor that should be created for the
1296 relationship. Valid values are C<single> (for when there is only a single
1297 related object), C<multi> (when there can be many), and C<filter> (for
1298 when there is a single related object, but you also want the relationship
1299 accessor to double as a column accessor). For C<multi> accessors, an
1300 add_to_* method is also created, which calls C<create_related> for the
1301 relationship.
1302
1303 =back
1304
1305 Throws an exception if the condition is improperly supplied, or cannot
1306 be resolved.
1307
1308 =cut
1309
1310 sub add_relationship {
1311   my ($self, $rel, $f_source_name, $cond, $attrs) = @_;
1312   $self->throw_exception("Can't create relationship without join condition")
1313     unless $cond;
1314   $attrs ||= {};
1315
1316   # Check foreign and self are right in cond
1317   if ( (ref $cond ||'') eq 'HASH') {
1318     for (keys %$cond) {
1319       $self->throw_exception("Keys of condition should be of form 'foreign.col', not '$_'")
1320         if /\./ && !/^foreign\./;
1321     }
1322   }
1323
1324   my %rels = %{ $self->_relationships };
1325   $rels{$rel} = { class => $f_source_name,
1326                   source => $f_source_name,
1327                   cond  => $cond,
1328                   attrs => $attrs };
1329   $self->_relationships(\%rels);
1330
1331   return $self;
1332
1333 # XXX disabled. doesn't work properly currently. skip in tests.
1334
1335   my $f_source = $self->schema->source($f_source_name);
1336   unless ($f_source) {
1337     $self->ensure_class_loaded($f_source_name);
1338     $f_source = $f_source_name->result_source;
1339     #my $s_class = ref($self->schema);
1340     #$f_source_name =~ m/^${s_class}::(.*)$/;
1341     #$self->schema->register_class(($1 || $f_source_name), $f_source_name);
1342     #$f_source = $self->schema->source($f_source_name);
1343   }
1344   return unless $f_source; # Can't test rel without f_source
1345
1346   try { $self->_resolve_join($rel, 'me', {}, []) }
1347   catch {
1348     # If the resolve failed, back out and re-throw the error
1349     delete $rels{$rel};
1350     $self->_relationships(\%rels);
1351     $self->throw_exception("Error creating relationship $rel: $_");
1352   };
1353
1354   1;
1355 }
1356
1357 =head2 relationships
1358
1359 =over 4
1360
1361 =item Arguments: none
1362
1363 =item Return Value: L<@rel_names|DBIx::Class::Relationship>
1364
1365 =back
1366
1367   my @rel_names = $source->relationships();
1368
1369 Returns all relationship names for this source.
1370
1371 =cut
1372
1373 sub relationships {
1374   return keys %{shift->_relationships};
1375 }
1376
1377 =head2 relationship_info
1378
1379 =over 4
1380
1381 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1382
1383 =item Return Value: L<\%rel_data|DBIx::Class::Relationship::Base/add_relationship>
1384
1385 =back
1386
1387 Returns a hash of relationship information for the specified relationship
1388 name. The keys/values are as specified for L<DBIx::Class::Relationship::Base/add_relationship>.
1389
1390 =cut
1391
1392 sub relationship_info {
1393   #my ($self, $rel) = @_;
1394   return shift->_relationships->{+shift};
1395 }
1396
1397 =head2 has_relationship
1398
1399 =over 4
1400
1401 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1402
1403 =item Return Value: 1/0 (true/false)
1404
1405 =back
1406
1407 Returns true if the source has a relationship of this name, false otherwise.
1408
1409 =cut
1410
1411 sub has_relationship {
1412   #my ($self, $rel) = @_;
1413   return exists shift->_relationships->{+shift};
1414 }
1415
1416 =head2 reverse_relationship_info
1417
1418 =over 4
1419
1420 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1421
1422 =item Return Value: L<\%rel_data|DBIx::Class::Relationship::Base/add_relationship>
1423
1424 =back
1425
1426 Looks through all the relationships on the source this relationship
1427 points to, looking for one whose condition is the reverse of the
1428 condition on this relationship.
1429
1430 A common use of this is to find the name of the C<belongs_to> relation
1431 opposing a C<has_many> relation. For definition of these look in
1432 L<DBIx::Class::Relationship>.
1433
1434 The returned hashref is keyed by the name of the opposing
1435 relationship, and contains its data in the same manner as
1436 L</relationship_info>.
1437
1438 =cut
1439
1440 sub reverse_relationship_info {
1441   my ($self, $rel) = @_;
1442
1443   my $rel_info = $self->relationship_info($rel)
1444     or $self->throw_exception("No such relationship '$rel'");
1445
1446   my $ret = {};
1447
1448   return $ret unless ((ref $rel_info->{cond}) eq 'HASH');
1449
1450   my $stripped_cond = $self->__strip_relcond ($rel_info->{cond});
1451
1452   my $registered_source_name = $self->source_name;
1453
1454   # this may be a partial schema or something else equally esoteric
1455   my $other_rsrc = $self->related_source($rel);
1456
1457   # Get all the relationships for that source that related to this source
1458   # whose foreign column set are our self columns on $rel and whose self
1459   # columns are our foreign columns on $rel
1460   foreach my $other_rel ($other_rsrc->relationships) {
1461
1462     # only consider stuff that points back to us
1463     # "us" here is tricky - if we are in a schema registration, we want
1464     # to use the source_names, otherwise we will use the actual classes
1465
1466     # the schema may be partial
1467     my $roundtrip_rsrc = try { $other_rsrc->related_source($other_rel) }
1468       or next;
1469
1470     if ($registered_source_name) {
1471       next if $registered_source_name ne ($roundtrip_rsrc->source_name || '')
1472     }
1473     else {
1474       next if $self->result_class ne $roundtrip_rsrc->result_class;
1475     }
1476
1477     my $other_rel_info = $other_rsrc->relationship_info($other_rel);
1478
1479     # this can happen when we have a self-referential class
1480     next if $other_rel_info eq $rel_info;
1481
1482     next unless ref $other_rel_info->{cond} eq 'HASH';
1483     my $other_stripped_cond = $self->__strip_relcond($other_rel_info->{cond});
1484
1485     $ret->{$other_rel} = $other_rel_info if (
1486       $self->_compare_relationship_keys (
1487         [ keys %$stripped_cond ], [ values %$other_stripped_cond ]
1488       )
1489         and
1490       $self->_compare_relationship_keys (
1491         [ values %$stripped_cond ], [ keys %$other_stripped_cond ]
1492       )
1493     );
1494   }
1495
1496   return $ret;
1497 }
1498
1499 # all this does is removes the foreign/self prefix from a condition
1500 sub __strip_relcond {
1501   +{
1502     map
1503       { map { /^ (?:foreign|self) \. (\w+) $/x } ($_, $_[1]{$_}) }
1504       keys %{$_[1]}
1505   }
1506 }
1507
1508 sub compare_relationship_keys {
1509   carp 'compare_relationship_keys is a private method, stop calling it';
1510   my $self = shift;
1511   $self->_compare_relationship_keys (@_);
1512 }
1513
1514 # Returns true if both sets of keynames are the same, false otherwise.
1515 sub _compare_relationship_keys {
1516 #  my ($self, $keys1, $keys2) = @_;
1517   return
1518     join ("\x00", sort @{$_[1]})
1519       eq
1520     join ("\x00", sort @{$_[2]})
1521   ;
1522 }
1523
1524 # optionally takes either an arrayref of column names, or a hashref of already
1525 # retrieved colinfos
1526 # returns an arrayref of column names of the shortest unique constraint
1527 # (matching some of the input if any), giving preference to the PK
1528 sub _identifying_column_set {
1529   my ($self, $cols) = @_;
1530
1531   my %unique = $self->unique_constraints;
1532   my $colinfos = ref $cols eq 'HASH' ? $cols : $self->columns_info($cols||());
1533
1534   # always prefer the PK first, and then shortest constraints first
1535   USET:
1536   for my $set (delete $unique{primary}, sort { @$a <=> @$b } (values %unique) ) {
1537     next unless $set && @$set;
1538
1539     for (@$set) {
1540       next USET unless ($colinfos->{$_} && !$colinfos->{$_}{is_nullable} );
1541     }
1542
1543     # copy so we can mangle it at will
1544     return [ @$set ];
1545   }
1546
1547   return undef;
1548 }
1549
1550 # Returns the {from} structure used to express JOIN conditions
1551 sub _resolve_join {
1552   my ($self, $join, $alias, $seen, $jpath, $parent_force_left) = @_;
1553
1554   # we need a supplied one, because we do in-place modifications, no returns
1555   $self->throw_exception ('You must supply a seen hashref as the 3rd argument to _resolve_join')
1556     unless ref $seen eq 'HASH';
1557
1558   $self->throw_exception ('You must supply a joinpath arrayref as the 4th argument to _resolve_join')
1559     unless ref $jpath eq 'ARRAY';
1560
1561   $jpath = [@$jpath]; # copy
1562
1563   if (not defined $join or not length $join) {
1564     return ();
1565   }
1566   elsif (ref $join eq 'ARRAY') {
1567     return
1568       map {
1569         $self->_resolve_join($_, $alias, $seen, $jpath, $parent_force_left);
1570       } @$join;
1571   }
1572   elsif (ref $join eq 'HASH') {
1573
1574     my @ret;
1575     for my $rel (keys %$join) {
1576
1577       my $rel_info = $self->relationship_info($rel)
1578         or $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
1579
1580       my $force_left = $parent_force_left;
1581       $force_left ||= lc($rel_info->{attrs}{join_type}||'') eq 'left';
1582
1583       # the actual seen value will be incremented by the recursion
1584       my $as = $self->storage->relname_to_table_alias(
1585         $rel, ($seen->{$rel} && $seen->{$rel} + 1)
1586       );
1587
1588       push @ret, (
1589         $self->_resolve_join($rel, $alias, $seen, [@$jpath], $force_left),
1590         $self->related_source($rel)->_resolve_join(
1591           $join->{$rel}, $as, $seen, [@$jpath, { $rel => $as }], $force_left
1592         )
1593       );
1594     }
1595     return @ret;
1596
1597   }
1598   elsif (ref $join) {
1599     $self->throw_exception("No idea how to resolve join reftype ".ref $join);
1600   }
1601   else {
1602     my $count = ++$seen->{$join};
1603     my $as = $self->storage->relname_to_table_alias(
1604       $join, ($count > 1 && $count)
1605     );
1606
1607     my $rel_info = $self->relationship_info($join)
1608       or $self->throw_exception("No such relationship $join on " . $self->source_name);
1609
1610     my $rel_src = $self->related_source($join);
1611     return [ { $as => $rel_src->from,
1612                -rsrc => $rel_src,
1613                -join_type => $parent_force_left
1614                   ? 'left'
1615                   : $rel_info->{attrs}{join_type}
1616                 ,
1617                -join_path => [@$jpath, { $join => $as } ],
1618                -is_single => (
1619                   (! $rel_info->{attrs}{accessor})
1620                     or
1621                   first { $rel_info->{attrs}{accessor} eq $_ } (qw/single filter/)
1622                 ),
1623                -alias => $as,
1624                -relation_chain_depth => ( $seen->{-relation_chain_depth} || 0 ) + 1,
1625              },
1626              scalar $self->_resolve_condition($rel_info->{cond}, $as, $alias, $join)
1627           ];
1628   }
1629 }
1630
1631 sub pk_depends_on {
1632   carp 'pk_depends_on is a private method, stop calling it';
1633   my $self = shift;
1634   $self->_pk_depends_on (@_);
1635 }
1636
1637 # Determines whether a relation is dependent on an object from this source
1638 # having already been inserted. Takes the name of the relationship and a
1639 # hashref of columns of the related object.
1640 sub _pk_depends_on {
1641   my ($self, $rel_name, $rel_data) = @_;
1642
1643   my $relinfo = $self->relationship_info($rel_name);
1644
1645   # don't assume things if the relationship direction is specified
1646   return $relinfo->{attrs}{is_foreign_key_constraint}
1647     if exists ($relinfo->{attrs}{is_foreign_key_constraint});
1648
1649   my $cond = $relinfo->{cond};
1650   return 0 unless ref($cond) eq 'HASH';
1651
1652   # map { foreign.foo => 'self.bar' } to { bar => 'foo' }
1653   my $keyhash = { map { my $x = $_; $x =~ s/.*\.//; $x; } reverse %$cond };
1654
1655   # assume anything that references our PK probably is dependent on us
1656   # rather than vice versa, unless the far side is (a) defined or (b)
1657   # auto-increment
1658   my $rel_source = $self->related_source($rel_name);
1659
1660   foreach my $p ($self->primary_columns) {
1661     if (exists $keyhash->{$p}) {
1662       unless (defined($rel_data->{$keyhash->{$p}})
1663               || $rel_source->column_info($keyhash->{$p})
1664                             ->{is_auto_increment}) {
1665         return 0;
1666       }
1667     }
1668   }
1669
1670   return 1;
1671 }
1672
1673 sub _resolve_condition {
1674 #  carp_unique sprintf
1675 #    '_resolve_condition is a private method, and moreover is about to go '
1676 #  . 'away. Please contact the development team at %s if you believe you '
1677 #  . 'have a genuine use for this method, in order to discuss alternatives.',
1678 #    DBIx::Class::_ENV_::HELP_URL,
1679 #  ;
1680
1681 #######################
1682 ### API Design? What's that...? (a backwards compatible shim, kill me now)
1683
1684   my ($self, $cond, @res_args, $rel_name);
1685
1686   # we *SIMPLY DON'T KNOW YET* which arg is which, yay
1687   ($self, $cond, $res_args[0], $res_args[1], $rel_name) = @_;
1688
1689   # assume that an undef is an object-like unset (set_from_related(undef))
1690   my @is_objlike = map { ! defined $_ or length ref $_ } (@res_args);
1691
1692   # turn objlike into proper objects for saner code further down
1693   for (0,1) {
1694     next unless $is_objlike[$_];
1695
1696     if ( defined blessed $res_args[$_] ) {
1697
1698       # but wait - there is more!!! WHAT THE FUCK?!?!?!?!
1699       if ($res_args[$_]->isa('DBIx::Class::ResultSet')) {
1700         carp('Passing a resultset for relationship resolution makes no sense - invoking __gremlins__');
1701         $is_objlike[$_] = 0;
1702         $res_args[$_] = '__gremlins__';
1703       }
1704     }
1705     else {
1706       $res_args[$_] ||= {};
1707
1708       # hate everywhere - have to pass in as a plain hash
1709       # pretending to be an object at least for now
1710       $self->throw_exception("Unsupported object-like structure encountered: $res_args[$_]")
1711         unless ref $res_args[$_] eq 'HASH';
1712     }
1713   }
1714
1715   $self->throw_exception('No practical way to resolve a relationship between two structures')
1716     if $is_objlike[0] and $is_objlike[1];
1717
1718   my $args = {
1719     condition => $cond,
1720
1721     # where-is-waldo block guesses relname, then further down we override it if available
1722     (
1723       $is_objlike[1] ? ( rel_name => $res_args[0], self_alias => $res_args[0], foreign_alias => 'me',         self_resultobj    => $res_args[1] )
1724     : $is_objlike[0] ? ( rel_name => $res_args[1], self_alias => 'me',         foreign_alias => $res_args[1], foreign_resultobj => $res_args[0] )
1725     :                  ( rel_name => $res_args[0], self_alias => $res_args[1], foreign_alias => $res_args[0]                                    )
1726     ),
1727
1728     ( $rel_name ? ( rel_name => $rel_name ) : () ),
1729   };
1730 #######################
1731
1732   # now it's fucking easy isn't it?!
1733   my $rc = $self->_resolve_relationship_condition( $args );
1734
1735   my @res = (
1736     ( $rc->{join_free_condition} || $rc->{condition} ),
1737     ! $rc->{join_free_condition},
1738   );
1739
1740   # _resolve_relationship_condition always returns qualified cols even in the
1741   # case of join_free_condition, but nothing downstream expects this
1742   if (ref $res[0] eq 'HASH' and ($is_objlike[0] or $is_objlike[1]) ) {
1743     $res[0] = { map
1744       { ($_ =~ /\.(.+)/) => $res[0]{$_} }
1745       keys %{$res[0]}
1746     };
1747   }
1748
1749   # and more legacy
1750   return wantarray ? @res : $res[0];
1751 }
1752
1753 # Keep this indefinitely. There is evidence of both CPAN and
1754 # darkpan using it, and there isn't much harm in an extra var
1755 # anyway.
1756 our $UNRESOLVABLE_CONDITION = UNRESOLVABLE_CONDITION;
1757 # YES I KNOW THIS IS EVIL
1758 # it is there to save darkpan from themselves, since internally
1759 # we are moving to a constant
1760 Internals::SvREADONLY($UNRESOLVABLE_CONDITION => 1);
1761
1762 # Resolves the passed condition to a concrete query fragment and extra
1763 # metadata
1764 #
1765 ## self-explanatory API, modeled on the custom cond coderef:
1766 # rel_name
1767 # foreign_alias
1768 # foreign_resultobj
1769 # self_alias
1770 # self_resultobj
1771 # require_join_free_condition
1772 # infer_values_based_on (optional, mandatory hashref argument)
1773 # condition (optional, derived from $self->rel_info(rel_name))
1774 #
1775 ## returns a hash
1776 # condition
1777 # identity_map
1778 # join_free_condition (maybe unset)
1779 # inferred_values (always either complete or unset)
1780 #
1781 sub _resolve_relationship_condition {
1782   my $self = shift;
1783
1784   my $args = { ref $_[0] eq 'HASH' ? %{ $_[0] } : @_ };
1785
1786   for ( qw( rel_name self_alias foreign_alias ) ) {
1787     $self->throw_exception("Mandatory argument '$_' to _resolve_relationship_condition() is not a plain string")
1788       if !defined $args->{$_} or length ref $args->{$_};
1789   }
1790
1791   my $exception_rel_id = "relationship '$args->{rel_name}' on source '@{[ $self->source_name ]}'";
1792
1793   my $rel_info = $self->relationship_info($args->{rel_name});
1794   #  or $self->throw_exception( "No such $exception_rel_id" );
1795
1796   $self->throw_exception("No practical way to resolve $exception_rel_id between two objects")
1797     if defined $args->{self_resultobj} and defined $args->{foreign_resultobj};
1798
1799   $self->throw_exception( "Argument to infer_values_based_on must be a hash" )
1800     if exists $args->{infer_values_based_on} and ref $args->{infer_values_based_on} ne 'HASH';
1801
1802   $args->{require_join_free_condition} ||= !!$args->{infer_values_based_on};
1803
1804   $args->{condition} ||= $rel_info->{cond};
1805
1806   if (exists $args->{self_resultobj}) {
1807     if (defined blessed $args->{self_resultobj}) {
1808 #      $self->throw_exception( "Object '$args->{self_resultobj}' must be of class '@{[ $self->result_class ]}'" )
1809 #        unless $args->{self_resultobj}->isa($self->result_class);
1810     }
1811     else {
1812       $args->{self_resultobj} = DBIx::Class::Core->new({
1813         -result_source => $self,
1814         %{ $args->{self_resultobj}||{} }
1815       });
1816     }
1817   }
1818
1819   if (exists $args->{foreign_resultobj}) {
1820     if (defined blessed $args->{foreign_resultobj}) {
1821 #      $self->throw_exception( "Object '$args->{foreign_resultobj}' must be of class '$rel_info->{class}'" )
1822 #        unless $args->{foreign_resultobj}->isa($rel_info->{class});
1823     }
1824     else {
1825       $args->{foreign_resultobj} = DBIx::Class::Core->new({
1826         -result_source => $self->related_source($args->{rel_name}),
1827         %{ $args->{foreign_resultobj}||{} }
1828       });
1829     }
1830   }
1831
1832   my $ret;
1833
1834   if (ref $args->{condition} eq 'CODE') {
1835
1836     my $cref_args = {
1837       rel_name => $args->{rel_name},
1838       self_resultsource => $self,
1839       self_alias => $args->{self_alias},
1840       foreign_alias => $args->{foreign_alias},
1841       ( map
1842         { (exists $args->{$_}) ? ( $_ => $args->{$_} ) : () }
1843         qw( self_resultobj foreign_resultobj )
1844       ),
1845     };
1846
1847     # legacy - never remove these!!!
1848     $cref_args->{foreign_relname} = $cref_args->{rel_name};
1849
1850     $cref_args->{self_rowobj} = $cref_args->{self_resultobj}
1851       if exists $cref_args->{self_resultobj};
1852
1853     ($ret->{condition}, $ret->{join_free_condition}, my @extra) = $args->{condition}->($cref_args);
1854
1855     # FIXME sanity check
1856     carp_unique('A custom condition coderef can return at most 2 conditions: extra return values discarded')
1857       if @extra;
1858
1859     if (my $jfc = $ret->{join_free_condition}) {
1860
1861       $self->throw_exception (
1862         "The join-free condition returned for $exception_rel_id must be a hash reference"
1863       ) unless ref $jfc eq 'HASH';
1864
1865       my ($joinfree_alias, $joinfree_source);
1866       if (defined $args->{self_resultobj}) {
1867         $joinfree_alias = $args->{foreign_alias};
1868         $joinfree_source = $self->related_source($args->{rel_name});
1869       }
1870       elsif (defined $args->{foreign_resultobj}) {
1871         $joinfree_alias = $args->{self_alias};
1872         $joinfree_source = $self;
1873       }
1874
1875       # FIXME sanity check until things stabilize, remove at some point
1876       $self->throw_exception (
1877         "A join-free condition returned for $exception_rel_id without a result object to chain from"
1878       ) unless $joinfree_alias;
1879
1880       my $fq_col_list = { map
1881         { ( "$joinfree_alias.$_" => 1 ) }
1882         $joinfree_source->columns
1883       };
1884
1885       $fq_col_list->{$_} or $self->throw_exception (
1886         "The join-free condition returned for $exception_rel_id may only "
1887       . 'contain keys that are fully qualified column names of the corresponding source'
1888       ) for keys %$jfc;
1889
1890     }
1891   }
1892   elsif (ref $args->{condition} eq 'HASH') {
1893
1894     # the condition is static - use parallel arrays
1895     # for a "pivot" depending on which side of the
1896     # rel did we get as an object
1897     my (@f_cols, @l_cols);
1898     for my $fc (keys %{$args->{condition}}) {
1899       my $lc = $args->{condition}{$fc};
1900
1901       # FIXME STRICTMODE should probably check these are valid columns
1902       $fc =~ s/^foreign\.// ||
1903         $self->throw_exception("Invalid rel cond key '$fc'");
1904
1905       $lc =~ s/^self\.// ||
1906         $self->throw_exception("Invalid rel cond val '$lc'");
1907
1908       push @f_cols, $fc;
1909       push @l_cols, $lc;
1910     }
1911
1912     # construct the crosstable condition and the identity map
1913     for  (0..$#f_cols) {
1914       $ret->{condition}{"$args->{foreign_alias}.$f_cols[$_]"} = { -ident => "$args->{self_alias}.$l_cols[$_]" };
1915       $ret->{identity_map}{$l_cols[$_]} = $f_cols[$_];
1916     };
1917
1918     if (exists $args->{self_resultobj} or exists $args->{foreign_resultobj}) {
1919
1920       my ($obj, $obj_alias, $plain_alias, $obj_cols, $plain_cols) = defined $args->{self_resultobj}
1921         ? ( @{$args}{qw( self_resultobj self_alias foreign_alias )}, \@l_cols, \@f_cols )
1922         : ( @{$args}{qw( foreign_resultobj foreign_alias self_alias )}, \@f_cols, \@l_cols )
1923       ;
1924
1925       for my $i (0..$#$obj_cols) {
1926
1927         if (
1928           defined $args->{self_resultobj}
1929             and
1930           ! $obj->has_column_loaded($obj_cols->[$i])
1931         ) {
1932
1933           $self->throw_exception(sprintf
1934             "Unable to resolve relationship '%s' from object '%s': column '%s' not "
1935           . 'loaded from storage (or not passed to new() prior to insert()). You '
1936           . 'probably need to call ->discard_changes to get the server-side defaults '
1937           . 'from the database.',
1938             $args->{rel_name},
1939             $obj,
1940             $obj_cols->[$i],
1941           ) if $obj->in_storage;
1942
1943           # FIXME - temporarly force-override
1944           delete $args->{require_join_free_condition};
1945           $ret->{join_free_condition} = UNRESOLVABLE_CONDITION;
1946           last;
1947         }
1948         else {
1949           $ret->{join_free_condition}{"$plain_alias.$plain_cols->[$i]"} = $obj->get_column($obj_cols->[$i]);
1950         }
1951       }
1952     }
1953   }
1954   elsif (ref $args->{condition} eq 'ARRAY') {
1955     if (@{$args->{condition}} == 0) {
1956       $ret = {
1957         condition => UNRESOLVABLE_CONDITION,
1958         join_free_condition => UNRESOLVABLE_CONDITION,
1959       };
1960     }
1961     elsif (@{$args->{condition}} == 1) {
1962       $ret = $self->_resolve_relationship_condition({
1963         %$args,
1964         condition => $args->{condition}[0],
1965       });
1966     }
1967     else {
1968       # we are discarding inferred values here... likely incorrect...
1969       # then again - the entire thing is an OR, so we *can't* use them anyway
1970       for my $subcond ( map
1971         { $self->_resolve_relationship_condition({ %$args, condition => $_ }) }
1972         @{$args->{condition}}
1973       ) {
1974         $self->throw_exception('Either all or none of the OR-condition members can resolve to a join-free condition')
1975           if $ret->{join_free_condition} and ! $subcond->{join_free_condition};
1976
1977         $subcond->{$_} and push @{$ret->{$_}}, $subcond->{$_} for (qw(condition join_free_condition));
1978       }
1979     }
1980   }
1981   else {
1982     $self->throw_exception ("Can't handle condition $args->{condition} for $exception_rel_id yet :(");
1983   }
1984
1985   $self->throw_exception(ucfirst "$exception_rel_id does not resolve to a join-free condition fragment") if (
1986     $args->{require_join_free_condition}
1987       and
1988     ( ! $ret->{join_free_condition} or $ret->{join_free_condition} eq UNRESOLVABLE_CONDITION )
1989   );
1990
1991   # we got something back - sanity check and infer values if we can
1992   my @nonvalues;
1993   if ( my $jfc = $ret->{join_free_condition} and $ret->{join_free_condition} ne UNRESOLVABLE_CONDITION ) {
1994
1995     my $jfc_eqs = $self->schema->storage->_extract_fixed_condition_columns($jfc, 'consider_nulls');
1996
1997     if (keys %$jfc_eqs) {
1998
1999       for (keys %$jfc) {
2000         # $jfc is fully qualified by definition
2001         my ($col) = $_ =~ /\.(.+)/;
2002
2003         if (exists $jfc_eqs->{$_} and ($jfc_eqs->{$_}||'') ne UNRESOLVABLE_CONDITION) {
2004           $ret->{inferred_values}{$col} = $jfc_eqs->{$_};
2005         }
2006         elsif ( !$args->{infer_values_based_on} or ! exists $args->{infer_values_based_on}{$col} ) {
2007           push @nonvalues, $col;
2008         }
2009       }
2010
2011       # all or nothing
2012       delete $ret->{inferred_values} if @nonvalues;
2013     }
2014   }
2015
2016   # did the user explicitly ask
2017   if ($args->{infer_values_based_on}) {
2018
2019     $self->throw_exception(sprintf (
2020       "Unable to complete value inferrence - custom $exception_rel_id returns conditions instead of values for column(s): %s",
2021       map { "'$_'" } @nonvalues
2022     )) if @nonvalues;
2023
2024
2025     $ret->{inferred_values} ||= {};
2026
2027     $ret->{inferred_values}{$_} = $args->{infer_values_based_on}{$_}
2028       for keys %{$args->{infer_values_based_on}};
2029   }
2030
2031   # add the identities based on the main condition
2032   # (may already be there, since easy to calculate on the fly in the HASH case)
2033   if ( ! $ret->{identity_map} ) {
2034
2035     my $col_eqs = $self->schema->storage->_extract_fixed_condition_columns($ret->{condition});
2036
2037     my $colinfos;
2038     for my $lhs (keys %$col_eqs) {
2039
2040       next if $col_eqs->{$lhs} eq UNRESOLVABLE_CONDITION;
2041       my ($rhs) = @{ is_literal_value( $ret->{condition}{$lhs} ) || next };
2042
2043       # there is no way to know who is right and who is left
2044       # therefore the ugly scan below
2045       $colinfos ||= $self->schema->storage->_resolve_column_info([
2046         { -alias => $args->{self_alias}, -rsrc => $self },
2047         { -alias => $args->{foreign_alias}, -rsrc => $self->related_source($args->{rel_name}) },
2048       ]);
2049
2050       my ($l_col, $l_alias, $r_col, $r_alias) = map {
2051         ( reverse $_ =~ / ^ (?: ([^\.]+) $ | ([^\.]+) \. (.+) ) /x )[0,1]
2052       } ($lhs, $rhs);
2053
2054       if (
2055         $colinfos->{$l_col}
2056           and
2057         $colinfos->{$r_col}
2058           and
2059         $colinfos->{$l_col}{-source_alias} ne $colinfos->{$r_col}{-source_alias}
2060       ) {
2061         ( $colinfos->{$l_col}{-source_alias} eq $args->{self_alias} )
2062           ? ( $ret->{identity_map}{$l_col} = $r_col )
2063           : ( $ret->{identity_map}{$r_col} = $l_col )
2064         ;
2065       }
2066     }
2067   }
2068
2069   $ret
2070 }
2071
2072 =head2 related_source
2073
2074 =over 4
2075
2076 =item Arguments: $rel_name
2077
2078 =item Return Value: $source
2079
2080 =back
2081
2082 Returns the result source object for the given relationship.
2083
2084 =cut
2085
2086 sub related_source {
2087   my ($self, $rel) = @_;
2088   if( !$self->has_relationship( $rel ) ) {
2089     $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
2090   }
2091
2092   # if we are not registered with a schema - just use the prototype
2093   # however if we do have a schema - ask for the source by name (and
2094   # throw in the process if all fails)
2095   if (my $schema = try { $self->schema }) {
2096     $schema->source($self->relationship_info($rel)->{source});
2097   }
2098   else {
2099     my $class = $self->relationship_info($rel)->{class};
2100     $self->ensure_class_loaded($class);
2101     $class->result_source_instance;
2102   }
2103 }
2104
2105 =head2 related_class
2106
2107 =over 4
2108
2109 =item Arguments: $rel_name
2110
2111 =item Return Value: $classname
2112
2113 =back
2114
2115 Returns the class name for objects in the given relationship.
2116
2117 =cut
2118
2119 sub related_class {
2120   my ($self, $rel) = @_;
2121   if( !$self->has_relationship( $rel ) ) {
2122     $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
2123   }
2124   return $self->schema->class($self->relationship_info($rel)->{source});
2125 }
2126
2127 =head2 handle
2128
2129 =over 4
2130
2131 =item Arguments: none
2132
2133 =item Return Value: L<$source_handle|DBIx::Class::ResultSourceHandle>
2134
2135 =back
2136
2137 Obtain a new L<result source handle instance|DBIx::Class::ResultSourceHandle>
2138 for this source. Used as a serializable pointer to this resultsource, as it is not
2139 easy (nor advisable) to serialize CODErefs which may very well be present in e.g.
2140 relationship definitions.
2141
2142 =cut
2143
2144 sub handle {
2145   return DBIx::Class::ResultSourceHandle->new({
2146     source_moniker => $_[0]->source_name,
2147
2148     # so that a detached thaw can be re-frozen
2149     $_[0]->{_detached_thaw}
2150       ? ( _detached_source  => $_[0]          )
2151       : ( schema            => $_[0]->schema  )
2152     ,
2153   });
2154 }
2155
2156 my $global_phase_destroy;
2157 sub DESTROY {
2158   return if $global_phase_destroy ||= in_global_destruction;
2159
2160 ######
2161 # !!! ACHTUNG !!!!
2162 ######
2163 #
2164 # Under no circumstances shall $_[0] be stored anywhere else (like copied to
2165 # a lexical variable, or shifted, or anything else). Doing so will mess up
2166 # the refcount of this particular result source, and will allow the $schema
2167 # we are trying to save to reattach back to the source we are destroying.
2168 # The relevant code checking refcounts is in ::Schema::DESTROY()
2169
2170   # if we are not a schema instance holder - we don't matter
2171   return if(
2172     ! ref $_[0]->{schema}
2173       or
2174     isweak $_[0]->{schema}
2175   );
2176
2177   # weaken our schema hold forcing the schema to find somewhere else to live
2178   # during global destruction (if we have not yet bailed out) this will throw
2179   # which will serve as a signal to not try doing anything else
2180   # however beware - on older perls the exception seems randomly untrappable
2181   # due to some weird race condition during thread joining :(((
2182   local $@;
2183   eval {
2184     weaken $_[0]->{schema};
2185
2186     # if schema is still there reintroduce ourselves with strong refs back to us
2187     if ($_[0]->{schema}) {
2188       my $srcregs = $_[0]->{schema}->source_registrations;
2189       for (keys %$srcregs) {
2190         next unless $srcregs->{$_};
2191         $srcregs->{$_} = $_[0] if $srcregs->{$_} == $_[0];
2192       }
2193     }
2194
2195     1;
2196   } or do {
2197     $global_phase_destroy = 1;
2198   };
2199
2200   return;
2201 }
2202
2203 sub STORABLE_freeze { Storable::nfreeze($_[0]->handle) }
2204
2205 sub STORABLE_thaw {
2206   my ($self, $cloning, $ice) = @_;
2207   %$self = %{ (Storable::thaw($ice))->resolve };
2208 }
2209
2210 =head2 throw_exception
2211
2212 See L<DBIx::Class::Schema/"throw_exception">.
2213
2214 =cut
2215
2216 sub throw_exception {
2217   my $self = shift;
2218
2219   $self->{schema}
2220     ? $self->{schema}->throw_exception(@_)
2221     : DBIx::Class::Exception->throw(@_)
2222   ;
2223 }
2224
2225 =head2 source_info
2226
2227 Stores a hashref of per-source metadata.  No specific key names
2228 have yet been standardized, the examples below are purely hypothetical
2229 and don't actually accomplish anything on their own:
2230
2231   __PACKAGE__->source_info({
2232     "_tablespace" => 'fast_disk_array_3',
2233     "_engine" => 'InnoDB',
2234   });
2235
2236 =head2 new
2237
2238   $class->new();
2239
2240   $class->new({attribute_name => value});
2241
2242 Creates a new ResultSource object.  Not normally called directly by end users.
2243
2244 =head2 column_info_from_storage
2245
2246 =over
2247
2248 =item Arguments: 1/0 (default: 0)
2249
2250 =item Return Value: 1/0
2251
2252 =back
2253
2254   __PACKAGE__->column_info_from_storage(1);
2255
2256 Enables the on-demand automatic loading of the above column
2257 metadata from storage as necessary.  This is *deprecated*, and
2258 should not be used.  It will be removed before 1.0.
2259
2260
2261 =head1 AUTHOR AND CONTRIBUTORS
2262
2263 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
2264
2265 =head1 LICENSE
2266
2267 You may distribute this code under the same terms as Perl itself.
2268
2269 =cut
2270
2271 1;