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 /;
17 our $VERSION = '0.04999_04';
19 __PACKAGE__->mk_ro_accessors(qw/
26 additional_base_classes
41 default_resultset_class
51 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
55 See L<DBIx::Class::Schema::Loader>
59 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
60 classes, and implements the common functionality between them.
62 =head1 CONSTRUCTOR OPTIONS
64 These constructor options are the base options for
65 L<DBIx::Class::Schema::Loader/loader_opts>. Available constructor options are:
69 Use the specified class as the loader instead of
70 C<DBIx::Class::Schema::Loader${storage_type}>. This is mostly useful for
71 subclassing existing loaders or in conjunction with
72 L<DBIx::Class::Schema::Loader/dump_to_dir>.
74 =head2 skip_relationships
76 Skip setting up relationships. The default is to attempt the loading
81 If set to true, each constructive L<DBIx::Class> statement the loader
82 decides to execute will be C<warn>-ed before execution.
86 Set the name of the schema to load (schema in the sense that your database
87 vendor means it). Does not currently support loading more than one schema
92 Only load tables matching regex. Best specified as a qr// regex.
96 Exclude tables matching regex. Best specified as a qr// regex.
100 Overrides the default table name to moniker translation. Can be either
101 a hashref of table keys and moniker values, or a coderef for a translator
102 function taking a single scalar table name argument and returning
103 a scalar moniker. If the hash entry does not exist, or the function
104 returns a false value, the code falls back to default behavior
107 The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
108 which is to say: lowercase everything, split up the table name into chunks
109 anywhere a non-alpha-numeric character occurs, change the case of first letter
110 of each chunk to upper case, and put the chunks back together. Examples:
112 Table Name | Moniker Name
113 ---------------------------
115 luser_group | LuserGroup
116 luser-opts | LuserOpts
118 =head2 inflect_plural
120 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
121 if hash key does not exist or coderef returns false), but acts as a map
122 for pluralizing relationship names. The default behavior is to utilize
123 L<Lingua::EN::Inflect::Number/to_PL>.
125 =head2 inflect_singular
127 As L</inflect_plural> above, but for singularizing relationship names.
128 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
130 =head2 additional_base_classes
132 List of additional base classes all of your table classes will use.
134 =head2 left_base_classes
136 List of additional base classes all of your table classes will use
137 that need to be leftmost.
139 =head2 additional_classes
141 List of additional classes which all of your table classes will use.
145 List of additional components to be loaded into all of your table
146 classes. A good example would be C<ResultSetManager>.
148 =head2 resultset_components
150 List of additional ResultSet components to be loaded into your table
151 classes. A good example would be C<AlwaysRS>. Component
152 C<ResultSetManager> will be automatically added to the above
153 C<components> list if this option is set.
155 =head2 use_namespaces
157 Generate result class names suitable for
158 L<DBIx::Class::Schema/load_namespaces> and call that instead of
159 L<DBIx::Class::Schema/load_classes>. When using this option you can also
160 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
161 C<resultset_namespace>, C<default_resultset_class>), and they will be added
162 to the call (and the generated result class names adjusted appropriately).
164 =head2 dump_directory
166 This option is designed to be a tool to help you transition from this
167 loader to a manually-defined schema when you decide it's time to do so.
169 The value of this option is a perl libdir pathname. Within
170 that directory this module will create a baseline manual
171 L<DBIx::Class::Schema> module set, based on what it creates at runtime
174 The created schema class will have the same classname as the one on
175 which you are setting this option (and the ResultSource classes will be
176 based on this name as well).
178 Normally you wouldn't hard-code this setting in your schema class, as it
179 is meant for one-time manual usage.
181 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
182 recommended way to access this functionality.
184 =head2 dump_overwrite
186 Deprecated. See L</really_erase_my_files> below, which does *not* mean
187 the same thing as the old C<dump_overwrite> setting from previous releases.
189 =head2 really_erase_my_files
191 Default false. If true, Loader will unconditionally delete any existing
192 files before creating the new ones from scratch when dumping a schema to disk.
194 The default behavior is instead to only replace the top portion of the
195 file, up to and including the final stanza which contains
196 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
197 leaving any customizations you placed after that as they were.
199 When C<really_erase_my_files> is not set, if the output file already exists,
200 but the aforementioned final stanza is not found, or the checksum
201 contained there does not match the generated contents, Loader will
202 croak and not touch the file.
204 You should really be using version control on your schema classes (and all
205 of the rest of your code for that matter). Don't blame me if a bug in this
206 code wipes something out when it shouldn't have, you've been warned.
210 None of these methods are intended for direct invocation by regular
211 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
212 can also be found via standard L<DBIx::Class::Schema> methods somehow.
216 # ensure that a peice of object data is a valid arrayref, creating
217 # an empty one or encapsulating whatever's there.
218 sub _ensure_arrayref {
223 $self->{$_} = [ $self->{$_} ]
224 unless ref $self->{$_} eq 'ARRAY';
230 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
231 by L<DBIx::Class::Schema::Loader>.
236 my ( $class, %args ) = @_;
238 my $self = { %args };
240 bless $self => $class;
242 $self->_ensure_arrayref(qw/additional_classes
243 additional_base_classes
249 push(@{$self->{components}}, 'ResultSetManager')
250 if @{$self->{resultset_components}};
252 $self->{monikers} = {};
253 $self->{classes} = {};
255 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
256 $self->{schema} ||= $self->{schema_class};
258 croak "dump_overwrite is deprecated. Please read the"
259 . " DBIx::Class::Schema::Loader::Base documentation"
260 if $self->{dump_overwrite};
262 $self->{relbuilder} = DBIx::Class::Schema::Loader::RelBuilder->new(
263 $self->schema_class, $self->inflect_plural, $self->inflect_singular
264 ) if !$self->{skip_relationships};
269 sub _find_file_in_inc {
270 my ($self, $file) = @_;
272 foreach my $prefix (@INC) {
273 my $fullpath = $prefix . '/' . $file;
274 return $fullpath if -f $fullpath;
281 my ($self, $class) = @_;
283 my $class_path = $class;
284 $class_path =~ s{::}{/}g;
285 $class_path .= '.pm';
287 my $inc_path = $self->_find_file_in_inc($class_path);
289 return if !$inc_path;
291 my $real_dump_path = $self->dump_directory
293 File::Spec->catfile($self->dump_directory, $class_path)
296 my $real_inc_path = Cwd::abs_path($inc_path);
297 return if $real_inc_path eq $real_dump_path;
300 croak "Failed to load external class definition"
301 . " for '$class': $@"
304 # If we make it to here, we loaded an external definition
305 warn qq/# Loaded external class definition for '$class'\n/
308 # The rest is only relevant when dumping
309 return if !$self->dump_directory;
311 croak 'Failed to locate actual external module file for '
314 open(my $fh, '<', $real_inc_path)
315 or croak "Failed to open '$real_inc_path' for reading: $!";
316 $self->_ext_stmt($class,
317 qq|# These lines were loaded from '$real_inc_path' found in \@INC.|
318 .q|# They are now part of the custom portion of this file|
319 .q|# for you to hand-edit. If you do not either delete|
320 .q|# this section or remove that file from @INC, this section|
321 .q|# will be repeated redundantly when you re-create this|
322 .q|# file again via Loader!|
326 $self->_ext_stmt($class, $_);
328 $self->_ext_stmt($class,
329 qq|# End of lines loaded from '$real_inc_path' |
332 or croak "Failed to close $real_inc_path: $!";
337 Does the actual schema-construction work.
344 $self->_load_tables($self->_tables_list);
351 Rescan the database for newly added tables. Does
352 not process drops or changes. Returns a list of
353 the newly added table monikers.
355 The schema argument should be the schema class
356 or object to be affected. It should probably
357 be derived from the original schema_class used
363 my ($self, $schema) = @_;
365 $self->{schema} = $schema;
368 my @current = $self->_tables_list;
369 foreach my $table ($self->_tables_list) {
370 if(!exists $self->{_tables}->{$table}) {
371 push(@created, $table);
375 my $loaded = $self->_load_tables(@created);
377 return map { $self->monikers->{$_} } @$loaded;
381 my ($self, @tables) = @_;
383 # First, use _tables_list with constraint and exclude
384 # to get a list of tables to operate on
386 my $constraint = $self->constraint;
387 my $exclude = $self->exclude;
389 @tables = grep { /$constraint/ } @tables if $constraint;
390 @tables = grep { ! /$exclude/ } @tables if $exclude;
392 # Save the new tables to the tables list
394 $self->{_tables}->{$_} = 1;
397 # Set up classes/monikers
399 no warnings 'redefine';
400 local *Class::C3::reinitialize = sub { };
403 $self->_make_src_class($_) for @tables;
406 Class::C3::reinitialize;
408 $self->_setup_src_meta($_) for @tables;
410 if(!$self->skip_relationships) {
411 $self->_load_relationships($_) for @tables;
414 $self->_load_external($_)
415 for map { $self->classes->{$_} } @tables;
417 $self->_dump_to_dir if $self->dump_directory;
419 # Drop temporary cache
420 delete $self->{_cache};
425 sub _get_dump_filename {
426 my ($self, $class) = (@_);
429 return $self->dump_directory . q{/} . $class . q{.pm};
432 sub _ensure_dump_subdirs {
433 my ($self, $class) = (@_);
435 my @name_parts = split(/::/, $class);
436 pop @name_parts; # we don't care about the very last element,
437 # which is a filename
439 my $dir = $self->dump_directory;
442 mkdir($dir) or croak "mkdir('$dir') failed: $!";
444 last if !@name_parts;
445 $dir = File::Spec->catdir($dir, shift @name_parts);
452 my $target_dir = $self->dump_directory;
454 my $schema_class = $self->schema_class;
456 croak "Must specify target directory for dumping!" if ! $target_dir;
458 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n";
461 qq|package $schema_class;\n\n|
462 . qq|use strict;\nuse warnings;\n\n|
463 . qq|use base 'DBIx::Class::Schema';\n\n|;
466 if ($self->use_namespaces) {
467 $schema_text .= qq|__PACKAGE__->load_namespaces|;
468 my $namespace_options;
469 for my $attr (qw(result_namespace
471 default_resultset_class)) {
473 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
476 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
477 $schema_text .= qq|;\n|;
480 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
484 $self->_write_classfile($schema_class, $schema_text);
486 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
488 qq|package $src_class;\n\n|
489 . qq|use strict;\nuse warnings;\n\n|
490 . qq|use base 'DBIx::Class';\n\n|;
492 $self->_write_classfile($src_class, $src_text);
495 warn "Schema dump completed.\n";
498 sub _write_classfile {
499 my ($self, $class, $text) = @_;
501 my $filename = $self->_get_dump_filename($class);
502 $self->_ensure_dump_subdirs($class);
504 if (-f $filename && $self->really_erase_my_files) {
505 warn "Deleting existing file '$filename' due to "
506 . "'really_erase_my_files' setting\n";
510 my $custom_content = $self->_get_custom_content($class, $filename);
512 $custom_content ||= qq|\n\n# You can replace this text with custom|
513 . qq| content, and it will be preserved on regeneration|
517 for @{$self->{_dump_storage}->{$class} || []};
519 $text .= qq|\n\n# Created by DBIx::Class::Schema::Loader|
520 . qq| v| . $DBIx::Class::Schema::Loader::VERSION
521 . q| @ | . POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
522 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
524 open(my $fh, '>', $filename)
525 or croak "Cannot open '$filename' for writing: $!";
527 # Write the top half and its MD5 sum
528 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
530 # Write out anything loaded via external partial class file in @INC
532 for @{$self->{_ext_storage}->{$class} || []};
534 print $fh $custom_content;
537 or croak "Cannot close '$filename': $!";
540 sub _get_custom_content {
541 my ($self, $class, $filename) = @_;
543 return if ! -f $filename;
544 open(my $fh, '<', $filename)
545 or croak "Cannot open '$filename' for reading: $!";
548 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
553 if(!$found && /$mark_re/) {
556 croak "Checksum mismatch in '$filename'"
557 if Digest::MD5::md5_base64($buffer) ne $2;
566 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
567 . " it does not appear to have been generated by Loader"
579 warn "$target: use $_;" if $self->debug;
580 $self->_raw_stmt($target, "use $_;");
581 $_->require or croak ($_ . "->require: $@");
582 $evalstr .= "package $target; use $_;";
584 eval $evalstr if $evalstr;
591 my $schema_class = $self->schema_class;
593 my $blist = join(q{ }, @_);
594 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
595 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
597 $_->require or croak ($_ . "->require: $@");
598 $schema_class->inject_base($target, $_);
602 # Create class with applicable bases, setup monikers, etc
603 sub _make_src_class {
604 my ($self, $table) = @_;
606 my $schema = $self->schema;
607 my $schema_class = $self->schema_class;
609 my $table_moniker = $self->_table2moniker($table);
610 my @result_namespace = ($schema_class);
611 if ($self->use_namespaces) {
612 my $result_namespace = $self->result_namespace || 'Result';
613 if ($result_namespace =~ /^\+(.*)/) {
614 # Fully qualified namespace
615 @result_namespace = ($1)
619 push @result_namespace, $result_namespace;
622 my $table_class = join(q{::}, @result_namespace, $table_moniker);
624 my $table_normalized = lc $table;
625 $self->classes->{$table} = $table_class;
626 $self->classes->{$table_normalized} = $table_class;
627 $self->monikers->{$table} = $table_moniker;
628 $self->monikers->{$table_normalized} = $table_moniker;
630 { no strict 'refs'; @{"${table_class}::ISA"} = qw/DBIx::Class/ }
632 $self->_use ($table_class, @{$self->additional_classes});
633 $self->_inject($table_class, @{$self->additional_base_classes});
635 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, 'Core');
637 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
638 if @{$self->resultset_components};
639 $self->_inject($table_class, @{$self->left_base_classes});
642 # Set up metadata (cols, pks, etc) and register the class with the schema
643 sub _setup_src_meta {
644 my ($self, $table) = @_;
646 my $schema = $self->schema;
647 my $schema_class = $self->schema_class;
649 my $table_class = $self->classes->{$table};
650 my $table_moniker = $self->monikers->{$table};
652 $self->_dbic_stmt($table_class,'table',$table);
654 my $cols = $self->_table_columns($table);
656 eval { $col_info = $self->_columns_info_for($table) };
658 $self->_dbic_stmt($table_class,'add_columns',@$cols);
661 my %col_info_lc = map { lc($_), $col_info->{$_} } keys %$col_info;
662 my $fks = $self->_table_fk_info($table);
663 for my $fkdef (@$fks) {
664 for my $col (@{ $fkdef->{local_columns} }) {
665 $col_info_lc{$col}->{is_foreign_key} = 1;
671 map { $_, ($col_info_lc{$_}||{}) } @$cols
675 my $pks = $self->_table_pk_info($table) || [];
676 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
677 : carp("$table has no primary key");
679 my $uniqs = $self->_table_uniq_info($table) || [];
680 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
682 $schema_class->register_class($table_moniker, $table_class);
683 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
688 Returns a sorted list of loaded tables, using the original database table
696 return keys %{$self->_tables};
699 # Make a moniker from a table
701 my ( $self, $table ) = @_;
705 if( ref $self->moniker_map eq 'HASH' ) {
706 $moniker = $self->moniker_map->{$table};
708 elsif( ref $self->moniker_map eq 'CODE' ) {
709 $moniker = $self->moniker_map->($table);
712 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
717 sub _load_relationships {
718 my ($self, $table) = @_;
720 my $tbl_fk_info = $self->_table_fk_info($table);
721 foreach my $fkdef (@$tbl_fk_info) {
722 $fkdef->{remote_source} =
723 $self->monikers->{delete $fkdef->{remote_table}};
725 my $tbl_uniq_info = $self->_table_uniq_info($table);
727 my $local_moniker = $self->monikers->{$table};
728 my $rel_stmts = $self->{relbuilder}->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
730 foreach my $src_class (sort keys %$rel_stmts) {
731 my $src_stmts = $rel_stmts->{$src_class};
732 foreach my $stmt (@$src_stmts) {
733 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
738 # Overload these in driver class:
740 # Returns an arrayref of column names
741 sub _table_columns { croak "ABSTRACT METHOD" }
743 # Returns arrayref of pk col names
744 sub _table_pk_info { croak "ABSTRACT METHOD" }
746 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
747 sub _table_uniq_info { croak "ABSTRACT METHOD" }
749 # Returns an arrayref of foreign key constraints, each
750 # being a hashref with 3 keys:
751 # local_columns (arrayref), remote_columns (arrayref), remote_table
752 sub _table_fk_info { croak "ABSTRACT METHOD" }
754 # Returns an array of lower case table names
755 sub _tables_list { croak "ABSTRACT METHOD" }
757 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
763 if(!$self->debug && !$self->dump_directory) {
769 $args = '(' . $args . ')' if @_ < 2;
770 my $stmt = $method . $args . q{;};
772 warn qq|$class\->$stmt\n| if $self->debug;
774 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
777 # Store a raw source line for a class (for dumping purposes)
779 my ($self, $class, $stmt) = @_;
780 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
783 # Like above, but separately for the externally loaded stuff
785 my ($self, $class, $stmt) = @_;
786 push(@{$self->{_ext_storage}->{$class}}, $stmt) if $self->dump_directory;
791 Returns a hashref of loaded table to moniker mappings. There will
792 be two entries for each table, the original name and the "normalized"
793 name, in the case that the two are different (such as databases
794 that like uppercase table names, or preserve your original mixed-case
795 definitions, or what-have-you).
799 Returns a hashref of table to class mappings. In some cases it will
800 contain multiple entries per table for the original and normalized table
801 names, as above in L</monikers>.
805 L<DBIx::Class::Schema::Loader>