1 package DBIx::Class::Schema::Loader::Base;
5 use base qw/Class::Accessor::Grouped Class::C3::Componentised/;
6 use namespace::autoclean;
8 use Carp::Clan qw/^DBIx::Class/;
9 use DBIx::Class::Schema::Loader::RelBuilder;
10 use Data::Dump qw/ dump /;
15 use Lingua::EN::Inflect::Number qw//;
16 use Lingua::EN::Inflect::Phrase qw//;
19 use Class::Inspector ();
20 use Data::Dumper::Concise;
21 use Scalar::Util 'looks_like_number';
22 use File::Slurp 'slurp';
25 our $VERSION = '0.06001';
27 __PACKAGE__->mk_group_ro_accessors('simple', qw/
34 additional_base_classes
49 default_resultset_class
52 overwrite_modifications
70 __PACKAGE__->mk_group_accessors('simple', qw/
72 schema_version_to_dump
74 _upgrading_from_load_classes
75 _downgrading_to_load_classes
76 _rewriting_result_namespace
81 pod_comment_spillover_length
86 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
90 See L<DBIx::Class::Schema::Loader>
94 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
95 classes, and implements the common functionality between them.
97 =head1 CONSTRUCTOR OPTIONS
99 These constructor options are the base options for
100 L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
102 =head2 skip_relationships
104 Skip setting up relationships. The default is to attempt the loading
107 =head2 skip_load_external
109 Skip loading of other classes in @INC. The default is to merge all other classes
110 with the same name found in @INC into the schema file we are creating.
114 Static schemas (ones dumped to disk) will, by default, use the new-style
115 relationship names and singularized Results, unless you're overwriting an
116 existing dump made by an older version of L<DBIx::Class::Schema::Loader>, in
117 which case the backward compatible RelBuilder will be activated, and the
118 appropriate monikerization used.
124 will disable the backward-compatible RelBuilder and use
125 the new-style relationship names along with singularized Results, even when
126 overwriting a dump made with an earlier version.
128 The option also takes a hashref:
130 naming => { relationships => 'v6', monikers => 'v6' }
138 How to name relationship accessors.
142 How to name Result classes.
152 Latest style, whatever that happens to be.
156 Unsingularlized monikers, C<has_many> only relationships with no _id stripping.
160 Monikers singularized as whole words, C<might_have> relationships for FKs on
161 C<UNIQUE> constraints, C<_id> stripping for belongs_to relationships.
163 Some of the C<_id> stripping edge cases in C<0.05003> have been reverted for
168 All monikers and relationships inflected using L<Lingua::EN::Inflect::Phrase>,
169 more aggressive C<_id> stripping from relationships.
171 In general, there is very little difference between v5 and v6 schemas.
175 Dynamic schemas will always default to the 0.04XXX relationship names and won't
176 singularize Results for backward compatibility, to activate the new RelBuilder
177 and singularization put this in your C<Schema.pm> file:
179 __PACKAGE__->naming('current');
181 Or if you prefer to use 0.05XXX features but insure that nothing breaks in the
182 next major version upgrade:
184 __PACKAGE__->naming('v5');
188 By default POD will be generated for columns and relationships, using database
189 metadata for the text if available and supported.
191 Reading database metadata (e.g. C<COMMENT ON TABLE some_table ...>) is only
192 supported for Postgres right now.
194 Set this to C<0> to turn off all POD generation.
196 =head2 pod_comment_mode
198 Controls where table comments appear in the generated POD. Smaller table
199 comments are appended to the C<NAME> section of the documentation, and larger
200 ones are inserted into C<DESCRIPTION> instead. You can force a C<DESCRIPTION>
201 section to be generated with the comment always, only use C<NAME>, or choose
202 the length threshold at which the comment is forced into the description.
208 Use C<NAME> section only.
212 Force C<DESCRIPTION> always.
216 Use C<DESCRIPTION> if length > L</pod_comment_spillover_length>, this is the
221 =head2 pod_comment_spillover_length
223 When pod_comment_mode is set to C<auto>, this is the length of the comment at
224 which it will be forced into a separate description section.
228 =head2 relationship_attrs
230 Hashref of attributes to pass to each generated relationship, listed
231 by type. Also supports relationship type 'all', containing options to
232 pass to all generated relationships. Attributes set for more specific
233 relationship types override those set in 'all'.
237 relationship_attrs => {
238 all => { cascade_delete => 0 },
239 has_many => { cascade_delete => 1 },
242 will set the C<cascade_delete> option to 0 for all generated relationships,
243 except for C<has_many>, which will have cascade_delete as 1.
245 NOTE: this option is not supported if v4 backward-compatible naming is
246 set either globally (naming => 'v4') or just for relationships.
250 If set to true, each constructive L<DBIx::Class> statement the loader
251 decides to execute will be C<warn>-ed before execution.
255 Set the name of the schema to load (schema in the sense that your database
256 vendor means it). Does not currently support loading more than one schema
261 Only load tables matching regex. Best specified as a qr// regex.
265 Exclude tables matching regex. Best specified as a qr// regex.
269 Overrides the default table name to moniker translation. Can be either
270 a hashref of table keys and moniker values, or a coderef for a translator
271 function taking a single scalar table name argument and returning
272 a scalar moniker. If the hash entry does not exist, or the function
273 returns a false value, the code falls back to default behavior
276 The default behavior is to singularize the table name, and: C<join '', map
277 ucfirst, split /[\W_]+/, lc $table>, which is to say: lowercase everything,
278 split up the table name into chunks anywhere a non-alpha-numeric character
279 occurs, change the case of first letter of each chunk to upper case, and put
280 the chunks back together. Examples:
282 Table Name | Moniker Name
283 ---------------------------
285 luser_group | LuserGroup
286 luser-opts | LuserOpt
288 =head2 inflect_plural
290 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
291 if hash key does not exist or coderef returns false), but acts as a map
292 for pluralizing relationship names. The default behavior is to utilize
293 L<Lingua::EN::Inflect::Number/to_PL>.
295 =head2 inflect_singular
297 As L</inflect_plural> above, but for singularizing relationship names.
298 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
300 =head2 schema_base_class
302 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
304 =head2 result_base_class
306 Base class for your table classes (aka result classes). Defaults to
309 =head2 additional_base_classes
311 List of additional base classes all of your table classes will use.
313 =head2 left_base_classes
315 List of additional base classes all of your table classes will use
316 that need to be leftmost.
318 =head2 additional_classes
320 List of additional classes which all of your table classes will use.
324 List of additional components to be loaded into all of your table
325 classes. A good example would be C<ResultSetManager>.
327 =head2 resultset_components
329 List of additional ResultSet components to be loaded into your table
330 classes. A good example would be C<AlwaysRS>. Component
331 C<ResultSetManager> will be automatically added to the above
332 C<components> list if this option is set.
334 =head2 use_namespaces
336 This is now the default, to go back to L<DBIx::Class::Schema/load_classes> pass
339 Generate result class names suitable for
340 L<DBIx::Class::Schema/load_namespaces> and call that instead of
341 L<DBIx::Class::Schema/load_classes>. When using this option you can also
342 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
343 C<resultset_namespace>, C<default_resultset_class>), and they will be added
344 to the call (and the generated result class names adjusted appropriately).
346 =head2 dump_directory
348 This option is designed to be a tool to help you transition from this
349 loader to a manually-defined schema when you decide it's time to do so.
351 The value of this option is a perl libdir pathname. Within
352 that directory this module will create a baseline manual
353 L<DBIx::Class::Schema> module set, based on what it creates at runtime
356 The created schema class will have the same classname as the one on
357 which you are setting this option (and the ResultSource classes will be
358 based on this name as well).
360 Normally you wouldn't hard-code this setting in your schema class, as it
361 is meant for one-time manual usage.
363 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
364 recommended way to access this functionality.
366 =head2 dump_overwrite
368 Deprecated. See L</really_erase_my_files> below, which does *not* mean
369 the same thing as the old C<dump_overwrite> setting from previous releases.
371 =head2 really_erase_my_files
373 Default false. If true, Loader will unconditionally delete any existing
374 files before creating the new ones from scratch when dumping a schema to disk.
376 The default behavior is instead to only replace the top portion of the
377 file, up to and including the final stanza which contains
378 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
379 leaving any customizations you placed after that as they were.
381 When C<really_erase_my_files> is not set, if the output file already exists,
382 but the aforementioned final stanza is not found, or the checksum
383 contained there does not match the generated contents, Loader will
384 croak and not touch the file.
386 You should really be using version control on your schema classes (and all
387 of the rest of your code for that matter). Don't blame me if a bug in this
388 code wipes something out when it shouldn't have, you've been warned.
390 =head2 overwrite_modifications
392 Default false. If false, when updating existing files, Loader will
393 refuse to modify any Loader-generated code that has been modified
394 since its last run (as determined by the checksum Loader put in its
397 If true, Loader will discard any manual modifications that have been
398 made to Loader-generated code.
400 Again, you should be using version control on your schema classes. Be
401 careful with this option.
403 =head2 custom_column_info
405 Hook for adding extra attributes to the
406 L<column_info|DBIx::Class::ResultSource/column_info> for a column.
408 Must be a coderef that returns a hashref with the extra attributes.
410 Receives the table name, column name and column_info.
414 custom_column_info => sub {
415 my ($table_name, $column_name, $column_info) = @_;
417 if ($column_name eq 'dog' && $column_info->{default_value} eq 'snoopy') {
418 return { is_snoopy => 1 };
422 This attribute can also be used to set C<inflate_datetime> on a non-datetime
423 column so it also receives the L</datetime_timezone> and/or L</datetime_locale>.
425 =head2 datetime_timezone
427 Sets the timezone attribute for L<DBIx::Class::InflateColumn::DateTime> for all
428 columns with the DATE/DATETIME/TIMESTAMP data_types.
430 =head2 datetime_locale
432 Sets the locale attribute for L<DBIx::Class::InflateColumn::DateTime> for all
433 columns with the DATE/DATETIME/TIMESTAMP data_types.
437 File in Perl format, which should return a HASH reference, from which to read
442 None of these methods are intended for direct invocation by regular
443 users of L<DBIx::Class::Schema::Loader>. Some are proxied via
444 L<DBIx::Class::Schema::Loader>.
448 my $CURRENT_V = 'v6';
451 schema_base_class result_base_class additional_base_classes
452 left_base_classes additional_classes components resultset_components
455 # ensure that a peice of object data is a valid arrayref, creating
456 # an empty one or encapsulating whatever's there.
457 sub _ensure_arrayref {
462 $self->{$_} = [ $self->{$_} ]
463 unless ref $self->{$_} eq 'ARRAY';
469 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
470 by L<DBIx::Class::Schema::Loader>.
475 my ( $class, %args ) = @_;
477 my $self = { %args };
479 bless $self => $class;
481 if (my $config_file = $self->config_file) {
482 my $config_opts = do $config_file;
484 croak "Error reading config from $config_file: $@" if $@;
486 croak "Config file $config_file must be a hashref" unless ref($config_opts) eq 'HASH';
488 while (my ($k, $v) = each %$config_opts) {
489 $self->{$k} = $v unless exists $self->{$k};
493 $self->_ensure_arrayref(qw/additional_classes
494 additional_base_classes
500 $self->_validate_class_args;
502 push(@{$self->{components}}, 'ResultSetManager')
503 if @{$self->{resultset_components}};
505 $self->{monikers} = {};
506 $self->{classes} = {};
507 $self->{_upgrading_classes} = {};
509 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
510 $self->{schema} ||= $self->{schema_class};
512 croak "dump_overwrite is deprecated. Please read the"
513 . " DBIx::Class::Schema::Loader::Base documentation"
514 if $self->{dump_overwrite};
516 $self->{dynamic} = ! $self->{dump_directory};
517 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
522 $self->{dump_directory} ||= $self->{temp_directory};
524 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
525 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
527 if ((not ref $self->naming) && defined $self->naming) {
528 my $naming_ver = $self->naming;
530 relationships => $naming_ver,
531 monikers => $naming_ver,
536 for (values %{ $self->naming }) {
537 $_ = $CURRENT_V if $_ eq 'current';
540 $self->{naming} ||= {};
542 if ($self->custom_column_info && ref $self->custom_column_info ne 'CODE') {
543 croak 'custom_column_info must be a CODE ref';
546 $self->_check_back_compat;
548 $self->use_namespaces(1) unless defined $self->use_namespaces;
549 $self->generate_pod(1) unless defined $self->generate_pod;
550 $self->pod_comment_mode('auto') unless defined $self->pod_comment_mode;
551 $self->pod_comment_spillover_length(60) unless defined $self->pod_comment_spillover_length;
556 sub _check_back_compat {
559 # dynamic schemas will always be in 0.04006 mode, unless overridden
560 if ($self->dynamic) {
561 # just in case, though no one is likely to dump a dynamic schema
562 $self->schema_version_to_dump('0.04006');
564 if (not %{ $self->naming }) {
565 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
567 Dynamic schema detected, will run in 0.04006 mode.
569 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
570 to disable this warning.
572 Also consider setting 'use_namespaces => 1' if/when upgrading.
574 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
579 $self->_upgrading_from('v4');
582 $self->naming->{relationships} ||= 'v4';
583 $self->naming->{monikers} ||= 'v4';
585 if ($self->use_namespaces) {
586 $self->_upgrading_from_load_classes(1);
589 $self->use_namespaces(0);
595 # otherwise check if we need backcompat mode for a static schema
596 my $filename = $self->_get_dump_filename($self->schema_class);
597 return unless -e $filename;
599 open(my $fh, '<', $filename)
600 or croak "Cannot open '$filename' for reading: $!";
602 my $load_classes = 0;
603 my $result_namespace = '';
606 if (/^__PACKAGE__->load_classes;/) {
608 } elsif (/result_namespace => '([^']+)'/) {
609 $result_namespace = $1;
610 } elsif (my ($real_ver) =
611 /^# Created by DBIx::Class::Schema::Loader v(\d+\.\d+)/) {
613 if ($load_classes && (not defined $self->use_namespaces)) {
614 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
616 'load_classes;' static schema detected, turning off 'use_namespaces'.
618 Set the 'use_namespaces' attribute or the SCHEMA_LOADER_BACKCOMPAT environment
619 variable to disable this warning.
621 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
624 $self->use_namespaces(0);
626 elsif ($load_classes && $self->use_namespaces) {
627 $self->_upgrading_from_load_classes(1);
629 elsif ((not $load_classes) && defined $self->use_namespaces
630 && (not $self->use_namespaces)) {
631 $self->_downgrading_to_load_classes(
632 $result_namespace || 'Result'
635 elsif ((not defined $self->use_namespaces)
636 || $self->use_namespaces) {
637 if (not $self->result_namespace) {
638 $self->result_namespace($result_namespace || 'Result');
640 elsif ($result_namespace ne $self->result_namespace) {
641 $self->_rewriting_result_namespace(
642 $result_namespace || 'Result'
647 # XXX when we go past .0 this will need fixing
648 my ($v) = $real_ver =~ /([1-9])/;
651 last if $v eq $CURRENT_V || $real_ver =~ /^0\.\d\d999/;
653 if (not %{ $self->naming }) {
654 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
656 Version $real_ver static schema detected, turning on backcompat mode.
658 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
659 to disable this warning.
661 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 if upgrading
662 from version 0.04006.
666 $self->_upgrading_from($v);
670 $self->naming->{relationships} ||= $v;
671 $self->naming->{monikers} ||= $v;
673 $self->schema_version_to_dump($real_ver);
681 sub _validate_class_args {
685 foreach my $k (@CLASS_ARGS) {
686 next unless $self->$k;
688 my @classes = ref $self->$k eq 'ARRAY' ? @{ $self->$k } : $self->$k;
689 foreach my $c (@classes) {
690 # components default to being under the DBIx::Class namespace unless they
691 # are preceeded with a '+'
692 if ( $k =~ m/components$/ && $c !~ s/^\+// ) {
693 $c = 'DBIx::Class::' . $c;
696 # 1 == installed, 0 == not installed, undef == invalid classname
697 my $installed = Class::Inspector->installed($c);
698 if ( defined($installed) ) {
699 if ( $installed == 0 ) {
700 croak qq/$c, as specified in the loader option "$k", is not installed/;
703 croak qq/$c, as specified in the loader option "$k", is an invalid class name/;
709 sub _find_file_in_inc {
710 my ($self, $file) = @_;
712 foreach my $prefix (@INC) {
713 my $fullpath = File::Spec->catfile($prefix, $file);
714 return $fullpath if -f $fullpath
715 # abs_path throws on Windows for nonexistant files
716 and eval { Cwd::abs_path($fullpath) } ne
717 (eval { Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) } || '');
724 my ($self, $class) = @_;
726 my $class_path = $class;
727 $class_path =~ s{::}{/}g;
728 $class_path .= '.pm';
733 sub _find_class_in_inc {
734 my ($self, $class) = @_;
736 return $self->_find_file_in_inc($self->_class_path($class));
742 return $self->_upgrading_from
743 || $self->_upgrading_from_load_classes
744 || $self->_downgrading_to_load_classes
745 || $self->_rewriting_result_namespace
749 sub _rewrite_old_classnames {
750 my ($self, $code) = @_;
752 return $code unless $self->_rewriting;
754 my %old_classes = reverse %{ $self->_upgrading_classes };
756 my $re = join '|', keys %old_classes;
759 $code =~ s/$re/$old_classes{$1} || $1/eg;
765 my ($self, $class) = @_;
767 return if $self->{skip_load_external};
769 # so that we don't load our own classes, under any circumstances
770 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
772 my $real_inc_path = $self->_find_class_in_inc($class);
774 my $old_class = $self->_upgrading_classes->{$class}
775 if $self->_rewriting;
777 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
778 if $old_class && $old_class ne $class;
780 return unless $real_inc_path || $old_real_inc_path;
782 if ($real_inc_path) {
783 # If we make it to here, we loaded an external definition
784 warn qq/# Loaded external class definition for '$class'\n/
787 open(my $fh, '<', $real_inc_path)
788 or croak "Failed to open '$real_inc_path' for reading: $!";
789 my $code = do { local $/; <$fh> };
791 or croak "Failed to close $real_inc_path: $!";
792 $code = $self->_rewrite_old_classnames($code);
794 if ($self->dynamic) { # load the class too
795 # kill redefined warnings
796 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
797 local $SIG{__WARN__} = sub {
799 unless $_[0] =~ /^Subroutine \S+ redefined/;
805 $self->_ext_stmt($class,
806 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
807 .qq|# They are now part of the custom portion of this file\n|
808 .qq|# for you to hand-edit. If you do not either delete\n|
809 .qq|# this section or remove that file from \@INC, this section\n|
810 .qq|# will be repeated redundantly when you re-create this\n|
811 .qq|# file again via Loader! See skip_load_external to disable\n|
812 .qq|# this feature.\n|
815 $self->_ext_stmt($class, $code);
816 $self->_ext_stmt($class,
817 qq|# End of lines loaded from '$real_inc_path' |
821 if ($old_real_inc_path) {
822 open(my $fh, '<', $old_real_inc_path)
823 or croak "Failed to open '$old_real_inc_path' for reading: $!";
824 $self->_ext_stmt($class, <<"EOF");
826 # These lines were loaded from '$old_real_inc_path',
827 # based on the Result class name that would have been created by an 0.04006
828 # version of the Loader. For a static schema, this happens only once during
829 # upgrade. See skip_load_external to disable this feature.
832 my $code = slurp $old_real_inc_path;
833 $code = $self->_rewrite_old_classnames($code);
835 if ($self->dynamic) {
838 Detected external content in '$old_real_inc_path', a class name that would have
839 been used by an 0.04006 version of the Loader.
841 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
842 new name of the Result.
844 # kill redefined warnings
845 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
846 local $SIG{__WARN__} = sub {
848 unless $_[0] =~ /^Subroutine \S+ redefined/;
855 $self->_ext_stmt($class, $code);
856 $self->_ext_stmt($class,
857 qq|# End of lines loaded from '$old_real_inc_path' |
864 Does the actual schema-construction work.
872 $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude })
880 Rescan the database for newly added tables. Does
881 not process drops or changes. Returns a list of
882 the newly added table monikers.
884 The schema argument should be the schema class
885 or object to be affected. It should probably
886 be derived from the original schema_class used
892 my ($self, $schema) = @_;
894 $self->{schema} = $schema;
895 $self->_relbuilder->{schema} = $schema;
898 my @current = $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude });
899 foreach my $table (@current) {
900 if(!exists $self->{_tables}->{$table}) {
901 push(@created, $table);
905 my $loaded = $self->_load_tables(@created);
907 return map { $self->monikers->{$_} } @$loaded;
911 no warnings 'uninitialized';
914 return if $self->{skip_relationships};
916 if ($self->naming->{relationships} eq 'v4') {
917 require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040;
918 return $self->{relbuilder} ||=
919 DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040->new(
920 $self->schema, $self->inflect_plural, $self->inflect_singular
923 elsif ($self->naming->{relationships} eq 'v5') {
924 require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_05;
925 return $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_05->new (
927 $self->inflect_plural,
928 $self->inflect_singular,
929 $self->relationship_attrs,
933 return $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder->new (
935 $self->inflect_plural,
936 $self->inflect_singular,
937 $self->relationship_attrs,
942 my ($self, @tables) = @_;
944 # Save the new tables to the tables list
946 $self->{_tables}->{$_} = 1;
949 $self->_make_src_class($_) for @tables;
951 # sanity-check for moniker clashes
952 my $inverse_moniker_idx;
953 for (keys %{$self->monikers}) {
954 push @{$inverse_moniker_idx->{$self->monikers->{$_}}}, $_;
958 for (keys %$inverse_moniker_idx) {
959 my $tables = $inverse_moniker_idx->{$_};
961 push @clashes, sprintf ("tables %s reduced to the same source moniker '%s'",
962 join (', ', map { "'$_'" } @$tables),
969 die 'Unable to load schema - chosen moniker/class naming style results in moniker clashes. '
970 . 'Either change the naming style, or supply an explicit moniker_map: '
971 . join ('; ', @clashes)
977 $self->_setup_src_meta($_) for @tables;
979 if(!$self->skip_relationships) {
980 # The relationship loader needs a working schema
982 local $self->{dump_directory} = $self->{temp_directory};
983 $self->_reload_classes(\@tables);
984 $self->_load_relationships($_) for @tables;
987 # Remove that temp dir from INC so it doesn't get reloaded
988 @INC = grep $_ ne $self->dump_directory, @INC;
991 $self->_load_external($_)
992 for map { $self->classes->{$_} } @tables;
994 # Reload without unloading first to preserve any symbols from external
996 $self->_reload_classes(\@tables, 0);
998 # Drop temporary cache
999 delete $self->{_cache};
1004 sub _reload_classes {
1005 my ($self, $tables, $unload) = @_;
1007 my @tables = @$tables;
1008 $unload = 1 unless defined $unload;
1010 # so that we don't repeat custom sections
1011 @INC = grep $_ ne $self->dump_directory, @INC;
1013 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
1015 unshift @INC, $self->dump_directory;
1018 my %have_source = map { $_ => $self->schema->source($_) }
1019 $self->schema->sources;
1021 for my $table (@tables) {
1022 my $moniker = $self->monikers->{$table};
1023 my $class = $self->classes->{$table};
1026 no warnings 'redefine';
1027 local *Class::C3::reinitialize = sub {};
1030 Class::Unload->unload($class) if $unload;
1031 my ($source, $resultset_class);
1033 ($source = $have_source{$moniker})
1034 && ($resultset_class = $source->resultset_class)
1035 && ($resultset_class ne 'DBIx::Class::ResultSet')
1037 my $has_file = Class::Inspector->loaded_filename($resultset_class);
1038 Class::Unload->unload($resultset_class) if $unload;
1039 $self->_reload_class($resultset_class) if $has_file;
1041 $self->_reload_class($class);
1043 push @to_register, [$moniker, $class];
1046 Class::C3->reinitialize;
1047 for (@to_register) {
1048 $self->schema->register_class(@$_);
1052 # We use this instead of ensure_class_loaded when there are package symbols we
1055 my ($self, $class) = @_;
1057 my $class_path = $self->_class_path($class);
1058 delete $INC{ $class_path };
1060 # kill redefined warnings
1061 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
1062 local $SIG{__WARN__} = sub {
1064 unless $_[0] =~ /^Subroutine \S+ redefined/;
1066 eval "require $class;";
1069 sub _get_dump_filename {
1070 my ($self, $class) = (@_);
1072 $class =~ s{::}{/}g;
1073 return $self->dump_directory . q{/} . $class . q{.pm};
1076 sub _ensure_dump_subdirs {
1077 my ($self, $class) = (@_);
1079 my @name_parts = split(/::/, $class);
1080 pop @name_parts; # we don't care about the very last element,
1081 # which is a filename
1083 my $dir = $self->dump_directory;
1086 mkdir($dir) or croak "mkdir('$dir') failed: $!";
1088 last if !@name_parts;
1089 $dir = File::Spec->catdir($dir, shift @name_parts);
1094 my ($self, @classes) = @_;
1096 my $schema_class = $self->schema_class;
1097 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
1099 my $target_dir = $self->dump_directory;
1100 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
1101 unless $self->{dynamic} or $self->{quiet};
1104 qq|package $schema_class;\n\n|
1105 . qq|# Created by DBIx::Class::Schema::Loader\n|
1106 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1107 . qq|use strict;\nuse warnings;\n\n|
1108 . qq|use base '$schema_base_class';\n\n|;
1110 if ($self->use_namespaces) {
1111 $schema_text .= qq|__PACKAGE__->load_namespaces|;
1112 my $namespace_options;
1114 my @attr = qw/resultset_namespace default_resultset_class/;
1116 unshift @attr, 'result_namespace' unless (not $self->result_namespace) || $self->result_namespace eq 'Result';
1118 for my $attr (@attr) {
1120 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
1123 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
1124 $schema_text .= qq|;\n|;
1127 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
1131 local $self->{version_to_dump} = $self->schema_version_to_dump;
1132 $self->_write_classfile($schema_class, $schema_text, 1);
1135 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
1137 foreach my $src_class (@classes) {
1139 qq|package $src_class;\n\n|
1140 . qq|# Created by DBIx::Class::Schema::Loader\n|
1141 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1142 . qq|use strict;\nuse warnings;\n\n|
1143 . qq|use base '$result_base_class';\n\n|;
1145 $self->_write_classfile($src_class, $src_text);
1148 # remove Result dir if downgrading from use_namespaces, and there are no
1150 if (my $result_ns = $self->_downgrading_to_load_classes
1151 || $self->_rewriting_result_namespace) {
1152 my $result_namespace = $self->_result_namespace(
1157 (my $result_dir = $result_namespace) =~ s{::}{/}g;
1158 $result_dir = $self->dump_directory . '/' . $result_dir;
1160 unless (my @files = glob "$result_dir/*") {
1165 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
1170 my ($self, $version, $ts) = @_;
1171 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
1174 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
1177 sub _write_classfile {
1178 my ($self, $class, $text, $is_schema) = @_;
1180 my $filename = $self->_get_dump_filename($class);
1181 $self->_ensure_dump_subdirs($class);
1183 if (-f $filename && $self->really_erase_my_files) {
1184 warn "Deleting existing file '$filename' due to "
1185 . "'really_erase_my_files' setting\n" unless $self->{quiet};
1189 my ($custom_content, $old_md5, $old_ver, $old_ts) = $self->_get_custom_content($class, $filename);
1191 if (my $old_class = $self->_upgrading_classes->{$class}) {
1192 my $old_filename = $self->_get_dump_filename($old_class);
1194 my ($old_custom_content) = $self->_get_custom_content(
1195 $old_class, $old_filename, 0 # do not add default comment
1198 $old_custom_content =~ s/\n\n# You can replace.*\n1;\n//;
1200 if ($old_custom_content) {
1202 "\n" . $old_custom_content . "\n" . $custom_content;
1205 unlink $old_filename;
1208 $custom_content = $self->_rewrite_old_classnames($custom_content);
1211 for @{$self->{_dump_storage}->{$class} || []};
1213 # Check and see if the dump is infact differnt
1217 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
1220 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
1221 return unless $self->_upgrading_from && $is_schema;
1225 $text .= $self->_sig_comment(
1226 $self->version_to_dump,
1227 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
1230 open(my $fh, '>', $filename)
1231 or croak "Cannot open '$filename' for writing: $!";
1233 # Write the top half and its MD5 sum
1234 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
1236 # Write out anything loaded via external partial class file in @INC
1238 for @{$self->{_ext_storage}->{$class} || []};
1240 # Write out any custom content the user has added
1241 print $fh $custom_content;
1244 or croak "Error closing '$filename': $!";
1247 sub _default_custom_content {
1248 return qq|\n\n# You can replace this text with custom|
1249 . qq| content, and it will be preserved on regeneration|
1253 sub _get_custom_content {
1254 my ($self, $class, $filename, $add_default) = @_;
1256 $add_default = 1 unless defined $add_default;
1258 return ($self->_default_custom_content) if ! -f $filename;
1260 open(my $fh, '<', $filename)
1261 or croak "Cannot open '$filename' for reading: $!";
1264 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
1267 my ($md5, $ts, $ver);
1269 if(!$md5 && /$mark_re/) {
1273 # Pull out the previous version and timestamp
1274 ($ver, $ts) = $buffer =~ m/# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)$/s;
1277 croak "Checksum mismatch in '$filename', the auto-generated part of the file has been modified outside of this loader. Aborting.\nIf you want to overwrite these modifications, set the 'overwrite_modifications' loader option.\n"
1278 if !$self->overwrite_modifications && Digest::MD5::md5_base64($buffer) ne $md5;
1287 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
1288 . " it does not appear to have been generated by Loader"
1291 # Default custom content:
1292 $buffer ||= $self->_default_custom_content if $add_default;
1294 return ($buffer, $md5, $ver, $ts);
1302 warn "$target: use $_;" if $self->debug;
1303 $self->_raw_stmt($target, "use $_;");
1310 my $schema_class = $self->schema_class;
1312 my $blist = join(q{ }, @_);
1313 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
1314 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
1317 sub _result_namespace {
1318 my ($self, $schema_class, $ns) = @_;
1319 my @result_namespace;
1321 if ($ns =~ /^\+(.*)/) {
1322 # Fully qualified namespace
1323 @result_namespace = ($1)
1326 # Relative namespace
1327 @result_namespace = ($schema_class, $ns);
1330 return wantarray ? @result_namespace : join '::', @result_namespace;
1333 # Create class with applicable bases, setup monikers, etc
1334 sub _make_src_class {
1335 my ($self, $table) = @_;
1337 my $schema = $self->schema;
1338 my $schema_class = $self->schema_class;
1340 my $table_moniker = $self->_table2moniker($table);
1341 my @result_namespace = ($schema_class);
1342 if ($self->use_namespaces) {
1343 my $result_namespace = $self->result_namespace || 'Result';
1344 @result_namespace = $self->_result_namespace(
1349 my $table_class = join(q{::}, @result_namespace, $table_moniker);
1351 if ((my $upgrading_v = $self->_upgrading_from)
1352 || $self->_rewriting) {
1353 local $self->naming->{monikers} = $upgrading_v
1356 my @result_namespace = @result_namespace;
1357 if ($self->_upgrading_from_load_classes) {
1358 @result_namespace = ($schema_class);
1360 elsif (my $ns = $self->_downgrading_to_load_classes) {
1361 @result_namespace = $self->_result_namespace(
1366 elsif ($ns = $self->_rewriting_result_namespace) {
1367 @result_namespace = $self->_result_namespace(
1373 my $old_class = join(q{::}, @result_namespace,
1374 $self->_table2moniker($table));
1376 $self->_upgrading_classes->{$table_class} = $old_class
1377 unless $table_class eq $old_class;
1380 # this was a bad idea, should be ok now without it
1381 # my $table_normalized = lc $table;
1382 # $self->classes->{$table_normalized} = $table_class;
1383 # $self->monikers->{$table_normalized} = $table_moniker;
1385 $self->classes->{$table} = $table_class;
1386 $self->monikers->{$table} = $table_moniker;
1388 $self->_use ($table_class, @{$self->additional_classes});
1389 $self->_inject($table_class, @{$self->left_base_classes});
1391 if (my @components = @{ $self->components }) {
1392 $self->_dbic_stmt($table_class, 'load_components', @components);
1395 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
1396 if @{$self->resultset_components};
1397 $self->_inject($table_class, @{$self->additional_base_classes});
1400 sub _resolve_col_accessor_collisions {
1401 my ($self, $col_info) = @_;
1403 my $base = $self->result_base_class || 'DBIx::Class::Core';
1404 my @components = map "DBIx::Class::$_", @{ $self->components || [] };
1408 for my $class ($base, @components) {
1409 eval "require ${class};";
1412 push @methods, @{ Class::Inspector->methods($class) || [] };
1416 @methods{@methods} = ();
1418 while (my ($col, $info) = each %$col_info) {
1419 my $accessor = $info->{accessor} || $col;
1421 next if $accessor eq 'id'; # XXX fix this in DBIC
1423 if (exists $methods{$accessor}) {
1424 $info->{accessor} = ucfirst $accessor;
1429 # Set up metadata (cols, pks, etc)
1430 sub _setup_src_meta {
1431 my ($self, $table) = @_;
1433 my $schema = $self->schema;
1434 my $schema_class = $self->schema_class;
1436 my $table_class = $self->classes->{$table};
1437 my $table_moniker = $self->monikers->{$table};
1439 my $table_name = $table;
1440 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1442 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1443 $table_name = \ $self->_quote_table_name($table_name);
1446 $self->_dbic_stmt($table_class,'table',$table_name);
1448 my $cols = $self->_table_columns($table);
1449 my $col_info = $self->__columns_info_for($table);
1450 if ($self->_is_case_sensitive) {
1451 for my $col (keys %$col_info) {
1452 $col_info->{$col}{accessor} = lc $col
1453 if $col ne lc($col);
1456 $col_info = { map { lc($_), $col_info->{$_} } keys %$col_info };
1459 $self->_resolve_col_accessor_collisions($col_info);
1461 my $fks = $self->_table_fk_info($table);
1463 for my $fkdef (@$fks) {
1464 for my $col (@{ $fkdef->{local_columns} }) {
1465 $col_info->{$col}{is_foreign_key} = 1;
1471 map { $_, ($col_info->{$_}||{}) } @$cols
1474 my %uniq_tag; # used to eliminate duplicate uniqs
1476 my $pks = $self->_table_pk_info($table) || [];
1477 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1478 : carp("$table has no primary key");
1479 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1481 my $uniqs = $self->_table_uniq_info($table) || [];
1483 my ($name, $cols) = @$_;
1484 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1485 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1490 sub __columns_info_for {
1491 my ($self, $table) = @_;
1493 my $result = $self->_columns_info_for($table);
1495 while (my ($col, $info) = each %$result) {
1496 $info = { %$info, %{ $self->_custom_column_info ($table, $col, $info) } };
1497 $info = { %$info, %{ $self->_datetime_column_info($table, $col, $info) } };
1499 $result->{$col} = $info;
1507 Returns a sorted list of loaded tables, using the original database table
1515 return keys %{$self->_tables};
1518 # Make a moniker from a table
1519 sub _default_table2moniker {
1520 no warnings 'uninitialized';
1521 my ($self, $table) = @_;
1523 if ($self->naming->{monikers} eq 'v4') {
1524 return join '', map ucfirst, split /[\W_]+/, lc $table;
1526 elsif ($self->naming->{monikers} eq 'v5') {
1527 return join '', map ucfirst, split /[\W_]+/,
1528 Lingua::EN::Inflect::Number::to_S(lc $table);
1531 (my $as_phrase = lc $table) =~ s/_+/ /g;
1532 my $inflected = Lingua::EN::Inflect::Phrase::to_S($as_phrase);
1534 return join '', map ucfirst, split /\W+/, $inflected;
1537 sub _table2moniker {
1538 my ( $self, $table ) = @_;
1542 if( ref $self->moniker_map eq 'HASH' ) {
1543 $moniker = $self->moniker_map->{$table};
1545 elsif( ref $self->moniker_map eq 'CODE' ) {
1546 $moniker = $self->moniker_map->($table);
1549 $moniker ||= $self->_default_table2moniker($table);
1554 sub _load_relationships {
1555 my ($self, $table) = @_;
1557 my $tbl_fk_info = $self->_table_fk_info($table);
1558 foreach my $fkdef (@$tbl_fk_info) {
1559 $fkdef->{remote_source} =
1560 $self->monikers->{delete $fkdef->{remote_table}};
1562 my $tbl_uniq_info = $self->_table_uniq_info($table);
1564 my $local_moniker = $self->monikers->{$table};
1565 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1567 foreach my $src_class (sort keys %$rel_stmts) {
1568 my $src_stmts = $rel_stmts->{$src_class};
1569 foreach my $stmt (@$src_stmts) {
1570 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1575 # Overload these in driver class:
1577 # Returns an arrayref of column names
1578 sub _table_columns { croak "ABSTRACT METHOD" }
1580 # Returns arrayref of pk col names
1581 sub _table_pk_info { croak "ABSTRACT METHOD" }
1583 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1584 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1586 # Returns an arrayref of foreign key constraints, each
1587 # being a hashref with 3 keys:
1588 # local_columns (arrayref), remote_columns (arrayref), remote_table
1589 sub _table_fk_info { croak "ABSTRACT METHOD" }
1591 # Returns an array of lower case table names
1592 sub _tables_list { croak "ABSTRACT METHOD" }
1594 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1600 # generate the pod for this statement, storing it with $self->_pod
1601 $self->_make_pod( $class, $method, @_ ) if $self->generate_pod;
1603 my $args = dump(@_);
1604 $args = '(' . $args . ')' if @_ < 2;
1605 my $stmt = $method . $args . q{;};
1607 warn qq|$class\->$stmt\n| if $self->debug;
1608 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1612 # generates the accompanying pod for a DBIC class method statement,
1613 # storing it with $self->_pod
1619 if ( $method eq 'table' ) {
1621 my $pcm = $self->pod_comment_mode;
1622 my ($comment, $comment_overflows, $comment_in_name, $comment_in_desc);
1623 if ( $self->can('_table_comment') ) {
1624 $comment = $self->_table_comment($table);
1625 $comment_overflows = ($comment and length $comment > $self->pod_comment_spillover_length);
1626 $comment_in_name = ($pcm eq 'name' or ($pcm eq 'auto' and !$comment_overflows));
1627 $comment_in_desc = ($pcm eq 'description' or ($pcm eq 'auto' and $comment_overflows));
1629 $self->_pod( $class, "=head1 NAME" );
1630 my $table_descr = $class;
1631 $table_descr .= " - " . $comment if $comment and $comment_in_name;
1632 $self->{_class2table}{ $class } = $table;
1633 $self->_pod( $class, $table_descr );
1634 if ($comment and $comment_in_desc) {
1635 $self->_pod( $class, "=head1 DESCRIPTION" );
1636 $self->_pod( $class, $comment );
1638 $self->_pod_cut( $class );
1639 } elsif ( $method eq 'add_columns' ) {
1640 $self->_pod( $class, "=head1 ACCESSORS" );
1641 my $col_counter = 0;
1643 while( my ($name,$attrs) = splice @cols,0,2 ) {
1645 $self->_pod( $class, '=head2 ' . $name );
1646 $self->_pod( $class,
1648 my $s = $attrs->{$_};
1649 $s = !defined $s ? 'undef' :
1650 length($s) == 0 ? '(empty string)' :
1651 ref($s) eq 'SCALAR' ? $$s :
1658 looks_like_number($s) ? $s :
1663 } sort keys %$attrs,
1666 if( $self->can('_column_comment')
1667 and my $comment = $self->_column_comment( $self->{_class2table}{$class}, $col_counter)
1669 $self->_pod( $class, $comment );
1672 $self->_pod_cut( $class );
1673 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
1674 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
1675 my ( $accessor, $rel_class ) = @_;
1676 $self->_pod( $class, "=head2 $accessor" );
1677 $self->_pod( $class, 'Type: ' . $method );
1678 $self->_pod( $class, "Related object: L<$rel_class>" );
1679 $self->_pod_cut( $class );
1680 $self->{_relations_started} { $class } = 1;
1684 # Stores a POD documentation
1686 my ($self, $class, $stmt) = @_;
1687 $self->_raw_stmt( $class, "\n" . $stmt );
1691 my ($self, $class ) = @_;
1692 $self->_raw_stmt( $class, "\n=cut\n" );
1695 # Store a raw source line for a class (for dumping purposes)
1697 my ($self, $class, $stmt) = @_;
1698 push(@{$self->{_dump_storage}->{$class}}, $stmt);
1701 # Like above, but separately for the externally loaded stuff
1703 my ($self, $class, $stmt) = @_;
1704 push(@{$self->{_ext_storage}->{$class}}, $stmt);
1707 sub _quote_table_name {
1708 my ($self, $table) = @_;
1710 my $qt = $self->schema->storage->sql_maker->quote_char;
1712 return $table unless $qt;
1715 return $qt->[0] . $table . $qt->[1];
1718 return $qt . $table . $qt;
1721 sub _is_case_sensitive { 0 }
1723 sub _custom_column_info {
1724 my ( $self, $table_name, $column_name, $column_info ) = @_;
1726 if (my $code = $self->custom_column_info) {
1727 return $code->($table_name, $column_name, $column_info) || {};
1732 sub _datetime_column_info {
1733 my ( $self, $table_name, $column_name, $column_info ) = @_;
1735 my $type = $column_info->{data_type} || '';
1736 if ((grep $_, @{ $column_info }{map "inflate_$_", qw/date datetime timestamp/})
1737 or ($type =~ /date|timestamp/i)) {
1738 $result->{timezone} = $self->datetime_timezone if $self->datetime_timezone;
1739 $result->{locale} = $self->datetime_locale if $self->datetime_locale;
1744 # remove the dump dir from @INC on destruction
1748 @INC = grep $_ ne $self->dump_directory, @INC;
1753 Returns a hashref of loaded table to moniker mappings. There will
1754 be two entries for each table, the original name and the "normalized"
1755 name, in the case that the two are different (such as databases
1756 that like uppercase table names, or preserve your original mixed-case
1757 definitions, or what-have-you).
1761 Returns a hashref of table to class mappings. In some cases it will
1762 contain multiple entries per table for the original and normalized table
1763 names, as above in L</monikers>.
1767 L<DBIx::Class::Schema::Loader>
1771 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
1775 This library is free software; you can redistribute it and/or modify it under
1776 the same terms as Perl itself.
1781 # vim:et sts=4 sw=4 tw=0: