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_05';
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_options>. Available constructor options are:
67 =head2 skip_relationships
69 Skip setting up relationships. The default is to attempt the loading
74 If set to true, each constructive L<DBIx::Class> statement the loader
75 decides to execute will be C<warn>-ed before execution.
79 Set the name of the schema to load (schema in the sense that your database
80 vendor means it). Does not currently support loading more than one schema
85 Only load tables matching regex. Best specified as a qr// regex.
89 Exclude tables matching regex. Best specified as a qr// regex.
93 Overrides the default table name to moniker translation. Can be either
94 a hashref of table keys and moniker values, or a coderef for a translator
95 function taking a single scalar table name argument and returning
96 a scalar moniker. If the hash entry does not exist, or the function
97 returns a false value, the code falls back to default behavior
100 The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
101 which is to say: lowercase everything, split up the table name into chunks
102 anywhere a non-alpha-numeric character occurs, change the case of first letter
103 of each chunk to upper case, and put the chunks back together. Examples:
105 Table Name | Moniker Name
106 ---------------------------
108 luser_group | LuserGroup
109 luser-opts | LuserOpts
111 =head2 inflect_plural
113 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
114 if hash key does not exist or coderef returns false), but acts as a map
115 for pluralizing relationship names. The default behavior is to utilize
116 L<Lingua::EN::Inflect::Number/to_PL>.
118 =head2 inflect_singular
120 As L</inflect_plural> above, but for singularizing relationship names.
121 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
123 =head2 additional_base_classes
125 List of additional base classes all of your table classes will use.
127 =head2 left_base_classes
129 List of additional base classes all of your table classes will use
130 that need to be leftmost.
132 =head2 additional_classes
134 List of additional classes which all of your table classes will use.
138 List of additional components to be loaded into all of your table
139 classes. A good example would be C<ResultSetManager>.
141 =head2 resultset_components
143 List of additional ResultSet components to be loaded into your table
144 classes. A good example would be C<AlwaysRS>. Component
145 C<ResultSetManager> will be automatically added to the above
146 C<components> list if this option is set.
148 =head2 use_namespaces
150 Generate result class names suitable for
151 L<DBIx::Class::Schema/load_namespaces> and call that instead of
152 L<DBIx::Class::Schema/load_classes>. When using this option you can also
153 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
154 C<resultset_namespace>, C<default_resultset_class>), and they will be added
155 to the call (and the generated result class names adjusted appropriately).
157 =head2 dump_directory
159 This option is designed to be a tool to help you transition from this
160 loader to a manually-defined schema when you decide it's time to do so.
162 The value of this option is a perl libdir pathname. Within
163 that directory this module will create a baseline manual
164 L<DBIx::Class::Schema> module set, based on what it creates at runtime
167 The created schema class will have the same classname as the one on
168 which you are setting this option (and the ResultSource classes will be
169 based on this name as well).
171 Normally you wouldn't hard-code this setting in your schema class, as it
172 is meant for one-time manual usage.
174 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
175 recommended way to access this functionality.
177 =head2 dump_overwrite
179 Deprecated. See L</really_erase_my_files> below, which does *not* mean
180 the same thing as the old C<dump_overwrite> setting from previous releases.
182 =head2 really_erase_my_files
184 Default false. If true, Loader will unconditionally delete any existing
185 files before creating the new ones from scratch when dumping a schema to disk.
187 The default behavior is instead to only replace the top portion of the
188 file, up to and including the final stanza which contains
189 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
190 leaving any customizations you placed after that as they were.
192 When C<really_erase_my_files> is not set, if the output file already exists,
193 but the aforementioned final stanza is not found, or the checksum
194 contained there does not match the generated contents, Loader will
195 croak and not touch the file.
197 You should really be using version control on your schema classes (and all
198 of the rest of your code for that matter). Don't blame me if a bug in this
199 code wipes something out when it shouldn't have, you've been warned.
203 None of these methods are intended for direct invocation by regular
204 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
205 can also be found via standard L<DBIx::Class::Schema> methods somehow.
209 # ensure that a peice of object data is a valid arrayref, creating
210 # an empty one or encapsulating whatever's there.
211 sub _ensure_arrayref {
216 $self->{$_} = [ $self->{$_} ]
217 unless ref $self->{$_} eq 'ARRAY';
223 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
224 by L<DBIx::Class::Schema::Loader>.
229 my ( $class, %args ) = @_;
231 my $self = { %args };
233 bless $self => $class;
235 $self->_ensure_arrayref(qw/additional_classes
236 additional_base_classes
242 push(@{$self->{components}}, 'ResultSetManager')
243 if @{$self->{resultset_components}};
245 $self->{monikers} = {};
246 $self->{classes} = {};
248 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
249 $self->{schema} ||= $self->{schema_class};
251 croak "dump_overwrite is deprecated. Please read the"
252 . " DBIx::Class::Schema::Loader::Base documentation"
253 if $self->{dump_overwrite};
255 $self->{relbuilder} = DBIx::Class::Schema::Loader::RelBuilder->new(
256 $self->schema_class, $self->inflect_plural, $self->inflect_singular
257 ) if !$self->{skip_relationships};
262 sub _find_file_in_inc {
263 my ($self, $file) = @_;
265 foreach my $prefix (@INC) {
266 my $fullpath = $prefix . '/' . $file;
267 return $fullpath if -f $fullpath;
274 my ($self, $class) = @_;
276 my $class_path = $class;
277 $class_path =~ s{::}{/}g;
278 $class_path .= '.pm';
280 my $inc_path = $self->_find_file_in_inc($class_path);
282 return if !$inc_path;
284 my $real_dump_path = $self->dump_directory
286 File::Spec->catfile($self->dump_directory, $class_path)
289 my $real_inc_path = Cwd::abs_path($inc_path);
290 return if $real_inc_path eq $real_dump_path;
293 croak "Failed to load external class definition"
294 . " for '$class': $@"
297 # If we make it to here, we loaded an external definition
298 warn qq/# Loaded external class definition for '$class'\n/
301 # Make sure ResultSetManager picks up any :ResultSet methods from
302 # the external definition
303 $class->table($class->table);
305 # The rest is only relevant when dumping
306 return if !$self->dump_directory;
308 croak 'Failed to locate actual external module file for '
311 open(my $fh, '<', $real_inc_path)
312 or croak "Failed to open '$real_inc_path' for reading: $!";
313 $self->_ext_stmt($class,
314 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
315 .qq|# They are now part of the custom portion of this file\n|
316 .qq|# for you to hand-edit. If you do not either delete\n|
317 .qq|# this section or remove that file from \@INC, this section\n|
318 .qq|# will be repeated redundantly when you re-create this\n|
319 .qq|# file again via Loader!\n|
323 $self->_ext_stmt($class, $_);
325 $self->_ext_stmt($class,
326 qq|# End of lines loaded from '$real_inc_path' |
329 or croak "Failed to close $real_inc_path: $!";
334 Does the actual schema-construction work.
341 $self->_load_tables($self->_tables_list);
348 Rescan the database for newly added tables. Does
349 not process drops or changes. Returns a list of
350 the newly added table monikers.
352 The schema argument should be the schema class
353 or object to be affected. It should probably
354 be derived from the original schema_class used
360 my ($self, $schema) = @_;
362 $self->{schema} = $schema;
365 my @current = $self->_tables_list;
366 foreach my $table ($self->_tables_list) {
367 if(!exists $self->{_tables}->{$table}) {
368 push(@created, $table);
372 my $loaded = $self->_load_tables(@created);
374 return map { $self->monikers->{$_} } @$loaded;
378 my ($self, @tables) = @_;
380 # First, use _tables_list with constraint and exclude
381 # to get a list of tables to operate on
383 my $constraint = $self->constraint;
384 my $exclude = $self->exclude;
386 @tables = grep { /$constraint/ } @tables if $constraint;
387 @tables = grep { ! /$exclude/ } @tables if $exclude;
389 # Save the new tables to the tables list
391 $self->{_tables}->{$_} = 1;
394 # Set up classes/monikers
396 no warnings 'redefine';
397 local *Class::C3::reinitialize = sub { };
400 $self->_make_src_class($_) for @tables;
403 Class::C3::reinitialize;
405 $self->_setup_src_meta($_) for @tables;
407 if(!$self->skip_relationships) {
408 $self->_load_relationships($_) for @tables;
411 $self->_load_external($_)
412 for map { $self->classes->{$_} } @tables;
414 $self->_dump_to_dir if $self->dump_directory;
416 # Drop temporary cache
417 delete $self->{_cache};
422 sub _get_dump_filename {
423 my ($self, $class) = (@_);
426 return $self->dump_directory . q{/} . $class . q{.pm};
429 sub _ensure_dump_subdirs {
430 my ($self, $class) = (@_);
432 my @name_parts = split(/::/, $class);
433 pop @name_parts; # we don't care about the very last element,
434 # which is a filename
436 my $dir = $self->dump_directory;
439 mkdir($dir) or croak "mkdir('$dir') failed: $!";
441 last if !@name_parts;
442 $dir = File::Spec->catdir($dir, shift @name_parts);
449 my $target_dir = $self->dump_directory;
451 my $schema_class = $self->schema_class;
453 croak "Must specify target directory for dumping!" if ! $target_dir;
455 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n";
458 qq|package $schema_class;\n\n|
459 . qq|use strict;\nuse warnings;\n\n|
460 . qq|use base 'DBIx::Class::Schema';\n\n|;
463 if ($self->use_namespaces) {
464 $schema_text .= qq|__PACKAGE__->load_namespaces|;
465 my $namespace_options;
466 for my $attr (qw(result_namespace
468 default_resultset_class)) {
470 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
473 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
474 $schema_text .= qq|;\n|;
477 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
481 $self->_write_classfile($schema_class, $schema_text);
483 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
485 qq|package $src_class;\n\n|
486 . qq|use strict;\nuse warnings;\n\n|
487 . qq|use base 'DBIx::Class';\n\n|;
489 $self->_write_classfile($src_class, $src_text);
492 warn "Schema dump completed.\n";
495 sub _write_classfile {
496 my ($self, $class, $text) = @_;
498 my $filename = $self->_get_dump_filename($class);
499 $self->_ensure_dump_subdirs($class);
501 if (-f $filename && $self->really_erase_my_files) {
502 warn "Deleting existing file '$filename' due to "
503 . "'really_erase_my_files' setting\n";
507 my $custom_content = $self->_get_custom_content($class, $filename);
509 $custom_content ||= qq|\n\n# You can replace this text with custom|
510 . qq| content, and it will be preserved on regeneration|
514 for @{$self->{_dump_storage}->{$class} || []};
516 $text .= qq|\n\n# Created by DBIx::Class::Schema::Loader|
517 . qq| v| . $DBIx::Class::Schema::Loader::VERSION
518 . q| @ | . POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
519 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
521 open(my $fh, '>', $filename)
522 or croak "Cannot open '$filename' for writing: $!";
524 # Write the top half and its MD5 sum
525 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
527 # Write out anything loaded via external partial class file in @INC
529 for @{$self->{_ext_storage}->{$class} || []};
531 print $fh $custom_content;
534 or croak "Cannot close '$filename': $!";
537 sub _get_custom_content {
538 my ($self, $class, $filename) = @_;
540 return if ! -f $filename;
541 open(my $fh, '<', $filename)
542 or croak "Cannot open '$filename' for reading: $!";
545 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
550 if(!$found && /$mark_re/) {
553 croak "Checksum mismatch in '$filename'"
554 if Digest::MD5::md5_base64($buffer) ne $2;
563 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
564 . " it does not appear to have been generated by Loader"
576 warn "$target: use $_;" if $self->debug;
577 $self->_raw_stmt($target, "use $_;");
578 $_->require or croak ($_ . "->require: $@");
579 $evalstr .= "package $target; use $_;";
581 eval $evalstr if $evalstr;
588 my $schema_class = $self->schema_class;
590 my $blist = join(q{ }, map "+$_", @_);
591 warn "$target: __PACKAGE__->load_components( qw/ $blist / );" if $self->debug && @_;
592 $self->_raw_stmt($target, "__PACKAGE__->load_components( qw/ $blist / );") if @_;
594 $_->require or croak ($_ . "->require: $@");
595 $schema_class->inject_base($target, $_);
599 # Create class with applicable bases, setup monikers, etc
600 sub _make_src_class {
601 my ($self, $table) = @_;
603 my $schema = $self->schema;
604 my $schema_class = $self->schema_class;
606 my $table_moniker = $self->_table2moniker($table);
607 my @result_namespace = ($schema_class);
608 if ($self->use_namespaces) {
609 my $result_namespace = $self->result_namespace || 'Result';
610 if ($result_namespace =~ /^\+(.*)/) {
611 # Fully qualified namespace
612 @result_namespace = ($1)
616 push @result_namespace, $result_namespace;
619 my $table_class = join(q{::}, @result_namespace, $table_moniker);
621 my $table_normalized = lc $table;
622 $self->classes->{$table} = $table_class;
623 $self->classes->{$table_normalized} = $table_class;
624 $self->monikers->{$table} = $table_moniker;
625 $self->monikers->{$table_normalized} = $table_moniker;
627 { no strict 'refs'; @{"${table_class}::ISA"} = qw/DBIx::Class/ }
629 $self->_use ($table_class, @{$self->additional_classes});
630 $self->_inject($table_class, @{$self->additional_base_classes});
632 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, 'Core');
634 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
635 if @{$self->resultset_components};
636 $self->_inject($table_class, @{$self->left_base_classes});
639 # Set up metadata (cols, pks, etc) and register the class with the schema
640 sub _setup_src_meta {
641 my ($self, $table) = @_;
643 my $schema = $self->schema;
644 my $schema_class = $self->schema_class;
646 my $table_class = $self->classes->{$table};
647 my $table_moniker = $self->monikers->{$table};
649 $self->_dbic_stmt($table_class,'table',$table);
651 my $cols = $self->_table_columns($table);
653 eval { $col_info = $self->_columns_info_for($table) };
655 $self->_dbic_stmt($table_class,'add_columns',@$cols);
658 my %col_info_lc = map { lc($_), $col_info->{$_} } keys %$col_info;
659 my $fks = $self->_table_fk_info($table);
660 for my $fkdef (@$fks) {
661 for my $col (@{ $fkdef->{local_columns} }) {
662 $col_info_lc{$col}->{is_foreign_key} = 1;
668 map { $_, ($col_info_lc{$_}||{}) } @$cols
672 my $pks = $self->_table_pk_info($table) || [];
673 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
674 : carp("$table has no primary key");
676 my $uniqs = $self->_table_uniq_info($table) || [];
677 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
679 $schema_class->register_class($table_moniker, $table_class);
680 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
685 Returns a sorted list of loaded tables, using the original database table
693 return keys %{$self->_tables};
696 # Make a moniker from a table
698 my ( $self, $table ) = @_;
702 if( ref $self->moniker_map eq 'HASH' ) {
703 $moniker = $self->moniker_map->{$table};
705 elsif( ref $self->moniker_map eq 'CODE' ) {
706 $moniker = $self->moniker_map->($table);
709 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
714 sub _load_relationships {
715 my ($self, $table) = @_;
717 my $tbl_fk_info = $self->_table_fk_info($table);
718 foreach my $fkdef (@$tbl_fk_info) {
719 $fkdef->{remote_source} =
720 $self->monikers->{delete $fkdef->{remote_table}};
722 my $tbl_uniq_info = $self->_table_uniq_info($table);
724 my $local_moniker = $self->monikers->{$table};
725 my $rel_stmts = $self->{relbuilder}->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
727 foreach my $src_class (sort keys %$rel_stmts) {
728 my $src_stmts = $rel_stmts->{$src_class};
729 foreach my $stmt (@$src_stmts) {
730 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
735 # Overload these in driver class:
737 # Returns an arrayref of column names
738 sub _table_columns { croak "ABSTRACT METHOD" }
740 # Returns arrayref of pk col names
741 sub _table_pk_info { croak "ABSTRACT METHOD" }
743 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
744 sub _table_uniq_info { croak "ABSTRACT METHOD" }
746 # Returns an arrayref of foreign key constraints, each
747 # being a hashref with 3 keys:
748 # local_columns (arrayref), remote_columns (arrayref), remote_table
749 sub _table_fk_info { croak "ABSTRACT METHOD" }
751 # Returns an array of lower case table names
752 sub _tables_list { croak "ABSTRACT METHOD" }
754 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
760 if(!$self->debug && !$self->dump_directory) {
766 $args = '(' . $args . ')' if @_ < 2;
767 my $stmt = $method . $args . q{;};
769 warn qq|$class\->$stmt\n| if $self->debug;
771 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
774 # Store a raw source line for a class (for dumping purposes)
776 my ($self, $class, $stmt) = @_;
777 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
780 # Like above, but separately for the externally loaded stuff
782 my ($self, $class, $stmt) = @_;
783 push(@{$self->{_ext_storage}->{$class}}, $stmt) if $self->dump_directory;
788 Returns a hashref of loaded table to moniker mappings. There will
789 be two entries for each table, the original name and the "normalized"
790 name, in the case that the two are different (such as databases
791 that like uppercase table names, or preserve your original mixed-case
792 definitions, or what-have-you).
796 Returns a hashref of table to class mappings. In some cases it will
797 contain multiple entries per table for the original and normalized table
798 names, as above in L</monikers>.
802 L<DBIx::Class::Schema::Loader>