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//;
15 use Lingua::EN::Inflect::Phrase qw//;
18 use Class::Inspector ();
19 use Scalar::Util 'looks_like_number';
20 use File::Slurp 'slurp';
21 use DBIx::Class::Schema::Loader::Utils qw/split_name dumper_squashed eval_without_redefine_warnings/;
22 use DBIx::Class::Schema::Loader::Optional::Dependencies ();
27 our $VERSION = '0.07010';
29 __PACKAGE__->mk_group_ro_accessors('simple', qw/
36 additional_base_classes
51 default_resultset_class
55 overwrite_modifications
74 __PACKAGE__->mk_group_accessors('simple', qw/
76 schema_version_to_dump
78 _upgrading_from_load_classes
79 _downgrading_to_load_classes
80 _rewriting_result_namespace
85 pod_comment_spillover_length
91 datetime_undef_if_invalid
97 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
101 See L<DBIx::Class::Schema::Loader>
105 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
106 classes, and implements the common functionality between them.
108 =head1 CONSTRUCTOR OPTIONS
110 These constructor options are the base options for
111 L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
113 =head2 skip_relationships
115 Skip setting up relationships. The default is to attempt the loading
118 =head2 skip_load_external
120 Skip loading of other classes in @INC. The default is to merge all other classes
121 with the same name found in @INC into the schema file we are creating.
125 Static schemas (ones dumped to disk) will, by default, use the new-style
126 relationship names and singularized Results, unless you're overwriting an
127 existing dump made by an older version of L<DBIx::Class::Schema::Loader>, in
128 which case the backward compatible RelBuilder will be activated, and the
129 appropriate monikerization used.
135 will disable the backward-compatible RelBuilder and use
136 the new-style relationship names along with singularized Results, even when
137 overwriting a dump made with an earlier version.
139 The option also takes a hashref:
141 naming => { relationships => 'v7', monikers => 'v7' }
149 How to name relationship accessors.
153 How to name Result classes.
155 =item column_accessors
157 How to name column accessors in Result classes.
167 Latest style, whatever that happens to be.
171 Unsingularlized monikers, C<has_many> only relationships with no _id stripping.
175 Monikers singularized as whole words, C<might_have> relationships for FKs on
176 C<UNIQUE> constraints, C<_id> stripping for belongs_to relationships.
178 Some of the C<_id> stripping edge cases in C<0.05003> have been reverted for
183 All monikers and relationships are inflected using
184 L<Lingua::EN::Inflect::Phrase>, and there is more aggressive C<_id> stripping
185 from relationship names.
187 In general, there is very little difference between v5 and v6 schemas.
191 This mode is identical to C<v6> mode, except that monikerization of CamelCase
192 table names is also done correctly.
194 CamelCase column names in case-preserving mode will also be handled correctly
195 for relationship name inflection. See L</preserve_case>.
197 In this mode, CamelCase L</column_accessors> are normalized based on case
198 transition instead of just being lowercased, so C<FooId> becomes C<foo_id>.
200 If you don't have any CamelCase table or column names, you can upgrade without
201 breaking any of your code.
205 Dynamic schemas will always default to the 0.04XXX relationship names and won't
206 singularize Results for backward compatibility, to activate the new RelBuilder
207 and singularization put this in your C<Schema.pm> file:
209 __PACKAGE__->naming('current');
211 Or if you prefer to use 0.07XXX features but insure that nothing breaks in the
212 next major version upgrade:
214 __PACKAGE__->naming('v7');
218 By default POD will be generated for columns and relationships, using database
219 metadata for the text if available and supported.
221 Reading database metadata (e.g. C<COMMENT ON TABLE some_table ...>) is only
222 supported for Postgres right now.
224 Set this to C<0> to turn off all POD generation.
226 =head2 pod_comment_mode
228 Controls where table comments appear in the generated POD. Smaller table
229 comments are appended to the C<NAME> section of the documentation, and larger
230 ones are inserted into C<DESCRIPTION> instead. You can force a C<DESCRIPTION>
231 section to be generated with the comment always, only use C<NAME>, or choose
232 the length threshold at which the comment is forced into the description.
238 Use C<NAME> section only.
242 Force C<DESCRIPTION> always.
246 Use C<DESCRIPTION> if length > L</pod_comment_spillover_length>, this is the
251 =head2 pod_comment_spillover_length
253 When pod_comment_mode is set to C<auto>, this is the length of the comment at
254 which it will be forced into a separate description section.
258 =head2 relationship_attrs
260 Hashref of attributes to pass to each generated relationship, listed
261 by type. Also supports relationship type 'all', containing options to
262 pass to all generated relationships. Attributes set for more specific
263 relationship types override those set in 'all'.
267 relationship_attrs => {
268 belongs_to => { is_deferrable => 0 },
271 use this to turn off DEFERRABLE on your foreign key constraints.
275 If set to true, each constructive L<DBIx::Class> statement the loader
276 decides to execute will be C<warn>-ed before execution.
280 Set the name of the schema to load (schema in the sense that your database
281 vendor means it). Does not currently support loading more than one schema
286 Only load tables matching regex. Best specified as a qr// regex.
290 Exclude tables matching regex. Best specified as a qr// regex.
294 Overrides the default table name to moniker translation. Can be either
295 a hashref of table keys and moniker values, or a coderef for a translator
296 function taking a single scalar table name argument and returning
297 a scalar moniker. If the hash entry does not exist, or the function
298 returns a false value, the code falls back to default behavior
301 The default behavior is to split on case transition and non-alphanumeric
302 boundaries, singularize the resulting phrase, then join the titlecased words
305 Table Name | Moniker Name
306 ---------------------------------
308 luser_group | LuserGroup
309 luser-opts | LuserOpt
310 stations_visited | StationVisited
311 routeChange | RouteChange
313 =head2 col_accessor_map
315 Same as moniker_map, but for column accessor names. If a coderef is
316 passed, the code is called with arguments of
318 the name of the column in the underlying database,
319 default accessor name that DBICSL would ordinarily give this column,
321 table_class => name of the DBIC class we are building,
322 table_moniker => calculated moniker for this table (after moniker_map if present),
323 table_name => name of the database table,
324 full_table_name => schema-qualified name of the database table (RDBMS specific),
325 schema_class => name of the schema class we are building,
326 column_info => hashref of column info (data_type, is_nullable, etc),
329 =head2 inflect_plural
331 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
332 if hash key does not exist or coderef returns false), but acts as a map
333 for pluralizing relationship names. The default behavior is to utilize
334 L<Lingua::EN::Inflect::Phrase/to_PL>.
336 =head2 inflect_singular
338 As L</inflect_plural> above, but for singularizing relationship names.
339 Default behavior is to utilize L<Lingua::EN::Inflect::Phrase/to_S>.
341 =head2 schema_base_class
343 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
345 =head2 result_base_class
347 Base class for your table classes (aka result classes). Defaults to
350 =head2 additional_base_classes
352 List of additional base classes all of your table classes will use.
354 =head2 left_base_classes
356 List of additional base classes all of your table classes will use
357 that need to be leftmost.
359 =head2 additional_classes
361 List of additional classes which all of your table classes will use.
365 List of additional components to be loaded into all of your table
366 classes. A good example would be
367 L<InflateColumn::DateTime|DBIx::Class::InflateColumn::DateTime>
369 =head2 result_component_map
371 A hashref of moniker keys and component values. Unlike C<components>, which loads the
372 given components into every table class, this option allows you to load certain
373 components for specified tables. For example:
375 result_component_map => {
376 StationVisited => '+YourApp::Schema::Component::StationVisited',
378 '+YourApp::Schema::Component::RouteChange',
379 'InflateColumn::DateTime',
383 You may use this in conjunction with C<components>.
385 =head2 use_namespaces
387 This is now the default, to go back to L<DBIx::Class::Schema/load_classes> pass
390 Generate result class names suitable for
391 L<DBIx::Class::Schema/load_namespaces> and call that instead of
392 L<DBIx::Class::Schema/load_classes>. When using this option you can also
393 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
394 C<resultset_namespace>, C<default_resultset_class>), and they will be added
395 to the call (and the generated result class names adjusted appropriately).
397 =head2 dump_directory
399 The value of this option is a perl libdir pathname. Within
400 that directory this module will create a baseline manual
401 L<DBIx::Class::Schema> module set, based on what it creates at runtime.
403 The created schema class will have the same classname as the one on
404 which you are setting this option (and the ResultSource classes will be
405 based on this name as well).
407 Normally you wouldn't hard-code this setting in your schema class, as it
408 is meant for one-time manual usage.
410 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
411 recommended way to access this functionality.
413 =head2 dump_overwrite
415 Deprecated. See L</really_erase_my_files> below, which does *not* mean
416 the same thing as the old C<dump_overwrite> setting from previous releases.
418 =head2 really_erase_my_files
420 Default false. If true, Loader will unconditionally delete any existing
421 files before creating the new ones from scratch when dumping a schema to disk.
423 The default behavior is instead to only replace the top portion of the
424 file, up to and including the final stanza which contains
425 C<# DO NOT MODIFY THE FIRST PART OF THIS FILE>
426 leaving any customizations you placed after that as they were.
428 When C<really_erase_my_files> is not set, if the output file already exists,
429 but the aforementioned final stanza is not found, or the checksum
430 contained there does not match the generated contents, Loader will
431 croak and not touch the file.
433 You should really be using version control on your schema classes (and all
434 of the rest of your code for that matter). Don't blame me if a bug in this
435 code wipes something out when it shouldn't have, you've been warned.
437 =head2 overwrite_modifications
439 Default false. If false, when updating existing files, Loader will
440 refuse to modify any Loader-generated code that has been modified
441 since its last run (as determined by the checksum Loader put in its
444 If true, Loader will discard any manual modifications that have been
445 made to Loader-generated code.
447 Again, you should be using version control on your schema classes. Be
448 careful with this option.
450 =head2 custom_column_info
452 Hook for adding extra attributes to the
453 L<column_info|DBIx::Class::ResultSource/column_info> for a column.
455 Must be a coderef that returns a hashref with the extra attributes.
457 Receives the table name, column name and column_info.
461 custom_column_info => sub {
462 my ($table_name, $column_name, $column_info) = @_;
464 if ($column_name eq 'dog' && $column_info->{default_value} eq 'snoopy') {
465 return { is_snoopy => 1 };
469 This attribute can also be used to set C<inflate_datetime> on a non-datetime
470 column so it also receives the L</datetime_timezone> and/or L</datetime_locale>.
472 =head2 datetime_timezone
474 Sets the timezone attribute for L<DBIx::Class::InflateColumn::DateTime> for all
475 columns with the DATE/DATETIME/TIMESTAMP data_types.
477 =head2 datetime_locale
479 Sets the locale attribute for L<DBIx::Class::InflateColumn::DateTime> for all
480 columns with the DATE/DATETIME/TIMESTAMP data_types.
482 =head2 datetime_undef_if_invalid
484 Pass a C<0> for this option when using MySQL if you B<DON'T> want C<<
485 datetime_undef_if_invalid => 1 >> in your column info for DATE, DATETIME and
488 The default is recommended to deal with data such as C<00/00/00> which
489 sometimes ends up in such columns in MySQL.
493 File in Perl format, which should return a HASH reference, from which to read
498 Usually column names are lowercased, to make them easier to work with in
499 L<DBIx::Class>. This option lets you turn this behavior off, if the driver
502 Drivers for case sensitive databases like Sybase ASE or MSSQL with a
503 case-sensitive collation will turn this option on unconditionally.
505 Currently the drivers for SQLite, mysql, MSSQL and Firebird/InterBase support
508 =head2 qualify_objects
510 Set to true to prepend the L</db_schema> to table names for C<<
511 __PACKAGE__->table >> calls, and to some other things like Oracle sequences.
515 Creates Schema and Result classes that use L<Moose>, L<MooseX::NonMoose> and
516 L<namespace::autoclean>. The default content after the md5 sum also makes the
519 It is safe to upgrade your existing Schema to this option.
521 =head2 col_collision_map
523 This option controls how accessors for column names which collide with perl
524 methods are named. See L</COLUMN ACCESSOR COLLISIONS> for more information.
526 This option takes either a single L<sprintf|perlfunc/sprintf> format or a hashref of
527 strings which are compiled to regular expressions that map to
528 L<sprintf|perlfunc/sprintf> formats.
532 col_collision_map => 'column_%s'
534 col_collision_map => { '(.*)' => 'column_%s' }
536 col_collision_map => { '(foo).*(bar)' => 'column_%s_%s' }
538 =head2 rel_collision_map
540 Works just like L</col_collision_map>, but for relationship names/accessors
541 rather than column names/accessors.
543 The default is to just append C<_rel> to the relationship name, see
544 L</RELATIONSHIP NAME COLLISIONS>.
548 None of these methods are intended for direct invocation by regular
549 users of L<DBIx::Class::Schema::Loader>. Some are proxied via
550 L<DBIx::Class::Schema::Loader>.
554 my $CURRENT_V = 'v7';
557 schema_base_class result_base_class additional_base_classes
558 left_base_classes additional_classes components
561 # ensure that a peice of object data is a valid arrayref, creating
562 # an empty one or encapsulating whatever's there.
563 sub _ensure_arrayref {
568 $self->{$_} = [ $self->{$_} ]
569 unless ref $self->{$_} eq 'ARRAY';
575 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
576 by L<DBIx::Class::Schema::Loader>.
581 my ( $class, %args ) = @_;
583 if (exists $args{column_accessor_map}) {
584 $args{col_accessor_map} = delete $args{column_accessor_map};
587 my $self = { %args };
589 # don't lose undef options
590 for (values %$self) {
591 $_ = 0 unless defined $_;
594 bless $self => $class;
596 if (my $config_file = $self->config_file) {
597 my $config_opts = do $config_file;
599 croak "Error reading config from $config_file: $@" if $@;
601 croak "Config file $config_file must be a hashref" unless ref($config_opts) eq 'HASH';
603 while (my ($k, $v) = each %$config_opts) {
604 $self->{$k} = $v unless exists $self->{$k};
608 $self->_ensure_arrayref(qw/additional_classes
609 additional_base_classes
614 $self->_validate_class_args;
616 if ($self->result_component_map) {
617 my %rc_map = %{ $self->result_component_map };
618 foreach my $moniker (keys %rc_map) {
619 $rc_map{$moniker} = [ $rc_map{$moniker} ] unless ref $rc_map{$moniker};
621 $self->result_component_map(\%rc_map);
624 $self->result_component_map({});
626 $self->_validate_result_component_map;
628 if ($self->use_moose) {
629 if (not DBIx::Class::Schema::Loader::Optional::Dependencies->req_ok_for('use_moose')) {
630 die sprintf "You must install the following CPAN modules to enable the use_moose option: %s.\n",
631 DBIx::Class::Schema::Loader::Optional::Dependencies->req_missing_for('use_moose');
635 $self->{monikers} = {};
636 $self->{classes} = {};
637 $self->{_upgrading_classes} = {};
639 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
640 $self->{schema} ||= $self->{schema_class};
642 croak "dump_overwrite is deprecated. Please read the"
643 . " DBIx::Class::Schema::Loader::Base documentation"
644 if $self->{dump_overwrite};
646 $self->{dynamic} = ! $self->{dump_directory};
647 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
652 $self->{dump_directory} ||= $self->{temp_directory};
654 $self->real_dump_directory($self->{dump_directory});
656 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
657 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
659 if ((not ref $self->naming) && defined $self->naming) {
660 my $naming_ver = $self->naming;
662 relationships => $naming_ver,
663 monikers => $naming_ver,
664 column_accessors => $naming_ver,
669 for (values %{ $self->naming }) {
670 $_ = $CURRENT_V if $_ eq 'current';
673 $self->{naming} ||= {};
675 if ($self->custom_column_info && ref $self->custom_column_info ne 'CODE') {
676 croak 'custom_column_info must be a CODE ref';
679 $self->_check_back_compat;
681 $self->use_namespaces(1) unless defined $self->use_namespaces;
682 $self->generate_pod(1) unless defined $self->generate_pod;
683 $self->pod_comment_mode('auto') unless defined $self->pod_comment_mode;
684 $self->pod_comment_spillover_length(60) unless defined $self->pod_comment_spillover_length;
686 if (my $col_collision_map = $self->col_collision_map) {
687 if (my $reftype = ref $col_collision_map) {
688 if ($reftype ne 'HASH') {
689 croak "Invalid type $reftype for option 'col_collision_map'";
693 $self->col_collision_map({ '(.*)' => $col_collision_map });
700 sub _check_back_compat {
703 # dynamic schemas will always be in 0.04006 mode, unless overridden
704 if ($self->dynamic) {
705 # just in case, though no one is likely to dump a dynamic schema
706 $self->schema_version_to_dump('0.04006');
708 if (not %{ $self->naming }) {
709 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
711 Dynamic schema detected, will run in 0.04006 mode.
713 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
714 to disable this warning.
716 Also consider setting 'use_namespaces => 1' if/when upgrading.
718 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
723 $self->_upgrading_from('v4');
726 $self->naming->{relationships} ||= 'v4';
727 $self->naming->{monikers} ||= 'v4';
729 if ($self->use_namespaces) {
730 $self->_upgrading_from_load_classes(1);
733 $self->use_namespaces(0);
739 # otherwise check if we need backcompat mode for a static schema
740 my $filename = $self->_get_dump_filename($self->schema_class);
741 return unless -e $filename;
743 my ($old_gen, $old_md5, $old_ver, $old_ts, $old_custom) =
744 $self->_parse_generated_file($filename);
746 return unless $old_ver;
748 # determine if the existing schema was dumped with use_moose => 1
749 if (! defined $self->use_moose) {
750 $self->{use_moose} = 1 if $old_gen =~ /^ (?!\s*\#) use \s+ Moose/xm;
753 my $load_classes = ($old_gen =~ /^__PACKAGE__->load_classes;/m) ? 1 : 0;
754 my $result_namespace = do { ($old_gen =~ /result_namespace => '([^']+)'/) ? $1 : '' };
756 if ($load_classes && (not defined $self->use_namespaces)) {
757 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
759 'load_classes;' static schema detected, turning off 'use_namespaces'.
761 Set the 'use_namespaces' attribute or the SCHEMA_LOADER_BACKCOMPAT environment
762 variable to disable this warning.
764 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
767 $self->use_namespaces(0);
769 elsif ($load_classes && $self->use_namespaces) {
770 $self->_upgrading_from_load_classes(1);
772 elsif ((not $load_classes) && defined $self->use_namespaces && ! $self->use_namespaces) {
773 $self->_downgrading_to_load_classes(
774 $result_namespace || 'Result'
777 elsif ((not defined $self->use_namespaces) || $self->use_namespaces) {
778 if (not $self->result_namespace) {
779 $self->result_namespace($result_namespace || 'Result');
781 elsif ($result_namespace ne $self->result_namespace) {
782 $self->_rewriting_result_namespace(
783 $result_namespace || 'Result'
788 # XXX when we go past .0 this will need fixing
789 my ($v) = $old_ver =~ /([1-9])/;
792 return if ($v eq $CURRENT_V || $old_ver =~ /^0\.\d\d999/);
794 if (not %{ $self->naming }) {
795 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
797 Version $old_ver static schema detected, turning on backcompat mode.
799 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
800 to disable this warning.
802 See: 'naming' in perldoc DBIx::Class::Schema::Loader::Base .
804 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 if upgrading
805 from version 0.04006.
808 $self->naming->{relationships} ||= $v;
809 $self->naming->{monikers} ||= $v;
810 $self->naming->{column_accessors} ||= $v;
812 $self->schema_version_to_dump($old_ver);
815 $self->_upgrading_from($v);
819 sub _validate_class_args {
822 foreach my $k (@CLASS_ARGS) {
823 next unless $self->$k;
825 my @classes = ref $self->$k eq 'ARRAY' ? @{ $self->$k } : $self->$k;
826 $self->_validate_classes($k, \@classes);
830 sub _validate_result_component_map {
833 my $map = $self->result_component_map;
834 return unless $map && ref $map eq 'HASH';
836 foreach my $classes (values %$map) {
837 $self->_validate_classes('result_component_map', [@$classes]);
841 sub _validate_classes {
846 foreach my $c (@$classes) {
847 # components default to being under the DBIx::Class namespace unless they
848 # are preceeded with a '+'
849 if ( $key =~ m/component/ && $c !~ s/^\+// ) {
850 $c = 'DBIx::Class::' . $c;
853 # 1 == installed, 0 == not installed, undef == invalid classname
854 my $installed = Class::Inspector->installed($c);
855 if ( defined($installed) ) {
856 if ( $installed == 0 ) {
857 croak qq/$c, as specified in the loader option "$key", is not installed/;
860 croak qq/$c, as specified in the loader option "$key", is an invalid class name/;
866 sub _find_file_in_inc {
867 my ($self, $file) = @_;
869 foreach my $prefix (@INC) {
870 my $fullpath = File::Spec->catfile($prefix, $file);
871 return $fullpath if -f $fullpath
872 # abs_path throws on Windows for nonexistant files
873 and (try { Cwd::abs_path($fullpath) }) ne
874 ((try { Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) }) || '');
881 my ($self, $class) = @_;
883 my $class_path = $class;
884 $class_path =~ s{::}{/}g;
885 $class_path .= '.pm';
890 sub _find_class_in_inc {
891 my ($self, $class) = @_;
893 return $self->_find_file_in_inc($self->_class_path($class));
899 return $self->_upgrading_from
900 || $self->_upgrading_from_load_classes
901 || $self->_downgrading_to_load_classes
902 || $self->_rewriting_result_namespace
906 sub _rewrite_old_classnames {
907 my ($self, $code) = @_;
909 return $code unless $self->_rewriting;
911 my %old_classes = reverse %{ $self->_upgrading_classes };
913 my $re = join '|', keys %old_classes;
916 $code =~ s/$re/$old_classes{$1} || $1/eg;
922 my ($self, $class) = @_;
924 return if $self->{skip_load_external};
926 # so that we don't load our own classes, under any circumstances
927 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
929 my $real_inc_path = $self->_find_class_in_inc($class);
931 my $old_class = $self->_upgrading_classes->{$class}
932 if $self->_rewriting;
934 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
935 if $old_class && $old_class ne $class;
937 return unless $real_inc_path || $old_real_inc_path;
939 if ($real_inc_path) {
940 # If we make it to here, we loaded an external definition
941 warn qq/# Loaded external class definition for '$class'\n/
944 my $code = $self->_rewrite_old_classnames(scalar slurp $real_inc_path);
946 if ($self->dynamic) { # load the class too
947 eval_without_redefine_warnings($code);
950 $self->_ext_stmt($class,
951 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
952 .qq|# They are now part of the custom portion of this file\n|
953 .qq|# for you to hand-edit. If you do not either delete\n|
954 .qq|# this section or remove that file from \@INC, this section\n|
955 .qq|# will be repeated redundantly when you re-create this\n|
956 .qq|# file again via Loader! See skip_load_external to disable\n|
957 .qq|# this feature.\n|
960 $self->_ext_stmt($class, $code);
961 $self->_ext_stmt($class,
962 qq|# End of lines loaded from '$real_inc_path' |
966 if ($old_real_inc_path) {
967 my $code = slurp $old_real_inc_path;
969 $self->_ext_stmt($class, <<"EOF");
971 # These lines were loaded from '$old_real_inc_path',
972 # based on the Result class name that would have been created by an older
973 # version of the Loader. For a static schema, this happens only once during
974 # upgrade. See skip_load_external to disable this feature.
977 $code = $self->_rewrite_old_classnames($code);
979 if ($self->dynamic) {
982 Detected external content in '$old_real_inc_path', a class name that would have
983 been used by an older version of the Loader.
985 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
986 new name of the Result.
988 eval_without_redefine_warnings($code);
992 $self->_ext_stmt($class, $code);
993 $self->_ext_stmt($class,
994 qq|# End of lines loaded from '$old_real_inc_path' |
1001 Does the actual schema-construction work.
1008 $self->_load_tables(
1009 $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude })
1017 Rescan the database for changes. Returns a list of the newly added table
1020 The schema argument should be the schema class or object to be affected. It
1021 should probably be derived from the original schema_class used during L</load>.
1026 my ($self, $schema) = @_;
1028 $self->{schema} = $schema;
1029 $self->_relbuilder->{schema} = $schema;
1032 my @current = $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude });
1034 foreach my $table (@current) {
1035 if(!exists $self->{_tables}->{$table}) {
1036 push(@created, $table);
1041 @current{@current} = ();
1042 foreach my $table (keys %{ $self->{_tables} }) {
1043 if (not exists $current{$table}) {
1044 $self->_unregister_source_for_table($table);
1048 delete $self->{_dump_storage};
1049 delete $self->{_relations_started};
1051 my $loaded = $self->_load_tables(@current);
1053 return map { $self->monikers->{$_} } @created;
1059 return if $self->{skip_relationships};
1061 return $self->{relbuilder} ||= do {
1063 no warnings 'uninitialized';
1064 my $relbuilder_suff =
1070 ->{ $self->naming->{relationships}};
1072 my $relbuilder_class = 'DBIx::Class::Schema::Loader::RelBuilder'.$relbuilder_suff;
1073 $self->ensure_class_loaded($relbuilder_class);
1074 $relbuilder_class->new( $self );
1080 my ($self, @tables) = @_;
1082 # Save the new tables to the tables list
1084 $self->{_tables}->{$_} = 1;
1087 $self->_make_src_class($_) for @tables;
1089 # sanity-check for moniker clashes
1090 my $inverse_moniker_idx;
1091 for (keys %{$self->monikers}) {
1092 push @{$inverse_moniker_idx->{$self->monikers->{$_}}}, $_;
1096 for (keys %$inverse_moniker_idx) {
1097 my $tables = $inverse_moniker_idx->{$_};
1099 push @clashes, sprintf ("tables %s reduced to the same source moniker '%s'",
1100 join (', ', map { "'$_'" } @$tables),
1107 die 'Unable to load schema - chosen moniker/class naming style results in moniker clashes. '
1108 . 'Either change the naming style, or supply an explicit moniker_map: '
1109 . join ('; ', @clashes)
1115 $self->_setup_src_meta($_) for @tables;
1117 if(!$self->skip_relationships) {
1118 # The relationship loader needs a working schema
1120 local $self->{dump_directory} = $self->{temp_directory};
1121 $self->_reload_classes(\@tables);
1122 $self->_load_relationships($_) for @tables;
1123 $self->_relbuilder->cleanup;
1126 # Remove that temp dir from INC so it doesn't get reloaded
1127 @INC = grep $_ ne $self->dump_directory, @INC;
1130 $self->_load_external($_)
1131 for map { $self->classes->{$_} } @tables;
1133 # Reload without unloading first to preserve any symbols from external
1135 $self->_reload_classes(\@tables, { unload => 0 });
1137 # Drop temporary cache
1138 delete $self->{_cache};
1143 sub _reload_classes {
1144 my ($self, $tables, $opts) = @_;
1146 my @tables = @$tables;
1148 my $unload = $opts->{unload};
1149 $unload = 1 unless defined $unload;
1151 # so that we don't repeat custom sections
1152 @INC = grep $_ ne $self->dump_directory, @INC;
1154 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
1156 unshift @INC, $self->dump_directory;
1159 my %have_source = map { $_ => $self->schema->source($_) }
1160 $self->schema->sources;
1162 for my $table (@tables) {
1163 my $moniker = $self->monikers->{$table};
1164 my $class = $self->classes->{$table};
1167 no warnings 'redefine';
1168 local *Class::C3::reinitialize = sub {}; # to speed things up, reinitialized below
1171 if (my $mc = $self->_moose_metaclass($class)) {
1174 Class::Unload->unload($class) if $unload;
1175 my ($source, $resultset_class);
1177 ($source = $have_source{$moniker})
1178 && ($resultset_class = $source->resultset_class)
1179 && ($resultset_class ne 'DBIx::Class::ResultSet')
1181 my $has_file = Class::Inspector->loaded_filename($resultset_class);
1182 if (my $mc = $self->_moose_metaclass($resultset_class)) {
1185 Class::Unload->unload($resultset_class) if $unload;
1186 $self->_reload_class($resultset_class) if $has_file;
1188 $self->_reload_class($class);
1190 push @to_register, [$moniker, $class];
1193 Class::C3->reinitialize;
1194 for (@to_register) {
1195 $self->schema->register_class(@$_);
1199 sub _moose_metaclass {
1200 return undef unless $INC{'Class/MOP.pm'}; # if CMOP is not loaded the class could not have loaded in the 1st place
1204 my $mc = try { Class::MOP::class_of($class) }
1207 return $mc->isa('Moose::Meta::Class') ? $mc : undef;
1210 # We use this instead of ensure_class_loaded when there are package symbols we
1213 my ($self, $class) = @_;
1215 my $class_path = $self->_class_path($class);
1216 delete $INC{ $class_path };
1218 # kill redefined warnings
1220 eval_without_redefine_warnings ("require $class");
1223 my $source = slurp $self->_get_dump_filename($class);
1224 die "Failed to reload class $class: $_.\n\nCLASS SOURCE:\n\n$source";
1228 sub _get_dump_filename {
1229 my ($self, $class) = (@_);
1231 $class =~ s{::}{/}g;
1232 return $self->dump_directory . q{/} . $class . q{.pm};
1235 =head2 get_dump_filename
1239 Returns the full path to the file for a class that the class has been or will
1240 be dumped to. This is a file in a temp dir for a dynamic schema.
1244 sub get_dump_filename {
1245 my ($self, $class) = (@_);
1247 local $self->{dump_directory} = $self->real_dump_directory;
1249 return $self->_get_dump_filename($class);
1252 sub _ensure_dump_subdirs {
1253 my ($self, $class) = (@_);
1255 my @name_parts = split(/::/, $class);
1256 pop @name_parts; # we don't care about the very last element,
1257 # which is a filename
1259 my $dir = $self->dump_directory;
1262 mkdir($dir) or croak "mkdir('$dir') failed: $!";
1264 last if !@name_parts;
1265 $dir = File::Spec->catdir($dir, shift @name_parts);
1270 my ($self, @classes) = @_;
1272 my $schema_class = $self->schema_class;
1273 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
1275 my $target_dir = $self->dump_directory;
1276 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
1277 unless $self->{dynamic} or $self->{quiet};
1280 qq|package $schema_class;\n\n|
1281 . qq|# Created by DBIx::Class::Schema::Loader\n|
1282 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|;
1284 if ($self->use_moose) {
1285 $schema_text.= qq|use Moose;\nuse namespace::autoclean;\nextends '$schema_base_class';\n\n|;
1288 $schema_text .= qq|use strict;\nuse warnings;\n\nuse base '$schema_base_class';\n\n|;
1291 if ($self->use_namespaces) {
1292 $schema_text .= qq|__PACKAGE__->load_namespaces|;
1293 my $namespace_options;
1295 my @attr = qw/resultset_namespace default_resultset_class/;
1297 unshift @attr, 'result_namespace' unless (not $self->result_namespace) || $self->result_namespace eq 'Result';
1299 for my $attr (@attr) {
1301 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
1304 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
1305 $schema_text .= qq|;\n|;
1308 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
1312 local $self->{version_to_dump} = $self->schema_version_to_dump;
1313 $self->_write_classfile($schema_class, $schema_text, 1);
1316 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
1318 foreach my $src_class (@classes) {
1320 qq|package $src_class;\n\n|
1321 . qq|# Created by DBIx::Class::Schema::Loader\n|
1322 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
1323 . qq|use strict;\nuse warnings;\n\n|;
1324 if ($self->use_moose) {
1325 $src_text.= qq|use Moose;\nuse MooseX::NonMoose;\nuse namespace::autoclean;|;
1327 # these options 'use base' which is compile time
1328 if (@{ $self->left_base_classes } || @{ $self->additional_base_classes }) {
1329 $src_text .= qq|\nBEGIN { extends '$result_base_class' }\n\n|;
1332 $src_text .= qq|\nextends '$result_base_class';\n\n|;
1336 $src_text .= qq|use base '$result_base_class';\n\n|;
1338 $self->_write_classfile($src_class, $src_text);
1341 # remove Result dir if downgrading from use_namespaces, and there are no
1343 if (my $result_ns = $self->_downgrading_to_load_classes
1344 || $self->_rewriting_result_namespace) {
1345 my $result_namespace = $self->_result_namespace(
1350 (my $result_dir = $result_namespace) =~ s{::}{/}g;
1351 $result_dir = $self->dump_directory . '/' . $result_dir;
1353 unless (my @files = glob "$result_dir/*") {
1358 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
1363 my ($self, $version, $ts) = @_;
1364 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
1367 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
1370 sub _write_classfile {
1371 my ($self, $class, $text, $is_schema) = @_;
1373 my $filename = $self->_get_dump_filename($class);
1374 $self->_ensure_dump_subdirs($class);
1376 if (-f $filename && $self->really_erase_my_files) {
1377 warn "Deleting existing file '$filename' due to "
1378 . "'really_erase_my_files' setting\n" unless $self->{quiet};
1382 my ($old_gen, $old_md5, $old_ver, $old_ts, $old_custom)
1383 = $self->_parse_generated_file($filename);
1385 if (! $old_gen && -f $filename) {
1386 croak "Cannot overwrite '$filename' without 'really_erase_my_files',"
1387 . " it does not appear to have been generated by Loader"
1390 my $custom_content = $old_custom || '';
1392 # prepend extra custom content from a *renamed* class (singularization effect)
1393 if (my $renamed_class = $self->_upgrading_classes->{$class}) {
1394 my $old_filename = $self->_get_dump_filename($renamed_class);
1396 if (-f $old_filename) {
1397 my $extra_custom = ($self->_parse_generated_file ($old_filename))[4];
1399 $extra_custom =~ s/\n\n# You can replace.*\n1;\n//;
1401 $custom_content = join ("\n", '', $extra_custom, $custom_content)
1404 unlink $old_filename;
1408 $custom_content ||= $self->_default_custom_content($is_schema);
1410 # If upgrading to use_moose=1 replace default custom content with default Moose custom content.
1411 # If there is already custom content, which does not have the Moose content, add it.
1412 if ($self->use_moose) {
1414 my $non_moose_custom_content = do {
1415 local $self->{use_moose} = 0;
1416 $self->_default_custom_content;
1419 if ($custom_content eq $non_moose_custom_content) {
1420 $custom_content = $self->_default_custom_content($is_schema);
1422 elsif ($custom_content !~ /\Q@{[$self->_default_moose_custom_content($is_schema)]}\E/) {
1423 $custom_content .= $self->_default_custom_content($is_schema);
1426 elsif (defined $self->use_moose && $old_gen) {
1427 croak 'It is not possible to "downgrade" a schema that was loaded with use_moose => 1 to use_moose => 0, due to differing custom content'
1428 if $old_gen =~ /use \s+ MooseX?\b/x;
1431 $custom_content = $self->_rewrite_old_classnames($custom_content);
1434 for @{$self->{_dump_storage}->{$class} || []};
1436 # Check and see if the dump is infact differnt
1440 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
1441 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
1442 return unless $self->_upgrading_from && $is_schema;
1446 $text .= $self->_sig_comment(
1447 $self->version_to_dump,
1448 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
1451 open(my $fh, '>', $filename)
1452 or croak "Cannot open '$filename' for writing: $!";
1454 # Write the top half and its MD5 sum
1455 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
1457 # Write out anything loaded via external partial class file in @INC
1459 for @{$self->{_ext_storage}->{$class} || []};
1461 # Write out any custom content the user has added
1462 print $fh $custom_content;
1465 or croak "Error closing '$filename': $!";
1468 sub _default_moose_custom_content {
1469 my ($self, $is_schema) = @_;
1471 if (not $is_schema) {
1472 return qq|\n__PACKAGE__->meta->make_immutable;|;
1475 return qq|\n__PACKAGE__->meta->make_immutable(inline_constructor => 0);|;
1478 sub _default_custom_content {
1479 my ($self, $is_schema) = @_;
1480 my $default = qq|\n\n# You can replace this text with custom|
1481 . qq| code or comments, and it will be preserved on regeneration|;
1482 if ($self->use_moose) {
1483 $default .= $self->_default_moose_custom_content($is_schema);
1485 $default .= qq|\n1;\n|;
1489 sub _parse_generated_file {
1490 my ($self, $fn) = @_;
1492 return unless -f $fn;
1494 open(my $fh, '<', $fn)
1495 or croak "Cannot open '$fn' for reading: $!";
1498 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
1500 my ($md5, $ts, $ver, $gen);
1506 # Pull out the version and timestamp from the line above
1507 ($ver, $ts) = $gen =~ m/^# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)\Z/m;
1510 croak "Checksum mismatch in '$fn', 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"
1511 if !$self->overwrite_modifications && Digest::MD5::md5_base64($gen) ne $md5;
1520 my $custom = do { local $/; <$fh> }
1525 return ($gen, $md5, $ver, $ts, $custom);
1533 warn "$target: use $_;" if $self->debug;
1534 $self->_raw_stmt($target, "use $_;");
1542 my $blist = join(q{ }, @_);
1544 return unless $blist;
1546 warn "$target: use base qw/$blist/;" if $self->debug;
1547 $self->_raw_stmt($target, "use base qw/$blist/;");
1550 sub _result_namespace {
1551 my ($self, $schema_class, $ns) = @_;
1552 my @result_namespace;
1554 if ($ns =~ /^\+(.*)/) {
1555 # Fully qualified namespace
1556 @result_namespace = ($1)
1559 # Relative namespace
1560 @result_namespace = ($schema_class, $ns);
1563 return wantarray ? @result_namespace : join '::', @result_namespace;
1566 # Create class with applicable bases, setup monikers, etc
1567 sub _make_src_class {
1568 my ($self, $table) = @_;
1570 my $schema = $self->schema;
1571 my $schema_class = $self->schema_class;
1573 my $table_moniker = $self->_table2moniker($table);
1574 my @result_namespace = ($schema_class);
1575 if ($self->use_namespaces) {
1576 my $result_namespace = $self->result_namespace || 'Result';
1577 @result_namespace = $self->_result_namespace(
1582 my $table_class = join(q{::}, @result_namespace, $table_moniker);
1584 if ((my $upgrading_v = $self->_upgrading_from)
1585 || $self->_rewriting) {
1586 local $self->naming->{monikers} = $upgrading_v
1589 my @result_namespace = @result_namespace;
1590 if ($self->_upgrading_from_load_classes) {
1591 @result_namespace = ($schema_class);
1593 elsif (my $ns = $self->_downgrading_to_load_classes) {
1594 @result_namespace = $self->_result_namespace(
1599 elsif ($ns = $self->_rewriting_result_namespace) {
1600 @result_namespace = $self->_result_namespace(
1606 my $old_class = join(q{::}, @result_namespace,
1607 $self->_table2moniker($table));
1609 $self->_upgrading_classes->{$table_class} = $old_class
1610 unless $table_class eq $old_class;
1613 # this was a bad idea, should be ok now without it
1614 # my $table_normalized = lc $table;
1615 # $self->classes->{$table_normalized} = $table_class;
1616 # $self->monikers->{$table_normalized} = $table_moniker;
1618 $self->classes->{$table} = $table_class;
1619 $self->monikers->{$table} = $table_moniker;
1621 $self->_use ($table_class, @{$self->additional_classes});
1622 $self->_inject($table_class, @{$self->left_base_classes});
1624 my @components = @{ $self->components || [] };
1626 push @components, @{ $self->result_component_map->{$table_moniker} }
1627 if exists $self->result_component_map->{$table_moniker};
1629 $self->_dbic_stmt($table_class, 'load_components', @components) if @components;
1631 $self->_inject($table_class, @{$self->additional_base_classes});
1634 sub _is_result_class_method {
1635 my ($self, $name, $table_name) = @_;
1637 my $table_moniker = $table_name ? $self->_table2moniker($table_name) : '';
1639 if (not $self->_result_class_methods) {
1640 my (@methods, %methods);
1641 my $base = $self->result_base_class || 'DBIx::Class::Core';
1643 my @components = @{ $self->components || [] };
1645 push @components, @{ $self->result_component_map->{$table_moniker} }
1646 if exists $self->result_component_map->{$table_moniker};
1648 for my $c (@components) {
1649 $c = $c =~ /^\+/ ? substr($c,1) : "DBIx::Class::$c";
1652 for my $class ($base, @components, $self->use_moose ? 'Moose::Object' : ()) {
1653 $self->ensure_class_loaded($class);
1655 push @methods, @{ Class::Inspector->methods($class) || [] };
1658 push @methods, @{ Class::Inspector->methods('UNIVERSAL') };
1660 @methods{@methods} = ();
1662 $self->_result_class_methods(\%methods);
1664 my $result_methods = $self->_result_class_methods;
1666 return exists $result_methods->{$name};
1669 sub _resolve_col_accessor_collisions {
1670 my ($self, $table, $col_info) = @_;
1672 my $table_name = ref $table ? $$table : $table;
1674 while (my ($col, $info) = each %$col_info) {
1675 my $accessor = $info->{accessor} || $col;
1677 next if $accessor eq 'id'; # special case (very common column)
1679 if ($self->_is_result_class_method($accessor, $table_name)) {
1682 if (my $map = $self->col_collision_map) {
1683 for my $re (keys %$map) {
1684 if (my @matches = $col =~ /$re/) {
1685 $info->{accessor} = sprintf $map->{$re}, @matches;
1693 Column '$col' in table '$table_name' collides with an inherited method.
1694 See "COLUMN ACCESSOR COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
1696 $info->{accessor} = undef;
1702 # use the same logic to run moniker_map, col_accessor_map, and
1703 # relationship_name_map
1705 my ( $self, $map, $default_code, $ident, @extra ) = @_;
1707 my $default_ident = $default_code->( $ident, @extra );
1709 if( $map && ref $map eq 'HASH' ) {
1710 $new_ident = $map->{ $ident };
1712 elsif( $map && ref $map eq 'CODE' ) {
1713 $new_ident = $map->( $ident, $default_ident, @extra );
1716 $new_ident ||= $default_ident;
1721 sub _default_column_accessor_name {
1722 my ( $self, $column_name ) = @_;
1724 my $accessor_name = $column_name;
1725 $accessor_name =~ s/\W+/_/g;
1727 if ((($self->naming->{column_accessors}||'') =~ /(\d+)/ && $1 < 7) || (not $self->preserve_case)) {
1728 # older naming just lc'd the col accessor and that's all.
1729 return lc $accessor_name;
1732 return join '_', map lc, split_name $column_name;
1736 sub _make_column_accessor_name {
1737 my ($self, $column_name, $column_context_info ) = @_;
1739 my $accessor = $self->_run_user_map(
1740 $self->col_accessor_map,
1741 sub { $self->_default_column_accessor_name( shift ) },
1743 $column_context_info,
1749 # Set up metadata (cols, pks, etc)
1750 sub _setup_src_meta {
1751 my ($self, $table) = @_;
1753 my $schema = $self->schema;
1754 my $schema_class = $self->schema_class;
1756 my $table_class = $self->classes->{$table};
1757 my $table_moniker = $self->monikers->{$table};
1759 my $table_name = $table;
1760 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1762 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1763 $table_name = \ $self->_quote_table_name($table_name);
1766 my $full_table_name = ($self->qualify_objects ? ($self->db_schema . '.') : '') . (ref $table_name ? $$table_name : $table_name);
1768 # be careful to not create refs Data::Dump can "optimize"
1769 $full_table_name = \do {"".$full_table_name} if ref $table_name;
1771 $self->_dbic_stmt($table_class, 'table', $full_table_name);
1773 my $cols = $self->_table_columns($table);
1774 my $col_info = $self->__columns_info_for($table);
1776 ### generate all the column accessor names
1777 while (my ($col, $info) = each %$col_info) {
1778 # hashref of other info that could be used by
1779 # user-defined accessor map functions
1781 table_class => $table_class,
1782 table_moniker => $table_moniker,
1783 table_name => $table_name,
1784 full_table_name => $full_table_name,
1785 schema_class => $schema_class,
1786 column_info => $info,
1789 $info->{accessor} = $self->_make_column_accessor_name( $col, $context );
1792 $self->_resolve_col_accessor_collisions($full_table_name, $col_info);
1794 # prune any redundant accessor names
1795 while (my ($col, $info) = each %$col_info) {
1796 no warnings 'uninitialized';
1797 delete $info->{accessor} if $info->{accessor} eq $col;
1800 my $fks = $self->_table_fk_info($table);
1802 foreach my $fkdef (@$fks) {
1803 for my $col (@{ $fkdef->{local_columns} }) {
1804 $col_info->{$col}{is_foreign_key} = 1;
1808 my $pks = $self->_table_pk_info($table) || [];
1810 foreach my $pkcol (@$pks) {
1811 $col_info->{$pkcol}{is_nullable} = 0;
1817 map { $_, ($col_info->{$_}||{}) } @$cols
1820 my %uniq_tag; # used to eliminate duplicate uniqs
1822 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1823 : carp("$table has no primary key");
1824 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1826 my $uniqs = $self->_table_uniq_info($table) || [];
1828 my ($name, $cols) = @$_;
1829 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1830 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1835 sub __columns_info_for {
1836 my ($self, $table) = @_;
1838 my $result = $self->_columns_info_for($table);
1840 while (my ($col, $info) = each %$result) {
1841 $info = { %$info, %{ $self->_custom_column_info ($table, $col, $info) } };
1842 $info = { %$info, %{ $self->_datetime_column_info($table, $col, $info) } };
1844 $result->{$col} = $info;
1852 Returns a sorted list of loaded tables, using the original database table
1860 return keys %{$self->_tables};
1863 # Make a moniker from a table
1864 sub _default_table2moniker {
1865 no warnings 'uninitialized';
1866 my ($self, $table) = @_;
1868 if ($self->naming->{monikers} eq 'v4') {
1869 return join '', map ucfirst, split /[\W_]+/, lc $table;
1871 elsif ($self->naming->{monikers} eq 'v5') {
1872 return join '', map ucfirst, split /[\W_]+/,
1873 Lingua::EN::Inflect::Number::to_S(lc $table);
1875 elsif ($self->naming->{monikers} eq 'v6') {
1876 (my $as_phrase = lc $table) =~ s/_+/ /g;
1877 my $inflected = Lingua::EN::Inflect::Phrase::to_S($as_phrase);
1879 return join '', map ucfirst, split /\W+/, $inflected;
1882 my @words = map lc, split_name $table;
1883 my $as_phrase = join ' ', @words;
1885 my $inflected = Lingua::EN::Inflect::Phrase::to_S($as_phrase);
1887 return join '', map ucfirst, split /\W+/, $inflected;
1890 sub _table2moniker {
1891 my ( $self, $table ) = @_;
1893 $self->_run_user_map(
1895 sub { $self->_default_table2moniker( shift ) },
1900 sub _load_relationships {
1901 my ($self, $table) = @_;
1903 my $tbl_fk_info = $self->_table_fk_info($table);
1904 foreach my $fkdef (@$tbl_fk_info) {
1905 $fkdef->{remote_source} =
1906 $self->monikers->{delete $fkdef->{remote_table}};
1908 my $tbl_uniq_info = $self->_table_uniq_info($table);
1910 my $local_moniker = $self->monikers->{$table};
1911 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1913 foreach my $src_class (sort keys %$rel_stmts) {
1914 my $src_stmts = $rel_stmts->{$src_class};
1915 foreach my $stmt (@$src_stmts) {
1916 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1921 # Overload these in driver class:
1923 # Returns an arrayref of column names
1924 sub _table_columns { croak "ABSTRACT METHOD" }
1926 # Returns arrayref of pk col names
1927 sub _table_pk_info { croak "ABSTRACT METHOD" }
1929 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1930 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1932 # Returns an arrayref of foreign key constraints, each
1933 # being a hashref with 3 keys:
1934 # local_columns (arrayref), remote_columns (arrayref), remote_table
1935 sub _table_fk_info { croak "ABSTRACT METHOD" }
1937 # Returns an array of lower case table names
1938 sub _tables_list { croak "ABSTRACT METHOD" }
1940 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1946 # generate the pod for this statement, storing it with $self->_pod
1947 $self->_make_pod( $class, $method, @_ ) if $self->generate_pod;
1949 my $args = dump(@_);
1950 $args = '(' . $args . ')' if @_ < 2;
1951 my $stmt = $method . $args . q{;};
1953 warn qq|$class\->$stmt\n| if $self->debug;
1954 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1958 # generates the accompanying pod for a DBIC class method statement,
1959 # storing it with $self->_pod
1965 if ( $method eq 'table' ) {
1967 my $pcm = $self->pod_comment_mode;
1968 my ($comment, $comment_overflows, $comment_in_name, $comment_in_desc);
1969 $comment = $self->__table_comment($table);
1970 $comment_overflows = ($comment and length $comment > $self->pod_comment_spillover_length);
1971 $comment_in_name = ($pcm eq 'name' or ($pcm eq 'auto' and !$comment_overflows));
1972 $comment_in_desc = ($pcm eq 'description' or ($pcm eq 'auto' and $comment_overflows));
1973 $self->_pod( $class, "=head1 NAME" );
1974 my $table_descr = $class;
1975 $table_descr .= " - " . $comment if $comment and $comment_in_name;
1976 $self->{_class2table}{ $class } = $table;
1977 $self->_pod( $class, $table_descr );
1978 if ($comment and $comment_in_desc) {
1979 $self->_pod( $class, "=head1 DESCRIPTION" );
1980 $self->_pod( $class, $comment );
1982 $self->_pod_cut( $class );
1983 } elsif ( $method eq 'add_columns' ) {
1984 $self->_pod( $class, "=head1 ACCESSORS" );
1985 my $col_counter = 0;
1987 while( my ($name,$attrs) = splice @cols,0,2 ) {
1989 $self->_pod( $class, '=head2 ' . $name );
1990 $self->_pod( $class,
1992 my $s = $attrs->{$_};
1993 $s = !defined $s ? 'undef' :
1994 length($s) == 0 ? '(empty string)' :
1995 ref($s) eq 'SCALAR' ? $$s :
1996 ref($s) ? dumper_squashed $s :
1997 looks_like_number($s) ? $s : qq{'$s'};
2000 } sort keys %$attrs,
2002 if (my $comment = $self->__column_comment($self->{_class2table}{$class}, $col_counter, $name)) {
2003 $self->_pod( $class, $comment );
2006 $self->_pod_cut( $class );
2007 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
2008 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
2009 my ( $accessor, $rel_class ) = @_;
2010 $self->_pod( $class, "=head2 $accessor" );
2011 $self->_pod( $class, 'Type: ' . $method );
2012 $self->_pod( $class, "Related object: L<$rel_class>" );
2013 $self->_pod_cut( $class );
2014 $self->{_relations_started} { $class } = 1;
2018 sub _filter_comment {
2019 my ($self, $txt) = @_;
2021 $txt = '' if not defined $txt;
2023 $txt =~ s/(?:\015?\012|\015\012?)/\n/g;
2028 sub __table_comment {
2031 if (my $code = $self->can('_table_comment')) {
2032 return $self->_filter_comment($self->$code(@_));
2038 sub __column_comment {
2041 if (my $code = $self->can('_column_comment')) {
2042 return $self->_filter_comment($self->$code(@_));
2048 # Stores a POD documentation
2050 my ($self, $class, $stmt) = @_;
2051 $self->_raw_stmt( $class, "\n" . $stmt );
2055 my ($self, $class ) = @_;
2056 $self->_raw_stmt( $class, "\n=cut\n" );
2059 # Store a raw source line for a class (for dumping purposes)
2061 my ($self, $class, $stmt) = @_;
2062 push(@{$self->{_dump_storage}->{$class}}, $stmt);
2065 # Like above, but separately for the externally loaded stuff
2067 my ($self, $class, $stmt) = @_;
2068 push(@{$self->{_ext_storage}->{$class}}, $stmt);
2071 sub _quote_table_name {
2072 my ($self, $table) = @_;
2074 my $qt = $self->schema->storage->sql_maker->quote_char;
2076 return $table unless $qt;
2079 return $qt->[0] . $table . $qt->[1];
2082 return $qt . $table . $qt;
2085 sub _custom_column_info {
2086 my ( $self, $table_name, $column_name, $column_info ) = @_;
2088 if (my $code = $self->custom_column_info) {
2089 return $code->($table_name, $column_name, $column_info) || {};
2094 sub _datetime_column_info {
2095 my ( $self, $table_name, $column_name, $column_info ) = @_;
2097 my $type = $column_info->{data_type} || '';
2098 if ((grep $_, @{ $column_info }{map "inflate_$_", qw/date datetime timestamp/})
2099 or ($type =~ /date|timestamp/i)) {
2100 $result->{timezone} = $self->datetime_timezone if $self->datetime_timezone;
2101 $result->{locale} = $self->datetime_locale if $self->datetime_locale;
2107 my ($self, $name) = @_;
2109 return $self->preserve_case ? $name : lc($name);
2113 my ($self, $name) = @_;
2115 return $self->preserve_case ? $name : uc($name);
2118 sub _unregister_source_for_table {
2119 my ($self, $table) = @_;
2123 my $schema = $self->schema;
2124 # in older DBIC it's a private method
2125 my $unregister = $schema->can('unregister_source') || $schema->can('_unregister_source');
2126 $schema->$unregister($self->_table2moniker($table));
2127 delete $self->monikers->{$table};
2128 delete $self->classes->{$table};
2129 delete $self->_upgrading_classes->{$table};
2130 delete $self->{_tables}{$table};
2134 # remove the dump dir from @INC on destruction
2138 @INC = grep $_ ne $self->dump_directory, @INC;
2143 Returns a hashref of loaded table to moniker mappings. There will
2144 be two entries for each table, the original name and the "normalized"
2145 name, in the case that the two are different (such as databases
2146 that like uppercase table names, or preserve your original mixed-case
2147 definitions, or what-have-you).
2151 Returns a hashref of table to class mappings. In some cases it will
2152 contain multiple entries per table for the original and normalized table
2153 names, as above in L</monikers>.
2155 =head1 COLUMN ACCESSOR COLLISIONS
2157 Occasionally you may have a column name that collides with a perl method, such
2158 as C<can>. In such cases, the default action is to set the C<accessor> of the
2159 column spec to C<undef>.
2161 You can then name the accessor yourself by placing code such as the following
2164 __PACKAGE__->add_column('+can' => { accessor => 'my_can' });
2166 Another option is to use the L</col_collision_map> option.
2168 =head1 RELATIONSHIP NAME COLLISIONS
2170 In very rare cases, you may get a collision between a generated relationship
2171 name and a method in your Result class, for example if you have a foreign key
2172 called C<belongs_to>.
2174 This is a problem because relationship names are also relationship accessor
2175 methods in L<DBIx::Class>.
2177 The default behavior is to append C<_rel> to the relationship name and print
2178 out a warning that refers to this text.
2180 You can also control the renaming with the L</rel_collision_map> option.
2184 L<DBIx::Class::Schema::Loader>
2188 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
2192 This library is free software; you can redistribute it and/or modify it under
2193 the same terms as Perl itself.
2198 # vim:et sts=4 sw=4 tw=0: