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