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//;
18 use Class::Inspector ();
19 use Data::Dumper::Concise;
20 use Scalar::Util 'looks_like_number';
21 use File::Slurp 'slurp';
24 our $VERSION = '0.05003';
26 __PACKAGE__->mk_group_ro_accessors('simple', qw/
33 additional_base_classes
48 default_resultset_class
51 overwrite_modifications
67 __PACKAGE__->mk_group_accessors('simple', qw/
69 schema_version_to_dump
71 _upgrading_from_load_classes
72 _downgrading_to_load_classes
73 _rewriting_result_namespace
78 pod_comment_spillover_length
83 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
87 See L<DBIx::Class::Schema::Loader>
91 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
92 classes, and implements the common functionality between them.
94 =head1 CONSTRUCTOR OPTIONS
96 These constructor options are the base options for
97 L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
99 =head2 skip_relationships
101 Skip setting up relationships. The default is to attempt the loading
104 =head2 skip_load_external
106 Skip loading of other classes in @INC. The default is to merge all other classes
107 with the same name found in @INC into the schema file we are creating.
111 Static schemas (ones dumped to disk) will, by default, use the new-style 0.05XXX
112 relationship names and singularized Results, unless you're overwriting an
113 existing dump made by a 0.04XXX version of L<DBIx::Class::Schema::Loader>, in
114 which case the backward compatible RelBuilder will be activated, and
115 singularization will be turned off.
121 will disable the backward-compatible RelBuilder and use
122 the new-style relationship names along with singularized Results, even when
123 overwriting a dump made with an earlier version.
125 The option also takes a hashref:
127 naming => { relationships => 'v5', monikers => 'v4' }
135 How to name relationship accessors.
139 How to name Result classes.
149 Latest default style, whatever that happens to be.
153 Version 0.05XXX style.
157 Version 0.04XXX style.
161 Dynamic schemas will always default to the 0.04XXX relationship names and won't
162 singularize Results for backward compatibility, to activate the new RelBuilder
163 and singularization put this in your C<Schema.pm> file:
165 __PACKAGE__->naming('current');
167 Or if you prefer to use 0.05XXX features but insure that nothing breaks in the
168 next major version upgrade:
170 __PACKAGE__->naming('v5');
174 By default POD will be generated for columns and relationships, using database
175 metadata for the text if available and supported.
177 Reading database metadata (e.g. C<COMMENT ON TABLE some_table ...>) is only
178 supported for Postgres right now.
180 Set this to C<0> to turn off all POD generation.
182 =head2 pod_comment_mode
184 Controls where table comments appear in the generated POD. Smaller table
185 comments are appended to the C<NAME> section of the documentation, and larger
186 ones are inserted into C<DESCRIPTION> instead. You can force a C<DESCRIPTION>
187 section to be generated with the comment always, only use C<NAME>, or choose
188 the length threshold at which the comment is forced into the description.
194 Use C<NAME> section only.
198 Force C<DESCRIPTION> always.
202 Use C<DESCRIPTION> if length > L</pod_comment_spillover_length>, this is the
207 =head2 pod_comment_spillover_length
209 When pod_comment_mode is set to C<auto>, this is the length of the comment at
210 which it will be forced into a separate description section.
214 =head2 relationship_attrs
216 Hashref of attributes to pass to each generated relationship, listed
217 by type. Also supports relationship type 'all', containing options to
218 pass to all generated relationships. Attributes set for more specific
219 relationship types override those set in 'all'.
223 relationship_attrs => {
224 all => { cascade_delete => 0 },
225 has_many => { cascade_delete => 1 },
228 will set the C<cascade_delete> option to 0 for all generated relationships,
229 except for C<has_many>, which will have cascade_delete as 1.
231 NOTE: this option is not supported if v4 backward-compatible naming is
232 set either globally (naming => 'v4') or just for relationships.
236 If set to true, each constructive L<DBIx::Class> statement the loader
237 decides to execute will be C<warn>-ed before execution.
241 Set the name of the schema to load (schema in the sense that your database
242 vendor means it). Does not currently support loading more than one schema
247 Only load tables matching regex. Best specified as a qr// regex.
251 Exclude tables matching regex. Best specified as a qr// regex.
255 Overrides the default table name to moniker translation. Can be either
256 a hashref of table keys and moniker values, or a coderef for a translator
257 function taking a single scalar table name argument and returning
258 a scalar moniker. If the hash entry does not exist, or the function
259 returns a false value, the code falls back to default behavior
262 The default behavior is to singularize the table name, and: C<join '', map
263 ucfirst, split /[\W_]+/, lc $table>, which is to say: lowercase everything,
264 split up the table name into chunks anywhere a non-alpha-numeric character
265 occurs, change the case of first letter of each chunk to upper case, and put
266 the chunks back together. Examples:
268 Table Name | Moniker Name
269 ---------------------------
271 luser_group | LuserGroup
272 luser-opts | LuserOpt
274 =head2 inflect_plural
276 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
277 if hash key does not exist or coderef returns false), but acts as a map
278 for pluralizing relationship names. The default behavior is to utilize
279 L<Lingua::EN::Inflect::Number/to_PL>.
281 =head2 inflect_singular
283 As L</inflect_plural> above, but for singularizing relationship names.
284 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
286 =head2 schema_base_class
288 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
290 =head2 result_base_class
292 Base class for your table classes (aka result classes). Defaults to
295 =head2 additional_base_classes
297 List of additional base classes all of your table classes will use.
299 =head2 left_base_classes
301 List of additional base classes all of your table classes will use
302 that need to be leftmost.
304 =head2 additional_classes
306 List of additional classes which all of your table classes will use.
310 List of additional components to be loaded into all of your table
311 classes. A good example would be C<ResultSetManager>.
313 =head2 resultset_components
315 List of additional ResultSet components to be loaded into your table
316 classes. A good example would be C<AlwaysRS>. Component
317 C<ResultSetManager> will be automatically added to the above
318 C<components> list if this option is set.
320 =head2 use_namespaces
322 This is now the default, to go back to L<DBIx::Class::Schema/load_classes> pass
325 Generate result class names suitable for
326 L<DBIx::Class::Schema/load_namespaces> and call that instead of
327 L<DBIx::Class::Schema/load_classes>. When using this option you can also
328 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
329 C<resultset_namespace>, C<default_resultset_class>), and they will be added
330 to the call (and the generated result class names adjusted appropriately).
332 =head2 dump_directory
334 This option is designed to be a tool to help you transition from this
335 loader to a manually-defined schema when you decide it's time to do so.
337 The value of this option is a perl libdir pathname. Within
338 that directory this module will create a baseline manual
339 L<DBIx::Class::Schema> module set, based on what it creates at runtime
342 The created schema class will have the same classname as the one on
343 which you are setting this option (and the ResultSource classes will be
344 based on this name as well).
346 Normally you wouldn't hard-code this setting in your schema class, as it
347 is meant for one-time manual usage.
349 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
350 recommended way to access this functionality.
352 =head2 dump_overwrite
354 Deprecated. See L</really_erase_my_files> below, which does *not* mean
355 the same thing as the old C<dump_overwrite> setting from previous releases.
357 =head2 really_erase_my_files
359 Default false. If true, Loader will unconditionally delete any existing
360 files before creating the new ones from scratch when dumping a schema to disk.
362 The default behavior is instead to only replace the top portion of the
363 file, up to and including the final stanza which contains
364 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
365 leaving any customizations you placed after that as they were.
367 When C<really_erase_my_files> is not set, if the output file already exists,
368 but the aforementioned final stanza is not found, or the checksum
369 contained there does not match the generated contents, Loader will
370 croak and not touch the file.
372 You should really be using version control on your schema classes (and all
373 of the rest of your code for that matter). Don't blame me if a bug in this
374 code wipes something out when it shouldn't have, you've been warned.
376 =head2 overwrite_modifications
378 Default false. If false, when updating existing files, Loader will
379 refuse to modify any Loader-generated code that has been modified
380 since its last run (as determined by the checksum Loader put in its
383 If true, Loader will discard any manual modifications that have been
384 made to Loader-generated code.
386 Again, you should be using version control on your schema classes. Be
387 careful with this option.
389 =head2 custom_column_info
391 Hook for adding extra attributes to the
392 L<column_info|DBIx::Class::ResultSource/column_info> for a column.
394 Must be a coderef that returns a hashref with the extra attributes.
396 Receives the table name, column name and column_info.
400 custom_column_info => sub {
401 my ($table_name, $column_name, $column_info) = @_;
403 if ($column_name eq 'dog' && $column_info->{default_value} eq 'snoopy') {
404 return { is_snoopy => 1 };
408 This attribute can also be used to set C<inflate_datetime> on a non-datetime
409 column so it also receives the L</datetime_timezone> and/or L</datetime_locale>.
411 =head2 datetime_timezone
413 Sets the timezone attribute for L<DBIx::Class::InflateColumn::DateTime> for all
414 columns with the DATE/DATETIME/TIMESTAMP data_types.
416 =head2 datetime_locale
418 Sets the locale attribute for L<DBIx::Class::InflateColumn::DateTime> for all
419 columns with the DATE/DATETIME/TIMESTAMP data_types.
423 None of these methods are intended for direct invocation by regular
424 users of L<DBIx::Class::Schema::Loader>. Some are proxied via
425 L<DBIx::Class::Schema::Loader>.
429 my $CURRENT_V = 'v5';
432 schema_base_class result_base_class additional_base_classes
433 left_base_classes additional_classes components resultset_components
436 # ensure that a peice of object data is a valid arrayref, creating
437 # an empty one or encapsulating whatever's there.
438 sub _ensure_arrayref {
443 $self->{$_} = [ $self->{$_} ]
444 unless ref $self->{$_} eq 'ARRAY';
450 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
451 by L<DBIx::Class::Schema::Loader>.
456 my ( $class, %args ) = @_;
458 my $self = { %args };
460 bless $self => $class;
462 $self->_ensure_arrayref(qw/additional_classes
463 additional_base_classes
469 $self->_validate_class_args;
471 push(@{$self->{components}}, 'ResultSetManager')
472 if @{$self->{resultset_components}};
474 $self->{monikers} = {};
475 $self->{classes} = {};
476 $self->{_upgrading_classes} = {};
478 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
479 $self->{schema} ||= $self->{schema_class};
481 croak "dump_overwrite is deprecated. Please read the"
482 . " DBIx::Class::Schema::Loader::Base documentation"
483 if $self->{dump_overwrite};
485 $self->{dynamic} = ! $self->{dump_directory};
486 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
491 $self->{dump_directory} ||= $self->{temp_directory};
493 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
494 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
496 if ((not ref $self->naming) && defined $self->naming) {
497 my $naming_ver = $self->naming;
499 relationships => $naming_ver,
500 monikers => $naming_ver,
505 for (values %{ $self->naming }) {
506 $_ = $CURRENT_V if $_ eq 'current';
509 $self->{naming} ||= {};
511 if ($self->custom_column_info && ref $self->custom_column_info ne 'CODE') {
512 croak 'custom_column_info must be a CODE ref';
515 $self->_check_back_compat;
517 $self->use_namespaces(1) unless defined $self->use_namespaces;
518 $self->generate_pod(1) unless defined $self->generate_pod;
519 $self->pod_comment_mode('auto') unless defined $self->pod_comment_mode;
520 $self->pod_comment_spillover_length(60) unless defined $self->pod_comment_spillover_length;
525 sub _check_back_compat {
528 # dynamic schemas will always be in 0.04006 mode, unless overridden
529 if ($self->dynamic) {
530 # just in case, though no one is likely to dump a dynamic schema
531 $self->schema_version_to_dump('0.04006');
533 if (not %{ $self->naming }) {
534 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
536 Dynamic schema detected, will run in 0.04006 mode.
538 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
539 to disable this warning.
541 Also consider setting 'use_namespaces => 1' if/when upgrading.
543 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
548 $self->_upgrading_from('v4');
551 $self->naming->{relationships} ||= 'v4';
552 $self->naming->{monikers} ||= 'v4';
554 if ($self->use_namespaces) {
555 $self->_upgrading_from_load_classes(1);
558 $self->use_namespaces(0);
564 # otherwise check if we need backcompat mode for a static schema
565 my $filename = $self->_get_dump_filename($self->schema_class);
566 return unless -e $filename;
568 open(my $fh, '<', $filename)
569 or croak "Cannot open '$filename' for reading: $!";
571 my $load_classes = 0;
572 my $result_namespace = '';
575 if (/^__PACKAGE__->load_classes;/) {
577 } elsif (/result_namespace => '([^']+)'/) {
578 $result_namespace = $1;
579 } elsif (my ($real_ver) =
580 /^# Created by DBIx::Class::Schema::Loader v(\d+\.\d+)/) {
582 if ($load_classes && (not defined $self->use_namespaces)) {
583 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
585 'load_classes;' static schema detected, turning off 'use_namespaces'.
587 Set the 'use_namespaces' attribute or the SCHEMA_LOADER_BACKCOMPAT environment
588 variable to disable this warning.
590 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
593 $self->use_namespaces(0);
595 elsif ($load_classes && $self->use_namespaces) {
596 $self->_upgrading_from_load_classes(1);
598 elsif ((not $load_classes) && defined $self->use_namespaces
599 && (not $self->use_namespaces)) {
600 $self->_downgrading_to_load_classes(
601 $result_namespace || 'Result'
604 elsif ((not defined $self->use_namespaces)
605 || $self->use_namespaces) {
606 if (not $self->result_namespace) {
607 $self->result_namespace($result_namespace || 'Result');
609 elsif ($result_namespace ne $self->result_namespace) {
610 $self->_rewriting_result_namespace(
611 $result_namespace || 'Result'
616 # XXX when we go past .0 this will need fixing
617 my ($v) = $real_ver =~ /([1-9])/;
620 last if $v eq $CURRENT_V || $real_ver =~ /^0\.\d\d999/;
622 if (not %{ $self->naming }) {
623 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
625 Version $real_ver static schema detected, turning on backcompat mode.
627 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
628 to disable this warning.
630 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
635 $self->_upgrading_from($v);
639 $self->naming->{relationships} ||= $v;
640 $self->naming->{monikers} ||= $v;
642 $self->schema_version_to_dump($real_ver);
650 sub _validate_class_args {
654 foreach my $k (@CLASS_ARGS) {
655 next unless $self->$k;
657 my @classes = ref $self->$k eq 'ARRAY' ? @{ $self->$k } : $self->$k;
658 foreach my $c (@classes) {
659 # components default to being under the DBIx::Class namespace unless they
660 # are preceeded with a '+'
661 if ( $k =~ m/components$/ && $c !~ s/^\+// ) {
662 $c = 'DBIx::Class::' . $c;
665 # 1 == installed, 0 == not installed, undef == invalid classname
666 my $installed = Class::Inspector->installed($c);
667 if ( defined($installed) ) {
668 if ( $installed == 0 ) {
669 croak qq/$c, as specified in the loader option "$k", is not installed/;
672 croak qq/$c, as specified in the loader option "$k", is an invalid class name/;
678 sub _find_file_in_inc {
679 my ($self, $file) = @_;
681 foreach my $prefix (@INC) {
682 my $fullpath = File::Spec->catfile($prefix, $file);
683 return $fullpath if -f $fullpath
684 # abs_path throws on Windows for nonexistant files
685 and eval { Cwd::abs_path($fullpath) } ne
686 (eval { Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) } || '');
693 my ($self, $class) = @_;
695 my $class_path = $class;
696 $class_path =~ s{::}{/}g;
697 $class_path .= '.pm';
702 sub _find_class_in_inc {
703 my ($self, $class) = @_;
705 return $self->_find_file_in_inc($self->_class_path($class));
711 return $self->_upgrading_from
712 || $self->_upgrading_from_load_classes
713 || $self->_downgrading_to_load_classes
714 || $self->_rewriting_result_namespace
718 sub _rewrite_old_classnames {
719 my ($self, $code) = @_;
721 return $code unless $self->_rewriting;
723 my %old_classes = reverse %{ $self->_upgrading_classes };
725 my $re = join '|', keys %old_classes;
728 $code =~ s/$re/$old_classes{$1} || $1/eg;
734 my ($self, $class) = @_;
736 return if $self->{skip_load_external};
738 # so that we don't load our own classes, under any circumstances
739 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
741 my $real_inc_path = $self->_find_class_in_inc($class);
743 my $old_class = $self->_upgrading_classes->{$class}
744 if $self->_rewriting;
746 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
747 if $old_class && $old_class ne $class;
749 return unless $real_inc_path || $old_real_inc_path;
751 if ($real_inc_path) {
752 # If we make it to here, we loaded an external definition
753 warn qq/# Loaded external class definition for '$class'\n/
756 open(my $fh, '<', $real_inc_path)
757 or croak "Failed to open '$real_inc_path' for reading: $!";
758 my $code = do { local $/; <$fh> };
760 or croak "Failed to close $real_inc_path: $!";
761 $code = $self->_rewrite_old_classnames($code);
763 if ($self->dynamic) { # load the class too
764 # kill redefined warnings
765 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
766 local $SIG{__WARN__} = sub {
768 unless $_[0] =~ /^Subroutine \S+ redefined/;
774 $self->_ext_stmt($class,
775 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
776 .qq|# They are now part of the custom portion of this file\n|
777 .qq|# for you to hand-edit. If you do not either delete\n|
778 .qq|# this section or remove that file from \@INC, this section\n|
779 .qq|# will be repeated redundantly when you re-create this\n|
780 .qq|# file again via Loader! See skip_load_external to disable\n|
781 .qq|# this feature.\n|
784 $self->_ext_stmt($class, $code);
785 $self->_ext_stmt($class,
786 qq|# End of lines loaded from '$real_inc_path' |
790 if ($old_real_inc_path) {
791 open(my $fh, '<', $old_real_inc_path)
792 or croak "Failed to open '$old_real_inc_path' for reading: $!";
793 $self->_ext_stmt($class, <<"EOF");
795 # These lines were loaded from '$old_real_inc_path',
796 # based on the Result class name that would have been created by an 0.04006
797 # version of the Loader. For a static schema, this happens only once during
798 # upgrade. See skip_load_external to disable this feature.
801 my $code = slurp $old_real_inc_path;
802 $code = $self->_rewrite_old_classnames($code);
804 if ($self->dynamic) {
807 Detected external content in '$old_real_inc_path', a class name that would have
808 been used by an 0.04006 version of the Loader.
810 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
811 new name of the Result.
813 # kill redefined warnings
814 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
815 local $SIG{__WARN__} = sub {
817 unless $_[0] =~ /^Subroutine \S+ redefined/;
824 $self->_ext_stmt($class, $code);
825 $self->_ext_stmt($class,
826 qq|# End of lines loaded from '$old_real_inc_path' |
833 Does the actual schema-construction work.
840 $self->_load_tables($self->_tables_list);
847 Rescan the database for newly added tables. Does
848 not process drops or changes. Returns a list of
849 the newly added table monikers.
851 The schema argument should be the schema class
852 or object to be affected. It should probably
853 be derived from the original schema_class used
859 my ($self, $schema) = @_;
861 $self->{schema} = $schema;
862 $self->_relbuilder->{schema} = $schema;
865 my @current = $self->_tables_list;
866 foreach my $table ($self->_tables_list) {
867 if(!exists $self->{_tables}->{$table}) {
868 push(@created, $table);
872 my $loaded = $self->_load_tables(@created);
874 return map { $self->monikers->{$_} } @$loaded;
878 no warnings 'uninitialized';
881 return if $self->{skip_relationships};
883 if ($self->naming->{relationships} eq 'v4') {
884 require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040;
885 return $self->{relbuilder} ||=
886 DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040->new(
887 $self->schema, $self->inflect_plural, $self->inflect_singular
891 $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder->new (
893 $self->inflect_plural,
894 $self->inflect_singular,
895 $self->relationship_attrs,
900 my ($self, @tables) = @_;
902 # First, use _tables_list with constraint and exclude
903 # to get a list of tables to operate on
905 my $constraint = $self->constraint;
906 my $exclude = $self->exclude;
908 @tables = grep { /$constraint/ } @tables if $constraint;
909 @tables = grep { ! /$exclude/ } @tables if $exclude;
911 # Save the new tables to the tables list
913 $self->{_tables}->{$_} = 1;
916 $self->_make_src_class($_) for @tables;
917 $self->_setup_src_meta($_) for @tables;
919 if(!$self->skip_relationships) {
920 # The relationship loader needs a working schema
922 local $self->{dump_directory} = $self->{temp_directory};
923 $self->_reload_classes(\@tables);
924 $self->_load_relationships($_) for @tables;
927 # Remove that temp dir from INC so it doesn't get reloaded
928 @INC = grep $_ ne $self->dump_directory, @INC;
931 $self->_load_external($_)
932 for map { $self->classes->{$_} } @tables;
934 # Reload without unloading first to preserve any symbols from external
936 $self->_reload_classes(\@tables, 0);
938 # Drop temporary cache
939 delete $self->{_cache};
944 sub _reload_classes {
945 my ($self, $tables, $unload) = @_;
947 my @tables = @$tables;
948 $unload = 1 unless defined $unload;
950 # so that we don't repeat custom sections
951 @INC = grep $_ ne $self->dump_directory, @INC;
953 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
955 unshift @INC, $self->dump_directory;
958 my %have_source = map { $_ => $self->schema->source($_) }
959 $self->schema->sources;
961 for my $table (@tables) {
962 my $moniker = $self->monikers->{$table};
963 my $class = $self->classes->{$table};
966 no warnings 'redefine';
967 local *Class::C3::reinitialize = sub {};
970 Class::Unload->unload($class) if $unload;
971 my ($source, $resultset_class);
973 ($source = $have_source{$moniker})
974 && ($resultset_class = $source->resultset_class)
975 && ($resultset_class ne 'DBIx::Class::ResultSet')
977 my $has_file = Class::Inspector->loaded_filename($resultset_class);
978 Class::Unload->unload($resultset_class) if $unload;
979 $self->_reload_class($resultset_class) if $has_file;
981 $self->_reload_class($class);
983 push @to_register, [$moniker, $class];
986 Class::C3->reinitialize;
988 $self->schema->register_class(@$_);
992 # We use this instead of ensure_class_loaded when there are package symbols we
995 my ($self, $class) = @_;
997 my $class_path = $self->_class_path($class);
998 delete $INC{ $class_path };
1000 # kill redefined warnings
1001 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
1002 local $SIG{__WARN__} = sub {
1004 unless $_[0] =~ /^Subroutine \S+ redefined/;
1006 eval "require $class;";
1009 sub _get_dump_filename {
1010 my ($self, $class) = (@_);
1012 $class =~ s{::}{/}g;
1013 return $self->dump_directory . q{/} . $class . q{.pm};
1016 sub _ensure_dump_subdirs {
1017 my ($self, $class) = (@_);
1019 my @name_parts = split(/::/, $class);
1020 pop @name_parts; # we don't care about the very last element,
1021 # which is a filename
1023 my $dir = $self->dump_directory;
1026 mkdir($dir) or croak "mkdir('$dir') failed: $!";
1028 last if !@name_parts;
1029 $dir = File::Spec->catdir($dir, shift @name_parts);
1034 my ($self, @classes) = @_;
1036 my $schema_class = $self->schema_class;
1037 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
1039 my $target_dir = $self->dump_directory;
1040 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
1041 unless $self->{dynamic} or $self->{quiet};
1044 qq|package $schema_class;\n\n|
1045 . qq|# Created by DBIx::Class::Schema::Loader\n|
1046 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1047 . qq|use strict;\nuse warnings;\n\n|
1048 . qq|use base '$schema_base_class';\n\n|;
1050 if ($self->use_namespaces) {
1051 $schema_text .= qq|__PACKAGE__->load_namespaces|;
1052 my $namespace_options;
1053 for my $attr (qw(result_namespace
1055 default_resultset_class)) {
1057 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
1060 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
1061 $schema_text .= qq|;\n|;
1064 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
1068 local $self->{version_to_dump} = $self->schema_version_to_dump;
1069 $self->_write_classfile($schema_class, $schema_text, 1);
1072 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
1074 foreach my $src_class (@classes) {
1076 qq|package $src_class;\n\n|
1077 . qq|# Created by DBIx::Class::Schema::Loader\n|
1078 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1079 . qq|use strict;\nuse warnings;\n\n|
1080 . qq|use base '$result_base_class';\n\n|;
1082 $self->_write_classfile($src_class, $src_text);
1085 # remove Result dir if downgrading from use_namespaces, and there are no
1087 if (my $result_ns = $self->_downgrading_to_load_classes
1088 || $self->_rewriting_result_namespace) {
1089 my $result_namespace = $self->_result_namespace(
1094 (my $result_dir = $result_namespace) =~ s{::}{/}g;
1095 $result_dir = $self->dump_directory . '/' . $result_dir;
1097 unless (my @files = glob "$result_dir/*") {
1102 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
1107 my ($self, $version, $ts) = @_;
1108 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
1111 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
1114 sub _write_classfile {
1115 my ($self, $class, $text, $is_schema) = @_;
1117 my $filename = $self->_get_dump_filename($class);
1118 $self->_ensure_dump_subdirs($class);
1120 if (-f $filename && $self->really_erase_my_files) {
1121 warn "Deleting existing file '$filename' due to "
1122 . "'really_erase_my_files' setting\n" unless $self->{quiet};
1126 my ($custom_content, $old_md5, $old_ver, $old_ts) = $self->_get_custom_content($class, $filename);
1128 if (my $old_class = $self->_upgrading_classes->{$class}) {
1129 my $old_filename = $self->_get_dump_filename($old_class);
1131 my ($old_custom_content) = $self->_get_custom_content(
1132 $old_class, $old_filename, 0 # do not add default comment
1135 $old_custom_content =~ s/\n\n# You can replace.*\n1;\n//;
1137 if ($old_custom_content) {
1139 "\n" . $old_custom_content . "\n" . $custom_content;
1142 unlink $old_filename;
1145 $custom_content = $self->_rewrite_old_classnames($custom_content);
1148 for @{$self->{_dump_storage}->{$class} || []};
1150 # Check and see if the dump is infact differnt
1154 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
1157 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
1158 return unless $self->_upgrading_from && $is_schema;
1162 $text .= $self->_sig_comment(
1163 $self->version_to_dump,
1164 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
1167 open(my $fh, '>', $filename)
1168 or croak "Cannot open '$filename' for writing: $!";
1170 # Write the top half and its MD5 sum
1171 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
1173 # Write out anything loaded via external partial class file in @INC
1175 for @{$self->{_ext_storage}->{$class} || []};
1177 # Write out any custom content the user has added
1178 print $fh $custom_content;
1181 or croak "Error closing '$filename': $!";
1184 sub _default_custom_content {
1185 return qq|\n\n# You can replace this text with custom|
1186 . qq| content, and it will be preserved on regeneration|
1190 sub _get_custom_content {
1191 my ($self, $class, $filename, $add_default) = @_;
1193 $add_default = 1 unless defined $add_default;
1195 return ($self->_default_custom_content) if ! -f $filename;
1197 open(my $fh, '<', $filename)
1198 or croak "Cannot open '$filename' for reading: $!";
1201 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
1204 my ($md5, $ts, $ver);
1206 if(!$md5 && /$mark_re/) {
1210 # Pull out the previous version and timestamp
1211 ($ver, $ts) = $buffer =~ m/# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)$/s;
1214 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"
1215 if !$self->overwrite_modifications && Digest::MD5::md5_base64($buffer) ne $md5;
1224 croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
1225 . " it does not appear to have been generated by Loader"
1228 # Default custom content:
1229 $buffer ||= $self->_default_custom_content if $add_default;
1231 return ($buffer, $md5, $ver, $ts);
1239 warn "$target: use $_;" if $self->debug;
1240 $self->_raw_stmt($target, "use $_;");
1247 my $schema_class = $self->schema_class;
1249 my $blist = join(q{ }, @_);
1250 warn "$target: use base qw/ $blist /;" if $self->debug && @_;
1251 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
1254 sub _result_namespace {
1255 my ($self, $schema_class, $ns) = @_;
1256 my @result_namespace;
1258 if ($ns =~ /^\+(.*)/) {
1259 # Fully qualified namespace
1260 @result_namespace = ($1)
1263 # Relative namespace
1264 @result_namespace = ($schema_class, $ns);
1267 return wantarray ? @result_namespace : join '::', @result_namespace;
1270 # Create class with applicable bases, setup monikers, etc
1271 sub _make_src_class {
1272 my ($self, $table) = @_;
1274 my $schema = $self->schema;
1275 my $schema_class = $self->schema_class;
1277 my $table_moniker = $self->_table2moniker($table);
1278 my @result_namespace = ($schema_class);
1279 if ($self->use_namespaces) {
1280 my $result_namespace = $self->result_namespace || 'Result';
1281 @result_namespace = $self->_result_namespace(
1286 my $table_class = join(q{::}, @result_namespace, $table_moniker);
1288 if ((my $upgrading_v = $self->_upgrading_from)
1289 || $self->_rewriting) {
1290 local $self->naming->{monikers} = $upgrading_v
1293 my @result_namespace = @result_namespace;
1294 if ($self->_upgrading_from_load_classes) {
1295 @result_namespace = ($schema_class);
1297 elsif (my $ns = $self->_downgrading_to_load_classes) {
1298 @result_namespace = $self->_result_namespace(
1303 elsif ($ns = $self->_rewriting_result_namespace) {
1304 @result_namespace = $self->_result_namespace(
1310 my $old_class = join(q{::}, @result_namespace,
1311 $self->_table2moniker($table));
1313 $self->_upgrading_classes->{$table_class} = $old_class
1314 unless $table_class eq $old_class;
1317 my $table_normalized = lc $table;
1318 $self->classes->{$table} = $table_class;
1319 $self->classes->{$table_normalized} = $table_class;
1320 $self->monikers->{$table} = $table_moniker;
1321 $self->monikers->{$table_normalized} = $table_moniker;
1323 $self->_use ($table_class, @{$self->additional_classes});
1324 $self->_inject($table_class, @{$self->left_base_classes});
1326 if (my @components = @{ $self->components }) {
1327 $self->_dbic_stmt($table_class, 'load_components', @components);
1330 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
1331 if @{$self->resultset_components};
1332 $self->_inject($table_class, @{$self->additional_base_classes});
1335 # Set up metadata (cols, pks, etc)
1336 sub _setup_src_meta {
1337 my ($self, $table) = @_;
1339 my $schema = $self->schema;
1340 my $schema_class = $self->schema_class;
1342 my $table_class = $self->classes->{$table};
1343 my $table_moniker = $self->monikers->{$table};
1345 my $table_name = $table;
1346 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1348 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1349 $table_name = \ $self->_quote_table_name($table_name);
1352 $self->_dbic_stmt($table_class,'table',$table_name);
1354 my $cols = $self->_table_columns($table);
1355 my $col_info = $self->__columns_info_for($table);
1356 if ($self->_is_case_sensitive) {
1357 for my $col (keys %$col_info) {
1358 $col_info->{$col}{accessor} = lc $col
1359 if $col ne lc($col);
1362 $col_info = { map { lc($_), $col_info->{$_} } keys %$col_info };
1365 my $fks = $self->_table_fk_info($table);
1367 for my $fkdef (@$fks) {
1368 for my $col (@{ $fkdef->{local_columns} }) {
1369 $col_info->{$col}{is_foreign_key} = 1;
1375 map { $_, ($col_info->{$_}||{}) } @$cols
1378 my %uniq_tag; # used to eliminate duplicate uniqs
1380 my $pks = $self->_table_pk_info($table) || [];
1381 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1382 : carp("$table has no primary key");
1383 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1385 my $uniqs = $self->_table_uniq_info($table) || [];
1387 my ($name, $cols) = @$_;
1388 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1389 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1394 sub __columns_info_for {
1395 my ($self, $table) = @_;
1397 my $result = $self->_columns_info_for($table);
1399 while (my ($col, $info) = each %$result) {
1400 $info = { %$info, %{ $self->_custom_column_info ($table, $col, $info) } };
1401 $info = { %$info, %{ $self->_datetime_column_info($table, $col, $info) } };
1403 $result->{$col} = $info;
1411 Returns a sorted list of loaded tables, using the original database table
1419 return keys %{$self->_tables};
1422 # Make a moniker from a table
1423 sub _default_table2moniker {
1424 no warnings 'uninitialized';
1425 my ($self, $table) = @_;
1427 if ($self->naming->{monikers} eq 'v4') {
1428 return join '', map ucfirst, split /[\W_]+/, lc $table;
1431 return join '', map ucfirst, split /[\W_]+/,
1432 Lingua::EN::Inflect::Number::to_S(lc $table);
1435 sub _table2moniker {
1436 my ( $self, $table ) = @_;
1440 if( ref $self->moniker_map eq 'HASH' ) {
1441 $moniker = $self->moniker_map->{$table};
1443 elsif( ref $self->moniker_map eq 'CODE' ) {
1444 $moniker = $self->moniker_map->($table);
1447 $moniker ||= $self->_default_table2moniker($table);
1452 sub _load_relationships {
1453 my ($self, $table) = @_;
1455 my $tbl_fk_info = $self->_table_fk_info($table);
1456 foreach my $fkdef (@$tbl_fk_info) {
1457 $fkdef->{remote_source} =
1458 $self->monikers->{delete $fkdef->{remote_table}};
1460 my $tbl_uniq_info = $self->_table_uniq_info($table);
1462 my $local_moniker = $self->monikers->{$table};
1463 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1465 foreach my $src_class (sort keys %$rel_stmts) {
1466 my $src_stmts = $rel_stmts->{$src_class};
1467 foreach my $stmt (@$src_stmts) {
1468 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1473 # Overload these in driver class:
1475 # Returns an arrayref of column names
1476 sub _table_columns { croak "ABSTRACT METHOD" }
1478 # Returns arrayref of pk col names
1479 sub _table_pk_info { croak "ABSTRACT METHOD" }
1481 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1482 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1484 # Returns an arrayref of foreign key constraints, each
1485 # being a hashref with 3 keys:
1486 # local_columns (arrayref), remote_columns (arrayref), remote_table
1487 sub _table_fk_info { croak "ABSTRACT METHOD" }
1489 # Returns an array of lower case table names
1490 sub _tables_list { croak "ABSTRACT METHOD" }
1492 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1498 # generate the pod for this statement, storing it with $self->_pod
1499 $self->_make_pod( $class, $method, @_ ) if $self->generate_pod;
1501 my $args = dump(@_);
1502 $args = '(' . $args . ')' if @_ < 2;
1503 my $stmt = $method . $args . q{;};
1505 warn qq|$class\->$stmt\n| if $self->debug;
1506 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1510 # generates the accompanying pod for a DBIC class method statement,
1511 # storing it with $self->_pod
1517 if ( $method eq 'table' ) {
1519 my $pcm = $self->pod_comment_mode;
1520 my ($comment, $comment_overflows, $comment_in_name, $comment_in_desc);
1521 if ( $self->can('_table_comment') ) {
1522 $comment = $self->_table_comment($table);
1523 $comment_overflows = ($comment and length $comment > $self->pod_comment_spillover_length);
1524 $comment_in_name = ($pcm eq 'name' or ($pcm eq 'auto' and !$comment_overflows));
1525 $comment_in_desc = ($pcm eq 'description' or ($pcm eq 'auto' and $comment_overflows));
1527 $self->_pod( $class, "=head1 NAME" );
1528 my $table_descr = $class;
1529 $table_descr .= " - " . $comment if $comment and $comment_in_name;
1530 $self->{_class2table}{ $class } = $table;
1531 $self->_pod( $class, $table_descr );
1532 if ($comment and $comment_in_desc) {
1533 $self->_pod( $class, "=head1 DESCRIPTION" );
1534 $self->_pod( $class, $comment );
1536 $self->_pod_cut( $class );
1537 } elsif ( $method eq 'add_columns' ) {
1538 $self->_pod( $class, "=head1 ACCESSORS" );
1539 my $col_counter = 0;
1541 while( my ($name,$attrs) = splice @cols,0,2 ) {
1543 $self->_pod( $class, '=head2 ' . $name );
1544 $self->_pod( $class,
1546 my $s = $attrs->{$_};
1547 $s = !defined $s ? 'undef' :
1548 length($s) == 0 ? '(empty string)' :
1549 ref($s) eq 'SCALAR' ? $$s :
1556 looks_like_number($s) ? $s :
1561 } sort keys %$attrs,
1564 if( $self->can('_column_comment')
1565 and my $comment = $self->_column_comment( $self->{_class2table}{$class}, $col_counter)
1567 $self->_pod( $class, $comment );
1570 $self->_pod_cut( $class );
1571 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
1572 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
1573 my ( $accessor, $rel_class ) = @_;
1574 $self->_pod( $class, "=head2 $accessor" );
1575 $self->_pod( $class, 'Type: ' . $method );
1576 $self->_pod( $class, "Related object: L<$rel_class>" );
1577 $self->_pod_cut( $class );
1578 $self->{_relations_started} { $class } = 1;
1582 # Stores a POD documentation
1584 my ($self, $class, $stmt) = @_;
1585 $self->_raw_stmt( $class, "\n" . $stmt );
1589 my ($self, $class ) = @_;
1590 $self->_raw_stmt( $class, "\n=cut\n" );
1593 # Store a raw source line for a class (for dumping purposes)
1595 my ($self, $class, $stmt) = @_;
1596 push(@{$self->{_dump_storage}->{$class}}, $stmt);
1599 # Like above, but separately for the externally loaded stuff
1601 my ($self, $class, $stmt) = @_;
1602 push(@{$self->{_ext_storage}->{$class}}, $stmt);
1605 sub _quote_table_name {
1606 my ($self, $table) = @_;
1608 my $qt = $self->schema->storage->sql_maker->quote_char;
1610 return $table unless $qt;
1613 return $qt->[0] . $table . $qt->[1];
1616 return $qt . $table . $qt;
1619 sub _is_case_sensitive { 0 }
1621 sub _custom_column_info {
1622 my ( $self, $table_name, $column_name, $column_info ) = @_;
1624 if (my $code = $self->custom_column_info) {
1625 return $code->($table_name, $column_name, $column_info) || {};
1630 sub _datetime_column_info {
1631 my ( $self, $table_name, $column_name, $column_info ) = @_;
1633 my $type = $column_info->{data_type} || '';
1634 if ((grep $_, @{ $column_info }{map "inflate_$_", qw/date datetime timestamp/})
1635 or ($type =~ /date|timestamp/i)) {
1636 $result->{timezone} = $self->datetime_timezone if $self->datetime_timezone;
1637 $result->{locale} = $self->datetime_locale if $self->datetime_locale;
1642 # remove the dump dir from @INC on destruction
1646 @INC = grep $_ ne $self->dump_directory, @INC;
1651 Returns a hashref of loaded table to moniker mappings. There will
1652 be two entries for each table, the original name and the "normalized"
1653 name, in the case that the two are different (such as databases
1654 that like uppercase table names, or preserve your original mixed-case
1655 definitions, or what-have-you).
1659 Returns a hashref of table to class mappings. In some cases it will
1660 contain multiple entries per table for the original and normalized table
1661 names, as above in L</monikers>.
1665 L<DBIx::Class::Schema::Loader>
1669 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
1673 This library is free software; you can redistribute it and/or modify it under
1674 the same terms as Perl itself.