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