some TODO additions
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / Base.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::Base;
2
3use strict;
4use warnings;
5use base qw/Class::Accessor::Fast/;
6use Class::C3;
7use Carp;
8use UNIVERSAL::require;
9use DBIx::Class::Schema::Loader::RelBuilder;
10use Data::Dump qw/ dump /;
11use POSIX qw//;
12require DBIx::Class;
13
14__PACKAGE__->mk_ro_accessors(qw/
15 schema
16 schema_class
17
18 exclude
19 constraint
20 additional_classes
21 additional_base_classes
22 left_base_classes
23 components
24 resultset_components
25 relationships
26 moniker_map
27 inflect_singular
28 inflect_plural
29 debug
30 dump_directory
31
32 legacy_default_inflections
33
34 db_schema
35 _tables
36 classes
37 monikers
38 /);
39
40=head1 NAME
41
42DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
43
44=head1 SYNOPSIS
45
46See L<DBIx::Class::Schema::Loader>
47
48=head1 DESCRIPTION
49
50This is the base class for the storage-specific C<DBIx::Class::Schema::*>
51classes, and implements the common functionality between them.
52
53=head1 CONSTRUCTOR OPTIONS
54
55These constructor options are the base options for
56L<DBIx::Class::Schema::Loader/loader_opts>. Available constructor options are:
57
58=head2 relationships
59
60Try to automatically detect/setup has_a and has_many relationships.
61
62=head2 debug
63
64If set to true, each constructive L<DBIx::Class> statement the loader
65decides to execute will be C<warn>-ed before execution.
66
67=head2 constraint
68
69Only load tables matching regex. Best specified as a qr// regex.
70
71=head2 exclude
72
73Exclude tables matching regex. Best specified as a qr// regex.
74
75=head2 moniker_map
76
8f9d7ce5 77Overrides the default table name to moniker translation. Can be either
78a hashref of table keys and moniker values, or a coderef for a translator
996be9ee 79function taking a single scalar table name argument and returning
80a scalar moniker. If the hash entry does not exist, or the function
81returns a false value, the code falls back to default behavior
82for that table name.
83
84The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
85which is to say: lowercase everything, split up the table name into chunks
86anywhere a non-alpha-numeric character occurs, change the case of first letter
87of each chunk to upper case, and put the chunks back together. Examples:
88
89 Table Name | Moniker Name
90 ---------------------------
91 luser | Luser
92 luser_group | LuserGroup
93 luser-opts | LuserOpts
94
95=head2 inflect_plural
96
97Just like L</moniker_map> above (can be hash/code-ref, falls back to default
98if hash key does not exist or coderef returns false), but acts as a map
99for pluralizing relationship names. The default behavior is to utilize
100L<Lingua::EN::Inflect::Number/to_PL>.
101
102=head2 inflect_singular
103
104As L</inflect_plural> above, but for singularizing relationship names.
105Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
106
107=head2 additional_base_classes
108
109List of additional base classes all of your table classes will use.
110
111=head2 left_base_classes
112
113List of additional base classes all of your table classes will use
114that need to be leftmost.
115
116=head2 additional_classes
117
118List of additional classes which all of your table classes will use.
119
120=head2 components
121
122List of additional components to be loaded into all of your table
123classes. A good example would be C<ResultSetManager>.
124
125=head2 resultset_components
126
8f9d7ce5 127List of additional ResultSet components to be loaded into your table
996be9ee 128classes. A good example would be C<AlwaysRS>. Component
129C<ResultSetManager> will be automatically added to the above
130C<components> list if this option is set.
131
132=head2 legacy_default_inflections
133
134Setting this option changes the default fallback for L</inflect_plural> to
8f9d7ce5 135utilize L<Lingua::EN::Inflect/PL>, and L</inflect_singular> to a no-op.
136Those choices produce substandard results, but might be necessary to support
996be9ee 137your existing code if you started developing on a version prior to 0.03 and
138don't wish to go around updating all your relationship names to the new
139defaults.
140
141=head2 dump_directory
142
143This option is designed to be a tool to help you transition from this
144loader to a manually-defined schema when you decide it's time to do so.
145
146The value of this option is a perl libdir pathname. Within
147that directory this module will create a baseline manual
148L<DBIx::Class::Schema> module set, based on what it creates at runtime
149in memory.
150
151The created schema class will have the same classname as the one on
152which you are setting this option (and the ResultSource classes will be
153based on this name as well). Therefore it is wise to note that if you
154point the C<dump_directory> option of a schema class at the live libdir
155where that class is currently located, it will overwrite itself with a
156manual version of itself. This might be a really good or bad thing
157depending on your situation and perspective.
158
8f9d7ce5 159Normally you wouldn't hard-code this setting in your schema class, as it
996be9ee 160is meant for one-time manual usage.
161
162See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
163recommended way to access this functionality.
164
165=head1 DEPRECATED CONSTRUCTOR OPTIONS
166
167=head2 inflect_map
168
169Equivalent to L</inflect_plural>.
170
171=head2 inflect
172
173Equivalent to L</inflect_plural>.
174
175=head2 connect_info, dsn, user, password, options
176
177You connect these schemas the same way you would any L<DBIx::Class::Schema>,
178which is by calling either C<connect> or C<connection> on a schema class
179or object. These options are only supported via the deprecated
180C<load_from_connection> interface, which will be removed in the future.
181
182=head1 METHODS
183
184None of these methods are intended for direct invocation by regular
185users of L<DBIx::Class::Schema::Loader>. Anything you can find here
186can also be found via standard L<DBIx::Class::Schema> methods somehow.
187
188=cut
189
190# ensure that a peice of object data is a valid arrayref, creating
191# an empty one or encapsulating whatever's there.
192sub _ensure_arrayref {
193 my $self = shift;
194
195 foreach (@_) {
196 $self->{$_} ||= [];
197 $self->{$_} = [ $self->{$_} ]
198 unless ref $self->{$_} eq 'ARRAY';
199 }
200}
201
202=head2 new
203
204Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
205by L<DBIx::Class::Schema::Loader>.
206
207=cut
208
209sub new {
210 my ( $class, %args ) = @_;
211
212 my $self = { %args };
213
214 bless $self => $class;
215
216 $self->{db_schema} ||= '';
217 $self->_ensure_arrayref(qw/additional_classes
218 additional_base_classes
219 left_base_classes
220 components
221 resultset_components
222 /);
223
224 push(@{$self->{components}}, 'ResultSetManager')
225 if @{$self->{resultset_components}};
226
227 $self->{monikers} = {};
228 $self->{classes} = {};
229
230 # Support deprecated arguments
231 for(qw/inflect_map inflect/) {
232 warn "Argument $_ is deprecated in favor of 'inflect_plural'"
233 if $self->{$_};
234 }
235 $self->{inflect_plural} ||= $self->{inflect_map} || $self->{inflect};
236
237 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
238 $self->{schema} ||= $self->{schema_class};
239
240 $self;
241}
242
243sub _load_external {
244 my $self = shift;
245
246 foreach my $table_class (values %{$self->classes}) {
247 $table_class->require;
248 if($@ && $@ !~ /^Can't locate /) {
249 croak "Failed to load external class definition"
250 . " for '$table_class': $@";
251 }
252 next if $@; # "Can't locate" error
253
254 # If we make it to here, we loaded an external definition
255 warn qq/# Loaded external class definition for '$table_class'\n/
256 if $self->debug;
257
258 if($self->dump_directory) {
259 my $class_path = $table_class;
260 $class_path =~ s{::}{/}g;
e50425a9 261 $class_path .= '.pm';
996be9ee 262 my $filename = $INC{$class_path};
263 croak 'Failed to locate actual external module file for '
264 . "'$table_class'"
265 if !$filename;
266 open(my $fh, '<', $filename)
267 or croak "Failed to open $filename for reading: $!";
268 $self->_raw_stmt($table_class,
269 q|# These lines loaded from user-supplied external file: |
270 );
271 while(<$fh>) {
272 chomp;
273 $self->_raw_stmt($table_class, $_);
274 }
275 $self->_raw_stmt($table_class,
276 q|# End of lines loaded from user-supplied external file |
277 );
278 close($fh)
279 or croak "Failed to close $filename: $!";
280 }
281 }
282}
283
284=head2 load
285
286Does the actual schema-construction work.
287
288=cut
289
290sub load {
291 my $self = shift;
292
293 $self->_load_classes;
294 $self->_load_relationships if $self->relationships;
295 $self->_load_external;
296 $self->_dump_to_dir if $self->dump_directory;
297
5223f24a 298 # Drop temporary cache
299 delete $self->{_cache};
300
996be9ee 301 1;
302}
303
304sub _get_dump_filename {
305 my ($self, $class) = (@_);
306
307 $class =~ s{::}{/}g;
308 return $self->dump_directory . q{/} . $class . q{.pm};
309}
310
311sub _ensure_dump_subdirs {
312 my ($self, $class) = (@_);
313
314 my @name_parts = split(/::/, $class);
315 pop @name_parts;
316 my $dir = $self->dump_directory;
317 foreach (@name_parts) {
318 $dir .= q{/} . $_;
319 if(! -d $dir) {
320 mkdir($dir) or die "mkdir('$dir') failed: $!";
321 }
322 }
323}
324
325sub _dump_to_dir {
326 my ($self) = @_;
327
328 my $target_dir = $self->dump_directory;
fc2b71fd 329 my $schema_class = $self->schema_class;
996be9ee 330
331 die "Must specify target directory for dumping!" if ! $target_dir;
332
fc2b71fd 333 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n";
996be9ee 334
335 if(! -d $target_dir) {
336 mkdir($target_dir) or die "mkdir('$target_dir') failed: $!";
337 }
338
339 my $verstr = $DBIx::Class::Schema::Loader::VERSION;
340 my $datestr = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
341 my $tagline = qq|# Created by DBIx::Class::Schema::Loader v$verstr @ $datestr|;
342
996be9ee 343 $self->_ensure_dump_subdirs($schema_class);
344
345 my $schema_fn = $self->_get_dump_filename($schema_class);
346 open(my $schema_fh, '>', $schema_fn)
347 or die "Cannot open $schema_fn for writing: $!";
348 print $schema_fh qq|package $schema_class;\n\n$tagline\n\n|;
349 print $schema_fh qq|use strict;\nuse warnings;\n\n|;
350 print $schema_fh qq|use base 'DBIx::Class::Schema';\n\n|;
351 print $schema_fh qq|__PACKAGE__->load_classes;\n|;
352 print $schema_fh qq|\n1;\n\n|;
353 close($schema_fh)
354 or die "Cannot close $schema_fn: $!";
355
356 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
357 $self->_ensure_dump_subdirs($src_class);
358 my $src_fn = $self->_get_dump_filename($src_class);
359 open(my $src_fh, '>', $src_fn)
360 or die "Cannot open $src_fn for writing: $!";
361 print $src_fh qq|package $src_class;\n\n$tagline\n\n|;
362 print $src_fh qq|use strict;\nuse warnings;\n\n|;
363 print $src_fh qq|use base 'DBIx::Class';\n\n|;
364 print $src_fh qq|$_\n|
365 for @{$self->{_dump_storage}->{$src_class}};
366 print $src_fh qq|\n1;\n\n|;
367 close($src_fh)
368 or die "Cannot close $src_fn: $!";
369 }
370
371 warn "Schema dump completed.\n";
372}
373
374sub _use {
375 my $self = shift;
376 my $target = shift;
377
378 foreach (@_) {
379 $_->require or croak ($_ . "->require: $@");
380 $self->_raw_stmt($target, "use $_;");
381 warn "$target: use $_" if $self->debug;
382 eval "package $target; use $_;";
383 croak "use $_: $@" if $@;
384 }
385}
386
387sub _inject {
388 my $self = shift;
389 my $target = shift;
390 my $schema_class = $self->schema_class;
391
392 my $blist = join(q{ }, @_);
393 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
394 warn "$target: use base qw/ $blist /" if $self->debug;
395 foreach (@_) {
396 $_->require or croak ($_ . "->require: $@");
397 $schema_class->inject_base($target, $_);
398 }
399}
400
401# Load and setup classes
402sub _load_classes {
403 my $self = shift;
404
405 my $schema = $self->schema;
406 my $schema_class = $self->schema_class;
407
408 my $constraint = $self->constraint;
409 my $exclude = $self->exclude;
410 my @tables = sort $self->_tables_list;
411
412 warn "No tables found in database, nothing to load" if !@tables;
413
414 if(@tables) {
415 @tables = grep { /$constraint/ } @tables if $constraint;
416 @tables = grep { ! /$exclude/ } @tables if $exclude;
417
418 warn "All tables excluded by constraint/exclude, nothing to load"
419 if !@tables;
420 }
421
422 $self->{_tables} = \@tables;
423
424 foreach my $table (@tables) {
425 my $table_moniker = $self->_table2moniker($table);
426 my $table_class = $schema_class . q{::} . $table_moniker;
427
428 my $table_normalized = lc $table;
429 $self->classes->{$table} = $table_class;
430 $self->classes->{$table_normalized} = $table_class;
431 $self->monikers->{$table} = $table_moniker;
432 $self->monikers->{$table_normalized} = $table_moniker;
433
434 no warnings 'redefine';
435 local *Class::C3::reinitialize = sub { };
436 use warnings;
437
438 { no strict 'refs';
439 @{"${table_class}::ISA"} = qw/DBIx::Class/;
440 }
441 $self->_use ($table_class, @{$self->additional_classes});
442 $self->_inject($table_class, @{$self->additional_base_classes});
443
444 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, qw/PK::Auto Core/);
445
446 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
447 if @{$self->resultset_components};
448 $self->_inject($table_class, @{$self->left_base_classes});
449 }
450
451 Class::C3::reinitialize;
452
453 foreach my $table (@tables) {
454 my $table_class = $self->classes->{$table};
455 my $table_moniker = $self->monikers->{$table};
456
457 $self->_dbic_stmt($table_class,'table',$table);
458
459 my $cols = $self->_table_columns($table);
460 $self->_dbic_stmt($table_class,'add_columns',@$cols);
461
462 my $pks = $self->_table_pk_info($table) || [];
463 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
464 : carp("$table has no primary key");
465
466 my $uniqs = $self->_table_uniq_info($table) || [];
467 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
468
469 $schema_class->register_class($table_moniker, $table_class);
470 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
471 }
472}
473
474=head2 tables
475
476Returns a sorted list of loaded tables, using the original database table
477names.
478
479=cut
480
481sub tables {
482 my $self = shift;
483
484 return @{$self->_tables};
485}
486
487# Make a moniker from a table
488sub _table2moniker {
489 my ( $self, $table ) = @_;
490
491 my $moniker;
492
493 if( ref $self->moniker_map eq 'HASH' ) {
494 $moniker = $self->moniker_map->{$table};
495 }
496 elsif( ref $self->moniker_map eq 'CODE' ) {
497 $moniker = $self->moniker_map->($table);
498 }
499
500 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
501
502 return $moniker;
503}
504
505sub _load_relationships {
506 my $self = shift;
507
508 # Construct the fk_info RelBuilder wants to see, by
509 # translating table names to monikers in the _fk_info output
510 my %fk_info;
511 foreach my $table ($self->tables) {
512 my $tbl_fk_info = $self->_table_fk_info($table);
513 foreach my $fkdef (@$tbl_fk_info) {
514 $fkdef->{remote_source} =
515 $self->monikers->{delete $fkdef->{remote_table}};
516 }
517 my $moniker = $self->monikers->{$table};
518 $fk_info{$moniker} = $tbl_fk_info;
519 }
520
521 my $relbuilder = DBIx::Class::Schema::Loader::RelBuilder->new(
522 $self->schema_class, \%fk_info, $self->inflect_plural,
523 $self->inflect_singular
524 );
525
526 my $rel_stmts = $relbuilder->generate_code;
527 foreach my $src_class (sort keys %$rel_stmts) {
528 my $src_stmts = $rel_stmts->{$src_class};
529 foreach my $stmt (@$src_stmts) {
530 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
531 }
532 }
533}
534
535# Overload these in driver class:
536
537# Returns an arrayref of column names
538sub _table_columns { croak "ABSTRACT METHOD" }
539
540# Returns arrayref of pk col names
541sub _table_pk_info { croak "ABSTRACT METHOD" }
542
543# Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
544sub _table_uniq_info { croak "ABSTRACT METHOD" }
545
546# Returns an arrayref of foreign key constraints, each
547# being a hashref with 3 keys:
548# local_columns (arrayref), remote_columns (arrayref), remote_table
549sub _table_fk_info { croak "ABSTRACT METHOD" }
550
551# Returns an array of lower case table names
552sub _tables_list { croak "ABSTRACT METHOD" }
553
554# Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
555sub _dbic_stmt {
556 my $self = shift;
557 my $class = shift;
558 my $method = shift;
559
560 if(!$self->debug && !$self->dump_directory) {
561 $class->$method(@_);
562 return;
563 }
564
565 my $args = dump(@_);
566 $args = '(' . $args . ')' if @_ < 2;
567 my $stmt = $method . $args . q{;};
568
569 warn qq|$class\->$stmt\n| if $self->debug;
570 $class->$method(@_);
571 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
572}
573
574# Store a raw source line for a class (for dumping purposes)
575sub _raw_stmt {
576 my ($self, $class, $stmt) = @_;
577 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
578}
579
580=head2 monikers
581
8f9d7ce5 582Returns a hashref of loaded table to moniker mappings. There will
996be9ee 583be two entries for each table, the original name and the "normalized"
584name, in the case that the two are different (such as databases
585that like uppercase table names, or preserve your original mixed-case
586definitions, or what-have-you).
587
588=head2 classes
589
8f9d7ce5 590Returns a hashref of table to class mappings. In some cases it will
996be9ee 591contain multiple entries per table for the original and normalized table
592names, as above in L</monikers>.
593
594=head1 SEE ALSO
595
596L<DBIx::Class::Schema::Loader>
597
598=cut
599
6001;