1 package DBIx::Class::Schema::Loader::Base;
5 use base qw/Class::Accessor::Fast/;
7 use Carp::Clan qw/^DBIx::Class/;
8 use UNIVERSAL::require;
9 use DBIx::Class::Schema::Loader::RelBuilder;
10 use Data::Dump qw/ dump /;
16 our $VERSION = '0.03999_01';
18 __PACKAGE__->mk_ro_accessors(qw/
25 additional_base_classes
45 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
49 See L<DBIx::Class::Schema::Loader>
53 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
54 classes, and implements the common functionality between them.
56 =head1 CONSTRUCTOR OPTIONS
58 These constructor options are the base options for
59 L<DBIx::Class::Schema::Loader/loader_opts>. Available constructor options are:
61 =head2 skip_relationships
63 Skip setting up relationships. The default is to attempt the loading
68 If set to true, each constructive L<DBIx::Class> statement the loader
69 decides to execute will be C<warn>-ed before execution.
73 Set the name of the schema to load (schema in the sense that your database
74 vendor means it). Does not currently support loading more than one schema
79 Only load tables matching regex. Best specified as a qr// regex.
83 Exclude tables matching regex. Best specified as a qr// regex.
87 Overrides the default table name to moniker translation. Can be either
88 a hashref of table keys and moniker values, or a coderef for a translator
89 function taking a single scalar table name argument and returning
90 a scalar moniker. If the hash entry does not exist, or the function
91 returns a false value, the code falls back to default behavior
94 The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
95 which is to say: lowercase everything, split up the table name into chunks
96 anywhere a non-alpha-numeric character occurs, change the case of first letter
97 of each chunk to upper case, and put the chunks back together. Examples:
99 Table Name | Moniker Name
100 ---------------------------
102 luser_group | LuserGroup
103 luser-opts | LuserOpts
105 =head2 inflect_plural
107 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
108 if hash key does not exist or coderef returns false), but acts as a map
109 for pluralizing relationship names. The default behavior is to utilize
110 L<Lingua::EN::Inflect::Number/to_PL>.
112 =head2 inflect_singular
114 As L</inflect_plural> above, but for singularizing relationship names.
115 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
117 =head2 additional_base_classes
119 List of additional base classes all of your table classes will use.
121 =head2 left_base_classes
123 List of additional base classes all of your table classes will use
124 that need to be leftmost.
126 =head2 additional_classes
128 List of additional classes which all of your table classes will use.
132 List of additional components to be loaded into all of your table
133 classes. A good example would be C<ResultSetManager>.
135 =head2 resultset_components
137 List of additional ResultSet components to be loaded into your table
138 classes. A good example would be C<AlwaysRS>. Component
139 C<ResultSetManager> will be automatically added to the above
140 C<components> list if this option is set.
142 =head2 dump_directory
144 This option is designed to be a tool to help you transition from this
145 loader to a manually-defined schema when you decide it's time to do so.
147 The value of this option is a perl libdir pathname. Within
148 that directory this module will create a baseline manual
149 L<DBIx::Class::Schema> module set, based on what it creates at runtime
152 The created schema class will have the same classname as the one on
153 which you are setting this option (and the ResultSource classes will be
154 based on this name as well).
156 Normally you wouldn't hard-code this setting in your schema class, as it
157 is meant for one-time manual usage.
159 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
160 recommended way to access this functionality.
162 =head2 dump_overwrite
164 Default false. If true, Loader will unconditionally delete any existing
165 files before creating the new ones from scratch when dumping a schema to disk.
167 The default behavior is instead to only replace the top portion of the
168 file, up to and including the final stanza which contains
169 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
170 leaving any customizations you placed after that as they were.
172 When C<dump_overwrite> is not set, if the output file already exists,
173 but the aforementioned final stanza is not found, or the checksum
174 contained there does not match the generated contents, Loader will
175 croak and not touch the file.
179 None of these methods are intended for direct invocation by regular
180 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
181 can also be found via standard L<DBIx::Class::Schema> methods somehow.
185 # ensure that a peice of object data is a valid arrayref, creating
186 # an empty one or encapsulating whatever's there.
187 sub _ensure_arrayref {
192 $self->{$_} = [ $self->{$_} ]
193 unless ref $self->{$_} eq 'ARRAY';
199 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
200 by L<DBIx::Class::Schema::Loader>.
205 my ( $class, %args ) = @_;
207 my $self = { %args };
209 bless $self => $class;
211 $self->{db_schema} ||= '';
212 $self->_ensure_arrayref(qw/additional_classes
213 additional_base_classes
219 push(@{$self->{components}}, 'ResultSetManager')
220 if @{$self->{resultset_components}};
222 $self->{monikers} = {};
223 $self->{classes} = {};
225 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
226 $self->{schema} ||= $self->{schema_class};
236 $abs_dump_dir = File::Spec->rel2abs($self->dump_directory)
237 if $self->dump_directory;
239 foreach my $class ($self->schema_class, values %{$self->classes}) {
241 if($@ && $@ !~ /^Can't locate /) {
242 croak "Failed to load external class definition"
243 . " for '$class': $@";
245 next if $@; # "Can't locate" error
247 # If we make it to here, we loaded an external definition
248 warn qq/# Loaded external class definition for '$class'\n/
252 my $class_path = $class;
253 $class_path =~ s{::}{/}g;
254 $class_path .= '.pm';
255 my $filename = File::Spec->rel2abs($INC{$class_path});
256 croak 'Failed to locate actual external module file for '
259 # XXX this should be done MUCH EARLIER, do not require dump_dir files!!!
260 next if($filename =~ /^$abs_dump_dir/);
261 open(my $fh, '<', $filename)
262 or croak "Failed to open $filename for reading: $!";
263 $self->_ext_stmt($class,
264 qq|# These lines were loaded from '$filename' found in \@INC.|
265 .q|# They are now part of the custom portion of this file|
266 .q|# for you to hand-edit. If you do not either delete|
267 .q|# this section or remove that file from @INC, this section|
268 .q|# will be repeated redundantly when you re-create this|
269 .q|# file again via Loader!|
273 $self->_ext_stmt($class, $_);
275 $self->_ext_stmt($class,
276 q|# End of lines loaded from '$filename' |
279 or croak "Failed to close $filename: $!";
286 Does the actual schema-construction work.
293 $self->_load_classes;
294 $self->_load_relationships if ! $self->skip_relationships;
295 $self->_load_external;
296 $self->_dump_to_dir if $self->dump_directory;
298 # Drop temporary cache
299 delete $self->{_cache};
304 sub _get_dump_filename {
305 my ($self, $class) = (@_);
308 return $self->dump_directory . q{/} . $class . q{.pm};
311 sub _ensure_dump_subdirs {
312 my ($self, $class) = (@_);
314 my @name_parts = split(/::/, $class);
315 pop @name_parts; # we don't care about the very last element,
316 # which is a filename
318 my $dir = $self->dump_directory;
321 mkdir($dir) or croak "mkdir('$dir') failed: $!";
323 last if !@name_parts;
324 $dir = File::Spec->catdir($dir, shift @name_parts);
331 my $target_dir = $self->dump_directory;
333 my $schema_class = $self->schema_class;
335 croak "Must specify target directory for dumping!" if ! $target_dir;
337 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n";
340 qq|package $schema_class;\n\n|
341 . qq|use strict;\nuse warnings;\n\n|
342 . qq|use base 'DBIx::Class::Schema';\n\n|
343 . qq|__PACKAGE__->load_classes;\n|;
345 $self->_write_classfile($schema_class, $schema_text);
347 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
349 qq|package $src_class;\n\n|
350 . qq|use strict;\nuse warnings;\n\n|
351 . qq|use base 'DBIx::Class';\n\n|;
353 $self->_write_classfile($src_class, $src_text);
356 warn "Schema dump completed.\n";
359 sub _write_classfile {
360 my ($self, $class, $text) = @_;
362 my $filename = $self->_get_dump_filename($class);
363 $self->_ensure_dump_subdirs($class);
365 if (-f $filename && $self->dump_overwrite) {
366 warn "Deleting existing file '$filename' due to "
367 . "'dump_overwrite' setting\n";
371 my $custom_content = $self->_get_custom_content($filename);
373 $custom_content ||= qq|\n# You can replace this text with custom|
374 . qq| content, and it will be preserved on regeneration|
378 for @{$self->{_dump_storage}->{$class} || []};
380 $text .= qq|\n\n# Created by DBIx::Class::Schema::Loader|
381 . qq| v| . $DBIx::Class::Schema::Loader::VERSION
382 . q| @ | . POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
383 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
385 open(my $fh, '>', $filename)
386 or croak "Cannot open '$filename' for writing: $!";
388 # Write the top half and its MD5 sum
389 print $fh $text . Digest::MD5::md5_base64($text) . "\n\n";
391 # Write out anything loaded via external partial class file in @INC
393 for @{$self->{_ext_storage}->{$class} || []};
395 print $fh $custom_content;
398 or croak "Cannot close '$filename': $!";
401 sub _get_custom_content {
402 my ($self, $class, $filename) = @_;
404 return if ! -f $filename;
405 open(my $fh, '<', $filename)
406 or croak "Cannot open '$filename' for reading: $!";
409 /^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n/;
414 if(!$found && /$mark_re/) {
418 croak "Checksum mismatch in '$filename'"
419 if Digest::MD5::md5_base64($buffer) ne $checksum;
428 croak "Cannot not overwrite '$filename' without 'dump_overwrite',"
429 " it does not appear to have been generated by Loader";
441 warn "$target: use $_;" if $self->debug;
442 $self->_raw_stmt($target, "use $_;");
443 $_->require or croak ($_ . "->require: $@");
444 $evalstr .= "package $target; use $_;";
446 eval $evalstr if $evalstr;
453 my $schema_class = $self->schema_class;
455 my $blist = join(q{ }, @_);
456 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
457 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
459 $_->require or croak ($_ . "->require: $@");
460 $schema_class->inject_base($target, $_);
464 # Load and setup classes
468 my $schema = $self->schema;
469 my $schema_class = $self->schema_class;
470 my $constraint = $self->constraint;
471 my $exclude = $self->exclude;
472 my @tables = sort $self->_tables_list;
474 warn "No tables found in database, nothing to load" if !@tables;
477 @tables = grep { /$constraint/ } @tables if $constraint;
478 @tables = grep { ! /$exclude/ } @tables if $exclude;
480 warn "All tables excluded by constraint/exclude, nothing to load"
484 $self->{_tables} = \@tables;
486 foreach my $table (@tables) {
487 my $table_moniker = $self->_table2moniker($table);
488 my $table_class = $schema_class . q{::} . $table_moniker;
490 my $table_normalized = lc $table;
491 $self->classes->{$table} = $table_class;
492 $self->classes->{$table_normalized} = $table_class;
493 $self->monikers->{$table} = $table_moniker;
494 $self->monikers->{$table_normalized} = $table_moniker;
496 no warnings 'redefine';
497 local *Class::C3::reinitialize = sub { };
500 { no strict 'refs'; @{"${table_class}::ISA"} = qw/DBIx::Class/ }
502 $self->_use ($table_class, @{$self->additional_classes});
503 $self->_inject($table_class, @{$self->additional_base_classes});
505 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, qw/PK::Auto Core/);
507 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
508 if @{$self->resultset_components};
509 $self->_inject($table_class, @{$self->left_base_classes});
512 Class::C3::reinitialize;
514 foreach my $table (@tables) {
515 my $table_class = $self->classes->{$table};
516 my $table_moniker = $self->monikers->{$table};
518 $self->_dbic_stmt($table_class,'table',$table);
520 my $cols = $self->_table_columns($table);
522 eval { $col_info = $self->_columns_info_for($table) };
524 $self->_dbic_stmt($table_class,'add_columns',@$cols);
527 my %col_info_lc = map { lc($_), $col_info->{$_} } keys %$col_info;
531 map { $_, ($col_info_lc{$_}||{}) } @$cols
535 my $pks = $self->_table_pk_info($table) || [];
536 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
537 : carp("$table has no primary key");
539 my $uniqs = $self->_table_uniq_info($table) || [];
540 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
542 $schema_class->register_class($table_moniker, $table_class);
543 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
549 Returns a sorted list of loaded tables, using the original database table
557 return @{$self->_tables};
560 # Make a moniker from a table
562 my ( $self, $table ) = @_;
566 if( ref $self->moniker_map eq 'HASH' ) {
567 $moniker = $self->moniker_map->{$table};
569 elsif( ref $self->moniker_map eq 'CODE' ) {
570 $moniker = $self->moniker_map->($table);
573 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
578 sub _load_relationships {
581 # Construct the fk_info RelBuilder wants to see, by
582 # translating table names to monikers in the _fk_info output
584 foreach my $table ($self->tables) {
585 my $tbl_fk_info = $self->_table_fk_info($table);
586 foreach my $fkdef (@$tbl_fk_info) {
587 $fkdef->{remote_source} =
588 $self->monikers->{delete $fkdef->{remote_table}};
590 my $moniker = $self->monikers->{$table};
591 $fk_info{$moniker} = $tbl_fk_info;
594 my $relbuilder = DBIx::Class::Schema::Loader::RelBuilder->new(
595 $self->schema_class, \%fk_info, $self->inflect_plural,
596 $self->inflect_singular
599 my $rel_stmts = $relbuilder->generate_code;
600 foreach my $src_class (sort keys %$rel_stmts) {
601 my $src_stmts = $rel_stmts->{$src_class};
602 foreach my $stmt (@$src_stmts) {
603 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
608 # Overload these in driver class:
610 # Returns an arrayref of column names
611 sub _table_columns { croak "ABSTRACT METHOD" }
613 # Returns arrayref of pk col names
614 sub _table_pk_info { croak "ABSTRACT METHOD" }
616 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
617 sub _table_uniq_info { croak "ABSTRACT METHOD" }
619 # Returns an arrayref of foreign key constraints, each
620 # being a hashref with 3 keys:
621 # local_columns (arrayref), remote_columns (arrayref), remote_table
622 sub _table_fk_info { croak "ABSTRACT METHOD" }
624 # Returns an array of lower case table names
625 sub _tables_list { croak "ABSTRACT METHOD" }
627 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
633 if(!$self->debug && !$self->dump_directory) {
639 $args = '(' . $args . ')' if @_ < 2;
640 my $stmt = $method . $args . q{;};
642 warn qq|$class\->$stmt\n| if $self->debug;
644 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
647 # Store a raw source line for a class (for dumping purposes)
649 my ($self, $class, $stmt) = @_;
650 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
653 # Like above, but separately for the externally loaded stuff
655 my ($self, $class, $stmt) = @_;
656 push(@{$self->{_ext_storage}->{$class}}, $stmt) if $self->dump_directory;
661 Returns a hashref of loaded table to moniker mappings. There will
662 be two entries for each table, the original name and the "normalized"
663 name, in the case that the two are different (such as databases
664 that like uppercase table names, or preserve your original mixed-case
665 definitions, or what-have-you).
669 Returns a hashref of table to class mappings. In some cases it will
670 contain multiple entries per table for the original and normalized table
671 names, as above in L</monikers>.
675 L<DBIx::Class::Schema::Loader>