add test (and fix) for loading external custom content from unsingularized results...
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / Base.pm
1 package DBIx::Class::Schema::Loader::Base;
2
3 use strict;
4 use warnings;
5 use base qw/Class::Accessor::Grouped Class::C3::Componentised/;
6 use Class::C3;
7 use Carp::Clan qw/^DBIx::Class/;
8 use DBIx::Class::Schema::Loader::RelBuilder;
9 use Data::Dump qw/ dump /;
10 use POSIX qw//;
11 use File::Spec qw//;
12 use Cwd qw//;
13 use Digest::MD5 qw//;
14 use Lingua::EN::Inflect::Number qw//;
15 use File::Temp qw//;
16 use Class::Unload;
17 require DBIx::Class;
18
19 our $VERSION = '0.04999_12';
20
21 __PACKAGE__->mk_group_ro_accessors('simple', qw/
22                                 schema
23                                 schema_class
24
25                                 exclude
26                                 constraint
27                                 additional_classes
28                                 additional_base_classes
29                                 left_base_classes
30                                 components
31                                 resultset_components
32                                 skip_relationships
33                                 skip_load_external
34                                 moniker_map
35                                 inflect_singular
36                                 inflect_plural
37                                 debug
38                                 dump_directory
39                                 dump_overwrite
40                                 really_erase_my_files
41                                 use_namespaces
42                                 result_namespace
43                                 resultset_namespace
44                                 default_resultset_class
45                                 schema_base_class
46                                 result_base_class
47                                 overwrite_modifications
48
49                                 relationship_attrs
50
51                                 db_schema
52                                 _tables
53                                 classes
54                                 _upgrading_classes
55                                 monikers
56                                 dynamic
57                                 naming
58 /);
59
60
61 __PACKAGE__->mk_group_accessors('simple', qw/
62                                 version_to_dump
63                                 schema_version_to_dump
64                                 _upgrading_from
65 /);
66
67 =head1 NAME
68
69 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
70
71 =head1 SYNOPSIS
72
73 See L<DBIx::Class::Schema::Loader>
74
75 =head1 DESCRIPTION
76
77 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
78 classes, and implements the common functionality between them.
79
80 =head1 CONSTRUCTOR OPTIONS
81
82 These constructor options are the base options for
83 L<DBIx::Class::Schema::Loader/loader_options>.  Available constructor options are:
84
85 =head2 skip_relationships
86
87 Skip setting up relationships.  The default is to attempt the loading
88 of relationships.
89
90 =head2 skip_load_external
91
92 Skip loading of other classes in @INC. The default is to merge all other classes
93 with the same name found in @INC into the schema file we are creating.
94
95 =head2 naming
96
97 Static schemas (ones dumped to disk) will, by default, use the new-style 0.05XXX
98 relationship names and singularized Results, unless you're overwriting an
99 existing dump made by a 0.04XXX version of L<DBIx::Class::Schema::Loader>, in
100 which case the backward compatible RelBuilder will be activated, and
101 singularization will be turned off.
102
103 Specifying
104
105     naming => 'v5'
106
107 will disable the backward-compatible RelBuilder and use
108 the new-style relationship names along with singularized Results, even when
109 overwriting a dump made with an earlier version.
110
111 The option also takes a hashref:
112
113     naming => { relationships => 'v5', monikers => 'v4' }
114
115 The keys are:
116
117 =over 4
118
119 =item relationships
120
121 How to name relationship accessors.
122
123 =item monikers
124
125 How to name Result classes.
126
127 =back
128
129 The values can be:
130
131 =over 4
132
133 =item current
134
135 Latest default style, whatever that happens to be.
136
137 =item v5
138
139 Version 0.05XXX style.
140
141 =item v4
142
143 Version 0.04XXX style.
144
145 =back
146
147 Dynamic schemas will always default to the 0.04XXX relationship names and won't
148 singularize Results for backward compatibility, to activate the new RelBuilder
149 and singularization put this in your C<Schema.pm> file:
150
151     __PACKAGE__->naming('current');
152
153 Or if you prefer to use 0.05XXX features but insure that nothing breaks in the
154 next major version upgrade:
155
156     __PACKAGE__->naming('v5');
157
158 =head2 relationship_attrs
159
160 Hashref of attributes to pass to each generated relationship, listed
161 by type.  Also supports relationship type 'all', containing options to
162 pass to all generated relationships.  Attributes set for more specific
163 relationship types override those set in 'all'.
164
165 For example:
166
167   relationship_attrs => {
168     all      => { cascade_delete => 0 },
169     has_many => { cascade_delete => 1 },
170   },
171
172 will set the C<cascade_delete> option to 0 for all generated relationships,
173 except for C<has_many>, which will have cascade_delete as 1.
174
175 NOTE: this option is not supported if v4 backward-compatible naming is
176 set either globally (naming => 'v4') or just for relationships.
177
178 =head2 debug
179
180 If set to true, each constructive L<DBIx::Class> statement the loader
181 decides to execute will be C<warn>-ed before execution.
182
183 =head2 db_schema
184
185 Set the name of the schema to load (schema in the sense that your database
186 vendor means it).  Does not currently support loading more than one schema
187 name.
188
189 =head2 constraint
190
191 Only load tables matching regex.  Best specified as a qr// regex.
192
193 =head2 exclude
194
195 Exclude tables matching regex.  Best specified as a qr// regex.
196
197 =head2 moniker_map
198
199 Overrides the default table name to moniker translation.  Can be either
200 a hashref of table keys and moniker values, or a coderef for a translator
201 function taking a single scalar table name argument and returning
202 a scalar moniker.  If the hash entry does not exist, or the function
203 returns a false value, the code falls back to default behavior
204 for that table name.
205
206 The default behavior is to singularize the table name, and: C<join '', map
207 ucfirst, split /[\W_]+/, lc $table>, which is to say: lowercase everything,
208 split up the table name into chunks anywhere a non-alpha-numeric character
209 occurs, change the case of first letter of each chunk to upper case, and put
210 the chunks back together.  Examples:
211
212     Table Name  | Moniker Name
213     ---------------------------
214     luser       | Luser
215     luser_group | LuserGroup
216     luser-opts  | LuserOpts
217
218 =head2 inflect_plural
219
220 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
221 if hash key does not exist or coderef returns false), but acts as a map
222 for pluralizing relationship names.  The default behavior is to utilize
223 L<Lingua::EN::Inflect::Number/to_PL>.
224
225 =head2 inflect_singular
226
227 As L</inflect_plural> above, but for singularizing relationship names.
228 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
229
230 =head2 schema_base_class
231
232 Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
233
234 =head2 result_base_class
235
236 Base class for your table classes (aka result classes). Defaults to
237 'DBIx::Class::Core'.
238
239 =head2 additional_base_classes
240
241 List of additional base classes all of your table classes will use.
242
243 =head2 left_base_classes
244
245 List of additional base classes all of your table classes will use
246 that need to be leftmost.
247
248 =head2 additional_classes
249
250 List of additional classes which all of your table classes will use.
251
252 =head2 components
253
254 List of additional components to be loaded into all of your table
255 classes.  A good example would be C<ResultSetManager>.
256
257 =head2 resultset_components
258
259 List of additional ResultSet components to be loaded into your table
260 classes.  A good example would be C<AlwaysRS>.  Component
261 C<ResultSetManager> will be automatically added to the above
262 C<components> list if this option is set.
263
264 =head2 use_namespaces
265
266 Generate result class names suitable for
267 L<DBIx::Class::Schema/load_namespaces> and call that instead of
268 L<DBIx::Class::Schema/load_classes>. When using this option you can also
269 specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
270 C<resultset_namespace>, C<default_resultset_class>), and they will be added
271 to the call (and the generated result class names adjusted appropriately).
272
273 =head2 dump_directory
274
275 This option is designed to be a tool to help you transition from this
276 loader to a manually-defined schema when you decide it's time to do so.
277
278 The value of this option is a perl libdir pathname.  Within
279 that directory this module will create a baseline manual
280 L<DBIx::Class::Schema> module set, based on what it creates at runtime
281 in memory.
282
283 The created schema class will have the same classname as the one on
284 which you are setting this option (and the ResultSource classes will be
285 based on this name as well).
286
287 Normally you wouldn't hard-code this setting in your schema class, as it
288 is meant for one-time manual usage.
289
290 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
291 recommended way to access this functionality.
292
293 =head2 dump_overwrite
294
295 Deprecated.  See L</really_erase_my_files> below, which does *not* mean
296 the same thing as the old C<dump_overwrite> setting from previous releases.
297
298 =head2 really_erase_my_files
299
300 Default false.  If true, Loader will unconditionally delete any existing
301 files before creating the new ones from scratch when dumping a schema to disk.
302
303 The default behavior is instead to only replace the top portion of the
304 file, up to and including the final stanza which contains
305 C<# DO NOT MODIFY THIS OR ANYTHING ABOVE!>
306 leaving any customizations you placed after that as they were.
307
308 When C<really_erase_my_files> is not set, if the output file already exists,
309 but the aforementioned final stanza is not found, or the checksum
310 contained there does not match the generated contents, Loader will
311 croak and not touch the file.
312
313 You should really be using version control on your schema classes (and all
314 of the rest of your code for that matter).  Don't blame me if a bug in this
315 code wipes something out when it shouldn't have, you've been warned.
316
317 =head2 overwrite_modifications
318
319 Default false.  If false, when updating existing files, Loader will
320 refuse to modify any Loader-generated code that has been modified
321 since its last run (as determined by the checksum Loader put in its
322 comment lines).
323
324 If true, Loader will discard any manual modifications that have been
325 made to Loader-generated code.
326
327 Again, you should be using version control on your schema classes.  Be
328 careful with this option.
329
330 =head1 METHODS
331
332 None of these methods are intended for direct invocation by regular
333 users of L<DBIx::Class::Schema::Loader>.  Anything you can find here
334 can also be found via standard L<DBIx::Class::Schema> methods somehow.
335
336 =cut
337
338 use constant CURRENT_V => 'v5';
339
340 # ensure that a peice of object data is a valid arrayref, creating
341 # an empty one or encapsulating whatever's there.
342 sub _ensure_arrayref {
343     my $self = shift;
344
345     foreach (@_) {
346         $self->{$_} ||= [];
347         $self->{$_} = [ $self->{$_} ]
348             unless ref $self->{$_} eq 'ARRAY';
349     }
350 }
351
352 =head2 new
353
354 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
355 by L<DBIx::Class::Schema::Loader>.
356
357 =cut
358
359 sub new {
360     my ( $class, %args ) = @_;
361
362     my $self = { %args };
363
364     bless $self => $class;
365
366     $self->_ensure_arrayref(qw/additional_classes
367                                additional_base_classes
368                                left_base_classes
369                                components
370                                resultset_components
371                               /);
372
373     push(@{$self->{components}}, 'ResultSetManager')
374         if @{$self->{resultset_components}};
375
376     $self->{monikers} = {};
377     $self->{classes} = {};
378     $self->{_upgrading_classes} = {};
379
380     $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
381     $self->{schema} ||= $self->{schema_class};
382
383     croak "dump_overwrite is deprecated.  Please read the"
384         . " DBIx::Class::Schema::Loader::Base documentation"
385             if $self->{dump_overwrite};
386
387     $self->{dynamic} = ! $self->{dump_directory};
388     $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
389                                                      TMPDIR  => 1,
390                                                      CLEANUP => 1,
391                                                    );
392
393     $self->{dump_directory} ||= $self->{temp_directory};
394
395     $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
396     $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
397
398     if ((not ref $self->naming) && defined $self->naming) {
399         my $naming_ver = $self->naming;
400         $self->{naming} = {
401             relationships => $naming_ver,
402             monikers => $naming_ver,
403         };
404     }
405
406     if ($self->naming) {
407         for (values %{ $self->naming }) {
408             $_ = CURRENT_V if $_ eq 'current';
409         }
410     }
411     $self->{naming} ||= {};
412
413     $self->_check_back_compat;
414
415     $self;
416 }
417
418 sub _check_back_compat {
419     my ($self) = @_;
420
421 # dynamic schemas will always be in 0.04006 mode, unless overridden
422     if ($self->dynamic) {
423 # just in case, though no one is likely to dump a dynamic schema
424         $self->schema_version_to_dump('0.04006');
425
426         if (not %{ $self->naming }) {
427             warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
428
429 Dynamic schema detected, will run in 0.04006 mode.
430
431 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
432 to disable this warning.
433
434 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
435 details.
436 EOF
437         }
438         else {
439             $self->_upgrading_from('v4');
440         }
441
442         $self->naming->{relationships} ||= 'v4';
443         $self->naming->{monikers}      ||= 'v4';
444
445         return;
446     }
447
448 # otherwise check if we need backcompat mode for a static schema
449     my $filename = $self->_get_dump_filename($self->schema_class);
450     return unless -e $filename;
451
452     open(my $fh, '<', $filename)
453         or croak "Cannot open '$filename' for reading: $!";
454
455     while (<$fh>) {
456         if (/^# Created by DBIx::Class::Schema::Loader v((\d+)\.(\d+))/) {
457             my $real_ver = $1;
458
459             # XXX when we go past .0 this will need fixing
460             my ($v) = $real_ver =~ /([1-9])/;
461             $v = "v$v";
462
463             last if $v eq CURRENT_V || $real_ver =~ /^0\.04999/;
464
465             if (not %{ $self->naming }) {
466                 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
467
468 Version $real_ver static schema detected, turning on backcompat mode.
469
470 Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
471 to disable this warning.
472
473 See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
474 details.
475 EOF
476             }
477             else {
478                 $self->_upgrading_from($v);
479             }
480
481             $self->naming->{relationships} ||= $v;
482             $self->naming->{monikers}      ||= $v;
483
484             $self->schema_version_to_dump($real_ver);
485
486             last;
487         }
488     }
489     close $fh;
490 }
491
492 sub _find_file_in_inc {
493     my ($self, $file) = @_;
494
495     foreach my $prefix (@INC) {
496         my $fullpath = File::Spec->catfile($prefix, $file);
497         return $fullpath if -f $fullpath
498             and Cwd::abs_path($fullpath) ne
499                (Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) || '');
500     }
501
502     return;
503 }
504
505 sub _class_path {
506     my ($self, $class) = @_;
507
508     my $class_path = $class;
509     $class_path =~ s{::}{/}g;
510     $class_path .= '.pm';
511
512     return $class_path;
513 }
514
515 sub _find_class_in_inc {
516     my ($self, $class) = @_;
517
518     return $self->_find_file_in_inc($self->_class_path($class));
519 }
520
521 sub _load_external {
522     my ($self, $class) = @_;
523
524     return if $self->{skip_load_external};
525
526     # so that we don't load our own classes, under any circumstances
527     local *INC = [ grep $_ ne $self->dump_directory, @INC ];
528
529     my $real_inc_path = $self->_find_class_in_inc($class);
530
531     my $old_class = $self->_upgrading_classes->{$class}
532         if $self->_upgrading_from;
533
534     my $old_real_inc_path = $self->_find_class_in_inc($old_class)
535         if $old_class && $old_class ne $class;
536
537     return unless $real_inc_path || $old_real_inc_path;
538
539     if ($real_inc_path) {
540         # If we make it to here, we loaded an external definition
541         warn qq/# Loaded external class definition for '$class'\n/
542             if $self->debug;
543
544         open(my $fh, '<', $real_inc_path)
545             or croak "Failed to open '$real_inc_path' for reading: $!";
546         $self->_ext_stmt($class,
547           qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
548          .qq|# They are now part of the custom portion of this file\n|
549          .qq|# for you to hand-edit.  If you do not either delete\n|
550          .qq|# this section or remove that file from \@INC, this section\n|
551          .qq|# will be repeated redundantly when you re-create this\n|
552          .qq|# file again via Loader!\n|
553         );
554         while(<$fh>) {
555             chomp;
556             $self->_ext_stmt($class, $_);
557         }
558         $self->_ext_stmt($class,
559             qq|# End of lines loaded from '$real_inc_path' |
560         );
561         close($fh)
562             or croak "Failed to close $real_inc_path: $!";
563
564         if ($self->dynamic) { # load the class too
565             # kill redefined warnings
566             my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
567             local $SIG{__WARN__} = sub {
568                 $warn_handler->(@_)
569                     unless $_[0] =~ /^Subroutine \S+ redefined/;
570             };
571             do $real_inc_path;
572             die $@ if $@;
573         }
574     }
575
576     if ($old_real_inc_path) {
577         open(my $fh, '<', $old_real_inc_path)
578             or croak "Failed to open '$old_real_inc_path' for reading: $!";
579         $self->_ext_stmt($class, <<"EOF");
580
581 # These lines were loaded from '$old_real_inc_path',
582 # based on the Result class name that would have been created by an 0.04006
583 # version of the Loader. For a static schema, this happens only once during
584 # upgrade.
585 EOF
586         if ($self->dynamic) {
587             warn <<"EOF";
588
589 Detected external content in '$old_real_inc_path', a class name that would have
590 been used by an 0.04006 version of the Loader.
591
592 * PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
593 new name of the Result.
594 EOF
595             # kill redefined warnings
596             my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
597             local $SIG{__WARN__} = sub {
598                 $warn_handler->(@_)
599                     unless $_[0] =~ /^Subroutine \S+ redefined/;
600             };
601             my $code = do {
602                 local ($/, @ARGV) = (undef, $old_real_inc_path); <>
603             };
604             $code =~ s/$old_class/$class/g;
605             eval $code;
606             die $@ if $@;
607         }
608
609         while(<$fh>) {
610             chomp;
611             s/$old_class/$class/g;
612             $self->_ext_stmt($class, $_);
613         }
614         $self->_ext_stmt($class,
615             qq|# End of lines loaded from '$old_real_inc_path' |
616         );
617
618         close($fh)
619             or croak "Failed to close $old_real_inc_path: $!";
620     }
621 }
622
623 =head2 load
624
625 Does the actual schema-construction work.
626
627 =cut
628
629 sub load {
630     my $self = shift;
631
632     $self->_load_tables($self->_tables_list);
633 }
634
635 =head2 rescan
636
637 Arguments: schema
638
639 Rescan the database for newly added tables.  Does
640 not process drops or changes.  Returns a list of
641 the newly added table monikers.
642
643 The schema argument should be the schema class
644 or object to be affected.  It should probably
645 be derived from the original schema_class used
646 during L</load>.
647
648 =cut
649
650 sub rescan {
651     my ($self, $schema) = @_;
652
653     $self->{schema} = $schema;
654     $self->_relbuilder->{schema} = $schema;
655
656     my @created;
657     my @current = $self->_tables_list;
658     foreach my $table ($self->_tables_list) {
659         if(!exists $self->{_tables}->{$table}) {
660             push(@created, $table);
661         }
662     }
663
664     my $loaded = $self->_load_tables(@created);
665
666     return map { $self->monikers->{$_} } @$loaded;
667 }
668
669 sub _relbuilder {
670     no warnings 'uninitialized';
671     my ($self) = @_;
672
673     return if $self->{skip_relationships};
674
675     if ($self->naming->{relationships} eq 'v4') {
676         require DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040;
677         return $self->{relbuilder} ||=
678             DBIx::Class::Schema::Loader::RelBuilder::Compat::v0_040->new(
679                 $self->schema, $self->inflect_plural, $self->inflect_singular
680             );
681     }
682
683     $self->{relbuilder} ||= DBIx::Class::Schema::Loader::RelBuilder->new (
684          $self->schema,
685          $self->inflect_plural,
686          $self->inflect_singular,
687          $self->relationship_attrs,
688     );
689 }
690
691 sub _load_tables {
692     my ($self, @tables) = @_;
693
694     # First, use _tables_list with constraint and exclude
695     #  to get a list of tables to operate on
696
697     my $constraint   = $self->constraint;
698     my $exclude      = $self->exclude;
699
700     @tables = grep { /$constraint/ } @tables if $constraint;
701     @tables = grep { ! /$exclude/ } @tables if $exclude;
702
703     # Save the new tables to the tables list
704     foreach (@tables) {
705         $self->{_tables}->{$_} = 1;
706     }
707
708     $self->_make_src_class($_) for @tables;
709     $self->_setup_src_meta($_) for @tables;
710
711     if(!$self->skip_relationships) {
712         # The relationship loader needs a working schema
713         $self->{quiet} = 1;
714         local $self->{dump_directory} = $self->{temp_directory};
715         $self->_reload_classes(\@tables);
716         $self->_load_relationships($_) for @tables;
717         $self->{quiet} = 0;
718
719         # Remove that temp dir from INC so it doesn't get reloaded
720         @INC = grep $_ ne $self->dump_directory, @INC;
721     }
722
723     $self->_load_external($_)
724         for map { $self->classes->{$_} } @tables;
725
726     # Reload without unloading first to preserve any symbols from external
727     # packages.
728     $self->_reload_classes(\@tables, 0);
729
730     # Drop temporary cache
731     delete $self->{_cache};
732
733     return \@tables;
734 }
735
736 sub _reload_classes {
737     my ($self, $tables, $unload) = @_;
738
739     my @tables = @$tables;
740     $unload = 1 unless defined $unload;
741
742     # so that we don't repeat custom sections
743     @INC = grep $_ ne $self->dump_directory, @INC;
744
745     $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
746
747     unshift @INC, $self->dump_directory;
748     
749     my @to_register;
750     my %have_source = map { $_ => $self->schema->source($_) }
751         $self->schema->sources;
752
753     for my $table (@tables) {
754         my $moniker = $self->monikers->{$table};
755         my $class = $self->classes->{$table};
756         
757         {
758             no warnings 'redefine';
759             local *Class::C3::reinitialize = sub {};
760             use warnings;
761
762             Class::Unload->unload($class) if $unload;
763             my ($source, $resultset_class);
764             if (
765                 ($source = $have_source{$moniker})
766                 && ($resultset_class = $source->resultset_class)
767                 && ($resultset_class ne 'DBIx::Class::ResultSet')
768             ) {
769                 my $has_file = Class::Inspector->loaded_filename($resultset_class);
770                 Class::Unload->unload($resultset_class) if $unload;
771                 $self->_reload_class($resultset_class) if $has_file;
772             }
773             $self->_reload_class($class);
774         }
775         push @to_register, [$moniker, $class];
776     }
777
778     Class::C3->reinitialize;
779     for (@to_register) {
780         $self->schema->register_class(@$_);
781     }
782 }
783
784 # We use this instead of ensure_class_loaded when there are package symbols we
785 # want to preserve.
786 sub _reload_class {
787     my ($self, $class) = @_;
788
789     my $class_path = $self->_class_path($class);
790     delete $INC{ $class_path };
791
792 # kill redefined warnings
793     my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
794     local $SIG{__WARN__} = sub {
795         $warn_handler->(@_)
796             unless $_[0] =~ /^Subroutine \S+ redefined/;
797     };
798     eval "require $class;";
799 }
800
801 sub _get_dump_filename {
802     my ($self, $class) = (@_);
803
804     $class =~ s{::}{/}g;
805     return $self->dump_directory . q{/} . $class . q{.pm};
806 }
807
808 sub _ensure_dump_subdirs {
809     my ($self, $class) = (@_);
810
811     my @name_parts = split(/::/, $class);
812     pop @name_parts; # we don't care about the very last element,
813                      # which is a filename
814
815     my $dir = $self->dump_directory;
816     while (1) {
817         if(!-d $dir) {
818             mkdir($dir) or croak "mkdir('$dir') failed: $!";
819         }
820         last if !@name_parts;
821         $dir = File::Spec->catdir($dir, shift @name_parts);
822     }
823 }
824
825 sub _dump_to_dir {
826     my ($self, @classes) = @_;
827
828     my $schema_class = $self->schema_class;
829     my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
830
831     my $target_dir = $self->dump_directory;
832     warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
833         unless $self->{dynamic} or $self->{quiet};
834
835     my $schema_text =
836           qq|package $schema_class;\n\n|
837         . qq|# Created by DBIx::Class::Schema::Loader\n|
838         . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
839         . qq|use strict;\nuse warnings;\n\n|
840         . qq|use base '$schema_base_class';\n\n|;
841
842     if ($self->use_namespaces) {
843         $schema_text .= qq|__PACKAGE__->load_namespaces|;
844         my $namespace_options;
845         for my $attr (qw(result_namespace
846                          resultset_namespace
847                          default_resultset_class)) {
848             if ($self->$attr) {
849                 $namespace_options .= qq|    $attr => '| . $self->$attr . qq|',\n|
850             }
851         }
852         $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
853         $schema_text .= qq|;\n|;
854     }
855     else {
856         $schema_text .= qq|__PACKAGE__->load_classes;\n|;
857     }
858
859     {
860         local $self->{version_to_dump} = $self->schema_version_to_dump;
861         $self->_write_classfile($schema_class, $schema_text);
862     }
863
864     my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
865
866     foreach my $src_class (@classes) {
867         my $src_text = 
868               qq|package $src_class;\n\n|
869             . qq|# Created by DBIx::Class::Schema::Loader\n|
870             . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
871             . qq|use strict;\nuse warnings;\n\n|
872             . qq|use base '$result_base_class';\n\n|;
873
874         $self->_write_classfile($src_class, $src_text);
875     }
876
877     warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
878
879 }
880
881 sub _sig_comment {
882     my ($self, $version, $ts) = @_;
883     return qq|\n\n# Created by DBIx::Class::Schema::Loader|
884          . qq| v| . $version
885          . q| @ | . $ts 
886          . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
887 }
888
889 sub _write_classfile {
890     my ($self, $class, $text) = @_;
891
892     my $filename = $self->_get_dump_filename($class);
893     $self->_ensure_dump_subdirs($class);
894
895     if (-f $filename && $self->really_erase_my_files) {
896         warn "Deleting existing file '$filename' due to "
897             . "'really_erase_my_files' setting\n" unless $self->{quiet};
898         unlink($filename);
899     }    
900
901     my ($custom_content, $old_md5, $old_ver, $old_ts) = $self->_get_custom_content($class, $filename);
902
903     if ($self->_upgrading_from) {
904         my $old_class = $self->_upgrading_classes->{$class};
905
906         if ($old_class && ($old_class ne $class)) {
907             my $old_filename = $self->_get_dump_filename($old_class);
908
909             my ($old_custom_content) = $self->_get_custom_content(
910                 $old_class, $old_filename, 0 # do not add default comment
911             );
912
913             $old_custom_content =~ s/\n\n# You can replace.*\n1;\n//;
914
915             if ($old_custom_content) {
916                 $custom_content =
917                     "\n" . $old_custom_content . "\n" . $custom_content;
918             }
919
920             unlink $old_filename;
921         }
922     }
923
924     $text .= qq|$_\n|
925         for @{$self->{_dump_storage}->{$class} || []};
926
927     # Check and see if the dump is infact differnt
928
929     my $compare_to;
930     if ($old_md5) {
931       $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
932       
933
934       if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
935         return;
936       }
937     }
938
939     $text .= $self->_sig_comment(
940       $self->version_to_dump,
941       POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
942     );
943
944     open(my $fh, '>', $filename)
945         or croak "Cannot open '$filename' for writing: $!";
946
947     # Write the top half and its MD5 sum
948     print $fh $text . Digest::MD5::md5_base64($text) . "\n";
949
950     # Write out anything loaded via external partial class file in @INC
951     print $fh qq|$_\n|
952         for @{$self->{_ext_storage}->{$class} || []};
953
954     # Write out any custom content the user has added
955     print $fh $custom_content;
956
957     close($fh)
958         or croak "Error closing '$filename': $!";
959 }
960
961 sub _default_custom_content {
962     return qq|\n\n# You can replace this text with custom|
963          . qq| content, and it will be preserved on regeneration|
964          . qq|\n1;\n|;
965 }
966
967 sub _get_custom_content {
968     my ($self, $class, $filename, $add_default) = @_;
969
970     $add_default = 1 unless defined $add_default;
971
972     return ($self->_default_custom_content) if ! -f $filename;
973
974     open(my $fh, '<', $filename)
975         or croak "Cannot open '$filename' for reading: $!";
976
977     my $mark_re = 
978         qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
979
980     my $buffer = '';
981     my ($md5, $ts, $ver);
982     while(<$fh>) {
983         if(!$md5 && /$mark_re/) {
984             $md5 = $2;
985             my $line = $1;
986
987             # Pull out the previous version and timestamp
988             ($ver, $ts) = $buffer =~ m/# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)$/s;
989
990             $buffer .= $line;
991             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"
992                 if !$self->overwrite_modifications && Digest::MD5::md5_base64($buffer) ne $md5;
993
994             $buffer = '';
995         }
996         else {
997             $buffer .= $_;
998         }
999     }
1000
1001     croak "Cannot not overwrite '$filename' without 'really_erase_my_files',"
1002         . " it does not appear to have been generated by Loader"
1003             if !$md5;
1004
1005     # Default custom content:
1006     $buffer ||= $self->_default_custom_content if $add_default;
1007
1008     return ($buffer, $md5, $ver, $ts);
1009 }
1010
1011 sub _use {
1012     my $self = shift;
1013     my $target = shift;
1014
1015     foreach (@_) {
1016         warn "$target: use $_;" if $self->debug;
1017         $self->_raw_stmt($target, "use $_;");
1018     }
1019 }
1020
1021 sub _inject {
1022     my $self = shift;
1023     my $target = shift;
1024     my $schema_class = $self->schema_class;
1025
1026     my $blist = join(q{ }, @_);
1027     warn "$target: use base qw/ $blist /;" if $self->debug && @_;
1028     $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
1029 }
1030
1031 # Create class with applicable bases, setup monikers, etc
1032 sub _make_src_class {
1033     my ($self, $table) = @_;
1034
1035     my $schema       = $self->schema;
1036     my $schema_class = $self->schema_class;
1037
1038     my $table_moniker = $self->_table2moniker($table);
1039     my @result_namespace = ($schema_class);
1040     if ($self->use_namespaces) {
1041         my $result_namespace = $self->result_namespace || 'Result';
1042         if ($result_namespace =~ /^\+(.*)/) {
1043             # Fully qualified namespace
1044             @result_namespace =  ($1)
1045         }
1046         else {
1047             # Relative namespace
1048             push @result_namespace, $result_namespace;
1049         }
1050     }
1051     my $table_class = join(q{::}, @result_namespace, $table_moniker);
1052
1053     if (my $upgrading_v = $self->_upgrading_from) {
1054         local $self->naming->{monikers} = $upgrading_v;
1055
1056         my $old_class = join(q{::}, @result_namespace,
1057             $self->_table2moniker($table));
1058
1059         $self->_upgrading_classes->{$table_class} = $old_class;
1060     }
1061
1062     my $table_normalized = lc $table;
1063     $self->classes->{$table} = $table_class;
1064     $self->classes->{$table_normalized} = $table_class;
1065     $self->monikers->{$table} = $table_moniker;
1066     $self->monikers->{$table_normalized} = $table_moniker;
1067
1068     $self->_use   ($table_class, @{$self->additional_classes});
1069     $self->_inject($table_class, @{$self->left_base_classes});
1070
1071     if (my @components = @{ $self->components }) {
1072         $self->_dbic_stmt($table_class, 'load_components', @components);
1073     }
1074
1075     $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
1076         if @{$self->resultset_components};
1077     $self->_inject($table_class, @{$self->additional_base_classes});
1078 }
1079
1080 # Set up metadata (cols, pks, etc)
1081 sub _setup_src_meta {
1082     my ($self, $table) = @_;
1083
1084     my $schema       = $self->schema;
1085     my $schema_class = $self->schema_class;
1086
1087     my $table_class = $self->classes->{$table};
1088     my $table_moniker = $self->monikers->{$table};
1089
1090     my $table_name = $table;
1091     my $name_sep   = $self->schema->storage->sql_maker->name_sep;
1092
1093     if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
1094         $table_name = \ $self->_quote_table_name($table_name);
1095     }
1096
1097     $self->_dbic_stmt($table_class,'table',$table_name);
1098
1099     my $cols = $self->_table_columns($table);
1100     my $col_info;
1101     eval { $col_info = $self->_columns_info_for($table) };
1102     if($@) {
1103         $self->_dbic_stmt($table_class,'add_columns',@$cols);
1104     }
1105     else {
1106         if ($self->_is_case_sensitive) {
1107             for my $col (keys %$col_info) {
1108                 $col_info->{$col}{accessor} = lc $col
1109                     if $col ne lc($col);
1110             }
1111         } else {
1112             $col_info = { map { lc($_), $col_info->{$_} } keys %$col_info };
1113         }
1114
1115         my $fks = $self->_table_fk_info($table);
1116
1117         for my $fkdef (@$fks) {
1118             for my $col (@{ $fkdef->{local_columns} }) {
1119                 $col_info->{$col}{is_foreign_key} = 1;
1120             }
1121         }
1122         $self->_dbic_stmt(
1123             $table_class,
1124             'add_columns',
1125             map { $_, ($col_info->{$_}||{}) } @$cols
1126         );
1127     }
1128
1129     my %uniq_tag; # used to eliminate duplicate uniqs
1130
1131     my $pks = $self->_table_pk_info($table) || [];
1132     @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1133           : carp("$table has no primary key");
1134     $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
1135
1136     my $uniqs = $self->_table_uniq_info($table) || [];
1137     for (@$uniqs) {
1138         my ($name, $cols) = @$_;
1139         next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1140         $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1141     }
1142
1143 }
1144
1145 =head2 tables
1146
1147 Returns a sorted list of loaded tables, using the original database table
1148 names.
1149
1150 =cut
1151
1152 sub tables {
1153     my $self = shift;
1154
1155     return keys %{$self->_tables};
1156 }
1157
1158 # Make a moniker from a table
1159 sub _default_table2moniker {
1160     no warnings 'uninitialized';
1161     my ($self, $table) = @_;
1162
1163     if ($self->naming->{monikers} eq 'v4') {
1164         return join '', map ucfirst, split /[\W_]+/, lc $table;
1165     }
1166
1167     return join '', map ucfirst, split /[\W_]+/,
1168         Lingua::EN::Inflect::Number::to_S(lc $table);
1169 }
1170
1171 sub _table2moniker {
1172     my ( $self, $table ) = @_;
1173
1174     my $moniker;
1175
1176     if( ref $self->moniker_map eq 'HASH' ) {
1177         $moniker = $self->moniker_map->{$table};
1178     }
1179     elsif( ref $self->moniker_map eq 'CODE' ) {
1180         $moniker = $self->moniker_map->($table);
1181     }
1182
1183     $moniker ||= $self->_default_table2moniker($table);
1184
1185     return $moniker;
1186 }
1187
1188 sub _load_relationships {
1189     my ($self, $table) = @_;
1190
1191     my $tbl_fk_info = $self->_table_fk_info($table);
1192     foreach my $fkdef (@$tbl_fk_info) {
1193         $fkdef->{remote_source} =
1194             $self->monikers->{delete $fkdef->{remote_table}};
1195     }
1196     my $tbl_uniq_info = $self->_table_uniq_info($table);
1197
1198     my $local_moniker = $self->monikers->{$table};
1199     my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
1200
1201     foreach my $src_class (sort keys %$rel_stmts) {
1202         my $src_stmts = $rel_stmts->{$src_class};
1203         foreach my $stmt (@$src_stmts) {
1204             $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1205         }
1206     }
1207 }
1208
1209 # Overload these in driver class:
1210
1211 # Returns an arrayref of column names
1212 sub _table_columns { croak "ABSTRACT METHOD" }
1213
1214 # Returns arrayref of pk col names
1215 sub _table_pk_info { croak "ABSTRACT METHOD" }
1216
1217 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1218 sub _table_uniq_info { croak "ABSTRACT METHOD" }
1219
1220 # Returns an arrayref of foreign key constraints, each
1221 #   being a hashref with 3 keys:
1222 #   local_columns (arrayref), remote_columns (arrayref), remote_table
1223 sub _table_fk_info { croak "ABSTRACT METHOD" }
1224
1225 # Returns an array of lower case table names
1226 sub _tables_list { croak "ABSTRACT METHOD" }
1227
1228 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1229 sub _dbic_stmt {
1230     my $self   = shift;
1231     my $class  = shift;
1232     my $method = shift;
1233
1234     # generate the pod for this statement, storing it with $self->_pod
1235     $self->_make_pod( $class, $method, @_ );
1236
1237     my $args = dump(@_);
1238     $args = '(' . $args . ')' if @_ < 2;
1239     my $stmt = $method . $args . q{;};
1240
1241     warn qq|$class\->$stmt\n| if $self->debug;
1242     $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1243     return;
1244 }
1245
1246 # generates the accompanying pod for a DBIC class method statement,
1247 # storing it with $self->_pod
1248 sub _make_pod {
1249     my $self   = shift;
1250     my $class  = shift;
1251     my $method = shift;
1252
1253     if ( $method eq 'table' ) {
1254         my ($table) = @_;
1255         $self->_pod( $class, "=head1 NAME" );
1256         my $table_descr = $class;
1257         if ( $self->can('_table_comment') ) {
1258             my $comment = $self->_table_comment($table);
1259             $table_descr .= " - " . $comment if $comment;
1260         }
1261         $self->{_class2table}{ $class } = $table;
1262         $self->_pod( $class, $table_descr );
1263         $self->_pod_cut( $class );
1264     } elsif ( $method eq 'add_columns' ) {
1265         $self->_pod( $class, "=head1 ACCESSORS" );
1266         my $col_counter = 0;
1267         my @cols = @_;
1268         while( my ($name,$attrs) = splice @cols,0,2 ) {
1269             $col_counter++;
1270             $self->_pod( $class, '=head2 ' . $name  );
1271             $self->_pod( $class,
1272                          join "\n", map {
1273                              my $s = $attrs->{$_};
1274                              $s = !defined $s      ? 'undef'          :
1275                                   length($s) == 0  ? '(empty string)' :
1276                                                      $s;
1277
1278                              "  $_: $s"
1279                          } sort keys %$attrs,
1280                        );
1281
1282             if( $self->can('_column_comment')
1283                 and my $comment = $self->_column_comment( $self->{_class2table}{$class}, $col_counter)
1284               ) {
1285                 $self->_pod( $class, $comment );
1286             }
1287         }
1288         $self->_pod_cut( $class );
1289     } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
1290         $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
1291         my ( $accessor, $rel_class ) = @_;
1292         $self->_pod( $class, "=head2 $accessor" );
1293         $self->_pod( $class, 'Type: ' . $method );
1294         $self->_pod( $class, "Related object: L<$rel_class>" );
1295         $self->_pod_cut( $class );
1296         $self->{_relations_started} { $class } = 1;
1297     }
1298 }
1299
1300 # Stores a POD documentation
1301 sub _pod {
1302     my ($self, $class, $stmt) = @_;
1303     $self->_raw_stmt( $class, "\n" . $stmt  );
1304 }
1305
1306 sub _pod_cut {
1307     my ($self, $class ) = @_;
1308     $self->_raw_stmt( $class, "\n=cut\n" );
1309 }
1310
1311
1312 # Store a raw source line for a class (for dumping purposes)
1313 sub _raw_stmt {
1314     my ($self, $class, $stmt) = @_;
1315     push(@{$self->{_dump_storage}->{$class}}, $stmt);
1316 }
1317
1318 # Like above, but separately for the externally loaded stuff
1319 sub _ext_stmt {
1320     my ($self, $class, $stmt) = @_;
1321     push(@{$self->{_ext_storage}->{$class}}, $stmt);
1322 }
1323
1324 sub _quote_table_name {
1325     my ($self, $table) = @_;
1326
1327     my $qt = $self->schema->storage->sql_maker->quote_char;
1328
1329     return $table unless $qt;
1330
1331     if (ref $qt) {
1332         return $qt->[0] . $table . $qt->[1];
1333     }
1334
1335     return $qt . $table . $qt;
1336 }
1337
1338 sub _is_case_sensitive { 0 }
1339
1340 # remove the dump dir from @INC on destruction
1341 sub DESTROY {
1342     my $self = shift;
1343
1344     @INC = grep $_ ne $self->dump_directory, @INC;
1345 }
1346
1347 =head2 monikers
1348
1349 Returns a hashref of loaded table to moniker mappings.  There will
1350 be two entries for each table, the original name and the "normalized"
1351 name, in the case that the two are different (such as databases
1352 that like uppercase table names, or preserve your original mixed-case
1353 definitions, or what-have-you).
1354
1355 =head2 classes
1356
1357 Returns a hashref of table to class mappings.  In some cases it will
1358 contain multiple entries per table for the original and normalized table
1359 names, as above in L</monikers>.
1360
1361 =head1 SEE ALSO
1362
1363 L<DBIx::Class::Schema::Loader>
1364
1365 =head1 AUTHOR
1366
1367 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
1368
1369 =head1 LICENSE
1370
1371 This library is free software; you can redistribute it and/or modify it under
1372 the same terms as Perl itself.
1373
1374 =cut
1375
1376 1;