Refactor SQLA/select interaction (in reality just cleanup)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSource.pm
CommitLineData
9c992ba1 1package DBIx::Class::ResultSource;
2
3use strict;
4use warnings;
5
6use DBIx::Class::ResultSet;
aec3eff1 7use DBIx::Class::ResultSourceHandle;
1a58752c 8
9use DBIx::Class::Exception;
701da8c4 10use Carp::Clan qw/^DBIx::Class/;
6da5894c 11
9c992ba1 12use base qw/DBIx::Class/;
9c992ba1 13
aa1088bf 14__PACKAGE__->mk_group_accessors('simple' => qw/_ordered_columns
15 _columns _primaries _unique_constraints name resultset_attributes
acbe81cf 16 schema from _relationships column_info_from_storage source_info
f89bb832 17 source_name sqlt_deploy_callback/);
aa1088bf 18
fac560c2 19__PACKAGE__->mk_group_accessors('component_class' => qw/resultset_class
b0dd0e03 20 result_class/);
9c992ba1 21
75d07914 22=head1 NAME
9c992ba1 23
24DBIx::Class::ResultSource - Result source object
25
26=head1 SYNOPSIS
27
16ccb4fe 28 # Create a table based result source, in a result class.
29
30 package MyDB::Schema::Result::Artist;
d88ecca6 31 use base qw/DBIx::Class::Core/;
16ccb4fe 32
16ccb4fe 33 __PACKAGE__->table('artist');
34 __PACKAGE__->add_columns(qw/ artistid name /);
35 __PACKAGE__->set_primary_key('artistid');
36 __PACKAGE__->has_many(cds => 'MyDB::Schema::Result::CD');
37
38 1;
39
40 # Create a query (view) based result source, in a result class
41 package MyDB::Schema::Result::Year2000CDs;
d88ecca6 42 use base qw/DBIx::Class::Core/;
16ccb4fe 43
d88ecca6 44 __PACKAGE__->load_components('InflateColumn::DateTime');
16ccb4fe 45 __PACKAGE__->table_class('DBIx::Class::ResultSource::View');
46
47 __PACKAGE__->table('year2000cds');
48 __PACKAGE__->result_source_instance->is_virtual(1);
49 __PACKAGE__->result_source_instance->view_definition(
50 "SELECT cdid, artist, title FROM cd WHERE year ='2000'"
51 );
52
53
9c992ba1 54=head1 DESCRIPTION
55
16ccb4fe 56A ResultSource is an object that represents a source of data for querying.
57
58This class is a base class for various specialised types of result
59sources, for example L<DBIx::Class::ResultSource::Table>. Table is the
60default result source type, so one is created for you when defining a
61result class as described in the synopsis above.
62
d88ecca6 63More specifically, the L<DBIx::Class::Core> base class pulls in the
64L<DBIx::Class::ResultSourceProxy::Table> component, which defines
65the L<table|DBIx::Class::ResultSourceProxy::Table/table> method.
66When called, C<table> creates and stores an instance of
16ccb4fe 67L<DBIx::Class::ResultSoure::Table>. Luckily, to use tables as result
68sources, you don't need to remember any of this.
69
70Result sources representing select queries, or views, can also be
71created, see L<DBIx::Class::ResultSource::View> for full details.
72
73=head2 Finding result source objects
74
75As mentioned above, a result source instance is created and stored for
76you when you define a L<Result Class|DBIx::Class::Manual::Glossary/Result Class>.
77
78You can retrieve the result source at runtime in the following ways:
79
80=over
81
82=item From a Schema object:
83
84 $schema->source($source_name);
85
86=item From a Row object:
9c992ba1 87
16ccb4fe 88 $row->result_source;
89
90=item From a ResultSet object:
91
92 $rs->result_source;
93
94=back
00be2e0b 95
9c992ba1 96=head1 METHODS
97
7eb4ecc8 98=pod
99
9c992ba1 100=cut
101
102sub new {
103 my ($class, $attrs) = @_;
104 $class = ref $class if ref $class;
04786a4c 105
6b051e14 106 my $new = bless { %{$attrs || {}} }, $class;
9c992ba1 107 $new->{resultset_class} ||= 'DBIx::Class::ResultSet';
5ac6a044 108 $new->{resultset_attributes} = { %{$new->{resultset_attributes} || {}} };
6da5894c 109 $new->{_ordered_columns} = [ @{$new->{_ordered_columns}||[]}];
110 $new->{_columns} = { %{$new->{_columns}||{}} };
111 $new->{_relationships} = { %{$new->{_relationships}||{}} };
9c992ba1 112 $new->{name} ||= "!!NAME NOT SET!!";
5afa2a15 113 $new->{_columns_info_loaded} ||= 0;
f89bb832 114 $new->{sqlt_deploy_callback} ||= "default_sqlt_deploy_hook";
9c992ba1 115 return $new;
116}
117
988bf309 118=pod
119
5ac6a044 120=head2 add_columns
121
391ccf38 122=over
123
124=item Arguments: @columns
125
126=item Return value: The ResultSource object
127
128=back
129
843f6bc1 130 $source->add_columns(qw/col1 col2 col3/);
5ac6a044 131
843f6bc1 132 $source->add_columns('col1' => \%col1_info, 'col2' => \%col2_info, ...);
5ac6a044 133
16ccb4fe 134Adds columns to the result source. If supplied colname => hashref
135pairs, uses the hashref as the L</column_info> for that column. Repeated
136calls of this method will add more columns, not replace them.
5ac6a044 137
5d9d9e87 138The column names given will be created as accessor methods on your
7e51afbf 139L<DBIx::Class::Row> objects. You can change the name of the accessor
5d9d9e87 140by supplying an L</accessor> in the column_info hash.
141
157ce0cf 142If a column name beginning with a plus sign ('+col1') is provided, the
143attributes provided will be merged with any existing attributes for the
144column, with the new attributes taking precedence in the case that an
145attribute already exists. Using this without a hashref
146(C<< $source->add_columns(qw/+col1 +col2/) >>) is legal, but useless --
147it does the same thing it would do without the plus.
148
2053ab2a 149The contents of the column_info are not set in stone. The following
150keys are currently recognised/used by DBIx::Class:
988bf309 151
152=over 4
153
75d07914 154=item accessor
988bf309 155
16ccb4fe 156 { accessor => '_name' }
157
158 # example use, replace standard accessor with one of your own:
159 sub name {
160 my ($self, $value) = @_;
161
162 die "Name cannot contain digits!" if($value =~ /\d/);
163 $self->_name($value);
164
165 return $self->_name();
166 }
167
5d9d9e87 168Use this to set the name of the accessor method for this column. If unset,
988bf309 169the name of the column will be used.
170
171=item data_type
172
16ccb4fe 173 { data_type => 'integer' }
174
175This contains the column type. It is automatically filled if you use the
176L<SQL::Translator::Producer::DBIx::Class::File> producer, or the
177L<DBIx::Class::Schema::Loader> module.
988bf309 178
2053ab2a 179Currently there is no standard set of values for the data_type. Use
180whatever your database supports.
988bf309 181
182=item size
183
16ccb4fe 184 { size => 20 }
185
988bf309 186The length of your column, if it is a column type that can have a size
16ccb4fe 187restriction. This is currently only used to create tables from your
188schema, see L<DBIx::Class::Schema/deploy>.
988bf309 189
190=item is_nullable
191
16ccb4fe 192 { is_nullable => 1 }
193
194Set this to a true value for a columns that is allowed to contain NULL
195values, default is false. This is currently only used to create tables
196from your schema, see L<DBIx::Class::Schema/deploy>.
988bf309 197
198=item is_auto_increment
199
16ccb4fe 200 { is_auto_increment => 1 }
201
2053ab2a 202Set this to a true value for a column whose value is somehow
16ccb4fe 203automatically set, defaults to false. This is used to determine which
204columns to empty when cloning objects using
205L<DBIx::Class::Row/copy>. It is also used by
d7be2784 206L<DBIx::Class::Schema/deploy>.
988bf309 207
26a29815 208=item is_numeric
209
16ccb4fe 210 { is_numeric => 1 }
211
26a29815 212Set this to a true or false value (not C<undef>) to explicitly specify
213if this column contains numeric data. This controls how set_column
214decides whether to consider a column dirty after an update: if
0bad1823 215C<is_numeric> is true a numeric comparison C<< != >> will take place
26a29815 216instead of the usual C<eq>
217
218If not specified the storage class will attempt to figure this out on
219first access to the column, based on the column C<data_type>. The
220result will be cached in this attribute.
221
988bf309 222=item is_foreign_key
223
16ccb4fe 224 { is_foreign_key => 1 }
225
2053ab2a 226Set this to a true value for a column that contains a key from a
16ccb4fe 227foreign table, defaults to false. This is currently only used to
228create tables from your schema, see L<DBIx::Class::Schema/deploy>.
988bf309 229
230=item default_value
231
16ccb4fe 232 { default_value => \'now()' }
233
234Set this to the default value which will be inserted into a column by
235the database. Can contain either a value or a function (use a
4858fea7 236reference to a scalar e.g. C<\'now()'> if you want a function). This
16ccb4fe 237is currently only used to create tables from your schema, see
238L<DBIx::Class::Schema/deploy>.
988bf309 239
a4fcda00 240See the note on L<DBIx::Class::Row/new> for more information about possible
241issues related to db-side default values.
242
988bf309 243=item sequence
244
16ccb4fe 245 { sequence => 'my_table_seq' }
246
2053ab2a 247Set this on a primary key column to the name of the sequence used to
248generate a new key value. If not specified, L<DBIx::Class::PK::Auto>
249will attempt to retrieve the name of the sequence from the database
250automatically.
988bf309 251
838ef78d 252=item auto_nextval
253
ca791b95 254Set this to a true value for a column whose value is retrieved automatically
255from a sequence or function (if supported by your Storage driver.) For a
256sequence, if you do not use a trigger to get the nextval, you have to set the
257L</sequence> value as well.
258
259Also set this for MSSQL columns with the 'uniqueidentifier'
e1958268 260L<data_type|DBIx::Class::ResultSource/data_type> whose values you want to
261automatically generate using C<NEWID()>, unless they are a primary key in which
262case this will be done anyway.
838ef78d 263
190615a7 264=item extra
d7be2784 265
266This is used by L<DBIx::Class::Schema/deploy> and L<SQL::Translator>
190615a7 267to add extra non-generic data to the column. For example: C<< extra
d7be2784 268=> { unsigned => 1} >> is used by the MySQL producer to set an integer
269column to unsigned. For more details, see
270L<SQL::Translator::Producer::MySQL>.
271
988bf309 272=back
273
5ac6a044 274=head2 add_column
275
391ccf38 276=over
277
16ccb4fe 278=item Arguments: $colname, \%columninfo?
391ccf38 279
280=item Return value: 1/0 (true/false)
281
282=back
283
16ccb4fe 284 $source->add_column('col' => \%info);
5ac6a044 285
391ccf38 286Add a single column and optional column info. Uses the same column
287info keys as L</add_columns>.
5ac6a044 288
289=cut
290
9c992ba1 291sub add_columns {
292 my ($self, @cols) = @_;
8e04bf91 293 $self->_ordered_columns(\@cols) unless $self->_ordered_columns;
002a359a 294
20518cb4 295 my @added;
296 my $columns = $self->_columns;
9c992ba1 297 while (my $col = shift @cols) {
157ce0cf 298 my $column_info = {};
299 if ($col =~ s/^\+//) {
300 $column_info = $self->column_info($col);
301 }
302
8e04bf91 303 # If next entry is { ... } use that for the column info, if not
304 # use an empty hashref
157ce0cf 305 if (ref $cols[0]) {
306 my $new_info = shift(@cols);
307 %$column_info = (%$column_info, %$new_info);
308 }
20518cb4 309 push(@added, $col) unless exists $columns->{$col};
20518cb4 310 $columns->{$col} = $column_info;
9c992ba1 311 }
20518cb4 312 push @{ $self->_ordered_columns }, @added;
30126ac7 313 return $self;
9c992ba1 314}
315
b25e9fa0 316sub add_column { shift->add_columns(@_); } # DO NOT CHANGE THIS TO GLOB
9c992ba1 317
3842b955 318=head2 has_column
319
391ccf38 320=over
321
322=item Arguments: $colname
323
324=item Return value: 1/0 (true/false)
325
326=back
327
843f6bc1 328 if ($source->has_column($colname)) { ... }
988bf309 329
2053ab2a 330Returns true if the source has a column of this name, false otherwise.
988bf309 331
332=cut
9c992ba1 333
334sub has_column {
335 my ($self, $column) = @_;
336 return exists $self->_columns->{$column};
337}
338
87c4e602 339=head2 column_info
9c992ba1 340
391ccf38 341=over
342
343=item Arguments: $colname
344
345=item Return value: Hashref of info
346
347=back
348
843f6bc1 349 my $info = $source->column_info($col);
9c992ba1 350
391ccf38 351Returns the column metadata hashref for a column, as originally passed
16ccb4fe 352to L</add_columns>. See L</add_columns> above for information on the
353contents of the hashref.
9c992ba1 354
988bf309 355=cut
9c992ba1 356
357sub column_info {
358 my ($self, $column) = @_;
75d07914 359 $self->throw_exception("No such column $column")
701da8c4 360 unless exists $self->_columns->{$column};
5afa2a15 361 #warn $self->{_columns_info_loaded}, "\n";
75d07914 362 if ( ! $self->_columns->{$column}{data_type}
6eda9bcf 363 and $self->column_info_from_storage
75d07914 364 and ! $self->{_columns_info_loaded}
8e04bf91 365 and $self->schema and $self->storage )
366 {
367 $self->{_columns_info_loaded}++;
d51f93c8 368 my $info = {};
369 my $lc_info = {};
75d07914 370 # eval for the case of storage without table
955f1590 371 eval { $info = $self->storage->columns_info_for( $self->from ) };
8e04bf91 372 unless ($@) {
0b88a5bb 373 for my $realcol ( keys %{$info} ) {
374 $lc_info->{lc $realcol} = $info->{$realcol};
375 }
8e04bf91 376 foreach my $col ( keys %{$self->_columns} ) {
d51f93c8 377 $self->_columns->{$col} = {
378 %{ $self->_columns->{$col} },
379 %{ $info->{$col} || $lc_info->{lc $col} || {} }
380 };
a953d8d9 381 }
8e04bf91 382 }
a953d8d9 383 }
9c992ba1 384 return $self->_columns->{$column};
385}
386
387=head2 columns
388
391ccf38 389=over
390
391=item Arguments: None
392
393=item Return value: Ordered list of column names
394
395=back
396
397 my @column_names = $source->columns;
20518cb4 398
391ccf38 399Returns all column names in the order they were declared to L</add_columns>.
87f0da6a 400
401=cut
9c992ba1 402
403sub columns {
8e04bf91 404 my $self = shift;
aa1088bf 405 $self->throw_exception(
406 "columns() is a read-only accessor, did you mean add_columns()?"
9851dada 407 ) if @_;
701da8c4 408 return @{$self->{_ordered_columns}||[]};
571dced3 409}
410
002a359a 411=head2 remove_columns
412
391ccf38 413=over
002a359a 414
391ccf38 415=item Arguments: @colnames
416
417=item Return value: undefined
418
419=back
420
421 $source->remove_columns(qw/col1 col2 col3/);
422
423Removes the given list of columns by name, from the result source.
424
425B<Warning>: Removing a column that is also used in the sources primary
426key, or in one of the sources unique constraints, B<will> result in a
427broken result source.
002a359a 428
429=head2 remove_column
430
391ccf38 431=over
432
433=item Arguments: $colname
434
435=item Return value: undefined
436
437=back
002a359a 438
391ccf38 439 $source->remove_column('col');
440
441Remove a single column by name from the result source, similar to
442L</remove_columns>.
443
444B<Warning>: Removing a column that is also used in the sources primary
445key, or in one of the sources unique constraints, B<will> result in a
446broken result source.
002a359a 447
448=cut
449
450sub remove_columns {
4738027b 451 my ($self, @to_remove) = @_;
002a359a 452
4738027b 453 my $columns = $self->_columns
454 or return;
002a359a 455
4738027b 456 my %to_remove;
457 for (@to_remove) {
a918d901 458 delete $columns->{$_};
4738027b 459 ++$to_remove{$_};
460 }
002a359a 461
4738027b 462 $self->_ordered_columns([ grep { not $to_remove{$_} } @{$self->_ordered_columns} ]);
002a359a 463}
464
b25e9fa0 465sub remove_column { shift->remove_columns(@_); } # DO NOT CHANGE THIS TO GLOB
002a359a 466
87c4e602 467=head2 set_primary_key
468
27f01d1f 469=over 4
470
ebc77b53 471=item Arguments: @cols
27f01d1f 472
391ccf38 473=item Return value: undefined
474
27f01d1f 475=back
87f0da6a 476
16ccb4fe 477Defines one or more columns as primary key for this source. Must be
391ccf38 478called after L</add_columns>.
87f0da6a 479
391ccf38 480Additionally, defines a L<unique constraint|add_unique_constraint>
481named C<primary>.
87f0da6a 482
90f250bc 483Note: you normally do want to define a primary key on your sources
484B<even if the underlying database table does not have a primary key>.
485See
486L<DBIx::Class::Intro/The Significance and Importance of Primary Keys>
487for more info.
988bf309 488
87f0da6a 489=cut
9c992ba1 490
491sub set_primary_key {
492 my ($self, @cols) = @_;
493 # check if primary key columns are valid columns
8e04bf91 494 foreach my $col (@cols) {
495 $self->throw_exception("No such column $col on table " . $self->name)
496 unless $self->has_column($col);
9c992ba1 497 }
498 $self->_primaries(\@cols);
87f0da6a 499
500 $self->add_unique_constraint(primary => \@cols);
9c992ba1 501}
502
87f0da6a 503=head2 primary_columns
504
391ccf38 505=over 4
506
507=item Arguments: None
508
509=item Return value: Ordered list of primary column names
510
511=back
512
513Read-only accessor which returns the list of primary keys, supplied by
514L</set_primary_key>.
30126ac7 515
87f0da6a 516=cut
9c992ba1 517
518sub primary_columns {
519 return @{shift->_primaries||[]};
520}
521
b1d8e3fd 522# a helper method that will automatically die with a descriptive message if
523# no pk is defined on the source in question. For internal use to save
524# on if @pks... boilerplate
e8fb771b 525sub _pri_cols {
526 my $self = shift;
527 my @pcols = $self->primary_columns
528 or $self->throw_exception (sprintf(
455a33cb 529 "Operation requires a primary key to be declared on '%s' via set_primary_key",
530 $self->source_name,
e8fb771b 531 ));
532 return @pcols;
533}
534
87f0da6a 535=head2 add_unique_constraint
536
391ccf38 537=over 4
538
16ccb4fe 539=item Arguments: $name?, \@colnames
391ccf38 540
541=item Return value: undefined
542
543=back
544
87f0da6a 545Declare a unique constraint on this source. Call once for each unique
58b5bb8c 546constraint.
27f01d1f 547
548 # For UNIQUE (column1, column2)
549 __PACKAGE__->add_unique_constraint(
550 constraint_name => [ qw/column1 column2/ ],
551 );
87f0da6a 552
368a5228 553Alternatively, you can specify only the columns:
554
555 __PACKAGE__->add_unique_constraint([ qw/column1 column2/ ]);
556
16ccb4fe 557This will result in a unique constraint named
558C<table_column1_column2>, where C<table> is replaced with the table
559name.
368a5228 560
16ccb4fe 561Unique constraints are used, for example, when you pass the constraint
562name as the C<key> attribute to L<DBIx::Class::ResultSet/find>. Then
563only columns in the constraint are searched.
58b5bb8c 564
391ccf38 565Throws an error if any of the given column names do not yet exist on
566the result source.
567
87f0da6a 568=cut
569
570sub add_unique_constraint {
368a5228 571 my $self = shift;
572 my $cols = pop @_;
573 my $name = shift;
574
575 $name ||= $self->name_unique_constraint($cols);
87f0da6a 576
8e04bf91 577 foreach my $col (@$cols) {
578 $self->throw_exception("No such column $col on table " . $self->name)
579 unless $self->has_column($col);
87f0da6a 580 }
581
582 my %unique_constraints = $self->unique_constraints;
583 $unique_constraints{$name} = $cols;
584 $self->_unique_constraints(\%unique_constraints);
585}
586
d9c74322 587=head2 name_unique_constraint
368a5228 588
391ccf38 589=over 4
590
591=item Arguments: @colnames
592
593=item Return value: Constraint name
594
595=back
596
597 $source->table('mytable');
598 $source->name_unique_constraint('col1', 'col2');
599 # returns
600 'mytable_col1_col2'
601
602Return a name for a unique constraint containing the specified
603columns. The name is created by joining the table name and each column
604name, using an underscore character.
368a5228 605
606For example, a constraint on a table named C<cd> containing the columns
607C<artist> and C<title> would result in a constraint name of C<cd_artist_title>.
608
391ccf38 609This is used by L</add_unique_constraint> if you do not specify the
610optional constraint name.
611
368a5228 612=cut
613
614sub name_unique_constraint {
615 my ($self, $cols) = @_;
616
3e6c1131 617 my $name = $self->name;
4678e9da 618 $name = $$name if (ref $name eq 'SCALAR');
3e6c1131 619
620 return join '_', $name, @$cols;
368a5228 621}
622
87f0da6a 623=head2 unique_constraints
624
391ccf38 625=over 4
626
627=item Arguments: None
628
629=item Return value: Hash of unique constraint data
630
631=back
632
633 $source->unique_constraints();
634
16ccb4fe 635Read-only accessor which returns a hash of unique constraints on this
636source.
391ccf38 637
638The hash is keyed by constraint name, and contains an arrayref of
639column names as values.
87f0da6a 640
641=cut
642
643sub unique_constraints {
644 return %{shift->_unique_constraints||{}};
645}
646
e6a0e17c 647=head2 unique_constraint_names
648
391ccf38 649=over 4
650
651=item Arguments: None
652
653=item Return value: Unique constraint names
654
655=back
656
657 $source->unique_constraint_names();
658
e6a0e17c 659Returns the list of unique constraint names defined on this source.
660
661=cut
662
663sub unique_constraint_names {
664 my ($self) = @_;
665
666 my %unique_constraints = $self->unique_constraints;
667
668 return keys %unique_constraints;
669}
670
671=head2 unique_constraint_columns
672
391ccf38 673=over 4
674
675=item Arguments: $constraintname
676
677=item Return value: List of constraint columns
678
679=back
680
681 $source->unique_constraint_columns('myconstraint');
682
e6a0e17c 683Returns the list of columns that make up the specified unique constraint.
684
685=cut
686
687sub unique_constraint_columns {
688 my ($self, $constraint_name) = @_;
689
690 my %unique_constraints = $self->unique_constraints;
691
692 $self->throw_exception(
693 "Unknown unique constraint $constraint_name on '" . $self->name . "'"
694 ) unless exists $unique_constraints{$constraint_name};
695
696 return @{ $unique_constraints{$constraint_name} };
697}
698
880c075b 699=head2 sqlt_deploy_callback
700
701=over
702
703=item Arguments: $callback
704
705=back
706
707 __PACKAGE__->sqlt_deploy_callback('mycallbackmethod');
708
709An accessor to set a callback to be called during deployment of
710the schema via L<DBIx::Class::Schema/create_ddl_dir> or
711L<DBIx::Class::Schema/deploy>.
712
713The callback can be set as either a code reference or the name of a
714method in the current result class.
715
716If not set, the L</default_sqlt_deploy_hook> is called.
717
718Your callback will be passed the $source object representing the
719ResultSource instance being deployed, and the
720L<SQL::Translator::Schema::Table> object being created from it. The
721callback can be used to manipulate the table object or add your own
722customised indexes. If you need to manipulate a non-table object, use
723the L<DBIx::Class::Schema/sqlt_deploy_hook>.
724
725See L<DBIx::Class::Manual::Cookbook/Adding Indexes And Functions To
726Your SQL> for examples.
727
728This sqlt deployment callback can only be used to manipulate
729SQL::Translator objects as they get turned into SQL. To execute
730post-deploy statements which SQL::Translator does not currently
731handle, override L<DBIx::Class::Schema/deploy> in your Schema class
732and call L<dbh_do|DBIx::Class::Storage::DBI/dbh_do>.
733
734=head2 default_sqlt_deploy_hook
735
736=over
737
738=item Arguments: $source, $sqlt_table
739
740=item Return value: undefined
741
742=back
743
744This is the sensible default for L</sqlt_deploy_callback>.
745
746If a method named C<sqlt_deploy_hook> exists in your Result class, it
747will be called and passed the current C<$source> and the
748C<$sqlt_table> being deployed.
749
750=cut
751
752sub default_sqlt_deploy_hook {
753 my $self = shift;
754
755 my $class = $self->result_class;
756
757 if ($class and $class->can('sqlt_deploy_hook')) {
758 $class->sqlt_deploy_hook(@_);
759 }
760}
761
762sub _invoke_sqlt_deploy_hook {
763 my $self = shift;
764 if ( my $hook = $self->sqlt_deploy_callback) {
765 $self->$hook(@_);
766 }
767}
768
843f6bc1 769=head2 resultset
770
771=over 4
772
773=item Arguments: None
774
775=item Return value: $resultset
776
777=back
778
779Returns a resultset for the given source. This will initially be created
780on demand by calling
781
782 $self->resultset_class->new($self, $self->resultset_attributes)
783
784but is cached from then on unless resultset_class changes.
785
786=head2 resultset_class
787
788=over 4
789
790=item Arguments: $classname
791
792=item Return value: $classname
793
794=back
795
16ccb4fe 796 package My::Schema::ResultSet::Artist;
843f6bc1 797 use base 'DBIx::Class::ResultSet';
798 ...
799
16ccb4fe 800 # In the result class
801 __PACKAGE__->resultset_class('My::Schema::ResultSet::Artist');
802
803 # Or in code
804 $source->resultset_class('My::Schema::ResultSet::Artist');
843f6bc1 805
7e51afbf 806Set the class of the resultset. This is useful if you want to create your
843f6bc1 807own resultset methods. Create your own class derived from
808L<DBIx::Class::ResultSet>, and set it here. If called with no arguments,
809this method returns the name of the existing resultset class, if one
810exists.
811
812=head2 resultset_attributes
813
814=over 4
815
816=item Arguments: \%attrs
817
818=item Return value: \%attrs
819
820=back
821
16ccb4fe 822 # In the result class
823 __PACKAGE__->resultset_attributes({ order_by => [ 'id' ] });
824
825 # Or in code
843f6bc1 826 $source->resultset_attributes({ order_by => [ 'id' ] });
827
828Store a collection of resultset attributes, that will be set on every
829L<DBIx::Class::ResultSet> produced from this result source. For a full
830list see L<DBIx::Class::ResultSet/ATTRIBUTES>.
831
832=cut
833
834sub resultset {
835 my $self = shift;
836 $self->throw_exception(
837 'resultset does not take any arguments. If you want another resultset, '.
838 'call it on the schema instead.'
839 ) if scalar @_;
840
841 return $self->resultset_class->new(
842 $self,
843 {
844 %{$self->{resultset_attributes}},
845 %{$self->schema->default_resultset_attributes}
846 },
847 );
848}
849
850=head2 source_name
851
852=over 4
853
854=item Arguments: $source_name
855
856=item Result value: $source_name
857
858=back
859
860Set an alternate name for the result source when it is loaded into a schema.
861This is useful if you want to refer to a result source by a name other than
862its class name.
863
864 package ArchivedBooks;
865 use base qw/DBIx::Class/;
866 __PACKAGE__->table('books_archive');
867 __PACKAGE__->source_name('Books');
868
869 # from your schema...
870 $schema->resultset('Books')->find(1);
871
9c992ba1 872=head2 from
873
391ccf38 874=over 4
875
876=item Arguments: None
877
878=item Return value: FROM clause
879
880=back
881
882 my $from_clause = $source->from();
883
9c992ba1 884Returns an expression of the source to be supplied to storage to specify
2053ab2a 885retrieval from this source. In the case of a database, the required FROM
886clause contents.
9c992ba1 887
f9b7bd6e 888=head2 schema
889
391ccf38 890=over 4
891
892=item Arguments: None
893
894=item Return value: A schema object
895
896=back
897
898 my $schema = $source->schema();
899
f9b7bd6e 900Returns the L<DBIx::Class::Schema> object that this result source
391ccf38 901belongs to.
9c992ba1 902
903=head2 storage
904
391ccf38 905=over 4
906
907=item Arguments: None
908
909=item Return value: A Storage object
910
911=back
912
913 $source->storage->debug(1);
914
75d07914 915Returns the storage handle for the current schema.
988bf309 916
917See also: L<DBIx::Class::Storage>
9c992ba1 918
919=cut
920
921sub storage { shift->schema->storage; }
922
8452e496 923=head2 add_relationship
924
391ccf38 925=over 4
926
927=item Arguments: $relname, $related_source_name, \%cond, [ \%attrs ]
928
929=item Return value: 1/true if it succeeded
930
931=back
932
8452e496 933 $source->add_relationship('relname', 'related_source', $cond, $attrs);
934
391ccf38 935L<DBIx::Class::Relationship> describes a series of methods which
936create pre-defined useful types of relationships. Look there first
937before using this method directly.
938
24d67825 939The relationship name can be arbitrary, but must be unique for each
940relationship attached to this result source. 'related_source' should
941be the name with which the related result source was registered with
942the current schema. For example:
8452e496 943
24d67825 944 $schema->source('Book')->add_relationship('reviews', 'Review', {
945 'foreign.book_id' => 'self.id',
946 });
947
2053ab2a 948The condition C<$cond> needs to be an L<SQL::Abstract>-style
24d67825 949representation of the join between the tables. For example, if you're
391ccf38 950creating a relation from Author to Book,
988bf309 951
952 { 'foreign.author_id' => 'self.id' }
953
954will result in the JOIN clause
955
956 author me JOIN book foreign ON foreign.author_id = me.id
957
8452e496 958You can specify as many foreign => self mappings as necessary.
959
988bf309 960Valid attributes are as follows:
961
962=over 4
963
964=item join_type
965
966Explicitly specifies the type of join to use in the relationship. Any
967SQL join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in
968the SQL command immediately before C<JOIN>.
969
970=item proxy
971
24d67825 972An arrayref containing a list of accessors in the foreign class to proxy in
973the main class. If, for example, you do the following:
002a359a 974
24d67825 975 CD->might_have(liner_notes => 'LinerNotes', undef, {
976 proxy => [ qw/notes/ ],
977 });
002a359a 978
24d67825 979Then, assuming LinerNotes has an accessor named notes, you can do:
988bf309 980
24d67825 981 my $cd = CD->find(1);
2053ab2a 982 # set notes -- LinerNotes object is created if it doesn't exist
983 $cd->notes('Notes go here');
988bf309 984
985=item accessor
986
987Specifies the type of accessor that should be created for the
75d07914 988relationship. Valid values are C<single> (for when there is only a single
989related object), C<multi> (when there can be many), and C<filter> (for
990when there is a single related object, but you also want the relationship
991accessor to double as a column accessor). For C<multi> accessors, an
992add_to_* method is also created, which calls C<create_related> for the
988bf309 993relationship.
994
8452e496 995=back
996
391ccf38 997Throws an exception if the condition is improperly supplied, or cannot
6d0ee587 998be resolved.
391ccf38 999
8452e496 1000=cut
1001
1002sub add_relationship {
1003 my ($self, $rel, $f_source_name, $cond, $attrs) = @_;
27f01d1f 1004 $self->throw_exception("Can't create relationship without join condition")
1005 unless $cond;
8452e496 1006 $attrs ||= {};
87772e46 1007
eba322a7 1008 # Check foreign and self are right in cond
1009 if ( (ref $cond ||'') eq 'HASH') {
1010 for (keys %$cond) {
1011 $self->throw_exception("Keys of condition should be of form 'foreign.col', not '$_'")
1012 if /\./ && !/^foreign\./;
1013 }
1014 }
1015
8452e496 1016 my %rels = %{ $self->_relationships };
1017 $rels{$rel} = { class => $f_source_name,
87772e46 1018 source => $f_source_name,
8452e496 1019 cond => $cond,
1020 attrs => $attrs };
1021 $self->_relationships(\%rels);
1022
30126ac7 1023 return $self;
87772e46 1024
953a18ef 1025 # XXX disabled. doesn't work properly currently. skip in tests.
1026
8452e496 1027 my $f_source = $self->schema->source($f_source_name);
1028 unless ($f_source) {
c037c03a 1029 $self->ensure_class_loaded($f_source_name);
8452e496 1030 $f_source = $f_source_name->result_source;
87772e46 1031 #my $s_class = ref($self->schema);
1032 #$f_source_name =~ m/^${s_class}::(.*)$/;
1033 #$self->schema->register_class(($1 || $f_source_name), $f_source_name);
1034 #$f_source = $self->schema->source($f_source_name);
8452e496 1035 }
1036 return unless $f_source; # Can't test rel without f_source
1037
88a66388 1038 eval { $self->_resolve_join($rel, 'me', {}, []) };
8452e496 1039
1040 if ($@) { # If the resolve failed, back out and re-throw the error
75d07914 1041 delete $rels{$rel}; #
8452e496 1042 $self->_relationships(\%rels);
701da8c4 1043 $self->throw_exception("Error creating relationship $rel: $@");
8452e496 1044 }
1045 1;
1046}
1047
87c4e602 1048=head2 relationships
8452e496 1049
391ccf38 1050=over 4
1051
1052=item Arguments: None
1053
1054=item Return value: List of relationship names
1055
1056=back
1057
1058 my @relnames = $source->relationships();
1059
2053ab2a 1060Returns all relationship names for this source.
8452e496 1061
1062=cut
1063
1064sub relationships {
1065 return keys %{shift->_relationships};
1066}
1067
87c4e602 1068=head2 relationship_info
1069
27f01d1f 1070=over 4
1071
ebc77b53 1072=item Arguments: $relname
27f01d1f 1073
391ccf38 1074=item Return value: Hashref of relation data,
1075
27f01d1f 1076=back
8452e496 1077
2053ab2a 1078Returns a hash of relationship information for the specified relationship
391ccf38 1079name. The keys/values are as specified for L</add_relationship>.
8452e496 1080
1081=cut
1082
1083sub relationship_info {
1084 my ($self, $rel) = @_;
1085 return $self->_relationships->{$rel};
75d07914 1086}
8452e496 1087
87c4e602 1088=head2 has_relationship
1089
27f01d1f 1090=over 4
1091
ebc77b53 1092=item Arguments: $rel
27f01d1f 1093
391ccf38 1094=item Return value: 1/0 (true/false)
1095
27f01d1f 1096=back
953a18ef 1097
2053ab2a 1098Returns true if the source has a relationship of this name, false otherwise.
988bf309 1099
1100=cut
953a18ef 1101
1102sub has_relationship {
1103 my ($self, $rel) = @_;
1104 return exists $self->_relationships->{$rel};
1105}
1106
de60a93d 1107=head2 reverse_relationship_info
1108
1109=over 4
1110
1111=item Arguments: $relname
1112
391ccf38 1113=item Return value: Hashref of relationship data
1114
de60a93d 1115=back
1116
391ccf38 1117Looks through all the relationships on the source this relationship
1118points to, looking for one whose condition is the reverse of the
1119condition on this relationship.
1120
1121A common use of this is to find the name of the C<belongs_to> relation
1122opposing a C<has_many> relation. For definition of these look in
1123L<DBIx::Class::Relationship>.
1124
1125The returned hashref is keyed by the name of the opposing
faaba25f 1126relationship, and contains its data in the same manner as
391ccf38 1127L</relationship_info>.
de60a93d 1128
1129=cut
1130
1131sub reverse_relationship_info {
1132 my ($self, $rel) = @_;
1133 my $rel_info = $self->relationship_info($rel);
1134 my $ret = {};
1135
1136 return $ret unless ((ref $rel_info->{cond}) eq 'HASH');
1137
1138 my @cond = keys(%{$rel_info->{cond}});
1139 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
1140 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
bab77431 1141
de60a93d 1142 # Get the related result source for this relationship
1143 my $othertable = $self->related_source($rel);
1144
1145 # Get all the relationships for that source that related to this source
1146 # whose foreign column set are our self columns on $rel and whose self
bab77431 1147 # columns are our foreign columns on $rel.
de60a93d 1148 my @otherrels = $othertable->relationships();
1149 my $otherrelationship;
1150 foreach my $otherrel (@otherrels) {
1151 my $otherrel_info = $othertable->relationship_info($otherrel);
1152
1153 my $back = $othertable->related_source($otherrel);
f3fb2641 1154 next unless $back->source_name eq $self->source_name;
de60a93d 1155
1156 my @othertestconds;
1157
1158 if (ref $otherrel_info->{cond} eq 'HASH') {
1159 @othertestconds = ($otherrel_info->{cond});
1160 }
1161 elsif (ref $otherrel_info->{cond} eq 'ARRAY') {
1162 @othertestconds = @{$otherrel_info->{cond}};
1163 }
1164 else {
1165 next;
1166 }
1167
1168 foreach my $othercond (@othertestconds) {
1169 my @other_cond = keys(%$othercond);
1170 my @other_refkeys = map {/^\w+\.(\w+)$/} @other_cond;
1171 my @other_keys = map {$othercond->{$_} =~ /^\w+\.(\w+)$/} @other_cond;
6d0ee587 1172 next if (!$self->_compare_relationship_keys(\@refkeys, \@other_keys) ||
1173 !$self->_compare_relationship_keys(\@other_refkeys, \@keys));
de60a93d 1174 $ret->{$otherrel} = $otherrel_info;
1175 }
1176 }
1177 return $ret;
1178}
1179
de60a93d 1180sub compare_relationship_keys {
6d0ee587 1181 carp 'compare_relationship_keys is a private method, stop calling it';
1182 my $self = shift;
1183 $self->_compare_relationship_keys (@_);
1184}
1185
1186# Returns true if both sets of keynames are the same, false otherwise.
1187sub _compare_relationship_keys {
de60a93d 1188 my ($self, $keys1, $keys2) = @_;
1189
1190 # Make sure every keys1 is in keys2
1191 my $found;
1192 foreach my $key (@$keys1) {
1193 $found = 0;
1194 foreach my $prim (@$keys2) {
1195 if ($prim eq $key) {
1196 $found = 1;
1197 last;
1198 }
1199 }
1200 last unless $found;
1201 }
1202
1203 # Make sure every key2 is in key1
1204 if ($found) {
1205 foreach my $prim (@$keys2) {
1206 $found = 0;
1207 foreach my $key (@$keys1) {
1208 if ($prim eq $key) {
1209 $found = 1;
1210 last;
1211 }
1212 }
1213 last unless $found;
1214 }
1215 }
1216
1217 return $found;
1218}
1219
6d0ee587 1220# Returns the {from} structure used to express JOIN conditions
1221sub _resolve_join {
8a3fa4ae 1222 my ($self, $join, $alias, $seen, $jpath, $parent_force_left) = @_;
1979278e 1223
1224 # we need a supplied one, because we do in-place modifications, no returns
6d0ee587 1225 $self->throw_exception ('You must supply a seen hashref as the 3rd argument to _resolve_join')
88a66388 1226 unless ref $seen eq 'HASH';
1979278e 1227
88a66388 1228 $self->throw_exception ('You must supply a joinpath arrayref as the 4th argument to _resolve_join')
1229 unless ref $jpath eq 'ARRAY';
1230
38f42d85 1231 $jpath = [@$jpath]; # copy
1979278e 1232
8a3fa4ae 1233 if (not defined $join) {
1234 return ();
1235 }
1236 elsif (ref $join eq 'ARRAY') {
caac1708 1237 return
1238 map {
8a3fa4ae 1239 $self->_resolve_join($_, $alias, $seen, $jpath, $parent_force_left);
caac1708 1240 } @$join;
8a3fa4ae 1241 }
1242 elsif (ref $join eq 'HASH') {
1243
1244 my @ret;
1245 for my $rel (keys %$join) {
1246
1247 my $rel_info = $self->relationship_info($rel)
455a33cb 1248 or $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
8a3fa4ae 1249
1250 my $force_left = $parent_force_left;
1251 $force_left ||= lc($rel_info->{attrs}{join_type}||'') eq 'left';
1252
1253 # the actual seen value will be incremented by the recursion
6c0230de 1254 my $as = $self->storage->relname_to_table_alias(
1255 $rel, ($seen->{$rel} && $seen->{$rel} + 1)
1256 );
1979278e 1257
8a3fa4ae 1258 push @ret, (
1259 $self->_resolve_join($rel, $alias, $seen, [@$jpath], $force_left),
1260 $self->related_source($rel)->_resolve_join(
38f42d85 1261 $join->{$rel}, $as, $seen, [@$jpath, { $rel => $as }], $force_left
8a3fa4ae 1262 )
1263 );
1264 }
1265 return @ret;
096395af 1266
8a3fa4ae 1267 }
1268 elsif (ref $join) {
1269 $self->throw_exception("No idea how to resolve join reftype ".ref $join);
1270 }
1271 else {
489709af 1272 my $count = ++$seen->{$join};
6c0230de 1273 my $as = $self->storage->relname_to_table_alias(
1274 $join, ($count > 1 && $count)
1275 );
1979278e 1276
8a3fa4ae 1277 my $rel_info = $self->relationship_info($join)
455a33cb 1278 or $self->throw_exception("No such relationship $join on " . $self->source_name);
ba61fa2a 1279
1280 my $rel_src = $self->related_source($join);
1281 return [ { $as => $rel_src->from,
35ec0366 1282 -source_handle => $rel_src->handle,
8a3fa4ae 1283 -join_type => $parent_force_left
1284 ? 'left'
1285 : $rel_info->{attrs}{join_type}
1286 ,
38f42d85 1287 -join_path => [@$jpath, { $join => $as } ],
b82c8a28 1288 -is_single => (
1289 $rel_info->{attrs}{accessor}
1290 &&
1291 List::Util::first { $rel_info->{attrs}{accessor} eq $_ } (qw/single filter/)
1292 ),
ba61fa2a 1293 -alias => $as,
1979278e 1294 -relation_chain_depth => $seen->{-relation_chain_depth} || 0,
1295 },
6d0ee587 1296 $self->_resolve_condition($rel_info->{cond}, $as, $alias) ];
953a18ef 1297 }
1298}
1299
370f2ba2 1300sub pk_depends_on {
6d0ee587 1301 carp 'pk_depends_on is a private method, stop calling it';
1302 my $self = shift;
1303 $self->_pk_depends_on (@_);
1304}
1305
1306# Determines whether a relation is dependent on an object from this source
1307# having already been inserted. Takes the name of the relationship and a
1308# hashref of columns of the related object.
1309sub _pk_depends_on {
370f2ba2 1310 my ($self, $relname, $rel_data) = @_;
370f2ba2 1311
c39b48e5 1312 my $relinfo = $self->relationship_info($relname);
1313
1314 # don't assume things if the relationship direction is specified
1315 return $relinfo->{attrs}{is_foreign_key_constraint}
1316 if exists ($relinfo->{attrs}{is_foreign_key_constraint});
1317
1318 my $cond = $relinfo->{cond};
370f2ba2 1319 return 0 unless ref($cond) eq 'HASH';
1320
1321 # map { foreign.foo => 'self.bar' } to { bar => 'foo' }
370f2ba2 1322 my $keyhash = { map { my $x = $_; $x =~ s/.*\.//; $x; } reverse %$cond };
1323
1324 # assume anything that references our PK probably is dependent on us
1325 # rather than vice versa, unless the far side is (a) defined or (b)
1326 # auto-increment
370f2ba2 1327 my $rel_source = $self->related_source($relname);
1328
1329 foreach my $p ($self->primary_columns) {
1330 if (exists $keyhash->{$p}) {
1331 unless (defined($rel_data->{$keyhash->{$p}})
1332 || $rel_source->column_info($keyhash->{$p})
1333 ->{is_auto_increment}) {
1334 return 0;
1335 }
1336 }
1337 }
1338
1339 return 1;
1340}
1341
6d0ee587 1342sub resolve_condition {
1343 carp 'resolve_condition is a private method, stop calling it';
1344 my $self = shift;
1345 $self->_resolve_condition (@_);
1346}
953a18ef 1347
6d0ee587 1348# Resolves the passed condition to a concrete query fragment. If given an alias,
1349# returns a join condition; if given an object, inverts that object to produce
1350# a related conditional from that object.
8c368cf3 1351our $UNRESOLVABLE_CONDITION = \'1 = 0';
1352
6d0ee587 1353sub _resolve_condition {
489709af 1354 my ($self, $cond, $as, $for) = @_;
953a18ef 1355 if (ref $cond eq 'HASH') {
1356 my %ret;
bd054cb4 1357 foreach my $k (keys %{$cond}) {
1358 my $v = $cond->{$k};
953a18ef 1359 # XXX should probably check these are valid columns
27f01d1f 1360 $k =~ s/^foreign\.// ||
75d07914 1361 $self->throw_exception("Invalid rel cond key ${k}");
27f01d1f 1362 $v =~ s/^self\.// ||
75d07914 1363 $self->throw_exception("Invalid rel cond val ${v}");
953a18ef 1364 if (ref $for) { # Object
3842b955 1365 #warn "$self $k $for $v";
370f2ba2 1366 unless ($for->has_column_loaded($v)) {
1367 if ($for->in_storage) {
8bbfe6b2 1368 $self->throw_exception(sprintf
5c89c897 1369 "Unable to resolve relationship '%s' from object %s: column '%s' not "
1370 . 'loaded from storage (or not passed to new() prior to insert()). You '
1371 . 'probably need to call ->discard_changes to get the server-side defaults '
1372 . 'from the database.',
8bbfe6b2 1373 $as,
971beb94 1374 $for,
5c89c897 1375 $v,
a4fcda00 1376 );
370f2ba2 1377 }
68f3b0dd 1378 return $UNRESOLVABLE_CONDITION;
370f2ba2 1379 }
1380 $ret{$k} = $for->get_column($v);
1381 #$ret{$k} = $for->get_column($v) if $for->has_column_loaded($v);
3842b955 1382 #warn %ret;
2c037e6b 1383 } elsif (!defined $for) { # undef, i.e. "no object"
1384 $ret{$k} = undef;
2ec8e594 1385 } elsif (ref $as eq 'HASH') { # reverse hashref
1386 $ret{$v} = $as->{$k};
fde6e28e 1387 } elsif (ref $as) { # reverse object
1388 $ret{$v} = $as->get_column($k);
2c037e6b 1389 } elsif (!defined $as) { # undef, i.e. "no reverse object"
1390 $ret{$v} = undef;
953a18ef 1391 } else {
489709af 1392 $ret{"${as}.${k}"} = "${for}.${v}";
953a18ef 1393 }
953a18ef 1394 }
1395 return \%ret;
5efe4c79 1396 } elsif (ref $cond eq 'ARRAY') {
6d0ee587 1397 return [ map { $self->_resolve_condition($_, $as, $for) } @$cond ];
953a18ef 1398 } else {
35c77aa3 1399 die("Can't handle condition $cond yet :(");
87772e46 1400 }
1401}
1402
988bf309 1403
6d0ee587 1404# Accepts one or more relationships for the current source and returns an
1405# array of column names for each of those relationships. Column names are
1406# prefixed relative to the current source, in accordance with where they appear
38f42d85 1407# in the supplied relationships.
b3e8ac9b 1408
6d0ee587 1409sub _resolve_prefetch {
1979278e 1410 my ($self, $pre, $alias, $alias_map, $order, $collapse, $pref_path) = @_;
1411 $pref_path ||= [];
1412
8a3fa4ae 1413 if (not defined $pre) {
1414 return ();
1415 }
1416 elsif( ref $pre eq 'ARRAY' ) {
0f66a01b 1417 return
6d0ee587 1418 map { $self->_resolve_prefetch( $_, $alias, $alias_map, $order, $collapse, [ @$pref_path ] ) }
0f66a01b 1419 @$pre;
b3e8ac9b 1420 }
1421 elsif( ref $pre eq 'HASH' ) {
1422 my @ret =
1423 map {
6d0ee587 1424 $self->_resolve_prefetch($_, $alias, $alias_map, $order, $collapse, [ @$pref_path ] ),
1425 $self->related_source($_)->_resolve_prefetch(
1979278e 1426 $pre->{$_}, "${alias}.$_", $alias_map, $order, $collapse, [ @$pref_path, $_] )
0f66a01b 1427 } keys %$pre;
b3e8ac9b 1428 return @ret;
1429 }
1430 elsif( ref $pre ) {
a86b1efe 1431 $self->throw_exception(
1432 "don't know how to resolve prefetch reftype ".ref($pre));
b3e8ac9b 1433 }
1434 else {
1979278e 1435 my $p = $alias_map;
1436 $p = $p->{$_} for (@$pref_path, $pre);
1437
1438 $self->throw_exception (
5e8cb53c 1439 "Unable to resolve prefetch '$pre' - join alias map does not contain an entry for path: "
1979278e 1440 . join (' -> ', @$pref_path, $pre)
1441 ) if (ref $p->{-join_aliases} ne 'ARRAY' or not @{$p->{-join_aliases}} );
88a66388 1442
1979278e 1443 my $as = shift @{$p->{-join_aliases}};
1444
b3e8ac9b 1445 my $rel_info = $self->relationship_info( $pre );
455a33cb 1446 $self->throw_exception( $self->source_name . " has no such relationship '$pre'" )
a86b1efe 1447 unless $rel_info;
37f23589 1448 my $as_prefix = ($alias =~ /^.*?\.(.+)$/ ? $1.'.' : '');
a86b1efe 1449 my $rel_source = $self->related_source($pre);
0f66a01b 1450
b82c8a28 1451 if ($rel_info->{attrs}{accessor} && $rel_info->{attrs}{accessor} eq 'multi') {
0f66a01b 1452 $self->throw_exception(
1453 "Can't prefetch has_many ${pre} (join cond too complex)")
1454 unless ref($rel_info->{cond}) eq 'HASH';
cb136e67 1455 my $dots = @{[$as_prefix =~ m/\./g]} + 1; # +1 to match the ".${as_prefix}"
1456 if (my ($fail) = grep { @{[$_ =~ m/\./g]} == $dots }
1457 keys %{$collapse}) {
1458 my ($last) = ($fail =~ /([^\.]+)$/);
616b461d 1459 carp (
1460 "Prefetching multiple has_many rels ${last} and ${pre} "
1461 .(length($as_prefix)
1462 ? "at the same level (${as_prefix}) "
1463 : "at top level "
1464 )
2e251255 1465 . 'will explode the number of row objects retrievable via ->next or ->all. '
616b461d 1466 . 'Use at your own risk.'
1467 );
cb136e67 1468 }
b25e9fa0 1469 #my @col = map { (/^self\.(.+)$/ ? ("${as_prefix}.$1") : ()); }
1470 # values %{$rel_info->{cond}};
b1d8e3fd 1471 $collapse->{".${as_prefix}${pre}"} = [ $rel_source->_pri_cols ];
b25e9fa0 1472 # action at a distance. prepending the '.' allows simpler code
1473 # in ResultSet->_collapse_result
37f23589 1474 my @key = map { (/^foreign\.(.+)$/ ? ($1) : ()); }
0f66a01b 1475 keys %{$rel_info->{cond}};
5a5bec6c 1476 my @ord = (ref($rel_info->{attrs}{order_by}) eq 'ARRAY'
1477 ? @{$rel_info->{attrs}{order_by}}
b82c8a28 1478
1479 : (defined $rel_info->{attrs}{order_by}
5a5bec6c 1480 ? ($rel_info->{attrs}{order_by})
1481 : ()));
1482 push(@$order, map { "${as}.$_" } (@key, @ord));
0f66a01b 1483 }
1484
489709af 1485 return map { [ "${as}.$_", "${as_prefix}${pre}.$_", ] }
a86b1efe 1486 $rel_source->columns;
b3e8ac9b 1487 }
1488}
953a18ef 1489
87c4e602 1490=head2 related_source
1491
27f01d1f 1492=over 4
1493
ebc77b53 1494=item Arguments: $relname
27f01d1f 1495
391ccf38 1496=item Return value: $source
1497
27f01d1f 1498=back
87772e46 1499
2053ab2a 1500Returns the result source object for the given relationship.
87772e46 1501
1502=cut
1503
1504sub related_source {
1505 my ($self, $rel) = @_;
aea52c85 1506 if( !$self->has_relationship( $rel ) ) {
455a33cb 1507 $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
aea52c85 1508 }
87772e46 1509 return $self->schema->source($self->relationship_info($rel)->{source});
8452e496 1510}
1511
77254782 1512=head2 related_class
1513
27f01d1f 1514=over 4
1515
ebc77b53 1516=item Arguments: $relname
27f01d1f 1517
391ccf38 1518=item Return value: $classname
1519
27f01d1f 1520=back
77254782 1521
2053ab2a 1522Returns the class name for objects in the given relationship.
77254782 1523
1524=cut
1525
1526sub related_class {
1527 my ($self, $rel) = @_;
1528 if( !$self->has_relationship( $rel ) ) {
455a33cb 1529 $self->throw_exception("No such relationship '$rel' on " . $self->source_name);
77254782 1530 }
1531 return $self->schema->class($self->relationship_info($rel)->{source});
1532}
1533
aec3eff1 1534=head2 handle
1535
1536Obtain a new handle to this source. Returns an instance of a
1537L<DBIx::Class::ResultSourceHandle>.
1538
1539=cut
1540
1541sub handle {
24c349e8 1542 return DBIx::Class::ResultSourceHandle->new({
aec3eff1 1543 schema => $_[0]->schema,
3441fd57 1544 source_moniker => $_[0]->source_name
aec3eff1 1545 });
1546}
1547
701da8c4 1548=head2 throw_exception
1549
2053ab2a 1550See L<DBIx::Class::Schema/"throw_exception">.
701da8c4 1551
1552=cut
1553
1554sub throw_exception {
1555 my $self = shift;
1a58752c 1556
0b4926ce 1557 if (defined $self->schema) {
701da8c4 1558 $self->schema->throw_exception(@_);
1a58752c 1559 }
1560 else {
1561 DBIx::Class::Exception->throw(@_);
701da8c4 1562 }
1563}
1564
843f6bc1 1565=head2 source_info
d2f3e87b 1566
843f6bc1 1567Stores a hashref of per-source metadata. No specific key names
1568have yet been standardized, the examples below are purely hypothetical
1569and don't actually accomplish anything on their own:
391ccf38 1570
843f6bc1 1571 __PACKAGE__->source_info({
1572 "_tablespace" => 'fast_disk_array_3',
1573 "_engine" => 'InnoDB',
1574 });
391ccf38 1575
843f6bc1 1576=head2 new
391ccf38 1577
843f6bc1 1578 $class->new();
391ccf38 1579
843f6bc1 1580 $class->new({attribute_name => value});
d2f3e87b 1581
843f6bc1 1582Creates a new ResultSource object. Not normally called directly by end users.
391ccf38 1583
843f6bc1 1584=head2 column_info_from_storage
1585
1586=over
1587
1588=item Arguments: 1/0 (default: 0)
1589
1590=item Return value: 1/0
1591
1592=back
1593
880c075b 1594 __PACKAGE__->column_info_from_storage(1);
1595
843f6bc1 1596Enables the on-demand automatic loading of the above column
c1300297 1597metadata from storage as necessary. This is *deprecated*, and
843f6bc1 1598should not be used. It will be removed before 1.0.
1599
f89bb832 1600
9c992ba1 1601=head1 AUTHORS
1602
1603Matt S. Trout <mst@shadowcatsystems.co.uk>
1604
1605=head1 LICENSE
1606
1607You may distribute this code under the same terms as Perl itself.
1608
1609=cut
1610
b25e9fa0 16111;