passing all these positional arguments into the relbuilder is stupid. let's not.
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / RelBuilder.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::RelBuilder;
2
3use strict;
4use warnings;
7824616e 5use Class::C3;
fa994d3c 6use Carp::Clan qw/^DBIx::Class/;
39b22ca9 7use Lingua::EN::Inflect::Phrase ();
cc4f11a2 8use DBIx::Class::Schema::Loader::Utils 'split_name';
996be9ee 9
6b1d4f76 10our $VERSION = '0.07001';
32f784fc 11
996be9ee 12=head1 NAME
13
14DBIx::Class::Schema::Loader::RelBuilder - Builds relationships for DBIx::Class::Schema::Loader
15
16=head1 SYNOPSIS
17
19b7d71c 18See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
996be9ee 19
20=head1 DESCRIPTION
21
22This class builds relationships for L<DBIx::Class::Schema::Loader>. This
23is module is not (yet) for external use.
24
25=head1 METHODS
26
27=head2 new
28
4c7b5f46 29Arguments: $base object
996be9ee 30
31=head2 generate_code
32
e8ad6491 33Arguments: local_moniker (scalar), fk_info (arrayref)
34
35This generates the code for the relationships of a given table.
36
37C<local_moniker> is the moniker name of the table which had the REFERENCES
38statements. The fk_info arrayref's contents should take the form:
39
40 [
41 {
42 local_columns => [ 'col2', 'col3' ],
43 remote_columns => [ 'col5', 'col7' ],
44 remote_moniker => 'AnotherTableMoniker',
45 },
46 {
47 local_columns => [ 'col1', 'col4' ],
48 remote_columns => [ 'col1', 'col2' ],
49 remote_moniker => 'YetAnotherTableMoniker',
50 },
51 # ...
52 ],
53
54This method will return the generated relationships as a hashref keyed on the
55class names. The values are arrayrefs of hashes containing method name and
56arguments, like so:
996be9ee 57
58 {
59 'Some::Source::Class' => [
b97c2c1e 60 { method => 'belongs_to', arguments => [ 'col1', 'Another::Source::Class' ],
61 { method => 'has_many', arguments => [ 'anothers', 'Yet::Another::Source::Class', 'col15' ],
996be9ee 62 ],
63 'Another::Source::Class' => [
64 # ...
65 ],
66 # ...
67 }
8f9d7ce5 68
996be9ee 69=cut
70
4c7b5f46 71
996be9ee 72sub new {
4c7b5f46 73 my ( $class, $base ) = @_;
74
75 # from old POD about this constructor:
76 # C<$schema_class> should be a schema class name, where the source
77 # classes have already been set up and registered. Column info,
78 # primary key, and unique constraints will be drawn from this
79 # schema for all of the existing source monikers.
80
81 # Options inflect_plural and inflect_singular are optional, and
82 # are better documented in L<DBIx::Class::Schema::Loader::Base>.
996be9ee 83
84 my $self = {
4c7b5f46 85 base => $base,
86 schema => $base->schema,
87 inflect_plural => $base->inflect_plural,
88 inflect_singular => $base->inflect_singular,
89 relationship_attrs => $base->relationship_attrs,
996be9ee 90 };
91
4c7b5f46 92 Scalar::Util::weaken $self->{base}; #< don't leak
93
c8c27020 94 # validate the relationship_attrs arg
95 if( defined $self->{relationship_attrs} ) {
4c7b5f46 96 ref $self->{relationship_attrs} eq 'HASH'
c8c27020 97 or croak "relationship_attrs must be a hashref";
98 }
996be9ee 99
c8c27020 100 return bless $self => $class;
996be9ee 101}
102
103
104# pluralize a relationship name
105sub _inflect_plural {
ecf930e6 106 my ($self, $relname) = @_;
996be9ee 107
39ef3bfe 108 return '' if !defined $relname || $relname eq '';
109
996be9ee 110 if( ref $self->{inflect_plural} eq 'HASH' ) {
111 return $self->{inflect_plural}->{$relname}
112 if exists $self->{inflect_plural}->{$relname};
113 }
114 elsif( ref $self->{inflect_plural} eq 'CODE' ) {
115 my $inflected = $self->{inflect_plural}->($relname);
116 return $inflected if $inflected;
117 }
118
ecf930e6 119 return $self->_to_PL($relname);
996be9ee 120}
121
122# Singularize a relationship name
123sub _inflect_singular {
ecf930e6 124 my ($self, $relname) = @_;
996be9ee 125
39ef3bfe 126 return '' if !defined $relname || $relname eq '';
127
996be9ee 128 if( ref $self->{inflect_singular} eq 'HASH' ) {
129 return $self->{inflect_singular}->{$relname}
130 if exists $self->{inflect_singular}->{$relname};
131 }
132 elsif( ref $self->{inflect_singular} eq 'CODE' ) {
133 my $inflected = $self->{inflect_singular}->($relname);
134 return $inflected if $inflected;
135 }
136
ecf930e6 137 return $self->_to_S($relname);
c496748b 138}
139
140sub _to_PL {
141 my ($self, $name) = @_;
142
143 $name =~ s/_/ /g;
39b22ca9 144 my $plural = Lingua::EN::Inflect::Phrase::to_PL($name);
c496748b 145 $plural =~ s/ /_/g;
146
147 return $plural;
148}
149
c496748b 150sub _to_S {
151 my ($self, $name) = @_;
152
39b22ca9 153 $name =~ s/_/ /g;
154 my $singular = Lingua::EN::Inflect::Phrase::to_S($name);
155 $singular =~ s/ /_/g;
156
157 return $singular;
996be9ee 158}
159
53ef681d 160sub _default_relationship_attrs { +{
161 has_many => {
162 cascade_delete => 0,
163 cascade_copy => 0,
164 },
165 might_have => {
166 cascade_delete => 0,
167 cascade_copy => 0,
168 },
169 belongs_to => {
170 on_delete => 'CASCADE',
171 on_update => 'CASCADE',
aa0867ee 172 is_deferrable => 1,
53ef681d 173 },
174} }
175
c8c27020 176# accessor for options to be passed to each generated relationship
177# type. take single argument, the relationship type name, and returns
178# either a hashref (if some options are set), or nothing
179sub _relationship_attrs {
180 my ( $self, $reltype ) = @_;
181 my $r = $self->{relationship_attrs};
c8c27020 182
53ef681d 183 my %composite = (
184 %{ $self->_default_relationship_attrs->{$reltype} || {} },
185 %{ $r->{all} || {} }
186 );
187
c8c27020 188 if( my $specific = $r->{$reltype} ) {
189 while( my ($k,$v) = each %$specific ) {
190 $composite{$k} = $v;
191 }
192 }
193 return \%composite;
194}
195
26f1c8c9 196sub _array_eq {
ecf930e6 197 my ($self, $a, $b) = @_;
26f1c8c9 198
199 return unless @$a == @$b;
200
201 for (my $i = 0; $i < @$a; $i++) {
202 return unless $a->[$i] eq $b->[$i];
203 }
204 return 1;
205}
206
c39e403e 207sub _remote_attrs {
c496748b 208 my ($self, $local_moniker, $local_cols) = @_;
c39e403e 209
c496748b 210 # get our base set of attrs from _relationship_attrs, if present
211 my $attrs = $self->_relationship_attrs('belongs_to') || {};
c8c27020 212
c496748b 213 # If the referring column is nullable, make 'belongs_to' an
214 # outer join, unless explicitly set by relationship_attrs
215 my $nullable = grep { $self->{schema}->source($local_moniker)->column_info($_)->{is_nullable} } @$local_cols;
216 $attrs->{join_type} = 'LEFT' if $nullable && !defined $attrs->{join_type};
c39e403e 217
c496748b 218 return $attrs;
c39e403e 219}
220
414c61a0 221sub _sanitize_name {
222 my ($self, $name) = @_;
223
224 if (ref $name) {
225 # scalar ref for weird table name (like one containing a '.')
226 ($name = $$name) =~ s/\W+/_/g;
227 }
228 else {
229 # remove 'schema.' prefix if any
230 $name =~ s/^[^.]+\.//;
231 }
232
233 return $name;
234}
235
19b7d71c 236sub _normalize_name {
237 my ($self, $name) = @_;
238
414c61a0 239 $name = $self->_sanitize_name($name);
240
cc4f11a2 241 my @words = split_name $name;
19b7d71c 242
243 return join '_', map lc, @words;
244}
245
f2fc8d01 246sub _remote_relname {
247 my ($self, $remote_table, $cond) = @_;
248
249 my $remote_relname;
250 # for single-column case, set the remote relname to the column
251 # name, to make filter accessors work, but strip trailing _id
252 if(scalar keys %{$cond} == 1) {
253 my ($col) = values %{$cond};
19b7d71c 254 $col = $self->_normalize_name($col);
f2fc8d01 255 $col =~ s/_id$//;
256 $remote_relname = $self->_inflect_singular($col);
257 }
258 else {
19b7d71c 259 $remote_relname = $self->_inflect_singular($self->_normalize_name($remote_table));
f2fc8d01 260 }
261
262 return $remote_relname;
263}
264
996be9ee 265sub generate_code {
26f1c8c9 266 my ($self, $local_moniker, $rels, $uniqs) = @_;
996be9ee 267
268 my $all_code = {};
269
e8ad6491 270 my $local_class = $self->{schema}->class($local_moniker);
057fbb08 271
e8ad6491 272 my %counters;
273 foreach my $rel (@$rels) {
274 next if !$rel->{remote_source};
275 $counters{$rel->{remote_source}}++;
276 }
277
278 foreach my $rel (@$rels) {
057fbb08 279 my $remote_moniker = $rel->{remote_source}
280 or next;
281
282 my $remote_class = $self->{schema}->class($remote_moniker);
283 my $remote_obj = $self->{schema}->source($remote_moniker);
284 my $remote_cols = $rel->{remote_columns} || [ $remote_obj->primary_columns ];
285
286 my $local_cols = $rel->{local_columns};
e8ad6491 287
288 if($#$local_cols != $#$remote_cols) {
289 croak "Column count mismatch: $local_moniker (@$local_cols) "
290 . "$remote_moniker (@$remote_cols)";
996be9ee 291 }
292
e8ad6491 293 my %cond;
294 foreach my $i (0 .. $#$local_cols) {
295 $cond{$remote_cols->[$i]} = $local_cols->[$i];
296 }
996be9ee 297
057fbb08 298 my ( $local_relname, $remote_relname, $remote_method ) =
39ef3bfe 299 $self->_relnames_and_method( $local_moniker, $rel, \%cond, $uniqs, \%counters );
7dba7c70 300
e8ad6491 301 push(@{$all_code->{$local_class}},
302 { method => 'belongs_to',
303 args => [ $remote_relname,
304 $remote_class,
305 \%cond,
c39e403e 306 $self->_remote_attrs($local_moniker, $local_cols),
e8ad6491 307 ],
996be9ee 308 }
e8ad6491 309 );
310
057fbb08 311 my %rev_cond = reverse %cond;
312 for (keys %rev_cond) {
313 $rev_cond{"foreign.$_"} = "self.".$rev_cond{$_};
314 delete $rev_cond{$_};
315 }
316
e8ad6491 317 push(@{$all_code->{$remote_class}},
26f1c8c9 318 { method => $remote_method,
e8ad6491 319 args => [ $local_relname,
320 $local_class,
321 \%rev_cond,
c8c27020 322 $self->_relationship_attrs($remote_method),
e8ad6491 323 ],
324 }
325 );
996be9ee 326 }
327
328 return $all_code;
329}
330
39ef3bfe 331sub _relnames_and_method {
057fbb08 332 my ( $self, $local_moniker, $rel, $cond, $uniqs, $counters ) = @_;
e9c09ed9 333
057fbb08 334 my $remote_moniker = $rel->{remote_source};
335 my $remote_obj = $self->{schema}->source( $remote_moniker );
336 my $remote_class = $self->{schema}->class( $remote_moniker );
ecf930e6 337 my $remote_relname = $self->_remote_relname( $remote_obj->from, $cond);
fa6f8d4e 338
057fbb08 339 my $local_cols = $rel->{local_columns};
340 my $local_table = $self->{schema}->source($local_moniker)->from;
341
342 # If more than one rel between this pair of tables, use the local
343 # col names to distinguish
ecf930e6 344 my ($local_relname, $local_relname_uninflected);
057fbb08 345 if ( $counters->{$remote_moniker} > 1) {
19b7d71c 346 my $colnames = q{_} . $self->_normalize_name(join '_', @$local_cols);
057fbb08 347 $remote_relname .= $colnames if keys %$cond > 1;
348
19b7d71c 349 $local_relname = $self->_normalize_name($local_table . $colnames);
c496748b 350 $local_relname =~ s/_id$//;
351
352 $local_relname_uninflected = $local_relname;
19b7d71c 353 $local_relname = $self->_inflect_plural($local_relname);
057fbb08 354 } else {
19b7d71c 355 $local_relname_uninflected = $self->_normalize_name($local_table);
356 $local_relname = $self->_inflect_plural($self->_normalize_name($local_table));
057fbb08 357 }
fa6f8d4e 358
057fbb08 359 my $remote_method = 'has_many';
360
361 # If the local columns have a UNIQUE constraint, this is a one-to-one rel
362 my $local_source = $self->{schema}->source($local_moniker);
ecf930e6 363 if ($self->_array_eq([ $local_source->primary_columns ], $local_cols) ||
364 grep { $self->_array_eq($_->[1], $local_cols) } @$uniqs) {
057fbb08 365 $remote_method = 'might_have';
c496748b 366 $local_relname = $self->_inflect_singular($local_relname_uninflected);
057fbb08 367 }
fa6f8d4e 368
057fbb08 369 return ( $local_relname, $remote_relname, $remote_method );
fa6f8d4e 370}
371
be80bba7 372=head1 AUTHOR
373
9cc8e7e1 374See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 375
376=head1 LICENSE
377
378This library is free software; you can redistribute it and/or modify it under
379the same terms as Perl itself.
380
381=cut
382
996be9ee 3831;
19b7d71c 384# vim:et sts=4 sw=4 tw=0: