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