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//;
17 use Class::Inspector ();
20 our $VERSION = '0.05002';
22 __PACKAGE__->mk_group_ro_accessors('simple', qw/
29 additional_base_classes
44 default_resultset_class
47 overwrite_modifications
63 __PACKAGE__->mk_group_accessors('simple', qw/
65 schema_version_to_dump
67 _upgrading_from_load_classes
68 _downgrading_to_load_classes
69 _rewriting_result_namespace
74 pod_comment_spillover_length
79 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
83 See L<DBIx::Class::Schema::Loader>
87 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
88 classes, and implements the common functionality between them.
90 =head1 CONSTRUCTOR OPTIONS
92 These constructor options are the base options for
93 L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
95 =head2 skip_relationships
97 Skip setting up relationships. The default is to attempt the loading
100 =head2 skip_load_external
102 Skip loading of other classes in @INC. The default is to merge all other classes
103 with the same name found in @INC into the schema file we are creating.
107 Static schemas (ones dumped to disk) will, by default, use the new-style 0.05XXX
108 relationship names and singularized Results, unless you're overwriting an
109 existing dump made by a 0.04XXX version of L<DBIx::Class::Schema::Loader>, in
110 which case the backward compatible RelBuilder will be activated, and
111 singularization will be turned off.
117 will disable the backward-compatible RelBuilder and use
118 the new-style relationship names along with singularized Results, even when
119 overwriting a dump made with an earlier version.
121 The option also takes a hashref:
123 naming => { relationships => 'v5', monikers => 'v4' }
131 How to name relationship accessors.
135 How to name Result classes.
145 Latest default style, whatever that happens to be.
149 Version 0.05XXX style.
153 Version 0.04XXX style.
157 Dynamic schemas will always default to the 0.04XXX relationship names and won't
158 singularize Results for backward compatibility, to activate the new RelBuilder
159 and singularization put this in your C<Schema.pm> file:
161 __PACKAGE__->naming('current');
163 Or if you prefer to use 0.05XXX features but insure that nothing breaks in the
164 next major version upgrade:
166 __PACKAGE__->naming('v5');
170 By default POD will be generated for columns and relationships, using database
171 metadata for the text if available and supported.
173 Reading database metadata (e.g. C<COMMENT ON TABLE some_table ...>) is only
174 supported for Postgres right now.
176 Set this to C<0> to turn off all POD generation.
178 =head2 pod_comment_mode
180 Controls where table comments appear in the generated POD. Smaller table
181 comments are appended to the C<NAME> section of the documentation, and larger
182 ones are inserted into C<DESCRIPTION> instead. You can force a C<DESCRIPTION>
183 section to be generated with the comment always, only use C<NAME>, or choose
184 the length threshold at which the comment is forced into the description.
190 Use C<NAME> section only.
194 Force C<DESCRIPTION> always.
198 Use C<DESCRIPTION> if length > L</pod_comment_spillover_length>, this is the
203 =head2 pod_comment_spillover_length
205 When pod_comment_mode is set to C<auto>, this is the length of the comment at
206 which it will be forced into a separate description section.
210 =head2 relationship_attrs
212 Hashref of attributes to pass to each generated relationship, listed
213 by type. Also supports relationship type 'all', containing options to
214 pass to all generated relationships. Attributes set for more specific
215 relationship types override those set in 'all'.
219 relationship_attrs => {
220 all => { cascade_delete => 0 },
221 has_many => { cascade_delete => 1 },
224 will set the C<cascade_delete> option to 0 for all generated relationships,
225 except for C<has_many>, which will have cascade_delete as 1.
227 NOTE: this option is not supported if v4 backward-compatible naming is
228 set either globally (naming => 'v4') or just for relationships.
232 If set to true, each constructive L<DBIx::Class> statement the loader
233 decides to execute will be C<warn>-ed before execution.
237 Set the name of the schema to load (schema in the sense that your database
238 vendor means it). Does not currently support loading more than one schema
243 Only load tables matching regex. Best specified as a qr// regex.
247 Exclude tables matching regex. Best specified as a qr// regex.
251 Overrides the default table name to moniker translation. Can be either
252 a hashref of table keys and moniker values, or a coderef for a translator
253 function taking a single scalar table name argument and returning
254 a scalar moniker. If the hash entry does not exist, or the function
255 returns a false value, the code falls back to default behavior
258 The default behavior is to singularize the table name, and: C<join '', map
259 ucfirst, split /[\W_]+/, lc $table>, which is to say: lowercase everything,
260 split up the table name into chunks anywhere a non-alpha-numeric character
261 occurs, change the case of first letter of each chunk to upper case, and put
262 the chunks back together. Examples:
264 Table Name | Moniker Name
265 ---------------------------
267 luser_group | LuserGroup
268 luser-opts | LuserOpt
270 =head2 inflect_plural
272 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
273 if hash key does not exist or coderef returns false), but acts as a map
274 for pluralizing relationship names. The default behavior is to utilize
275 L<Lingua::EN::Inflect::Number/to_PL>.
277 =head2 inflect_singular
279 As L</inflect_plural> above, but for singularizing relationship names.
280 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
282 =head2 schema_base_class
284 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
286 =head2 result_base_class
288 Base class for your table classes (aka result classes). Defaults to
291 =head2 additional_base_classes
293 List of additional base classes all of your table classes will use.
295 =head2 left_base_classes
297 List of additional base classes all of your table classes will use
298 that need to be leftmost.
300 =head2 additional_classes
302 List of additional classes which all of your table classes will use.
306 List of additional components to be loaded into all of your table
307 classes. A good example would be C<ResultSetManager>.
309 =head2 resultset_components
311 List of additional ResultSet components to be loaded into your table
312 classes. A good example would be C<AlwaysRS>. Component
313 C<ResultSetManager> will be automatically added to the above
314 C<components> list if this option is set.
316 =head2 use_namespaces
318 This is now the default, to go back to L<DBIx::Class::Schema/load_classes> pass
321 Generate result class names suitable for
322 L<DBIx::Class::Schema/load_namespaces> and call that instead of
323 L<DBIx::Class::Schema/load_classes>. When using this option you can also
324 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
325 C<resultset_namespace>, C<default_resultset_class>), and they will be added
326 to the call (and the generated result class names adjusted appropriately).
328 =head2 dump_directory
330 This option is designed to be a tool to help you transition from this
331 loader to a manually-defined schema when you decide it's time to do so.
333 The value of this option is a perl libdir pathname. Within
334 that directory this module will create a baseline manual
335 L<DBIx::Class::Schema> module set, based on what it creates at runtime
338 The created schema class will have the same classname as the one on
339 which you are setting this option (and the ResultSource classes will be
340 based on this name as well).
342 Normally you wouldn't hard-code this setting in your schema class, as it
343 is meant for one-time manual usage.
345 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
346 recommended way to access this functionality.
348 =head2 dump_overwrite
350 Deprecated. See L</really_erase_my_files> below, which does *not* mean
351 the same thing as the old C<dump_overwrite> setting from previous releases.
353 =head2 really_erase_my_files
355 Default false. If true, Loader will unconditionally delete any existing
356 files before creating the new ones from scratch when dumping a schema to disk.
358 The default behavior is instead to only replace the top portion of the
359 file, up to and including the final stanza which contains
360 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
361 leaving any customizations you placed after that as they were.
363 When C<really_erase_my_files> is not set, if the output file already exists,
364 but the aforementioned final stanza is not found, or the checksum
365 contained there does not match the generated contents, Loader will
366 croak and not touch the file.
368 You should really be using version control on your schema classes (and all
369 of the rest of your code for that matter). Don't blame me if a bug in this
370 code wipes something out when it shouldn't have, you've been warned.
372 =head2 overwrite_modifications
374 Default false. If false, when updating existing files, Loader will
375 refuse to modify any Loader-generated code that has been modified
376 since its last run (as determined by the checksum Loader put in its
379 If true, Loader will discard any manual modifications that have been
380 made to Loader-generated code.
382 Again, you should be using version control on your schema classes. Be
383 careful with this option.
385 =head2 custom_column_info
387 Must be a coderef, returing a hashref with the custom column informations.
391 custom_column_info => sub {
393 # Example from $info hashref:
395 # 'DECIMAL_DIGITS' => undef,
396 # 'COLUMN_DEF' => undef,
397 # 'TABLE_CAT' => undef,
398 # 'NUM_PREC_RADIX' => undef,
399 # 'TABLE_SCHEM' => 'TESTS',
400 # 'BUFFER_LENGTH' => '8',
401 # 'CHAR_OCTET_LENGTH' => undef,
402 # 'IS_NULLABLE' => 'NO',
403 # 'REMARKS' => undef,
404 # 'COLUMN_SIZE' => '8',
405 # 'ORDINAL_POSITION' => '1',
406 # 'COLUMN_NAME' => 'LOADER_TEST9',
407 # 'TYPE_NAME' => 'VARCHAR2',
409 # 'DATA_TYPE' => '12',
410 # 'TABLE_NAME' => 'LOADER_TEST9',
411 # 'SQL_DATA_TYPE' => '12',
412 # 'SQL_DATETIME_SUB' => undef
415 if ( $info->{TYPE_NAME} eq 'DATE' ){
416 return { timezone => "Europe/Berlin" };
421 Add to all columns with type DATE the attribute timezone => "Europe/Berlin".
423 =head2 datetime_timezone
425 Set timezone attribute for L<DBIx::Class::InflateColumn::DateTime>
426 to all columns with the type DATE.
428 =head2 datetime_locale
430 Set local attribute for L<DBIx::Class::InflateColumn::DateTime>
431 to all columns with the type DATE.
435 None of these methods are intended for direct invocation by regular
436 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
437 can also be found via standard L<DBIx::Class::Schema> methods somehow.
441 use constant CURRENT_V => 'v5';
443 use constant CLASS_ARGS => qw(
444 schema_base_class result_base_class additional_base_classes
445 left_base_classes additional_classes components resultset_components
448 # ensure that a peice of object data is a valid arrayref, creating
449 # an empty one or encapsulating whatever's there.
450 sub _ensure_arrayref {
455 $self->{$_} = [ $self->{$_} ]
456 unless ref $self->{$_} eq 'ARRAY';
462 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
463 by L<DBIx::Class::Schema::Loader>.
468 my ( $class, %args ) = @_;
470 my $self = { %args };
472 bless $self => $class;
474 $self->_ensure_arrayref(qw/additional_classes
475 additional_base_classes
481 $self->_validate_class_args;
483 push(@{$self->{components}}, 'ResultSetManager')
484 if @{$self->{resultset_components}};
486 $self->{monikers} = {};
487 $self->{classes} = {};
488 $self->{_upgrading_classes} = {};
490 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
491 $self->{schema} ||= $self->{schema_class};
493 croak "dump_overwrite is deprecated. Please read the"
494 . " DBIx::Class::Schema::Loader::Base documentation"
495 if $self->{dump_overwrite};
497 $self->{dynamic} = ! $self->{dump_directory};
498 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
503 $self->{dump_directory} ||= $self->{temp_directory};
505 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
506 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
508 if ((not ref $self->naming) && defined $self->naming) {
509 my $naming_ver = $self->naming;
511 relationships => $naming_ver,
512 monikers => $naming_ver,
517 for (values %{ $self->naming }) {
518 $_ = CURRENT_V if $_ eq 'current';
521 $self->{naming} ||= {};
523 $self->_check_back_compat;
525 $self->use_namespaces(1) unless defined $self->use_namespaces;
526 $self->generate_pod(1) unless defined $self->generate_pod;
527 $self->pod_comment_mode('auto') unless defined $self->pod_comment_mode;
528 $self->pod_comment_spillover_length(60) unless defined $self->pod_comment_spillover_length;
533 sub _check_back_compat {
536 # dynamic schemas will always be in 0.04006 mode, unless overridden
537 if ($self->dynamic) {
538 # just in case, though no one is likely to dump a dynamic schema
539 $self->schema_version_to_dump('0.04006');
541 if (not %{ $self->naming }) {
542 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
544 Dynamic schema detected, will run in 0.04006 mode.
546 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
547 to disable this warning.
549 Also consider setting 'use_namespaces => 1' if/when upgrading.
551 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
556 $self->_upgrading_from('v4');
559 $self->naming->{relationships} ||= 'v4';
560 $self->naming->{monikers} ||= 'v4';
562 if ($self->use_namespaces) {
563 $self->_upgrading_from_load_classes(1);
566 $self->use_namespaces(0);
572 # otherwise check if we need backcompat mode for a static schema
573 my $filename = $self->_get_dump_filename($self->schema_class);
574 return unless -e $filename;
576 open(my $fh, '<', $filename)
577 or croak "Cannot open '$filename' for reading: $!";
579 my $load_classes = 0;
580 my $result_namespace = '';
583 if (/^__PACKAGE__->load_classes;/) {
585 } elsif (/result_namespace => '([^']+)'/) {
586 $result_namespace = $1;
587 } elsif (my ($real_ver) =
588 /^# Created by DBIx::Class::Schema::Loader v(\d+\.\d+)/) {
590 if ($load_classes && (not defined $self->use_namespaces)) {
591 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
593 'load_classes;' static schema detected, turning off 'use_namespaces'.
595 Set the 'use_namespaces' attribute or the SCHEMA_LOADER_BACKCOMPAT environment
596 variable to disable this warning.
598 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
601 $self->use_namespaces(0);
603 elsif ($load_classes && $self->use_namespaces) {
604 $self->_upgrading_from_load_classes(1);
606 elsif ((not $load_classes) && defined $self->use_namespaces
607 && (not $self->use_namespaces)) {
608 $self->_downgrading_to_load_classes(
609 $result_namespace || 'Result'
612 elsif ((not defined $self->use_namespaces)
613 || $self->use_namespaces) {
614 if (not $self->result_namespace) {
615 $self->result_namespace($result_namespace || 'Result');
617 elsif ($result_namespace ne $self->result_namespace) {
618 $self->_rewriting_result_namespace(
619 $result_namespace || 'Result'
624 # XXX when we go past .0 this will need fixing
625 my ($v) = $real_ver =~ /([1-9])/;
628 last if $v eq CURRENT_V || $real_ver =~ /^0\.\d\d999/;
630 if (not %{ $self->naming }) {
631 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
633 Version $real_ver static schema detected, turning on backcompat mode.
635 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
636 to disable this warning.
638 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
643 $self->_upgrading_from($v);
647 $self->naming->{relationships} ||= $v;
648 $self->naming->{monikers} ||= $v;
650 $self->schema_version_to_dump($real_ver);
658 sub _validate_class_args {
662 foreach my $k (CLASS_ARGS) {
663 next unless $self->$k;
665 my @classes = ref $self->$k eq 'ARRAY' ? @{ $self->$k } : $self->$k;
666 foreach my $c (@classes) {
667 # components default to being under the DBIx::Class namespace unless they
668 # are preceeded with a '+'
669 if ( $k =~ m/components$/ && $c !~ s/^\+// ) {
670 $c = 'DBIx::Class::' . $c;
673 # 1 == installed, 0 == not installed, undef == invalid classname
674 my $installed = Class::Inspector->installed($c);
675 if ( defined($installed) ) {
676 if ( $installed == 0 ) {
677 croak qq/$c, as specified in the loader option "$k", is not installed/;
680 croak qq/$c, as specified in the loader option "$k", is an invalid class name/;
686 sub _find_file_in_inc {
687 my ($self, $file) = @_;
689 foreach my $prefix (@INC) {
690 my $fullpath = File::Spec->catfile($prefix, $file);
691 return $fullpath if -f $fullpath
692 # abs_path throws on Windows for nonexistant files
693 and eval { Cwd::abs_path($fullpath) } ne
694 (eval { Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) } || '');
701 my ($self, $class) = @_;
703 my $class_path = $class;
704 $class_path =~ s{::}{/}g;
705 $class_path .= '.pm';
710 sub _find_class_in_inc {
711 my ($self, $class) = @_;
713 return $self->_find_file_in_inc($self->_class_path($class));
719 return $self->_upgrading_from
720 || $self->_upgrading_from_load_classes
721 || $self->_downgrading_to_load_classes
722 || $self->_rewriting_result_namespace
726 sub _rewrite_old_classnames {
727 my ($self, $code) = @_;
729 return $code unless $self->_rewriting;
731 my %old_classes = reverse %{ $self->_upgrading_classes };
733 my $re = join '|', keys %old_classes;
736 $code =~ s/$re/$old_classes{$1} || $1/eg;
742 my ($self, $class) = @_;
744 return if $self->{skip_load_external};
746 # so that we don't load our own classes, under any circumstances
747 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
749 my $real_inc_path = $self->_find_class_in_inc($class);
751 my $old_class = $self->_upgrading_classes->{$class}
752 if $self->_rewriting;
754 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
755 if $old_class && $old_class ne $class;
757 return unless $real_inc_path || $old_real_inc_path;
759 if ($real_inc_path) {
760 # If we make it to here, we loaded an external definition
761 warn qq/# Loaded external class definition for '$class'\n/
764 open(my $fh, '<', $real_inc_path)
765 or croak "Failed to open '$real_inc_path' for reading: $!";
766 my $code = do { local $/; <$fh> };
768 or croak "Failed to close $real_inc_path: $!";
769 $code = $self->_rewrite_old_classnames($code);
771 if ($self->dynamic) { # load the class too
772 # kill redefined warnings
773 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
774 local $SIG{__WARN__} = sub {
776 unless $_[0] =~ /^Subroutine \S+ redefined/;
782 $self->_ext_stmt($class,
783 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
784 .qq|# They are now part of the custom portion of this file\n|
785 .qq|# for you to hand-edit. If you do not either delete\n|
786 .qq|# this section or remove that file from \@INC, this section\n|
787 .qq|# will be repeated redundantly when you re-create this\n|
788 .qq|# file again via Loader! See skip_load_external to disable\n|
789 .qq|# this feature.\n|
792 $self->_ext_stmt($class, $code);
793 $self->_ext_stmt($class,
794 qq|# End of lines loaded from '$real_inc_path' |
798 if ($old_real_inc_path) {
799 open(my $fh, '<', $old_real_inc_path)
800 or croak "Failed to open '$old_real_inc_path' for reading: $!";
801 $self->_ext_stmt($class, <<"EOF");
803 # These lines were loaded from '$old_real_inc_path',
804 # based on the Result class name that would have been created by an 0.04006
805 # version of the Loader. For a static schema, this happens only once during
806 # upgrade. See skip_load_external to disable this feature.
810 local ($/, @ARGV) = (undef, $old_real_inc_path); <>
812 $code = $self->_rewrite_old_classnames($code);
814 if ($self->dynamic) {
817 Detected external content in '$old_real_inc_path', a class name that would have
818 been used by an 0.04006 version of the Loader.
820 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
821 new name of the Result.
823 # kill redefined warnings
824 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
825 local $SIG{__WARN__} = sub {
827 unless $_[0] =~ /^Subroutine \S+ redefined/;
834 $self->_ext_stmt($class, $code);
835 $self->_ext_stmt($class,
836 qq|# End of lines loaded from '$old_real_inc_path' |
843 Does the actual schema-construction work.
850 $self->_load_tables($self->_tables_list);
857 Rescan the database for newly added tables. Does
858 not process drops or changes. Returns a list of
859 the newly added table monikers.
861 The schema argument should be the schema class
862 or object to be affected. It should probably
863 be derived from the original schema_class used
869 my ($self, $schema) = @_;
871 $self->{schema} = $schema;
872 $self->_relbuilder->{schema} = $schema;
875 my @current = $self->_tables_list;
876 foreach my $table ($self->_tables_list) {
877 if(!exists $self->{_tables}->{$table}) {
878 push(@created, $table);
882 my $loaded = $self->_load_tables(@created);
884 return map { $self->monikers->{$_} } @$loaded;
888 no warnings 'uninitialized';
891 return if $self->{skip_relationships};
893 if ($self->naming->{relationships} eq 'v4') {
894 require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040;
895 return $self->{relbuilder} ||=
896 DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040->new(
897 $self->schema, $self->inflect_plural, $self->inflect_singular
901 $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder->new (
903 $self->inflect_plural,
904 $self->inflect_singular,
905 $self->relationship_attrs,
910 my ($self, @tables) = @_;
912 # First, use _tables_list with constraint and exclude
913 # to get a list of tables to operate on
915 my $constraint = $self->constraint;
916 my $exclude = $self->exclude;
918 @tables = grep { /$constraint/ } @tables if $constraint;
919 @tables = grep { ! /$exclude/ } @tables if $exclude;
921 # Save the new tables to the tables list
923 $self->{_tables}->{$_} = 1;
926 $self->_make_src_class($_) for @tables;
927 $self->_setup_src_meta($_) for @tables;
929 if(!$self->skip_relationships) {
930 # The relationship loader needs a working schema
932 local $self->{dump_directory} = $self->{temp_directory};
933 $self->_reload_classes(\@tables);
934 $self->_load_relationships($_) for @tables;
937 # Remove that temp dir from INC so it doesn't get reloaded
938 @INC = grep $_ ne $self->dump_directory, @INC;
941 $self->_load_external($_)
942 for map { $self->classes->{$_} } @tables;
944 # Reload without unloading first to preserve any symbols from external
946 $self->_reload_classes(\@tables, 0);
948 # Drop temporary cache
949 delete $self->{_cache};
954 sub _reload_classes {
955 my ($self, $tables, $unload) = @_;
957 my @tables = @$tables;
958 $unload = 1 unless defined $unload;
960 # so that we don't repeat custom sections
961 @INC = grep $_ ne $self->dump_directory, @INC;
963 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
965 unshift @INC, $self->dump_directory;
968 my %have_source = map { $_ => $self->schema->source($_) }
969 $self->schema->sources;
971 for my $table (@tables) {
972 my $moniker = $self->monikers->{$table};
973 my $class = $self->classes->{$table};
976 no warnings 'redefine';
977 local *Class::C3::reinitialize = sub {};
980 Class::Unload->unload($class) if $unload;
981 my ($source, $resultset_class);
983 ($source = $have_source{$moniker})
984 && ($resultset_class = $source->resultset_class)
985 && ($resultset_class ne 'DBIx::Class::ResultSet')
987 my $has_file = Class::Inspector->loaded_filename($resultset_class);
988 Class::Unload->unload($resultset_class) if $unload;
989 $self->_reload_class($resultset_class) if $has_file;
991 $self->_reload_class($class);
993 push @to_register, [$moniker, $class];
996 Class::C3->reinitialize;
998 $self->schema->register_class(@$_);
1002 # We use this instead of ensure_class_loaded when there are package symbols we
1005 my ($self, $class) = @_;
1007 my $class_path = $self->_class_path($class);
1008 delete $INC{ $class_path };
1010 # kill redefined warnings
1011 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
1012 local $SIG{__WARN__} = sub {
1014 unless $_[0] =~ /^Subroutine \S+ redefined/;
1016 eval "require $class;";
1019 sub _get_dump_filename {
1020 my ($self, $class) = (@_);
1022 $class =~ s{::}{/}g;
1023 return $self->dump_directory . q{/} . $class . q{.pm};
1026 sub _ensure_dump_subdirs {
1027 my ($self, $class) = (@_);
1029 my @name_parts = split(/::/, $class);
1030 pop @name_parts; # we don't care about the very last element,
1031 # which is a filename
1033 my $dir = $self->dump_directory;
1036 mkdir($dir) or croak "mkdir('$dir') failed: $!";
1038 last if !@name_parts;
1039 $dir = File::Spec->catdir($dir, shift @name_parts);
1044 my ($self, @classes) = @_;
1046 my $schema_class = $self->schema_class;
1047 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
1049 my $target_dir = $self->dump_directory;
1050 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
1051 unless $self->{dynamic} or $self->{quiet};
1054 qq|package $schema_class;\n\n|
1055 . qq|# Created by DBIx::Class::Schema::Loader\n|
1056 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1057 . qq|use strict;\nuse warnings;\n\n|
1058 . qq|use base '$schema_base_class';\n\n|;
1060 if ($self->use_namespaces) {
1061 $schema_text .= qq|__PACKAGE__->load_namespaces|;
1062 my $namespace_options;
1063 for my $attr (qw(result_namespace
1065 default_resultset_class)) {
1067 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
1070 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
1071 $schema_text .= qq|;\n|;
1074 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
1078 local $self->{version_to_dump} = $self->schema_version_to_dump;
1079 $self->_write_classfile($schema_class, $schema_text, 1);
1082 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
1084 foreach my $src_class (@classes) {
1086 qq|package $src_class;\n\n|
1087 . qq|# Created by DBIx::Class::Schema::Loader\n|
1088 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1089 . qq|use strict;\nuse warnings;\n\n|
1090 . qq|use base '$result_base_class';\n\n|;
1092 $self->_write_classfile($src_class, $src_text);
1095 # remove Result dir if downgrading from use_namespaces, and there are no
1097 if (my $result_ns = $self->_downgrading_to_load_classes
1098 || $self->_rewriting_result_namespace) {
1099 my $result_namespace = $self->_result_namespace(
1104 (my $result_dir = $result_namespace) =~ s{::}{/}g;
1105 $result_dir = $self->dump_directory . '/' . $result_dir;
1107 unless (my @files = glob "$result_dir/*") {
1112 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
1117 my ($self, $version, $ts) = @_;
1118 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
1121 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
1124 sub _write_classfile {
1125 my ($self, $class, $text, $is_schema) = @_;
1127 my $filename = $self->_get_dump_filename($class);
1128 $self->_ensure_dump_subdirs($class);
1130 if (-f $filename && $self->really_erase_my_files) {
1131 warn "Deleting existing file '$filename' due to "
1132 . "'really_erase_my_files' setting\n" unless $self->{quiet};
1136 my ($custom_content, $old_md5, $old_ver, $old_ts) = $self->_get_custom_content($class, $filename);
1138 if (my $old_class = $self->_upgrading_classes->{$class}) {
1139 my $old_filename = $self->_get_dump_filename($old_class);
1141 my ($old_custom_content) = $self->_get_custom_content(
1142 $old_class, $old_filename, 0 # do not add default comment
1145 $old_custom_content =~ s/\n\n# You can replace.*\n1;\n//;
1147 if ($old_custom_content) {
1149 "\n" . $old_custom_content . "\n" . $custom_content;
1152 unlink $old_filename;
1155 $custom_content = $self->_rewrite_old_classnames($custom_content);
1158 for @{$self->{_dump_storage}->{$class} || []};
1160 # Check and see if the dump is infact differnt
1164 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
1167 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
1168 return unless $self->_upgrading_from && $is_schema;
1172 $text .= $self->_sig_comment(
1173 $self->version_to_dump,
1174 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
1177 open(my $fh, '>', $filename)
1178 or croak "Cannot open '$filename' for writing: $!";
1180 # Write the top half and its MD5 sum
1181 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
1183 # Write out anything loaded via external partial class file in @INC
1185 for @{$self->{_ext_storage}->{$class} || []};
1187 # Write out any custom content the user has added
1188 print $fh $custom_content;
1191 or croak "Error closing '$filename': $!";
1194 sub _default_custom_content {
1195 return qq|\n\n# You can replace this text with custom|
1196 . qq| content, and it will be preserved on regeneration|
1200 sub _get_custom_content {
1201 my ($self, $class, $filename, $add_default) = @_;
1203 $add_default = 1 unless defined $add_default;
1205 return ($self->_default_custom_content) if ! -f $filename;
1207 open(my $fh, '<', $filename)
1208 or croak "Cannot open '$filename' for reading: $!";
1211 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
1214 my ($md5, $ts, $ver);
1216 if(!$md5 && /$mark_re/) {
1220 # Pull out the previous version and timestamp
1221 ($ver, $ts) = $buffer =~ m/# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)$/s;
1224 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"
1225 if !$self->overwrite_modifications && Digest::MD5::md5_base64($buffer) ne $md5;
1234 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
1235 . " it does not appear to have been generated by Loader"
1238 # Default custom content:
1239 $buffer ||= $self->_default_custom_content if $add_default;
1241 return ($buffer, $md5, $ver, $ts);
1249 warn "$target: use $_;" if $self->debug;
1250 $self->_raw_stmt($target, "use $_;");
1257 my $schema_class = $self->schema_class;
1259 my $blist = join(q{ }, @_);
1260 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
1261 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
1264 sub _result_namespace {
1265 my ($self, $schema_class, $ns) = @_;
1266 my @result_namespace;
1268 if ($ns =~ /^\+(.*)/) {
1269 # Fully qualified namespace
1270 @result_namespace = ($1)
1273 # Relative namespace
1274 @result_namespace = ($schema_class, $ns);
1277 return wantarray ? @result_namespace : join '::', @result_namespace;
1280 # Create class with applicable bases, setup monikers, etc
1281 sub _make_src_class {
1282 my ($self, $table) = @_;
1284 my $schema = $self->schema;
1285 my $schema_class = $self->schema_class;
1287 my $table_moniker = $self->_table2moniker($table);
1288 my @result_namespace = ($schema_class);
1289 if ($self->use_namespaces) {
1290 my $result_namespace = $self->result_namespace || 'Result';
1291 @result_namespace = $self->_result_namespace(
1296 my $table_class = join(q{::}, @result_namespace, $table_moniker);
1298 if ((my $upgrading_v = $self->_upgrading_from)
1299 || $self->_rewriting) {
1300 local $self->naming->{monikers} = $upgrading_v
1303 my @result_namespace = @result_namespace;
1304 if ($self->_upgrading_from_load_classes) {
1305 @result_namespace = ($schema_class);
1307 elsif (my $ns = $self->_downgrading_to_load_classes) {
1308 @result_namespace = $self->_result_namespace(
1313 elsif ($ns = $self->_rewriting_result_namespace) {
1314 @result_namespace = $self->_result_namespace(
1320 my $old_class = join(q{::}, @result_namespace,
1321 $self->_table2moniker($table));
1323 $self->_upgrading_classes->{$table_class} = $old_class
1324 unless $table_class eq $old_class;
1327 my $table_normalized = lc $table;
1328 $self->classes->{$table} = $table_class;
1329 $self->classes->{$table_normalized} = $table_class;
1330 $self->monikers->{$table} = $table_moniker;
1331 $self->monikers->{$table_normalized} = $table_moniker;
1333 $self->_use ($table_class, @{$self->additional_classes});
1334 $self->_inject($table_class, @{$self->left_base_classes});
1336 if (my @components = @{ $self->components }) {
1337 $self->_dbic_stmt($table_class, 'load_components', @components);
1340 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
1341 if @{$self->resultset_components};
1342 $self->_inject($table_class, @{$self->additional_base_classes});
1345 # Set up metadata (cols, pks, etc)
1346 sub _setup_src_meta {
1347 my ($self, $table) = @_;
1349 my $schema = $self->schema;
1350 my $schema_class = $self->schema_class;
1352 my $table_class = $self->classes->{$table};
1353 my $table_moniker = $self->monikers->{$table};
1355 my $table_name = $table;
1356 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1358 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1359 $table_name = \ $self->_quote_table_name($table_name);
1362 $self->_dbic_stmt($table_class,'table',$table_name);
1364 my $cols = $self->_table_columns($table);
1366 eval { $col_info = $self->_columns_info_for($table) };
1368 $self->_dbic_stmt($table_class,'add_columns',@$cols);
1371 if ($self->_is_case_sensitive) {
1372 for my $col (keys %$col_info) {
1373 $col_info->{$col}{accessor} = lc $col
1374 if $col ne lc($col);
1377 $col_info = { map { lc($_), $col_info->{$_} } keys %$col_info };
1380 my $fks = $self->_table_fk_info($table);
1382 for my $fkdef (@$fks) {
1383 for my $col (@{ $fkdef->{local_columns} }) {
1384 $col_info->{$col}{is_foreign_key} = 1;
1390 map { $_, ($col_info->{$_}||{}) } @$cols
1394 my %uniq_tag; # used to eliminate duplicate uniqs
1396 my $pks = $self->_table_pk_info($table) || [];
1397 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1398 : carp("$table has no primary key");
1399 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1401 my $uniqs = $self->_table_uniq_info($table) || [];
1403 my ($name, $cols) = @$_;
1404 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1405 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1412 Returns a sorted list of loaded tables, using the original database table
1420 return keys %{$self->_tables};
1423 # Make a moniker from a table
1424 sub _default_table2moniker {
1425 no warnings 'uninitialized';
1426 my ($self, $table) = @_;
1428 if ($self->naming->{monikers} eq 'v4') {
1429 return join '', map ucfirst, split /[\W_]+/, lc $table;
1432 return join '', map ucfirst, split /[\W_]+/,
1433 Lingua::EN::Inflect::Number::to_S(lc $table);
1436 sub _table2moniker {
1437 my ( $self, $table ) = @_;
1441 if( ref $self->moniker_map eq 'HASH' ) {
1442 $moniker = $self->moniker_map->{$table};
1444 elsif( ref $self->moniker_map eq 'CODE' ) {
1445 $moniker = $self->moniker_map->($table);
1448 $moniker ||= $self->_default_table2moniker($table);
1453 sub _load_relationships {
1454 my ($self, $table) = @_;
1456 my $tbl_fk_info = $self->_table_fk_info($table);
1457 foreach my $fkdef (@$tbl_fk_info) {
1458 $fkdef->{remote_source} =
1459 $self->monikers->{delete $fkdef->{remote_table}};
1461 my $tbl_uniq_info = $self->_table_uniq_info($table);
1463 my $local_moniker = $self->monikers->{$table};
1464 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1466 foreach my $src_class (sort keys %$rel_stmts) {
1467 my $src_stmts = $rel_stmts->{$src_class};
1468 foreach my $stmt (@$src_stmts) {
1469 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1474 # Overload these in driver class:
1476 # Returns an arrayref of column names
1477 sub _table_columns { croak "ABSTRACT METHOD" }
1479 # Returns arrayref of pk col names
1480 sub _table_pk_info { croak "ABSTRACT METHOD" }
1482 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1483 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1485 # Returns an arrayref of foreign key constraints, each
1486 # being a hashref with 3 keys:
1487 # local_columns (arrayref), remote_columns (arrayref), remote_table
1488 sub _table_fk_info { croak "ABSTRACT METHOD" }
1490 # Returns an array of lower case table names
1491 sub _tables_list { croak "ABSTRACT METHOD" }
1493 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1499 # generate the pod for this statement, storing it with $self->_pod
1500 $self->_make_pod( $class, $method, @_ ) if $self->generate_pod;
1502 my $args = dump(@_);
1503 $args = '(' . $args . ')' if @_ < 2;
1504 my $stmt = $method . $args . q{;};
1506 warn qq|$class\->$stmt\n| if $self->debug;
1507 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1511 # generates the accompanying pod for a DBIC class method statement,
1512 # storing it with $self->_pod
1518 if ( $method eq 'table' ) {
1520 my $pcm = $self->pod_comment_mode;
1521 my ($comment, $comment_overflows, $comment_in_name, $comment_in_desc);
1522 if ( $self->can('_table_comment') ) {
1523 $comment = $self->_table_comment($table);
1524 $comment_overflows = ($comment and length $comment > $self->pod_comment_spillover_length);
1525 $comment_in_name = ($pcm eq 'name' or ($pcm eq 'auto' and !$comment_overflows));
1526 $comment_in_desc = ($pcm eq 'description' or ($pcm eq 'auto' and $comment_overflows));
1528 $self->_pod( $class, "=head1 NAME" );
1529 my $table_descr = $class;
1530 $table_descr .= " - " . $comment if $comment and $comment_in_name;
1531 $self->{_class2table}{ $class } = $table;
1532 $self->_pod( $class, $table_descr );
1533 if ($comment and $comment_in_desc) {
1534 $self->_pod( $class, "=head1 DESCRIPTION" );
1535 $self->_pod( $class, $comment );
1537 $self->_pod_cut( $class );
1538 } elsif ( $method eq 'add_columns' ) {
1539 $self->_pod( $class, "=head1 ACCESSORS" );
1540 my $col_counter = 0;
1542 while( my ($name,$attrs) = splice @cols,0,2 ) {
1544 $self->_pod( $class, '=head2 ' . $name );
1545 $self->_pod( $class,
1547 my $s = $attrs->{$_};
1548 $s = !defined $s ? 'undef' :
1549 length($s) == 0 ? '(empty string)' :
1553 } sort keys %$attrs,
1556 if( $self->can('_column_comment')
1557 and my $comment = $self->_column_comment( $self->{_class2table}{$class}, $col_counter)
1559 $self->_pod( $class, $comment );
1562 $self->_pod_cut( $class );
1563 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
1564 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
1565 my ( $accessor, $rel_class ) = @_;
1566 $self->_pod( $class, "=head2 $accessor" );
1567 $self->_pod( $class, 'Type: ' . $method );
1568 $self->_pod( $class, "Related object: L<$rel_class>" );
1569 $self->_pod_cut( $class );
1570 $self->{_relations_started} { $class } = 1;
1574 # Stores a POD documentation
1576 my ($self, $class, $stmt) = @_;
1577 $self->_raw_stmt( $class, "\n" . $stmt );
1581 my ($self, $class ) = @_;
1582 $self->_raw_stmt( $class, "\n=cut\n" );
1585 # Store a raw source line for a class (for dumping purposes)
1587 my ($self, $class, $stmt) = @_;
1588 push(@{$self->{_dump_storage}->{$class}}, $stmt);
1591 # Like above, but separately for the externally loaded stuff
1593 my ($self, $class, $stmt) = @_;
1594 push(@{$self->{_ext_storage}->{$class}}, $stmt);
1597 sub _quote_table_name {
1598 my ($self, $table) = @_;
1600 my $qt = $self->schema->storage->sql_maker->quote_char;
1602 return $table unless $qt;
1605 return $qt->[0] . $table . $qt->[1];
1608 return $qt . $table . $qt;
1611 sub _is_case_sensitive { 0 }
1613 sub _custom_column_info {
1614 my ( $self, $info ) = @_;
1616 if( ref $self->custom_column_info eq 'CODE' ) {
1617 return $self->custom_column_info->($info);
1622 sub _datetime_column_info {
1623 my ( $self, $info, $column_info) = @_;
1624 # warn "_datetime_column_info XXXXXXXXX";
1626 # warn Dumper $info;
1627 # warn Dumper $column_info;
1629 my $type = lc ( $info->{TYPE_NAME} );
1632 ( defined $column_info->{inflate_datetime} and $column_info->{inflate_datetime} )
1633 or ( defined $column_info->{inflate_date} and $column_info->{inflate_date} )
1634 or ( $type eq 'date')
1635 or ( $type eq 'datetime')
1636 or ( $type eq 'timestamp')
1638 $return->{timezone} = $self->datetime_timezone if $self->datetime_timezone;
1639 $return->{locale} = $self->datetime_locale if $self->datetime_locale;
1644 # remove the dump dir from @INC on destruction
1648 @INC = grep $_ ne $self->dump_directory, @INC;
1653 Returns a hashref of loaded table to moniker mappings. There will
1654 be two entries for each table, the original name and the "normalized"
1655 name, in the case that the two are different (such as databases
1656 that like uppercase table names, or preserve your original mixed-case
1657 definitions, or what-have-you).
1661 Returns a hashref of table to class mappings. In some cases it will
1662 contain multiple entries per table for the original and normalized table
1663 names, as above in L</monikers>.
1667 L<DBIx::Class::Schema::Loader>
1671 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
1675 This library is free software; you can redistribute it and/or modify it under
1676 the same terms as Perl itself.