1 package DBIx::Class::Schema::Loader::Base;
5 use base qw/Class::Accessor::Grouped Class::C3::Componentised/;
7 use Carp::Clan qw/^DBIx::Class/;
8 use DBIx::Class::Schema::Loader::RelBuilder;
9 use Data::Dump qw/ dump /;
14 use Lingua::EN::Inflect::Number qw//;
19 our $VERSION = '0.04999_12';
21 __PACKAGE__->mk_group_ro_accessors('simple', qw/
28 additional_base_classes
44 default_resultset_class
58 __PACKAGE__->mk_group_accessors('simple', qw/
60 schema_version_to_dump
66 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
70 See L<DBIx::Class::Schema::Loader>
74 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
75 classes, and implements the common functionality between them.
77 =head1 CONSTRUCTOR OPTIONS
79 These constructor options are the base options for
80 L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
82 =head2 skip_relationships
84 Skip setting up relationships. The default is to attempt the loading
87 =head2 skip_load_external
89 Skip loading of other classes in @INC. The default is to merge all other classes
90 with the same name found in @INC into the schema file we are creating.
94 Static schemas (ones dumped to disk) will, by default, use the new-style 0.05XXX
95 relationship names and singularized Results, unless you're overwriting an
96 existing dump made by a 0.04XXX version of L<DBIx::Class::Schema::Loader>, in
97 which case the backward compatible RelBuilder will be activated, and
98 singularization will be turned off.
104 will disable the backward-compatible RelBuilder and use
105 the new-style relationship names along with singularized Results, even when
106 overwriting a dump made with an earlier version.
108 The option also takes a hashref:
110 naming => { relationships => 'v5', monikers => 'v4' }
118 How to name relationship accessors.
122 How to name Result classes.
132 Latest default style, whatever that happens to be.
136 Version 0.05XXX style.
140 Version 0.04XXX style.
144 Dynamic schemas will always default to the 0.04XXX relationship names and won't
145 singularize Results for backward compatibility, to activate the new RelBuilder
146 and singularization put this in your C<Schema.pm> file:
148 __PACKAGE__->naming('current');
150 Or if you prefer to use 0.05XXX features but insure that nothing breaks in the
151 next major version upgrade:
153 __PACKAGE__->naming('v5');
157 If set to true, each constructive L<DBIx::Class> statement the loader
158 decides to execute will be C<warn>-ed before execution.
162 Set the name of the schema to load (schema in the sense that your database
163 vendor means it). Does not currently support loading more than one schema
168 Only load tables matching regex. Best specified as a qr// regex.
172 Exclude tables matching regex. Best specified as a qr// regex.
176 Overrides the default table name to moniker translation. Can be either
177 a hashref of table keys and moniker values, or a coderef for a translator
178 function taking a single scalar table name argument and returning
179 a scalar moniker. If the hash entry does not exist, or the function
180 returns a false value, the code falls back to default behavior
183 The default behavior is to singularize the table name, and: C<join '', map
184 ucfirst, split /[\W_]+/, lc $table>, which is to say: lowercase everything,
185 split up the table name into chunks anywhere a non-alpha-numeric character
186 occurs, change the case of first letter of each chunk to upper case, and put
187 the chunks back together. Examples:
189 Table Name | Moniker Name
190 ---------------------------
192 luser_group | LuserGroup
193 luser-opts | LuserOpts
195 =head2 inflect_plural
197 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
198 if hash key does not exist or coderef returns false), but acts as a map
199 for pluralizing relationship names. The default behavior is to utilize
200 L<Lingua::EN::Inflect::Number/to_PL>.
202 =head2 inflect_singular
204 As L</inflect_plural> above, but for singularizing relationship names.
205 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
207 =head2 schema_base_class
209 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
211 =head2 result_base_class
213 Base class for your table classes (aka result classes). Defaults to
216 =head2 additional_base_classes
218 List of additional base classes all of your table classes will use.
220 =head2 left_base_classes
222 List of additional base classes all of your table classes will use
223 that need to be leftmost.
225 =head2 additional_classes
227 List of additional classes which all of your table classes will use.
231 List of additional components to be loaded into all of your table
232 classes. A good example would be C<ResultSetManager>.
234 =head2 resultset_components
236 List of additional ResultSet components to be loaded into your table
237 classes. A good example would be C<AlwaysRS>. Component
238 C<ResultSetManager> will be automatically added to the above
239 C<components> list if this option is set.
241 =head2 use_namespaces
243 Generate result class names suitable for
244 L<DBIx::Class::Schema/load_namespaces> and call that instead of
245 L<DBIx::Class::Schema/load_classes>. When using this option you can also
246 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
247 C<resultset_namespace>, C<default_resultset_class>), and they will be added
248 to the call (and the generated result class names adjusted appropriately).
250 =head2 dump_directory
252 This option is designed to be a tool to help you transition from this
253 loader to a manually-defined schema when you decide it's time to do so.
255 The value of this option is a perl libdir pathname. Within
256 that directory this module will create a baseline manual
257 L<DBIx::Class::Schema> module set, based on what it creates at runtime
260 The created schema class will have the same classname as the one on
261 which you are setting this option (and the ResultSource classes will be
262 based on this name as well).
264 Normally you wouldn't hard-code this setting in your schema class, as it
265 is meant for one-time manual usage.
267 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
268 recommended way to access this functionality.
270 =head2 dump_overwrite
272 Deprecated. See L</really_erase_my_files> below, which does *not* mean
273 the same thing as the old C<dump_overwrite> setting from previous releases.
275 =head2 really_erase_my_files
277 Default false. If true, Loader will unconditionally delete any existing
278 files before creating the new ones from scratch when dumping a schema to disk.
280 The default behavior is instead to only replace the top portion of the
281 file, up to and including the final stanza which contains
282 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
283 leaving any customizations you placed after that as they were.
285 When C<really_erase_my_files> is not set, if the output file already exists,
286 but the aforementioned final stanza is not found, or the checksum
287 contained there does not match the generated contents, Loader will
288 croak and not touch the file.
290 You should really be using version control on your schema classes (and all
291 of the rest of your code for that matter). Don't blame me if a bug in this
292 code wipes something out when it shouldn't have, you've been warned.
296 None of these methods are intended for direct invocation by regular
297 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
298 can also be found via standard L<DBIx::Class::Schema> methods somehow.
302 use constant CURRENT_V => 'v5';
304 # ensure that a peice of object data is a valid arrayref, creating
305 # an empty one or encapsulating whatever's there.
306 sub _ensure_arrayref {
311 $self->{$_} = [ $self->{$_} ]
312 unless ref $self->{$_} eq 'ARRAY';
318 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
319 by L<DBIx::Class::Schema::Loader>.
324 my ( $class, %args ) = @_;
326 my $self = { %args };
328 bless $self => $class;
330 $self->_ensure_arrayref(qw/additional_classes
331 additional_base_classes
337 push(@{$self->{components}}, 'ResultSetManager')
338 if @{$self->{resultset_components}};
340 $self->{monikers} = {};
341 $self->{classes} = {};
342 $self->{_upgrading_classes} = {};
344 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
345 $self->{schema} ||= $self->{schema_class};
347 croak "dump_overwrite is deprecated. Please read the"
348 . " DBIx::Class::Schema::Loader::Base documentation"
349 if $self->{dump_overwrite};
351 $self->{dynamic} = ! $self->{dump_directory};
352 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
357 $self->{dump_directory} ||= $self->{temp_directory};
359 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
360 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
362 if ((not ref $self->naming) && defined $self->naming) {
363 my $naming_ver = $self->naming;
365 relationships => $naming_ver,
366 monikers => $naming_ver,
371 for (values %{ $self->naming }) {
372 $_ = CURRENT_V if $_ eq 'current';
375 $self->{naming} ||= {};
377 $self->_check_back_compat;
382 sub _check_back_compat {
385 # dynamic schemas will always be in 0.04006 mode, unless overridden
386 if ($self->dynamic) {
387 # just in case, though no one is likely to dump a dynamic schema
388 $self->schema_version_to_dump('0.04006');
390 if (not %{ $self->naming }) {
391 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
393 Dynamic schema detected, will run in 0.04006 mode.
395 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
396 to disable this warning.
398 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
403 $self->_upgrading_from('v4');
406 $self->naming->{relationships} ||= 'v4';
407 $self->naming->{monikers} ||= 'v4';
412 # otherwise check if we need backcompat mode for a static schema
413 my $filename = $self->_get_dump_filename($self->schema_class);
414 return unless -e $filename;
416 open(my $fh, '<', $filename)
417 or croak "Cannot open '$filename' for reading: $!";
420 if (/^# Created by DBIx::Class::Schema::Loader v((\d+)\.(\d+))/) {
423 # XXX when we go past .0 this will need fixing
424 my ($v) = $real_ver =~ /([1-9])/;
427 last if $v eq CURRENT_V || $real_ver =~ /^0\.04999/;
429 if (not %{ $self->naming }) {
430 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
432 Version $real_ver static schema detected, turning on backcompat mode.
434 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
435 to disable this warning.
437 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
442 $self->_upgrading_from($v);
445 $self->naming->{relationships} ||= $v;
446 $self->naming->{monikers} ||= $v;
448 $self->schema_version_to_dump($real_ver);
456 sub _find_file_in_inc {
457 my ($self, $file) = @_;
459 foreach my $prefix (@INC) {
460 my $fullpath = File::Spec->catfile($prefix, $file);
461 return $fullpath if -f $fullpath
462 and Cwd::abs_path($fullpath) ne
463 (Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) || '');
470 my ($self, $class) = @_;
472 my $class_path = $class;
473 $class_path =~ s{::}{/}g;
474 $class_path .= '.pm';
479 sub _find_class_in_inc {
480 my ($self, $class) = @_;
482 return $self->_find_file_in_inc($self->_class_path($class));
486 my ($self, $class) = @_;
488 return if $self->{skip_load_external};
490 # so that we don't load our own classes, under any circumstances
491 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
493 my $real_inc_path = $self->_find_class_in_inc($class);
495 my $old_class = $self->_upgrading_classes->{$class}
496 if $self->_upgrading_from;
498 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
499 if $old_class && $old_class ne $class;
501 return unless $real_inc_path || $old_real_inc_path;
503 if ($real_inc_path) {
504 # If we make it to here, we loaded an external definition
505 warn qq/# Loaded external class definition for '$class'\n/
508 open(my $fh, '<', $real_inc_path)
509 or croak "Failed to open '$real_inc_path' for reading: $!";
510 $self->_ext_stmt($class,
511 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
512 .qq|# They are now part of the custom portion of this file\n|
513 .qq|# for you to hand-edit. If you do not either delete\n|
514 .qq|# this section or remove that file from \@INC, this section\n|
515 .qq|# will be repeated redundantly when you re-create this\n|
516 .qq|# file again via Loader!\n|
520 $self->_ext_stmt($class, $_);
522 $self->_ext_stmt($class,
523 qq|# End of lines loaded from '$real_inc_path' |
526 or croak "Failed to close $real_inc_path: $!";
528 if ($self->dynamic) { # load the class too
529 # kill redefined warnings
530 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
531 local $SIG{__WARN__} = sub {
533 unless $_[0] =~ /^Subroutine \S+ redefined/;
540 if ($old_real_inc_path) {
541 open(my $fh, '<', $old_real_inc_path)
542 or croak "Failed to open '$old_real_inc_path' for reading: $!";
543 $self->_ext_stmt($class, <<"EOF");
545 # These lines were loaded from '$old_real_inc_path', based on the Result class
546 # name that would have been created by an 0.04006 version of the Loader. For a
547 # static schema, this happens only once during upgrade.
549 if ($self->dynamic) {
552 Detected external content in '$old_real_inc_path', a class name that would have
553 been used by an 0.04006 version of the Loader.
555 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
556 new name of the Result.
558 # kill redefined warnings
559 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
560 local $SIG{__WARN__} = sub {
562 unless $_[0] =~ /^Subroutine \S+ redefined/;
565 local ($/, @ARGV) = (undef, $old_real_inc_path); <>
567 $code =~ s/$old_class/$class/g;
574 $self->_ext_stmt($class, $_);
576 $self->_ext_stmt($class,
577 qq|# End of lines loaded from '$old_real_inc_path' |
581 or croak "Failed to close $old_real_inc_path: $!";
587 Does the actual schema-construction work.
594 $self->_load_tables($self->_tables_list);
601 Rescan the database for newly added tables. Does
602 not process drops or changes. Returns a list of
603 the newly added table monikers.
605 The schema argument should be the schema class
606 or object to be affected. It should probably
607 be derived from the original schema_class used
613 my ($self, $schema) = @_;
615 $self->{schema} = $schema;
616 $self->_relbuilder->{schema} = $schema;
619 my @current = $self->_tables_list;
620 foreach my $table ($self->_tables_list) {
621 if(!exists $self->{_tables}->{$table}) {
622 push(@created, $table);
626 my $loaded = $self->_load_tables(@created);
628 return map { $self->monikers->{$_} } @$loaded;
632 no warnings 'uninitialized';
635 return if $self->{skip_relationships};
637 if ($self->naming->{relationships} eq 'v4') {
638 require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040;
639 return $self->{relbuilder} ||=
640 DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040->new(
641 $self->schema, $self->inflect_plural, $self->inflect_singular
645 $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder->new(
646 $self->schema, $self->inflect_plural, $self->inflect_singular
651 my ($self, @tables) = @_;
653 # First, use _tables_list with constraint and exclude
654 # to get a list of tables to operate on
656 my $constraint = $self->constraint;
657 my $exclude = $self->exclude;
659 @tables = grep { /$constraint/ } @tables if $constraint;
660 @tables = grep { ! /$exclude/ } @tables if $exclude;
662 # Save the new tables to the tables list
664 $self->{_tables}->{$_} = 1;
667 $self->_make_src_class($_) for @tables;
668 $self->_setup_src_meta($_) for @tables;
670 if(!$self->skip_relationships) {
671 # The relationship loader needs a working schema
673 local $self->{dump_directory} = $self->{temp_directory};
674 $self->_reload_classes(\@tables);
675 $self->_load_relationships($_) for @tables;
678 # Remove that temp dir from INC so it doesn't get reloaded
679 @INC = grep $_ ne $self->dump_directory, @INC;
682 $self->_load_external($_)
683 for map { $self->classes->{$_} } @tables;
685 # Reload without unloading first to preserve any symbols from external
687 $self->_reload_classes(\@tables, 0);
689 # Drop temporary cache
690 delete $self->{_cache};
695 sub _reload_classes {
696 my ($self, $tables, $unload) = @_;
698 my @tables = @$tables;
699 $unload = 1 unless defined $unload;
701 # so that we don't repeat custom sections
702 @INC = grep $_ ne $self->dump_directory, @INC;
704 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
706 unshift @INC, $self->dump_directory;
709 my %have_source = map { $_ => $self->schema->source($_) }
710 $self->schema->sources;
712 for my $table (@tables) {
713 my $moniker = $self->monikers->{$table};
714 my $class = $self->classes->{$table};
717 no warnings 'redefine';
718 local *Class::C3::reinitialize = sub {};
721 Class::Unload->unload($class) if $unload;
722 my ($source, $resultset_class);
724 ($source = $have_source{$moniker})
725 && ($resultset_class = $source->resultset_class)
726 && ($resultset_class ne 'DBIx::Class::ResultSet')
728 my $has_file = Class::Inspector->loaded_filename($resultset_class);
729 Class::Unload->unload($resultset_class) if $unload;
730 $self->_reload_class($resultset_class) if $has_file;
732 $self->_reload_class($class);
734 push @to_register, [$moniker, $class];
737 Class::C3->reinitialize;
739 $self->schema->register_class(@$_);
743 # We use this instead of ensure_class_loaded when there are package symbols we
746 my ($self, $class) = @_;
748 my $class_path = $self->_class_path($class);
749 delete $INC{ $class_path };
751 # kill redefined warnings
752 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
753 local $SIG{__WARN__} = sub {
755 unless $_[0] =~ /^Subroutine \S+ redefined/;
757 eval "require $class;";
760 sub _get_dump_filename {
761 my ($self, $class) = (@_);
764 return $self->dump_directory . q{/} . $class . q{.pm};
767 sub _ensure_dump_subdirs {
768 my ($self, $class) = (@_);
770 my @name_parts = split(/::/, $class);
771 pop @name_parts; # we don't care about the very last element,
772 # which is a filename
774 my $dir = $self->dump_directory;
777 mkdir($dir) or croak "mkdir('$dir') failed: $!";
779 last if !@name_parts;
780 $dir = File::Spec->catdir($dir, shift @name_parts);
785 my ($self, @classes) = @_;
787 my $schema_class = $self->schema_class;
788 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
790 my $target_dir = $self->dump_directory;
791 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
792 unless $self->{dynamic} or $self->{quiet};
795 qq|package $schema_class;\n\n|
796 . qq|# Created by DBIx::Class::Schema::Loader\n|
797 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
798 . qq|use strict;\nuse warnings;\n\n|
799 . qq|use base '$schema_base_class';\n\n|;
801 if ($self->use_namespaces) {
802 $schema_text .= qq|__PACKAGE__->load_namespaces|;
803 my $namespace_options;
804 for my $attr (qw(result_namespace
806 default_resultset_class)) {
808 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
811 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
812 $schema_text .= qq|;\n|;
815 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
819 local $self->{version_to_dump} = $self->schema_version_to_dump;
820 $self->_write_classfile($schema_class, $schema_text);
823 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
825 foreach my $src_class (@classes) {
827 qq|package $src_class;\n\n|
828 . qq|# Created by DBIx::Class::Schema::Loader\n|
829 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
830 . qq|use strict;\nuse warnings;\n\n|
831 . qq|use base '$result_base_class';\n\n|;
833 $self->_write_classfile($src_class, $src_text);
836 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
841 my ($self, $version, $ts) = @_;
842 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
845 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
848 sub _write_classfile {
849 my ($self, $class, $text) = @_;
851 my $filename = $self->_get_dump_filename($class);
852 $self->_ensure_dump_subdirs($class);
854 if (-f $filename && $self->really_erase_my_files) {
855 warn "Deleting existing file '$filename' due to "
856 . "'really_erase_my_files' setting\n" unless $self->{quiet};
860 my ($custom_content, $old_md5, $old_ver, $old_ts) = $self->_get_custom_content($class, $filename);
862 if ($self->_upgrading_from) {
863 my $old_class = $self->_upgrading_classes->{$class};
865 if ($old_class && ($old_class ne $class)) {
866 my $old_filename = $self->_get_dump_filename($old_class);
868 my ($old_custom_content) = $self->_get_custom_content(
869 $old_class, $old_filename, 0 # do not add default comment
872 $old_custom_content =~ s/\n\n# You can replace.*\n1;\n//;
874 if ($old_custom_content) {
876 "\n" . $old_custom_content . "\n" . $custom_content;
879 unlink $old_filename;
884 for @{$self->{_dump_storage}->{$class} || []};
886 # Check and see if the dump is infact differnt
890 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
893 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
898 $text .= $self->_sig_comment(
899 $self->version_to_dump,
900 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
903 open(my $fh, '>', $filename)
904 or croak "Cannot open '$filename' for writing: $!";
906 # Write the top half and its MD5 sum
907 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
909 # Write out anything loaded via external partial class file in @INC
911 for @{$self->{_ext_storage}->{$class} || []};
913 # Write out any custom content the user has added
914 print $fh $custom_content;
917 or croak "Error closing '$filename': $!";
920 sub _default_custom_content {
921 return qq|\n\n# You can replace this text with custom|
922 . qq| content, and it will be preserved on regeneration|
926 sub _get_custom_content {
927 my ($self, $class, $filename, $add_default) = @_;
929 $add_default = 1 unless defined $add_default;
931 return ($self->_default_custom_content) if ! -f $filename;
933 open(my $fh, '<', $filename)
934 or croak "Cannot open '$filename' for reading: $!";
937 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
940 my ($md5, $ts, $ver);
942 if(!$md5 && /$mark_re/) {
946 # Pull out the previous version and timestamp
947 ($ver, $ts) = $buffer =~ m/# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)$/s;
950 croak "Checksum mismatch in '$filename'"
951 if Digest::MD5::md5_base64($buffer) ne $md5;
960 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
961 . " it does not appear to have been generated by Loader"
964 # Default custom content:
965 $buffer ||= $self->_default_custom_content if $add_default;
967 return ($buffer, $md5, $ver, $ts);
975 warn "$target: use $_;" if $self->debug;
976 $self->_raw_stmt($target, "use $_;");
983 my $schema_class = $self->schema_class;
985 my $blist = join(q{ }, @_);
986 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
987 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
990 # Create class with applicable bases, setup monikers, etc
991 sub _make_src_class {
992 my ($self, $table) = @_;
994 my $schema = $self->schema;
995 my $schema_class = $self->schema_class;
997 my $table_moniker = $self->_table2moniker($table);
998 my @result_namespace = ($schema_class);
999 if ($self->use_namespaces) {
1000 my $result_namespace = $self->result_namespace || 'Result';
1001 if ($result_namespace =~ /^\+(.*)/) {
1002 # Fully qualified namespace
1003 @result_namespace = ($1)
1006 # Relative namespace
1007 push @result_namespace, $result_namespace;
1010 my $table_class = join(q{::}, @result_namespace, $table_moniker);
1012 if (my $upgrading_v = $self->_upgrading_from) {
1013 local $self->naming->{monikers} = $upgrading_v;
1015 my $old_class = join(q{::}, @result_namespace,
1016 $self->_table2moniker($table));
1018 $self->_upgrading_classes->{$table_class} = $old_class;
1021 my $table_normalized = lc $table;
1022 $self->classes->{$table} = $table_class;
1023 $self->classes->{$table_normalized} = $table_class;
1024 $self->monikers->{$table} = $table_moniker;
1025 $self->monikers->{$table_normalized} = $table_moniker;
1027 $self->_use ($table_class, @{$self->additional_classes});
1028 $self->_inject($table_class, @{$self->left_base_classes});
1030 if (my @components = @{ $self->components }) {
1031 $self->_dbic_stmt($table_class, 'load_components', @components);
1034 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
1035 if @{$self->resultset_components};
1036 $self->_inject($table_class, @{$self->additional_base_classes});
1039 # Set up metadata (cols, pks, etc)
1040 sub _setup_src_meta {
1041 my ($self, $table) = @_;
1043 my $schema = $self->schema;
1044 my $schema_class = $self->schema_class;
1046 my $table_class = $self->classes->{$table};
1047 my $table_moniker = $self->monikers->{$table};
1049 my $table_name = $table;
1050 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1052 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1053 $table_name = \ $self->_quote_table_name($table_name);
1056 $self->_dbic_stmt($table_class,'table',$table_name);
1058 my $cols = $self->_table_columns($table);
1060 eval { $col_info = $self->_columns_info_for($table) };
1062 $self->_dbic_stmt($table_class,'add_columns',@$cols);
1065 if ($self->_is_case_sensitive) {
1066 for my $col (keys %$col_info) {
1067 $col_info->{$col}{accessor} = lc $col
1068 if $col ne lc($col);
1071 $col_info = { map { lc($_), $col_info->{$_} } keys %$col_info };
1074 my $fks = $self->_table_fk_info($table);
1076 for my $fkdef (@$fks) {
1077 for my $col (@{ $fkdef->{local_columns} }) {
1078 $col_info->{$col}{is_foreign_key} = 1;
1084 map { $_, ($col_info->{$_}||{}) } @$cols
1088 my %uniq_tag; # used to eliminate duplicate uniqs
1090 my $pks = $self->_table_pk_info($table) || [];
1091 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1092 : carp("$table has no primary key");
1093 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1095 my $uniqs = $self->_table_uniq_info($table) || [];
1097 my ($name, $cols) = @$_;
1098 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1099 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1106 Returns a sorted list of loaded tables, using the original database table
1114 return keys %{$self->_tables};
1117 # Make a moniker from a table
1118 sub _default_table2moniker {
1119 no warnings 'uninitialized';
1120 my ($self, $table) = @_;
1122 if ($self->naming->{monikers} eq 'v4') {
1123 return join '', map ucfirst, split /[\W_]+/, lc $table;
1126 return join '', map ucfirst, split /[\W_]+/,
1127 Lingua::EN::Inflect::Number::to_S(lc $table);
1130 sub _table2moniker {
1131 my ( $self, $table ) = @_;
1135 if( ref $self->moniker_map eq 'HASH' ) {
1136 $moniker = $self->moniker_map->{$table};
1138 elsif( ref $self->moniker_map eq 'CODE' ) {
1139 $moniker = $self->moniker_map->($table);
1142 $moniker ||= $self->_default_table2moniker($table);
1147 sub _load_relationships {
1148 my ($self, $table) = @_;
1150 my $tbl_fk_info = $self->_table_fk_info($table);
1151 foreach my $fkdef (@$tbl_fk_info) {
1152 $fkdef->{remote_source} =
1153 $self->monikers->{delete $fkdef->{remote_table}};
1155 my $tbl_uniq_info = $self->_table_uniq_info($table);
1157 my $local_moniker = $self->monikers->{$table};
1158 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1160 foreach my $src_class (sort keys %$rel_stmts) {
1161 my $src_stmts = $rel_stmts->{$src_class};
1162 foreach my $stmt (@$src_stmts) {
1163 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1168 # Overload these in driver class:
1170 # Returns an arrayref of column names
1171 sub _table_columns { croak "ABSTRACT METHOD" }
1173 # Returns arrayref of pk col names
1174 sub _table_pk_info { croak "ABSTRACT METHOD" }
1176 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1177 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1179 # Returns an arrayref of foreign key constraints, each
1180 # being a hashref with 3 keys:
1181 # local_columns (arrayref), remote_columns (arrayref), remote_table
1182 sub _table_fk_info { croak "ABSTRACT METHOD" }
1184 # Returns an array of lower case table names
1185 sub _tables_list { croak "ABSTRACT METHOD" }
1187 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1192 if ( $method eq 'table' ) {
1194 $self->_pod( $class, "=head1 NAME" );
1195 my $table_descr = $class;
1196 if ( $self->can('_table_comment') ) {
1197 my $comment = $self->_table_comment($table);
1198 $table_descr .= " - " . $comment if $comment;
1200 $self->{_class2table}{ $class } = $table;
1201 $self->_pod( $class, $table_descr );
1202 $self->_pod_cut( $class );
1203 } elsif ( $method eq 'add_columns' ) {
1204 $self->_pod( $class, "=head1 ACCESSORS" );
1209 $self->_pod( $class, '=head2 ' . $_ );
1211 $comment = $self->_column_comment( $self->{_class2table}{$class}, ($i - 1) / 2 + 1 ) if $self->can('_column_comment');
1212 $self->_pod( $class, $comment ) if $comment;
1214 $self->_pod_cut( $class );
1215 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
1216 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
1217 my ( $accessor, $rel_class ) = @_;
1218 $self->_pod( $class, "=head2 $accessor" );
1219 $self->_pod( $class, 'Type: ' . $method );
1220 $self->_pod( $class, "Related object: L<$rel_class>" );
1221 $self->_pod_cut( $class );
1222 $self->{_relations_started} { $class } = 1;
1224 my $args = dump(@_);
1225 $args = '(' . $args . ')' if @_ < 2;
1226 my $stmt = $method . $args . q{;};
1228 warn qq|$class\->$stmt\n| if $self->debug;
1229 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1233 # Stores a POD documentation
1235 my ($self, $class, $stmt) = @_;
1236 $self->_raw_stmt( $class, "\n" . $stmt );
1240 my ($self, $class ) = @_;
1241 $self->_raw_stmt( $class, "\n=cut\n" );
1245 # Store a raw source line for a class (for dumping purposes)
1247 my ($self, $class, $stmt) = @_;
1248 push(@{$self->{_dump_storage}->{$class}}, $stmt);
1251 # Like above, but separately for the externally loaded stuff
1253 my ($self, $class, $stmt) = @_;
1254 push(@{$self->{_ext_storage}->{$class}}, $stmt);
1257 sub _quote_table_name {
1258 my ($self, $table) = @_;
1260 my $qt = $self->schema->storage->sql_maker->quote_char;
1262 return $table unless $qt;
1265 return $qt->[0] . $table . $qt->[1];
1268 return $qt . $table . $qt;
1271 sub _is_case_sensitive { 0 }
1273 # remove the dump dir from @INC on destruction
1277 @INC = grep $_ ne $self->dump_directory, @INC;
1282 Returns a hashref of loaded table to moniker mappings. There will
1283 be two entries for each table, the original name and the "normalized"
1284 name, in the case that the two are different (such as databases
1285 that like uppercase table names, or preserve your original mixed-case
1286 definitions, or what-have-you).
1290 Returns a hashref of table to class mappings. In some cases it will
1291 contain multiple entries per table for the original and normalized table
1292 names, as above in L</monikers>.
1296 L<DBIx::Class::Schema::Loader>
1300 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
1304 This library is free software; you can redistribute it and/or modify it under
1305 the same terms as Perl itself.