Sanity-check columns added as primary key
[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 Devel::GlobalDestruction;
13 use Try::Tiny;
14 use List::Util 'first';
15 use Scalar::Util qw/blessed weaken isweak/;
16
17 use namespace::clean;
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 || $self->name || 'Unknown source...?',
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
592   my $colinfo = $self->columns_info(\@cols);
593   for my $col (@cols) {
594     carp_unique(sprintf (
595       "Primary key of source '%s' includes the column '%s' which has its "
596     . "'is_nullable' attribute set to true. This is a mistake and will cause "
597     . 'various Result-object operations to fail',
598       $self->source_name || $self->name || 'Unknown source...?',
599       $col,
600     )) if $colinfo->{$col}{is_nullable};
601   }
602
603   $self->_primaries(\@cols);
604
605   $self->add_unique_constraint(primary => \@cols);
606 }
607
608 =head2 primary_columns
609
610 =over 4
611
612 =item Arguments: none
613
614 =item Return Value: Ordered list of primary column names
615
616 =back
617
618 Read-only accessor which returns the list of primary keys, supplied by
619 L</set_primary_key>.
620
621 =cut
622
623 sub primary_columns {
624   return @{shift->_primaries||[]};
625 }
626
627 # a helper method that will automatically die with a descriptive message if
628 # no pk is defined on the source in question. For internal use to save
629 # on if @pks... boilerplate
630 sub _pri_cols {
631   my $self = shift;
632   my @pcols = $self->primary_columns
633     or $self->throw_exception (sprintf(
634       "Operation requires a primary key to be declared on '%s' via set_primary_key",
635       # source_name is set only after schema-registration
636       $self->source_name || $self->result_class || $self->name || 'Unknown source...?',
637     ));
638   return @pcols;
639 }
640
641 =head2 sequence
642
643 Manually define the correct sequence for your table, to avoid the overhead
644 associated with looking up the sequence automatically. The supplied sequence
645 will be applied to the L</column_info> of each L<primary_key|/set_primary_key>
646
647 =over 4
648
649 =item Arguments: $sequence_name
650
651 =item Return Value: not defined
652
653 =back
654
655 =cut
656
657 sub sequence {
658   my ($self,$seq) = @_;
659
660   my @pks = $self->primary_columns
661     or return;
662
663   $_->{sequence} = $seq
664     for values %{ $self->columns_info (\@pks) };
665 }
666
667
668 =head2 add_unique_constraint
669
670 =over 4
671
672 =item Arguments: $name?, \@colnames
673
674 =item Return Value: not defined
675
676 =back
677
678 Declare a unique constraint on this source. Call once for each unique
679 constraint.
680
681   # For UNIQUE (column1, column2)
682   __PACKAGE__->add_unique_constraint(
683     constraint_name => [ qw/column1 column2/ ],
684   );
685
686 Alternatively, you can specify only the columns:
687
688   __PACKAGE__->add_unique_constraint([ qw/column1 column2/ ]);
689
690 This will result in a unique constraint named
691 C<table_column1_column2>, where C<table> is replaced with the table
692 name.
693
694 Unique constraints are used, for example, when you pass the constraint
695 name as the C<key> attribute to L<DBIx::Class::ResultSet/find>. Then
696 only columns in the constraint are searched.
697
698 Throws an error if any of the given column names do not yet exist on
699 the result source.
700
701 =cut
702
703 sub add_unique_constraint {
704   my $self = shift;
705
706   if (@_ > 2) {
707     $self->throw_exception(
708         'add_unique_constraint() does not accept multiple constraints, use '
709       . 'add_unique_constraints() instead'
710     );
711   }
712
713   my $cols = pop @_;
714   if (ref $cols ne 'ARRAY') {
715     $self->throw_exception (
716       'Expecting an arrayref of constraint columns, got ' . ($cols||'NOTHING')
717     );
718   }
719
720   my $name = shift @_;
721
722   $name ||= $self->name_unique_constraint($cols);
723
724   foreach my $col (@$cols) {
725     $self->throw_exception("No such column $col on table " . $self->name)
726       unless $self->has_column($col);
727   }
728
729   my %unique_constraints = $self->unique_constraints;
730   $unique_constraints{$name} = $cols;
731   $self->_unique_constraints(\%unique_constraints);
732 }
733
734 =head2 add_unique_constraints
735
736 =over 4
737
738 =item Arguments: @constraints
739
740 =item Return Value: not defined
741
742 =back
743
744 Declare multiple unique constraints on this source.
745
746   __PACKAGE__->add_unique_constraints(
747     constraint_name1 => [ qw/column1 column2/ ],
748     constraint_name2 => [ qw/column2 column3/ ],
749   );
750
751 Alternatively, you can specify only the columns:
752
753   __PACKAGE__->add_unique_constraints(
754     [ qw/column1 column2/ ],
755     [ qw/column3 column4/ ]
756   );
757
758 This will result in unique constraints named C<table_column1_column2> and
759 C<table_column3_column4>, where C<table> is replaced with the table name.
760
761 Throws an error if any of the given column names do not yet exist on
762 the result source.
763
764 See also L</add_unique_constraint>.
765
766 =cut
767
768 sub add_unique_constraints {
769   my $self = shift;
770   my @constraints = @_;
771
772   if ( !(@constraints % 2) && first { ref $_ ne 'ARRAY' } @constraints ) {
773     # with constraint name
774     while (my ($name, $constraint) = splice @constraints, 0, 2) {
775       $self->add_unique_constraint($name => $constraint);
776     }
777   }
778   else {
779     # no constraint name
780     foreach my $constraint (@constraints) {
781       $self->add_unique_constraint($constraint);
782     }
783   }
784 }
785
786 =head2 name_unique_constraint
787
788 =over 4
789
790 =item Arguments: \@colnames
791
792 =item Return Value: Constraint name
793
794 =back
795
796   $source->table('mytable');
797   $source->name_unique_constraint(['col1', 'col2']);
798   # returns
799   'mytable_col1_col2'
800
801 Return a name for a unique constraint containing the specified
802 columns. The name is created by joining the table name and each column
803 name, using an underscore character.
804
805 For example, a constraint on a table named C<cd> containing the columns
806 C<artist> and C<title> would result in a constraint name of C<cd_artist_title>.
807
808 This is used by L</add_unique_constraint> if you do not specify the
809 optional constraint name.
810
811 =cut
812
813 sub name_unique_constraint {
814   my ($self, $cols) = @_;
815
816   my $name = $self->name;
817   $name = $$name if (ref $name eq 'SCALAR');
818
819   return join '_', $name, @$cols;
820 }
821
822 =head2 unique_constraints
823
824 =over 4
825
826 =item Arguments: none
827
828 =item Return Value: Hash of unique constraint data
829
830 =back
831
832   $source->unique_constraints();
833
834 Read-only accessor which returns a hash of unique constraints on this
835 source.
836
837 The hash is keyed by constraint name, and contains an arrayref of
838 column names as values.
839
840 =cut
841
842 sub unique_constraints {
843   return %{shift->_unique_constraints||{}};
844 }
845
846 =head2 unique_constraint_names
847
848 =over 4
849
850 =item Arguments: none
851
852 =item Return Value: Unique constraint names
853
854 =back
855
856   $source->unique_constraint_names();
857
858 Returns the list of unique constraint names defined on this source.
859
860 =cut
861
862 sub unique_constraint_names {
863   my ($self) = @_;
864
865   my %unique_constraints = $self->unique_constraints;
866
867   return keys %unique_constraints;
868 }
869
870 =head2 unique_constraint_columns
871
872 =over 4
873
874 =item Arguments: $constraintname
875
876 =item Return Value: List of constraint columns
877
878 =back
879
880   $source->unique_constraint_columns('myconstraint');
881
882 Returns the list of columns that make up the specified unique constraint.
883
884 =cut
885
886 sub unique_constraint_columns {
887   my ($self, $constraint_name) = @_;
888
889   my %unique_constraints = $self->unique_constraints;
890
891   $self->throw_exception(
892     "Unknown unique constraint $constraint_name on '" . $self->name . "'"
893   ) unless exists $unique_constraints{$constraint_name};
894
895   return @{ $unique_constraints{$constraint_name} };
896 }
897
898 =head2 sqlt_deploy_callback
899
900 =over
901
902 =item Arguments: $callback_name | \&callback_code
903
904 =item Return Value: $callback_name | \&callback_code
905
906 =back
907
908   __PACKAGE__->sqlt_deploy_callback('mycallbackmethod');
909
910    or
911
912   __PACKAGE__->sqlt_deploy_callback(sub {
913     my ($source_instance, $sqlt_table) = @_;
914     ...
915   } );
916
917 An accessor to set a callback to be called during deployment of
918 the schema via L<DBIx::Class::Schema/create_ddl_dir> or
919 L<DBIx::Class::Schema/deploy>.
920
921 The callback can be set as either a code reference or the name of a
922 method in the current result class.
923
924 Defaults to L</default_sqlt_deploy_hook>.
925
926 Your callback will be passed the $source object representing the
927 ResultSource instance being deployed, and the
928 L<SQL::Translator::Schema::Table> object being created from it. The
929 callback can be used to manipulate the table object or add your own
930 customised indexes. If you need to manipulate a non-table object, use
931 the L<DBIx::Class::Schema/sqlt_deploy_hook>.
932
933 See L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To
934 Your SQL> for examples.
935
936 This sqlt deployment callback can only be used to manipulate
937 SQL::Translator objects as they get turned into SQL. To execute
938 post-deploy statements which SQL::Translator does not currently
939 handle, override L<DBIx::Class::Schema/deploy> in your Schema class
940 and call L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
941
942 =head2 default_sqlt_deploy_hook
943
944 This is the default deploy hook implementation which checks if your
945 current Result class has a C<sqlt_deploy_hook> method, and if present
946 invokes it B<on the Result class directly>. This is to preserve the
947 semantics of C<sqlt_deploy_hook> which was originally designed to expect
948 the Result class name and the
949 L<$sqlt_table instance|SQL::Translator::Schema::Table> of the table being
950 deployed.
951
952 =cut
953
954 sub default_sqlt_deploy_hook {
955   my $self = shift;
956
957   my $class = $self->result_class;
958
959   if ($class and $class->can('sqlt_deploy_hook')) {
960     $class->sqlt_deploy_hook(@_);
961   }
962 }
963
964 sub _invoke_sqlt_deploy_hook {
965   my $self = shift;
966   if ( my $hook = $self->sqlt_deploy_callback) {
967     $self->$hook(@_);
968   }
969 }
970
971 =head2 result_class
972
973 =over 4
974
975 =item Arguments: $classname
976
977 =item Return Value: $classname
978
979 =back
980
981  use My::Schema::ResultClass::Inflator;
982  ...
983
984  use My::Schema::Artist;
985  ...
986  __PACKAGE__->result_class('My::Schema::ResultClass::Inflator');
987
988 Set the default result class for this source. You can use this to create
989 and use your own result inflator. See L<DBIx::Class::ResultSet/result_class>
990 for more details.
991
992 Please note that setting this to something like
993 L<DBIx::Class::ResultClass::HashRefInflator> will make every result unblessed
994 and make life more difficult.  Inflators like those are better suited to
995 temporary usage via L<DBIx::Class::ResultSet/result_class>.
996
997 =head2 resultset
998
999 =over 4
1000
1001 =item Arguments: none
1002
1003 =item Return Value: L<$resultset|DBIx::Class::ResultSet>
1004
1005 =back
1006
1007 Returns a resultset for the given source. This will initially be created
1008 on demand by calling
1009
1010   $self->resultset_class->new($self, $self->resultset_attributes)
1011
1012 but is cached from then on unless resultset_class changes.
1013
1014 =head2 resultset_class
1015
1016 =over 4
1017
1018 =item Arguments: $classname
1019
1020 =item Return Value: $classname
1021
1022 =back
1023
1024   package My::Schema::ResultSet::Artist;
1025   use base 'DBIx::Class::ResultSet';
1026   ...
1027
1028   # In the result class
1029   __PACKAGE__->resultset_class('My::Schema::ResultSet::Artist');
1030
1031   # Or in code
1032   $source->resultset_class('My::Schema::ResultSet::Artist');
1033
1034 Set the class of the resultset. This is useful if you want to create your
1035 own resultset methods. Create your own class derived from
1036 L<DBIx::Class::ResultSet>, and set it here. If called with no arguments,
1037 this method returns the name of the existing resultset class, if one
1038 exists.
1039
1040 =head2 resultset_attributes
1041
1042 =over 4
1043
1044 =item Arguments: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
1045
1046 =item Return Value: L<\%attrs|DBIx::Class::ResultSet/ATTRIBUTES>
1047
1048 =back
1049
1050   # In the result class
1051   __PACKAGE__->resultset_attributes({ order_by => [ 'id' ] });
1052
1053   # Or in code
1054   $source->resultset_attributes({ order_by => [ 'id' ] });
1055
1056 Store a collection of resultset attributes, that will be set on every
1057 L<DBIx::Class::ResultSet> produced from this result source.
1058
1059 B<CAVEAT>: C<resultset_attributes> comes with its own set of issues and
1060 bugs! While C<resultset_attributes> isn't deprecated per se, its usage is
1061 not recommended!
1062
1063 Since relationships use attributes to link tables together, the "default"
1064 attributes you set may cause unpredictable and undesired behavior.  Furthermore,
1065 the defaults cannot be turned off, so you are stuck with them.
1066
1067 In most cases, what you should actually be using are project-specific methods:
1068
1069   package My::Schema::ResultSet::Artist;
1070   use base 'DBIx::Class::ResultSet';
1071   ...
1072
1073   # BAD IDEA!
1074   #__PACKAGE__->resultset_attributes({ prefetch => 'tracks' });
1075
1076   # GOOD IDEA!
1077   sub with_tracks { shift->search({}, { prefetch => 'tracks' }) }
1078
1079   # in your code
1080   $schema->resultset('Artist')->with_tracks->...
1081
1082 This gives you the flexibility of not using it when you don't need it.
1083
1084 For more complex situations, another solution would be to use a virtual view
1085 via L<DBIx::Class::ResultSource::View>.
1086
1087 =cut
1088
1089 sub resultset {
1090   my $self = shift;
1091   $self->throw_exception(
1092     'resultset does not take any arguments. If you want another resultset, '.
1093     'call it on the schema instead.'
1094   ) if scalar @_;
1095
1096   $self->resultset_class->new(
1097     $self,
1098     {
1099       try { %{$self->schema->default_resultset_attributes} },
1100       %{$self->{resultset_attributes}},
1101     },
1102   );
1103 }
1104
1105 =head2 name
1106
1107 =over 4
1108
1109 =item Arguments: none
1110
1111 =item Result value: $name
1112
1113 =back
1114
1115 Returns the name of the result source, which will typically be the table
1116 name. This may be a scalar reference if the result source has a non-standard
1117 name.
1118
1119 =head2 source_name
1120
1121 =over 4
1122
1123 =item Arguments: $source_name
1124
1125 =item Result value: $source_name
1126
1127 =back
1128
1129 Set an alternate name for the result source when it is loaded into a schema.
1130 This is useful if you want to refer to a result source by a name other than
1131 its class name.
1132
1133   package ArchivedBooks;
1134   use base qw/DBIx::Class/;
1135   __PACKAGE__->table('books_archive');
1136   __PACKAGE__->source_name('Books');
1137
1138   # from your schema...
1139   $schema->resultset('Books')->find(1);
1140
1141 =head2 from
1142
1143 =over 4
1144
1145 =item Arguments: none
1146
1147 =item Return Value: FROM clause
1148
1149 =back
1150
1151   my $from_clause = $source->from();
1152
1153 Returns an expression of the source to be supplied to storage to specify
1154 retrieval from this source. In the case of a database, the required FROM
1155 clause contents.
1156
1157 =cut
1158
1159 sub from { die 'Virtual method!' }
1160
1161 =head2 schema
1162
1163 =over 4
1164
1165 =item Arguments: L<$schema?|DBIx::Class::Schema>
1166
1167 =item Return Value: L<$schema|DBIx::Class::Schema>
1168
1169 =back
1170
1171   my $schema = $source->schema();
1172
1173 Sets and/or returns the L<DBIx::Class::Schema> object to which this
1174 result source instance has been attached to.
1175
1176 =cut
1177
1178 sub schema {
1179   if (@_ > 1) {
1180     $_[0]->{schema} = $_[1];
1181   }
1182   else {
1183     $_[0]->{schema} || do {
1184       my $name = $_[0]->{source_name} || '_unnamed_';
1185       my $err = 'Unable to perform storage-dependent operations with a detached result source '
1186               . "(source '$name' is not associated with a schema).";
1187
1188       $err .= ' You need to use $schema->thaw() or manually set'
1189             . ' $DBIx::Class::ResultSourceHandle::thaw_schema while thawing.'
1190         if $_[0]->{_detached_thaw};
1191
1192       DBIx::Class::Exception->throw($err);
1193     };
1194   }
1195 }
1196
1197 =head2 storage
1198
1199 =over 4
1200
1201 =item Arguments: none
1202
1203 =item Return Value: L<$storage|DBIx::Class::Storage>
1204
1205 =back
1206
1207   $source->storage->debug(1);
1208
1209 Returns the L<storage handle|DBIx::Class::Storage> for the current schema.
1210
1211 =cut
1212
1213 sub storage { shift->schema->storage; }
1214
1215 =head2 add_relationship
1216
1217 =over 4
1218
1219 =item Arguments: $rel_name, $related_source_name, \%cond, \%attrs?
1220
1221 =item Return Value: 1/true if it succeeded
1222
1223 =back
1224
1225   $source->add_relationship('rel_name', 'related_source', $cond, $attrs);
1226
1227 L<DBIx::Class::Relationship> describes a series of methods which
1228 create pre-defined useful types of relationships. Look there first
1229 before using this method directly.
1230
1231 The relationship name can be arbitrary, but must be unique for each
1232 relationship attached to this result source. 'related_source' should
1233 be the name with which the related result source was registered with
1234 the current schema. For example:
1235
1236   $schema->source('Book')->add_relationship('reviews', 'Review', {
1237     'foreign.book_id' => 'self.id',
1238   });
1239
1240 The condition C<$cond> needs to be an L<SQL::Abstract>-style
1241 representation of the join between the tables. For example, if you're
1242 creating a relation from Author to Book,
1243
1244   { 'foreign.author_id' => 'self.id' }
1245
1246 will result in the JOIN clause
1247
1248   author me JOIN book foreign ON foreign.author_id = me.id
1249
1250 You can specify as many foreign => self mappings as necessary.
1251
1252 Valid attributes are as follows:
1253
1254 =over 4
1255
1256 =item join_type
1257
1258 Explicitly specifies the type of join to use in the relationship. Any
1259 SQL join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in
1260 the SQL command immediately before C<JOIN>.
1261
1262 =item proxy
1263
1264 An arrayref containing a list of accessors in the foreign class to proxy in
1265 the main class. If, for example, you do the following:
1266
1267   CD->might_have(liner_notes => 'LinerNotes', undef, {
1268     proxy => [ qw/notes/ ],
1269   });
1270
1271 Then, assuming LinerNotes has an accessor named notes, you can do:
1272
1273   my $cd = CD->find(1);
1274   # set notes -- LinerNotes object is created if it doesn't exist
1275   $cd->notes('Notes go here');
1276
1277 =item accessor
1278
1279 Specifies the type of accessor that should be created for the
1280 relationship. Valid values are C<single> (for when there is only a single
1281 related object), C<multi> (when there can be many), and C<filter> (for
1282 when there is a single related object, but you also want the relationship
1283 accessor to double as a column accessor). For C<multi> accessors, an
1284 add_to_* method is also created, which calls C<create_related> for the
1285 relationship.
1286
1287 =back
1288
1289 Throws an exception if the condition is improperly supplied, or cannot
1290 be resolved.
1291
1292 =cut
1293
1294 sub add_relationship {
1295   my ($self, $rel, $f_source_name, $cond, $attrs) = @_;
1296   $self->throw_exception("Can't create relationship without join condition")
1297     unless $cond;
1298   $attrs ||= {};
1299
1300   # Check foreign and self are right in cond
1301   if ( (ref $cond ||'') eq 'HASH') {
1302     for (keys %$cond) {
1303       $self->throw_exception("Keys of condition should be of form 'foreign.col', not '$_'")
1304         if /\./ && !/^foreign\./;
1305     }
1306   }
1307
1308   my %rels = %{ $self->_relationships };
1309   $rels{$rel} = { class => $f_source_name,
1310                   source => $f_source_name,
1311                   cond  => $cond,
1312                   attrs => $attrs };
1313   $self->_relationships(\%rels);
1314
1315   return $self;
1316
1317 # XXX disabled. doesn't work properly currently. skip in tests.
1318
1319   my $f_source = $self->schema->source($f_source_name);
1320   unless ($f_source) {
1321     $self->ensure_class_loaded($f_source_name);
1322     $f_source = $f_source_name->result_source;
1323     #my $s_class = ref($self->schema);
1324     #$f_source_name =~ m/^${s_class}::(.*)$/;
1325     #$self->schema->register_class(($1 || $f_source_name), $f_source_name);
1326     #$f_source = $self->schema->source($f_source_name);
1327   }
1328   return unless $f_source; # Can't test rel without f_source
1329
1330   try { $self->_resolve_join($rel, 'me', {}, []) }
1331   catch {
1332     # If the resolve failed, back out and re-throw the error
1333     delete $rels{$rel};
1334     $self->_relationships(\%rels);
1335     $self->throw_exception("Error creating relationship $rel: $_");
1336   };
1337
1338   1;
1339 }
1340
1341 =head2 relationships
1342
1343 =over 4
1344
1345 =item Arguments: none
1346
1347 =item Return Value: L<@rel_names|DBIx::Class::Relationship>
1348
1349 =back
1350
1351   my @relnames = $source->relationships();
1352
1353 Returns all relationship names for this source.
1354
1355 =cut
1356
1357 sub relationships {
1358   return keys %{shift->_relationships};
1359 }
1360
1361 =head2 relationship_info
1362
1363 =over 4
1364
1365 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1366
1367 =item Return Value: L<\%rel_data|DBIx::Class::Relationship::Base/add_relationship>
1368
1369 =back
1370
1371 Returns a hash of relationship information for the specified relationship
1372 name. The keys/values are as specified for L<DBIx::Class::Relationship::Base/add_relationship>.
1373
1374 =cut
1375
1376 sub relationship_info {
1377   #my ($self, $rel) = @_;
1378   return shift->_relationships->{+shift};
1379 }
1380
1381 =head2 has_relationship
1382
1383 =over 4
1384
1385 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1386
1387 =item Return Value: 1/0 (true/false)
1388
1389 =back
1390
1391 Returns true if the source has a relationship of this name, false otherwise.
1392
1393 =cut
1394
1395 sub has_relationship {
1396   #my ($self, $rel) = @_;
1397   return exists shift->_relationships->{+shift};
1398 }
1399
1400 =head2 reverse_relationship_info
1401
1402 =over 4
1403
1404 =item Arguments: L<$rel_name|DBIx::Class::Relationship>
1405
1406 =item Return Value: L<\%rel_data|DBIx::Class::Relationship::Base/add_relationship>
1407
1408 =back
1409
1410 Looks through all the relationships on the source this relationship
1411 points to, looking for one whose condition is the reverse of the
1412 condition on this relationship.
1413
1414 A common use of this is to find the name of the C<belongs_to> relation
1415 opposing a C<has_many> relation. For definition of these look in
1416 L<DBIx::Class::Relationship>.
1417
1418 The returned hashref is keyed by the name of the opposing
1419 relationship, and contains its data in the same manner as
1420 L</relationship_info>.
1421
1422 =cut
1423
1424 sub reverse_relationship_info {
1425   my ($self, $rel) = @_;
1426
1427   my $rel_info = $self->relationship_info($rel)
1428     or $self->throw_exception("No such relationship '$rel'");
1429
1430   my $ret = {};
1431
1432   return $ret unless ((ref $rel_info->{cond}) eq 'HASH');
1433
1434   my $stripped_cond = $self->__strip_relcond ($rel_info->{cond});
1435
1436   my $rsrc_schema_moniker = $self->source_name
1437     if try { $self->schema };
1438
1439   # this may be a partial schema or something else equally esoteric
1440   my $other_rsrc = try { $self->related_source($rel) }
1441     or return $ret;
1442
1443   # Get all the relationships for that source that related to this source
1444   # whose foreign column set are our self columns on $rel and whose self
1445   # columns are our foreign columns on $rel
1446   foreach my $other_rel ($other_rsrc->relationships) {
1447
1448     # only consider stuff that points back to us
1449     # "us" here is tricky - if we are in a schema registration, we want
1450     # to use the source_names, otherwise we will use the actual classes
1451
1452     # the schema may be partial
1453     my $roundtrip_rsrc = try { $other_rsrc->related_source($other_rel) }
1454       or next;
1455
1456     if ($rsrc_schema_moniker and try { $roundtrip_rsrc->schema } ) {
1457       next unless $rsrc_schema_moniker eq $roundtrip_rsrc->source_name;
1458     }
1459     else {
1460       next unless $self->result_class eq $roundtrip_rsrc->result_class;
1461     }
1462
1463     my $other_rel_info = $other_rsrc->relationship_info($other_rel);
1464
1465     # this can happen when we have a self-referential class
1466     next if $other_rel_info eq $rel_info;
1467
1468     next unless ref $other_rel_info->{cond} eq 'HASH';
1469     my $other_stripped_cond = $self->__strip_relcond($other_rel_info->{cond});
1470
1471     $ret->{$other_rel} = $other_rel_info if (
1472       $self->_compare_relationship_keys (
1473         [ keys %$stripped_cond ], [ values %$other_stripped_cond ]
1474       )
1475         and
1476       $self->_compare_relationship_keys (
1477         [ values %$stripped_cond ], [ keys %$other_stripped_cond ]
1478       )
1479     );
1480   }
1481
1482   return $ret;
1483 }
1484
1485 # all this does is removes the foreign/self prefix from a condition
1486 sub __strip_relcond {
1487   +{
1488     map
1489       { map { /^ (?:foreign|self) \. (\w+) $/x } ($_, $_[1]{$_}) }
1490       keys %{$_[1]}
1491   }
1492 }
1493
1494 sub compare_relationship_keys {
1495   carp 'compare_relationship_keys is a private method, stop calling it';
1496   my $self = shift;
1497   $self->_compare_relationship_keys (@_);
1498 }
1499
1500 # Returns true if both sets of keynames are the same, false otherwise.
1501 sub _compare_relationship_keys {
1502 #  my ($self, $keys1, $keys2) = @_;
1503   return
1504     join ("\x00", sort @{$_[1]})
1505       eq
1506     join ("\x00", sort @{$_[2]})
1507   ;
1508 }
1509
1510 # optionally takes either an arrayref of column names, or a hashref of already
1511 # retrieved colinfos
1512 # returns an arrayref of column names of the shortest unique constraint
1513 # (matching some of the input if any), giving preference to the PK
1514 sub _identifying_column_set {
1515   my ($self, $cols) = @_;
1516
1517   my %unique = $self->unique_constraints;
1518   my $colinfos = ref $cols eq 'HASH' ? $cols : $self->columns_info($cols||());
1519
1520   # always prefer the PK first, and then shortest constraints first
1521   USET:
1522   for my $set (delete $unique{primary}, sort { @$a <=> @$b } (values %unique) ) {
1523     next unless $set && @$set;
1524
1525     for (@$set) {
1526       next USET unless ($colinfos->{$_} && !$colinfos->{$_}{is_nullable} );
1527     }
1528
1529     # copy so we can mangle it at will
1530     return [ @$set ];
1531   }
1532
1533   return undef;
1534 }
1535
1536 # Returns the {from} structure used to express JOIN conditions
1537 sub _resolve_join {
1538   my ($self, $join, $alias, $seen, $jpath, $parent_force_left) = @_;
1539
1540   # we need a supplied one, because we do in-place modifications, no returns
1541   $self->throw_exception ('You must supply a seen hashref as the 3rd argument to _resolve_join')
1542     unless ref $seen eq 'HASH';
1543
1544   $self->throw_exception ('You must supply a joinpath arrayref as the 4th argument to _resolve_join')
1545     unless ref $jpath eq 'ARRAY';
1546
1547   $jpath = [@$jpath]; # copy
1548
1549   if (not defined $join or not length $join) {
1550     return ();
1551   }
1552   elsif (ref $join eq 'ARRAY') {
1553     return
1554       map {
1555         $self->_resolve_join($_, $alias, $seen, $jpath, $parent_force_left);
1556       } @$join;
1557   }
1558   elsif (ref $join eq 'HASH') {
1559
1560     my @ret;
1561     for my $rel (keys %$join) {
1562
1563       my $rel_info = $self->relationship_info($rel)
1564         or $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
1565
1566       my $force_left = $parent_force_left;
1567       $force_left ||= lc($rel_info->{attrs}{join_type}||'') eq 'left';
1568
1569       # the actual seen value will be incremented by the recursion
1570       my $as = $self->storage->relname_to_table_alias(
1571         $rel, ($seen->{$rel} && $seen->{$rel} + 1)
1572       );
1573
1574       push @ret, (
1575         $self->_resolve_join($rel, $alias, $seen, [@$jpath], $force_left),
1576         $self->related_source($rel)->_resolve_join(
1577           $join->{$rel}, $as, $seen, [@$jpath, { $rel => $as }], $force_left
1578         )
1579       );
1580     }
1581     return @ret;
1582
1583   }
1584   elsif (ref $join) {
1585     $self->throw_exception("No idea how to resolve join reftype ".ref $join);
1586   }
1587   else {
1588     my $count = ++$seen->{$join};
1589     my $as = $self->storage->relname_to_table_alias(
1590       $join, ($count > 1 && $count)
1591     );
1592
1593     my $rel_info = $self->relationship_info($join)
1594       or $self->throw_exception("No such relationship $join on " . $self->source_name);
1595
1596     my $rel_src = $self->related_source($join);
1597     return [ { $as => $rel_src->from,
1598                -rsrc => $rel_src,
1599                -join_type => $parent_force_left
1600                   ? 'left'
1601                   : $rel_info->{attrs}{join_type}
1602                 ,
1603                -join_path => [@$jpath, { $join => $as } ],
1604                -is_single => (
1605                   (! $rel_info->{attrs}{accessor})
1606                     or
1607                   first { $rel_info->{attrs}{accessor} eq $_ } (qw/single filter/)
1608                 ),
1609                -alias => $as,
1610                -relation_chain_depth => ( $seen->{-relation_chain_depth} || 0 ) + 1,
1611              },
1612              scalar $self->_resolve_condition($rel_info->{cond}, $as, $alias, $join)
1613           ];
1614   }
1615 }
1616
1617 sub pk_depends_on {
1618   carp 'pk_depends_on is a private method, stop calling it';
1619   my $self = shift;
1620   $self->_pk_depends_on (@_);
1621 }
1622
1623 # Determines whether a relation is dependent on an object from this source
1624 # having already been inserted. Takes the name of the relationship and a
1625 # hashref of columns of the related object.
1626 sub _pk_depends_on {
1627   my ($self, $rel_name, $rel_data) = @_;
1628
1629   my $relinfo = $self->relationship_info($rel_name);
1630
1631   # don't assume things if the relationship direction is specified
1632   return $relinfo->{attrs}{is_foreign_key_constraint}
1633     if exists ($relinfo->{attrs}{is_foreign_key_constraint});
1634
1635   my $cond = $relinfo->{cond};
1636   return 0 unless ref($cond) eq 'HASH';
1637
1638   # map { foreign.foo => 'self.bar' } to { bar => 'foo' }
1639   my $keyhash = { map { my $x = $_; $x =~ s/.*\.//; $x; } reverse %$cond };
1640
1641   # assume anything that references our PK probably is dependent on us
1642   # rather than vice versa, unless the far side is (a) defined or (b)
1643   # auto-increment
1644   my $rel_source = $self->related_source($rel_name);
1645
1646   foreach my $p ($self->primary_columns) {
1647     if (exists $keyhash->{$p}) {
1648       unless (defined($rel_data->{$keyhash->{$p}})
1649               || $rel_source->column_info($keyhash->{$p})
1650                             ->{is_auto_increment}) {
1651         return 0;
1652       }
1653     }
1654   }
1655
1656   return 1;
1657 }
1658
1659 sub resolve_condition {
1660   carp 'resolve_condition is a private method, stop calling it';
1661   my $self = shift;
1662   $self->_resolve_condition (@_);
1663 }
1664
1665 our $UNRESOLVABLE_CONDITION = \ '1 = 0';
1666
1667 # Resolves the passed condition to a concrete query fragment and a flag
1668 # indicating whether this is a cross-table condition. Also an optional
1669 # list of non-triviail values (notmally conditions) returned as a part
1670 # of a joinfree condition hash
1671 sub _resolve_condition {
1672   my ($self, $cond, $as, $for, $rel_name) = @_;
1673
1674   my $obj_rel = !!blessed $for;
1675
1676   if (ref $cond eq 'CODE') {
1677     my $relalias = $obj_rel ? 'me' : $as;
1678
1679     my ($crosstable_cond, $joinfree_cond) = $cond->({
1680       self_alias => $obj_rel ? $as : $for,
1681       foreign_alias => $relalias,
1682       self_resultsource => $self,
1683       foreign_relname => $rel_name || ($obj_rel ? $as : $for),
1684       self_rowobj => $obj_rel ? $for : undef
1685     });
1686
1687     my $cond_cols;
1688     if ($joinfree_cond) {
1689
1690       # FIXME sanity check until things stabilize, remove at some point
1691       $self->throw_exception (
1692         "A join-free condition returned for relationship '$rel_name' without a row-object to chain from"
1693       ) unless $obj_rel;
1694
1695       # FIXME another sanity check
1696       if (
1697         ref $joinfree_cond ne 'HASH'
1698           or
1699         first { $_ !~ /^\Q$relalias.\E.+/ } keys %$joinfree_cond
1700       ) {
1701         $self->throw_exception (
1702           "The join-free condition returned for relationship '$rel_name' must be a hash "
1703          .'reference with all keys being valid columns on the related result source'
1704         );
1705       }
1706
1707       # normalize
1708       for (values %$joinfree_cond) {
1709         $_ = $_->{'='} if (
1710           ref $_ eq 'HASH'
1711             and
1712           keys %$_ == 1
1713             and
1714           exists $_->{'='}
1715         );
1716       }
1717
1718       # see which parts of the joinfree cond are conditionals
1719       my $relcol_list = { map { $_ => 1 } $self->related_source($rel_name)->columns };
1720
1721       for my $c (keys %$joinfree_cond) {
1722         my ($colname) = $c =~ /^ (?: \Q$relalias.\E )? (.+)/x;
1723
1724         unless ($relcol_list->{$colname}) {
1725           push @$cond_cols, $colname;
1726           next;
1727         }
1728
1729         if (
1730           ref $joinfree_cond->{$c}
1731             and
1732           ref $joinfree_cond->{$c} ne 'SCALAR'
1733             and
1734           ref $joinfree_cond->{$c} ne 'REF'
1735         ) {
1736           push @$cond_cols, $colname;
1737           next;
1738         }
1739       }
1740
1741       return wantarray ? ($joinfree_cond, 0, $cond_cols) : $joinfree_cond;
1742     }
1743     else {
1744       return wantarray ? ($crosstable_cond, 1) : $crosstable_cond;
1745     }
1746   }
1747   elsif (ref $cond eq 'HASH') {
1748     my %ret;
1749     foreach my $k (keys %{$cond}) {
1750       my $v = $cond->{$k};
1751       # XXX should probably check these are valid columns
1752       $k =~ s/^foreign\.// ||
1753         $self->throw_exception("Invalid rel cond key ${k}");
1754       $v =~ s/^self\.// ||
1755         $self->throw_exception("Invalid rel cond val ${v}");
1756       if (ref $for) { # Object
1757         #warn "$self $k $for $v";
1758         unless ($for->has_column_loaded($v)) {
1759           if ($for->in_storage) {
1760             $self->throw_exception(sprintf
1761               "Unable to resolve relationship '%s' from object %s: column '%s' not "
1762             . 'loaded from storage (or not passed to new() prior to insert()). You '
1763             . 'probably need to call ->discard_changes to get the server-side defaults '
1764             . 'from the database.',
1765               $as,
1766               $for,
1767               $v,
1768             );
1769           }
1770           return $UNRESOLVABLE_CONDITION;
1771         }
1772         $ret{$k} = $for->get_column($v);
1773         #$ret{$k} = $for->get_column($v) if $for->has_column_loaded($v);
1774         #warn %ret;
1775       } elsif (!defined $for) { # undef, i.e. "no object"
1776         $ret{$k} = undef;
1777       } elsif (ref $as eq 'HASH') { # reverse hashref
1778         $ret{$v} = $as->{$k};
1779       } elsif (ref $as) { # reverse object
1780         $ret{$v} = $as->get_column($k);
1781       } elsif (!defined $as) { # undef, i.e. "no reverse object"
1782         $ret{$v} = undef;
1783       } else {
1784         $ret{"${as}.${k}"} = { -ident => "${for}.${v}" };
1785       }
1786     }
1787
1788     return wantarray
1789       ? ( \%ret, ($obj_rel || !defined $as || ref $as) ? 0 : 1 )
1790       : \%ret
1791     ;
1792   }
1793   elsif (ref $cond eq 'ARRAY') {
1794     my (@ret, $crosstable);
1795     for (@$cond) {
1796       my ($cond, $crosstab) = $self->_resolve_condition($_, $as, $for, $rel_name);
1797       push @ret, $cond;
1798       $crosstable ||= $crosstab;
1799     }
1800     return wantarray ? (\@ret, $crosstable) : \@ret;
1801   }
1802   else {
1803     $self->throw_exception ("Can't handle condition $cond for relationship '$rel_name' yet :(");
1804   }
1805 }
1806
1807 =head2 related_source
1808
1809 =over 4
1810
1811 =item Arguments: $rel_name
1812
1813 =item Return Value: $source
1814
1815 =back
1816
1817 Returns the result source object for the given relationship.
1818
1819 =cut
1820
1821 sub related_source {
1822   my ($self, $rel) = @_;
1823   if( !$self->has_relationship( $rel ) ) {
1824     $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
1825   }
1826
1827   # if we are not registered with a schema - just use the prototype
1828   # however if we do have a schema - ask for the source by name (and
1829   # throw in the process if all fails)
1830   if (my $schema = try { $self->schema }) {
1831     $schema->source($self->relationship_info($rel)->{source});
1832   }
1833   else {
1834     my $class = $self->relationship_info($rel)->{class};
1835     $self->ensure_class_loaded($class);
1836     $class->result_source_instance;
1837   }
1838 }
1839
1840 =head2 related_class
1841
1842 =over 4
1843
1844 =item Arguments: $rel_name
1845
1846 =item Return Value: $classname
1847
1848 =back
1849
1850 Returns the class name for objects in the given relationship.
1851
1852 =cut
1853
1854 sub related_class {
1855   my ($self, $rel) = @_;
1856   if( !$self->has_relationship( $rel ) ) {
1857     $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
1858   }
1859   return $self->schema->class($self->relationship_info($rel)->{source});
1860 }
1861
1862 =head2 handle
1863
1864 =over 4
1865
1866 =item Arguments: none
1867
1868 =item Return Value: L<$source_handle|DBIx::Class::ResultSourceHandle>
1869
1870 =back
1871
1872 Obtain a new L<result source handle instance|DBIx::Class::ResultSourceHandle>
1873 for this source. Used as a serializable pointer to this resultsource, as it is not
1874 easy (nor advisable) to serialize CODErefs which may very well be present in e.g.
1875 relationship definitions.
1876
1877 =cut
1878
1879 sub handle {
1880   return DBIx::Class::ResultSourceHandle->new({
1881     source_moniker => $_[0]->source_name,
1882
1883     # so that a detached thaw can be re-frozen
1884     $_[0]->{_detached_thaw}
1885       ? ( _detached_source  => $_[0]          )
1886       : ( schema            => $_[0]->schema  )
1887     ,
1888   });
1889 }
1890
1891 my $global_phase_destroy;
1892 sub DESTROY {
1893   return if $global_phase_destroy ||= in_global_destruction;
1894
1895 ######
1896 # !!! ACHTUNG !!!!
1897 ######
1898 #
1899 # Under no circumstances shall $_[0] be stored anywhere else (like copied to
1900 # a lexical variable, or shifted, or anything else). Doing so will mess up
1901 # the refcount of this particular result source, and will allow the $schema
1902 # we are trying to save to reattach back to the source we are destroying.
1903 # The relevant code checking refcounts is in ::Schema::DESTROY()
1904
1905   # if we are not a schema instance holder - we don't matter
1906   return if(
1907     ! ref $_[0]->{schema}
1908       or
1909     isweak $_[0]->{schema}
1910   );
1911
1912   # weaken our schema hold forcing the schema to find somewhere else to live
1913   # during global destruction (if we have not yet bailed out) this will throw
1914   # which will serve as a signal to not try doing anything else
1915   # however beware - on older perls the exception seems randomly untrappable
1916   # due to some weird race condition during thread joining :(((
1917   local $@;
1918   eval {
1919     weaken $_[0]->{schema};
1920
1921     # if schema is still there reintroduce ourselves with strong refs back to us
1922     if ($_[0]->{schema}) {
1923       my $srcregs = $_[0]->{schema}->source_registrations;
1924       for (keys %$srcregs) {
1925         next unless $srcregs->{$_};
1926         $srcregs->{$_} = $_[0] if $srcregs->{$_} == $_[0];
1927       }
1928     }
1929
1930     1;
1931   } or do {
1932     $global_phase_destroy = 1;
1933   };
1934
1935   return;
1936 }
1937
1938 sub STORABLE_freeze { Storable::nfreeze($_[0]->handle) }
1939
1940 sub STORABLE_thaw {
1941   my ($self, $cloning, $ice) = @_;
1942   %$self = %{ (Storable::thaw($ice))->resolve };
1943 }
1944
1945 =head2 throw_exception
1946
1947 See L<DBIx::Class::Schema/"throw_exception">.
1948
1949 =cut
1950
1951 sub throw_exception {
1952   my $self = shift;
1953
1954   $self->{schema}
1955     ? $self->{schema}->throw_exception(@_)
1956     : DBIx::Class::Exception->throw(@_)
1957   ;
1958 }
1959
1960 =head2 source_info
1961
1962 Stores a hashref of per-source metadata.  No specific key names
1963 have yet been standardized, the examples below are purely hypothetical
1964 and don't actually accomplish anything on their own:
1965
1966   __PACKAGE__->source_info({
1967     "_tablespace" => 'fast_disk_array_3',
1968     "_engine" => 'InnoDB',
1969   });
1970
1971 =head2 new
1972
1973   $class->new();
1974
1975   $class->new({attribute_name => value});
1976
1977 Creates a new ResultSource object.  Not normally called directly by end users.
1978
1979 =head2 column_info_from_storage
1980
1981 =over
1982
1983 =item Arguments: 1/0 (default: 0)
1984
1985 =item Return Value: 1/0
1986
1987 =back
1988
1989   __PACKAGE__->column_info_from_storage(1);
1990
1991 Enables the on-demand automatic loading of the above column
1992 metadata from storage as necessary.  This is *deprecated*, and
1993 should not be used.  It will be removed before 1.0.
1994
1995
1996 =head1 AUTHOR AND CONTRIBUTORS
1997
1998 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
1999
2000 =head1 LICENSE
2001
2002 You may distribute this code under the same terms as Perl itself.
2003
2004 =cut
2005
2006 1;