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