initialize result_component_map to empty hash if unset
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / Base.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::Base;
2
3use strict;
4use warnings;
65e705c3 5use base qw/Class::Accessor::Grouped Class::C3::Componentised/;
942bd5e0 6use mro 'c3';
fa994d3c 7use Carp::Clan qw/^DBIx::Class/;
996be9ee 8use DBIx::Class::Schema::Loader::RelBuilder;
9use Data::Dump qw/ dump /;
10use POSIX qw//;
dd03ee1a 11use File::Spec qw//;
419a2eeb 12use Cwd qw//;
7cab3ab7 13use Digest::MD5 qw//;
22270947 14use Lingua::EN::Inflect::Number qw//;
ecf930e6 15use Lingua::EN::Inflect::Phrase qw//;
af31090c 16use File::Temp qw//;
17use Class::Unload;
8048320c 18use Class::Inspector ();
f170d55b 19use Scalar::Util 'looks_like_number';
b0d2b300 20use File::Slurp 'slurp';
c38ec663 21use DBIx::Class::Schema::Loader::Utils qw/split_name dumper_squashed eval_without_redefine_warnings/;
ef8e9c69 22use DBIx::Class::Schema::Loader::Optional::Dependencies ();
906fa216 23use Try::Tiny;
ef8e9c69 24use DBIx::Class ();
b622b087 25use Class::Load 'load_class';
2b74a06b 26use namespace::clean;
996be9ee 27
4295c4b4 28our $VERSION = '0.07010';
32f784fc 29
3d95f9ff 30__PACKAGE__->mk_group_ro_accessors('simple', qw/
996be9ee 31 schema
32 schema_class
33
34 exclude
35 constraint
36 additional_classes
37 additional_base_classes
38 left_base_classes
39 components
59cfa251 40 skip_relationships
0ca61324 41 skip_load_external
996be9ee 42 moniker_map
3fea497f 43 col_accessor_map
b639d969 44 custom_column_info
996be9ee 45 inflect_singular
46 inflect_plural
47 debug
48 dump_directory
d65cda9e 49 dump_overwrite
28b4691d 50 really_erase_my_files
f44ecc2f 51 resultset_namespace
52 default_resultset_class
9c9c2f2b 53 schema_base_class
54 result_base_class
dcaf302a 55 use_moose
8de81918 56 overwrite_modifications
996be9ee 57
c8c27020 58 relationship_attrs
59
996be9ee 60 db_schema
61 _tables
62 classes
f53dcdf0 63 _upgrading_classes
996be9ee 64 monikers
106a976a 65 dynamic
a8d229ff 66 naming
42e785fa 67 datetime_timezone
68 datetime_locale
73099af4 69 config_file
71a6e88a 70 loader_class
69219349 71 qualify_objects
65e705c3 72/);
73
996be9ee 74
3d95f9ff 75__PACKAGE__->mk_group_accessors('simple', qw/
01012543 76 version_to_dump
1c95b304 77 schema_version_to_dump
f53dcdf0 78 _upgrading_from
f22644d7 79 _upgrading_from_load_classes
a4b94090 80 _downgrading_to_load_classes
540a8149 81 _rewriting_result_namespace
f22644d7 82 use_namespaces
540a8149 83 result_namespace
492dce8d 84 generate_pod
43b982ea 85 pod_comment_mode
86 pod_comment_spillover_length
bc1cb85e 87 preserve_case
15c4393b 88 col_collision_map
a7116285 89 rel_collision_map
1ad8e8c3 90 real_dump_directory
8d65c820 91 result_component_map
57a9fc92 92 datetime_undef_if_invalid
26c54680 93 _result_class_methods
01012543 94/);
95
996be9ee 96=head1 NAME
97
98DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
99
100=head1 SYNOPSIS
101
102See L<DBIx::Class::Schema::Loader>
103
104=head1 DESCRIPTION
105
106This is the base class for the storage-specific C<DBIx::Class::Schema::*>
107classes, and implements the common functionality between them.
108
109=head1 CONSTRUCTOR OPTIONS
110
111These constructor options are the base options for
29ddb54c 112L<DBIx::Class::Schema::Loader/loader_options>. Available constructor options are:
3953cbee 113
59cfa251 114=head2 skip_relationships
996be9ee 115
59cfa251 116Skip setting up relationships. The default is to attempt the loading
117of relationships.
996be9ee 118
0ca61324 119=head2 skip_load_external
120
121Skip loading of other classes in @INC. The default is to merge all other classes
122with the same name found in @INC into the schema file we are creating.
123
9a95164d 124=head2 naming
125
ecf930e6 126Static schemas (ones dumped to disk) will, by default, use the new-style
9a95164d 127relationship names and singularized Results, unless you're overwriting an
ecf930e6 128existing dump made by an older version of L<DBIx::Class::Schema::Loader>, in
129which case the backward compatible RelBuilder will be activated, and the
130appropriate monikerization used.
9a95164d 131
132Specifying
133
ecf930e6 134 naming => 'current'
9a95164d 135
136will disable the backward-compatible RelBuilder and use
137the new-style relationship names along with singularized Results, even when
138overwriting a dump made with an earlier version.
139
140The option also takes a hashref:
141
2a1ff2ee 142 naming => { relationships => 'v7', monikers => 'v7' }
a8d229ff 143
144The keys are:
145
146=over 4
147
148=item relationships
149
150How to name relationship accessors.
151
152=item monikers
153
154How to name Result classes.
155
f3a657ef 156=item column_accessors
157
158How to name column accessors in Result classes.
159
a8d229ff 160=back
9a95164d 161
162The values can be:
163
164=over 4
165
166=item current
167
ecf930e6 168Latest style, whatever that happens to be.
169
170=item v4
171
172Unsingularlized monikers, C<has_many> only relationships with no _id stripping.
9a95164d 173
174=item v5
175
ecf930e6 176Monikers singularized as whole words, C<might_have> relationships for FKs on
177C<UNIQUE> constraints, C<_id> stripping for belongs_to relationships.
9a95164d 178
ecf930e6 179Some of the C<_id> stripping edge cases in C<0.05003> have been reverted for
180the v5 RelBuilder.
181
182=item v6
9a95164d 183
19b7d71c 184All monikers and relationships are inflected using
185L<Lingua::EN::Inflect::Phrase>, and there is more aggressive C<_id> stripping
186from relationship names.
ecf930e6 187
188In general, there is very little difference between v5 and v6 schemas.
9a95164d 189
9990e58f 190=item v7
191
192This mode is identical to C<v6> mode, except that monikerization of CamelCase
193table names is also done correctly.
194
0c1d5b47 195CamelCase column names in case-preserving mode will also be handled correctly
196for relationship name inflection. See L</preserve_case>.
19b7d71c 197
f3a657ef 198In this mode, CamelCase L</column_accessors> are normalized based on case
199transition instead of just being lowercased, so C<FooId> becomes C<foo_id>.
200
19b7d71c 201If you don't have any CamelCase table or column names, you can upgrade without
202breaking any of your code.
9990e58f 203
9a95164d 204=back
205
206Dynamic schemas will always default to the 0.04XXX relationship names and won't
207singularize Results for backward compatibility, to activate the new RelBuilder
208and singularization put this in your C<Schema.pm> file:
209
210 __PACKAGE__->naming('current');
211
c9cf9b4d 212Or if you prefer to use 0.07XXX features but insure that nothing breaks in the
9a95164d 213next major version upgrade:
214
c9cf9b4d 215 __PACKAGE__->naming('v7');
9a95164d 216
492dce8d 217=head2 generate_pod
218
219By default POD will be generated for columns and relationships, using database
7f2de014 220metadata for the text if available and supported.
221
222Reading database metadata (e.g. C<COMMENT ON TABLE some_table ...>) is only
223supported for Postgres right now.
492dce8d 224
225Set this to C<0> to turn off all POD generation.
226
43b982ea 227=head2 pod_comment_mode
228
f7976fea 229Controls where table comments appear in the generated POD. Smaller table
230comments are appended to the C<NAME> section of the documentation, and larger
231ones are inserted into C<DESCRIPTION> instead. You can force a C<DESCRIPTION>
232section to be generated with the comment always, only use C<NAME>, or choose
233the length threshold at which the comment is forced into the description.
43b982ea 234
34896b5e 235=over 4
236
237=item name
238
239Use C<NAME> section only.
240
241=item description
242
243Force C<DESCRIPTION> always.
244
245=item auto
246
247Use C<DESCRIPTION> if length > L</pod_comment_spillover_length>, this is the
248default.
249
250=back
43b982ea 251
252=head2 pod_comment_spillover_length
253
254When pod_comment_mode is set to C<auto>, this is the length of the comment at
255which it will be forced into a separate description section.
256
257The default is C<60>
258
c8c27020 259=head2 relationship_attrs
260
261Hashref of attributes to pass to each generated relationship, listed
262by type. Also supports relationship type 'all', containing options to
263pass to all generated relationships. Attributes set for more specific
264relationship types override those set in 'all'.
265
266For example:
267
268 relationship_attrs => {
aa0867ee 269 belongs_to => { is_deferrable => 0 },
c8c27020 270 },
271
aa0867ee 272use this to turn off DEFERRABLE on your foreign key constraints.
c8c27020 273
996be9ee 274=head2 debug
275
276If set to true, each constructive L<DBIx::Class> statement the loader
277decides to execute will be C<warn>-ed before execution.
278
d65cda9e 279=head2 db_schema
280
281Set the name of the schema to load (schema in the sense that your database
282vendor means it). Does not currently support loading more than one schema
283name.
284
996be9ee 285=head2 constraint
286
287Only load tables matching regex. Best specified as a qr// regex.
288
289=head2 exclude
290
291Exclude tables matching regex. Best specified as a qr// regex.
292
293=head2 moniker_map
294
8f9d7ce5 295Overrides the default table name to moniker translation. Can be either
296a hashref of table keys and moniker values, or a coderef for a translator
996be9ee 297function taking a single scalar table name argument and returning
298a scalar moniker. If the hash entry does not exist, or the function
299returns a false value, the code falls back to default behavior
300for that table name.
301
9990e58f 302The default behavior is to split on case transition and non-alphanumeric
303boundaries, singularize the resulting phrase, then join the titlecased words
304together. Examples:
996be9ee 305
9990e58f 306 Table Name | Moniker Name
307 ---------------------------------
308 luser | Luser
309 luser_group | LuserGroup
310 luser-opts | LuserOpt
311 stations_visited | StationVisited
312 routeChange | RouteChange
996be9ee 313
3fea497f 314=head2 col_accessor_map
cfc5dce3 315
316Same as moniker_map, but for column accessor names. If a coderef is
317passed, the code is called with arguments of
318
319 the name of the column in the underlying database,
320 default accessor name that DBICSL would ordinarily give this column,
321 {
322 table_class => name of the DBIC class we are building,
323 table_moniker => calculated moniker for this table (after moniker_map if present),
324 table_name => name of the database table,
325 full_table_name => schema-qualified name of the database table (RDBMS specific),
326 schema_class => name of the schema class we are building,
327 column_info => hashref of column info (data_type, is_nullable, etc),
328 }
329
996be9ee 330=head2 inflect_plural
331
332Just like L</moniker_map> above (can be hash/code-ref, falls back to default
333if hash key does not exist or coderef returns false), but acts as a map
334for pluralizing relationship names. The default behavior is to utilize
a7a80921 335L<Lingua::EN::Inflect::Phrase/to_PL>.
996be9ee 336
337=head2 inflect_singular
338
339As L</inflect_plural> above, but for singularizing relationship names.
a7a80921 340Default behavior is to utilize L<Lingua::EN::Inflect::Phrase/to_S>.
996be9ee 341
9c9c2f2b 342=head2 schema_base_class
343
344Base class for your schema classes. Defaults to 'DBIx::Class::Schema'.
345
346=head2 result_base_class
347
2229729e 348Base class for your table classes (aka result classes). Defaults to
349'DBIx::Class::Core'.
9c9c2f2b 350
996be9ee 351=head2 additional_base_classes
352
353List of additional base classes all of your table classes will use.
354
355=head2 left_base_classes
356
357List of additional base classes all of your table classes will use
358that need to be leftmost.
359
360=head2 additional_classes
361
362List of additional classes which all of your table classes will use.
363
364=head2 components
365
366List of additional components to be loaded into all of your table
eccc52fe 367classes. A good example would be
368L<InflateColumn::DateTime|DBIx::Class::InflateColumn::DateTime>
996be9ee 369
8d65c820 370=head2 result_component_map
371
372A hashref of moniker keys and component values. Unlike C<components>, which loads the
373given components into every table class, this option allows you to load certain
374components for specified tables. For example:
375
376 result_component_map => {
377 StationVisited => '+YourApp::Schema::Component::StationVisited',
378 RouteChange => [
379 '+YourApp::Schema::Component::RouteChange',
380 'InflateColumn::DateTime',
381 ],
382 }
383
384You may use this in conjunction with C<components>.
385
f44ecc2f 386=head2 use_namespaces
387
f22644d7 388This is now the default, to go back to L<DBIx::Class::Schema/load_classes> pass
389a C<0>.
390
f44ecc2f 391Generate result class names suitable for
392L<DBIx::Class::Schema/load_namespaces> and call that instead of
393L<DBIx::Class::Schema/load_classes>. When using this option you can also
394specify any of the options for C<load_namespaces> (i.e. C<result_namespace>,
395C<resultset_namespace>, C<default_resultset_class>), and they will be added
396to the call (and the generated result class names adjusted appropriately).
397
996be9ee 398=head2 dump_directory
399
996be9ee 400The value of this option is a perl libdir pathname. Within
401that directory this module will create a baseline manual
1ad8e8c3 402L<DBIx::Class::Schema> module set, based on what it creates at runtime.
996be9ee 403
404The created schema class will have the same classname as the one on
405which you are setting this option (and the ResultSource classes will be
7cab3ab7 406based on this name as well).
996be9ee 407
8f9d7ce5 408Normally you wouldn't hard-code this setting in your schema class, as it
996be9ee 409is meant for one-time manual usage.
410
411See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
412recommended way to access this functionality.
413
d65cda9e 414=head2 dump_overwrite
415
28b4691d 416Deprecated. See L</really_erase_my_files> below, which does *not* mean
417the same thing as the old C<dump_overwrite> setting from previous releases.
418
419=head2 really_erase_my_files
420
7cab3ab7 421Default false. If true, Loader will unconditionally delete any existing
422files before creating the new ones from scratch when dumping a schema to disk.
423
424The default behavior is instead to only replace the top portion of the
425file, up to and including the final stanza which contains
1a8fd949 426C<# DO NOT MODIFY THE FIRST PART OF THIS FILE>
7cab3ab7 427leaving any customizations you placed after that as they were.
428
28b4691d 429When C<really_erase_my_files> is not set, if the output file already exists,
7cab3ab7 430but the aforementioned final stanza is not found, or the checksum
431contained there does not match the generated contents, Loader will
432croak and not touch the file.
d65cda9e 433
28b4691d 434You should really be using version control on your schema classes (and all
435of the rest of your code for that matter). Don't blame me if a bug in this
436code wipes something out when it shouldn't have, you've been warned.
437
639a1367 438=head2 overwrite_modifications
439
440Default false. If false, when updating existing files, Loader will
441refuse to modify any Loader-generated code that has been modified
442since its last run (as determined by the checksum Loader put in its
443comment lines).
444
445If true, Loader will discard any manual modifications that have been
446made to Loader-generated code.
447
448Again, you should be using version control on your schema classes. Be
449careful with this option.
450
3a368709 451=head2 custom_column_info
452
d67d058e 453Hook for adding extra attributes to the
454L<column_info|DBIx::Class::ResultSource/column_info> for a column.
455
456Must be a coderef that returns a hashref with the extra attributes.
457
458Receives the table name, column name and column_info.
459
460For example:
461
462 custom_column_info => sub {
463 my ($table_name, $column_name, $column_info) = @_;
464
465 if ($column_name eq 'dog' && $column_info->{default_value} eq 'snoopy') {
466 return { is_snoopy => 1 };
467 }
468 },
3a368709 469
d67d058e 470This attribute can also be used to set C<inflate_datetime> on a non-datetime
471column so it also receives the L</datetime_timezone> and/or L</datetime_locale>.
3a368709 472
42e785fa 473=head2 datetime_timezone
474
d67d058e 475Sets the timezone attribute for L<DBIx::Class::InflateColumn::DateTime> for all
476columns with the DATE/DATETIME/TIMESTAMP data_types.
42e785fa 477
478=head2 datetime_locale
479
d67d058e 480Sets the locale attribute for L<DBIx::Class::InflateColumn::DateTime> for all
481columns with the DATE/DATETIME/TIMESTAMP data_types.
42e785fa 482
57a9fc92 483=head2 datetime_undef_if_invalid
484
485Pass a C<0> for this option when using MySQL if you B<DON'T> want C<<
486datetime_undef_if_invalid => 1 >> in your column info for DATE, DATETIME and
487TIMESTAMP columns.
488
489The default is recommended to deal with data such as C<00/00/00> which
490sometimes ends up in such columns in MySQL.
491
7ffafa37 492=head2 config_file
73099af4 493
494File in Perl format, which should return a HASH reference, from which to read
495loader options.
496
7ffafa37 497=head2 preserve_case
bc1cb85e 498
499Usually column names are lowercased, to make them easier to work with in
500L<DBIx::Class>. This option lets you turn this behavior off, if the driver
501supports it.
502
503Drivers for case sensitive databases like Sybase ASE or MSSQL with a
504case-sensitive collation will turn this option on unconditionally.
505
506Currently the drivers for SQLite, mysql, MSSQL and Firebird/InterBase support
507setting this option.
508
7ffafa37 509=head2 qualify_objects
69219349 510
511Set to true to prepend the L</db_schema> to table names for C<<
512__PACKAGE__->table >> calls, and to some other things like Oracle sequences.
513
7d0ea6b9 514=head2 use_moose
515
516Creates Schema and Result classes that use L<Moose>, L<MooseX::NonMoose> and
1336ac63 517L<namespace::autoclean>. The default content after the md5 sum also makes the
518classes immutable.
7d0ea6b9 519
520It is safe to upgrade your existing Schema to this option.
521
15c4393b 522=head2 col_collision_map
523
524This option controls how accessors for column names which collide with perl
525methods are named. See L</COLUMN ACCESSOR COLLISIONS> for more information.
526
dcc51168 527This option takes either a single L<sprintf|perlfunc/sprintf> format or a hashref of
15c4393b 528strings which are compiled to regular expressions that map to
dcc51168 529L<sprintf|perlfunc/sprintf> formats.
15c4393b 530
531Examples:
532
533 col_collision_map => 'column_%s'
534
535 col_collision_map => { '(.*)' => 'column_%s' }
536
537 col_collision_map => { '(foo).*(bar)' => 'column_%s_%s' }
538
a7116285 539=head2 rel_collision_map
540
541Works just like L</col_collision_map>, but for relationship names/accessors
542rather than column names/accessors.
543
544The default is to just append C<_rel> to the relationship name, see
545L</RELATIONSHIP NAME COLLISIONS>.
546
996be9ee 547=head1 METHODS
548
549None of these methods are intended for direct invocation by regular
d67d058e 550users of L<DBIx::Class::Schema::Loader>. Some are proxied via
551L<DBIx::Class::Schema::Loader>.
996be9ee 552
553=cut
554
9990e58f 555my $CURRENT_V = 'v7';
8048320c 556
c5df7397 557my @CLASS_ARGS = qw(
8048320c 558 schema_base_class result_base_class additional_base_classes
1ad8e8c3 559 left_base_classes additional_classes components
8048320c 560);
66afce69 561
996be9ee 562# ensure that a peice of object data is a valid arrayref, creating
563# an empty one or encapsulating whatever's there.
564sub _ensure_arrayref {
565 my $self = shift;
566
567 foreach (@_) {
568 $self->{$_} ||= [];
569 $self->{$_} = [ $self->{$_} ]
570 unless ref $self->{$_} eq 'ARRAY';
571 }
572}
573
574=head2 new
575
576Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
577by L<DBIx::Class::Schema::Loader>.
578
579=cut
580
581sub new {
582 my ( $class, %args ) = @_;
583
3fea497f 584 if (exists $args{column_accessor_map}) {
585 $args{col_accessor_map} = delete $args{column_accessor_map};
586 }
587
996be9ee 588 my $self = { %args };
589
8de81918 590 # don't lose undef options
591 for (values %$self) {
592 $_ = 0 unless defined $_;
593 }
594
996be9ee 595 bless $self => $class;
596
73099af4 597 if (my $config_file = $self->config_file) {
598 my $config_opts = do $config_file;
599
600 croak "Error reading config from $config_file: $@" if $@;
601
602 croak "Config file $config_file must be a hashref" unless ref($config_opts) eq 'HASH';
603
604 while (my ($k, $v) = each %$config_opts) {
605 $self->{$k} = $v unless exists $self->{$k};
606 }
607 }
608
996be9ee 609 $self->_ensure_arrayref(qw/additional_classes
610 additional_base_classes
611 left_base_classes
612 components
996be9ee 613 /);
614
8048320c 615 $self->_validate_class_args;
616
8d65c820 617 if ($self->result_component_map) {
618 my %rc_map = %{ $self->result_component_map };
619 foreach my $moniker (keys %rc_map) {
620 $rc_map{$moniker} = [ $rc_map{$moniker} ] unless ref $rc_map{$moniker};
621 }
622 $self->result_component_map(\%rc_map);
623 }
95b0a8b9 624 else {
625 $self->result_component_map({});
626 }
8d65c820 627 $self->_validate_result_component_map;
628
c9cf9b4d 629 if ($self->use_moose) {
ef8e9c69 630 if (not DBIx::Class::Schema::Loader::Optional::Dependencies->req_ok_for('use_moose')) {
53e721bc 631 die sprintf "You must install the following CPAN modules to enable the use_moose option: %s.\n",
ef8e9c69 632 DBIx::Class::Schema::Loader::Optional::Dependencies->req_missing_for('use_moose');
c9cf9b4d 633 }
634 }
635
996be9ee 636 $self->{monikers} = {};
637 $self->{classes} = {};
f53dcdf0 638 $self->{_upgrading_classes} = {};
996be9ee 639
996be9ee 640 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
641 $self->{schema} ||= $self->{schema_class};
642
28b4691d 643 croak "dump_overwrite is deprecated. Please read the"
644 . " DBIx::Class::Schema::Loader::Base documentation"
645 if $self->{dump_overwrite};
646
af31090c 647 $self->{dynamic} = ! $self->{dump_directory};
79193756 648 $self->{temp_directory} ||= File::Temp::tempdir( 'dbicXXXX',
af31090c 649 TMPDIR => 1,
650 CLEANUP => 1,
651 );
652
79193756 653 $self->{dump_directory} ||= $self->{temp_directory};
654
1ad8e8c3 655 $self->real_dump_directory($self->{dump_directory});
656
01012543 657 $self->version_to_dump($DBIx::Class::Schema::Loader::VERSION);
1c95b304 658 $self->schema_version_to_dump($DBIx::Class::Schema::Loader::VERSION);
01012543 659
66afce69 660 if ((not ref $self->naming) && defined $self->naming) {
9cc8e7e1 661 my $naming_ver = $self->naming;
a8d229ff 662 $self->{naming} = {
663 relationships => $naming_ver,
664 monikers => $naming_ver,
f3a657ef 665 column_accessors => $naming_ver,
a8d229ff 666 };
667 }
668
66afce69 669 if ($self->naming) {
670 for (values %{ $self->naming }) {
c5df7397 671 $_ = $CURRENT_V if $_ eq 'current';
66afce69 672 }
673 }
674 $self->{naming} ||= {};
675
d67d058e 676 if ($self->custom_column_info && ref $self->custom_column_info ne 'CODE') {
677 croak 'custom_column_info must be a CODE ref';
678 }
679
7824616e 680 $self->_check_back_compat;
9c465d2c 681
f22644d7 682 $self->use_namespaces(1) unless defined $self->use_namespaces;
492dce8d 683 $self->generate_pod(1) unless defined $self->generate_pod;
43b982ea 684 $self->pod_comment_mode('auto') unless defined $self->pod_comment_mode;
685 $self->pod_comment_spillover_length(60) unless defined $self->pod_comment_spillover_length;
f22644d7 686
15c4393b 687 if (my $col_collision_map = $self->col_collision_map) {
688 if (my $reftype = ref $col_collision_map) {
689 if ($reftype ne 'HASH') {
690 croak "Invalid type $reftype for option 'col_collision_map'";
691 }
692 }
693 else {
694 $self->col_collision_map({ '(.*)' => $col_collision_map });
695 }
696 }
697
7824616e 698 $self;
699}
af31090c 700
7824616e 701sub _check_back_compat {
702 my ($self) = @_;
e8ad6491 703
a8d229ff 704# dynamic schemas will always be in 0.04006 mode, unless overridden
106a976a 705 if ($self->dynamic) {
fb3bb595 706# just in case, though no one is likely to dump a dynamic schema
1c95b304 707 $self->schema_version_to_dump('0.04006');
a8d229ff 708
66afce69 709 if (not %{ $self->naming }) {
710 warn <<EOF unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
711
712Dynamic schema detected, will run in 0.04006 mode.
713
714Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
715to disable this warning.
a0e0a56a 716
805dbe0a 717Also consider setting 'use_namespaces => 1' if/when upgrading.
718
a0e0a56a 719See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
720details.
66afce69 721EOF
722 }
f53dcdf0 723 else {
724 $self->_upgrading_from('v4');
725 }
66afce69 726
a8d229ff 727 $self->naming->{relationships} ||= 'v4';
728 $self->naming->{monikers} ||= 'v4';
729
805dbe0a 730 if ($self->use_namespaces) {
731 $self->_upgrading_from_load_classes(1);
732 }
733 else {
734 $self->use_namespaces(0);
735 }
f22644d7 736
01012543 737 return;
738 }
739
740# otherwise check if we need backcompat mode for a static schema
7824616e 741 my $filename = $self->_get_dump_filename($self->schema_class);
742 return unless -e $filename;
743
8de81918 744 my ($old_gen, $old_md5, $old_ver, $old_ts, $old_custom) =
745 $self->_parse_generated_file($filename);
7824616e 746
8de81918 747 return unless $old_ver;
748
749 # determine if the existing schema was dumped with use_moose => 1
750 if (! defined $self->use_moose) {
53e721bc 751 $self->{use_moose} = 1 if $old_gen =~ /^ (?!\s*\#) use \s+ Moose/xm;
8de81918 752 }
f22644d7 753
8de81918 754 my $load_classes = ($old_gen =~ /^__PACKAGE__->load_classes;/m) ? 1 : 0;
755 my $result_namespace = do { ($old_gen =~ /result_namespace => '([^']+)'/) ? $1 : '' };
805dbe0a 756
8de81918 757 if ($load_classes && (not defined $self->use_namespaces)) {
758 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
805dbe0a 759
a1a91c42 760'load_classes;' static schema detected, turning off 'use_namespaces'.
805dbe0a 761
762Set the 'use_namespaces' attribute or the SCHEMA_LOADER_BACKCOMPAT environment
763variable to disable this warning.
764
765See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 for more
766details.
767EOF
8de81918 768 $self->use_namespaces(0);
769 }
770 elsif ($load_classes && $self->use_namespaces) {
771 $self->_upgrading_from_load_classes(1);
772 }
773 elsif ((not $load_classes) && defined $self->use_namespaces && ! $self->use_namespaces) {
774 $self->_downgrading_to_load_classes(
775 $result_namespace || 'Result'
776 );
777 }
778 elsif ((not defined $self->use_namespaces) || $self->use_namespaces) {
779 if (not $self->result_namespace) {
780 $self->result_namespace($result_namespace || 'Result');
781 }
782 elsif ($result_namespace ne $self->result_namespace) {
783 $self->_rewriting_result_namespace(
784 $result_namespace || 'Result'
785 );
786 }
787 }
a8d229ff 788
8de81918 789 # XXX when we go past .0 this will need fixing
790 my ($v) = $old_ver =~ /([1-9])/;
791 $v = "v$v";
a8d229ff 792
8de81918 793 return if ($v eq $CURRENT_V || $old_ver =~ /^0\.\d\d999/);
a0e0a56a 794
8de81918 795 if (not %{ $self->naming }) {
796 warn <<"EOF" unless $ENV{SCHEMA_LOADER_BACKCOMPAT};
a0e0a56a 797
8de81918 798Version $old_ver static schema detected, turning on backcompat mode.
a0e0a56a 799
800Set the 'naming' attribute or the SCHEMA_LOADER_BACKCOMPAT environment variable
801to disable this warning.
802
9990e58f 803See: 'naming' in perldoc DBIx::Class::Schema::Loader::Base .
804
2a8e93e9 805See perldoc DBIx::Class::Schema::Loader::Manual::UpgradingFromV4 if upgrading
806from version 0.04006.
a0e0a56a 807EOF
a8d229ff 808
8de81918 809 $self->naming->{relationships} ||= $v;
810 $self->naming->{monikers} ||= $v;
811 $self->naming->{column_accessors} ||= $v;
a0e0a56a 812
8de81918 813 $self->schema_version_to_dump($old_ver);
814 }
815 else {
816 $self->_upgrading_from($v);
7824616e 817 }
996be9ee 818}
819
8048320c 820sub _validate_class_args {
821 my $self = shift;
8de81918 822
c5df7397 823 foreach my $k (@CLASS_ARGS) {
8048320c 824 next unless $self->$k;
825
826 my @classes = ref $self->$k eq 'ARRAY' ? @{ $self->$k } : $self->$k;
8d65c820 827 $self->_validate_classes($k, \@classes);
828 }
829}
8048320c 830
8d65c820 831sub _validate_result_component_map {
832 my $self = shift;
833
834 my $map = $self->result_component_map;
835 return unless $map && ref $map eq 'HASH';
836
837 foreach my $classes (values %$map) {
838 $self->_validate_classes('result_component_map', [@$classes]);
839 }
840}
841
842sub _validate_classes {
843 my $self = shift;
844 my $key = shift;
845 my $classes = shift;
846
847 foreach my $c (@$classes) {
848 # components default to being under the DBIx::Class namespace unless they
849 # are preceeded with a '+'
850 if ( $key =~ m/component/ && $c !~ s/^\+// ) {
851 $c = 'DBIx::Class::' . $c;
852 }
853
854 # 1 == installed, 0 == not installed, undef == invalid classname
855 my $installed = Class::Inspector->installed($c);
856 if ( defined($installed) ) {
857 if ( $installed == 0 ) {
858 croak qq/$c, as specified in the loader option "$key", is not installed/;
8048320c 859 }
8d65c820 860 } else {
861 croak qq/$c, as specified in the loader option "$key", is an invalid class name/;
8048320c 862 }
863 }
864}
865
8d65c820 866
419a2eeb 867sub _find_file_in_inc {
868 my ($self, $file) = @_;
869
870 foreach my $prefix (@INC) {
af31090c 871 my $fullpath = File::Spec->catfile($prefix, $file);
872 return $fullpath if -f $fullpath
281d0f3e 873 # abs_path throws on Windows for nonexistant files
1ad8e8c3 874 and (try { Cwd::abs_path($fullpath) }) ne
875 ((try { Cwd::abs_path(File::Spec->catfile($self->dump_directory, $file)) }) || '');
419a2eeb 876 }
877
878 return;
879}
880
fb3bb595 881sub _class_path {
f96ef30f 882 my ($self, $class) = @_;
883
884 my $class_path = $class;
885 $class_path =~ s{::}{/}g;
886 $class_path .= '.pm';
887
fb3bb595 888 return $class_path;
889}
890
891sub _find_class_in_inc {
892 my ($self, $class) = @_;
893
894 return $self->_find_file_in_inc($self->_class_path($class));
895}
896
a4b94090 897sub _rewriting {
898 my $self = shift;
899
900 return $self->_upgrading_from
901 || $self->_upgrading_from_load_classes
540a8149 902 || $self->_downgrading_to_load_classes
903 || $self->_rewriting_result_namespace
904 ;
a4b94090 905}
906
b24cb177 907sub _rewrite_old_classnames {
908 my ($self, $code) = @_;
909
a4b94090 910 return $code unless $self->_rewriting;
b24cb177 911
912 my %old_classes = reverse %{ $self->_upgrading_classes };
913
914 my $re = join '|', keys %old_classes;
915 $re = qr/\b($re)\b/;
916
68d49e50 917 $code =~ s/$re/$old_classes{$1} || $1/eg;
b24cb177 918
919 return $code;
920}
921
fb3bb595 922sub _load_external {
923 my ($self, $class) = @_;
924
0ca61324 925 return if $self->{skip_load_external};
926
ffc705f3 927 # so that we don't load our own classes, under any circumstances
928 local *INC = [ grep $_ ne $self->dump_directory, @INC ];
929
fb3bb595 930 my $real_inc_path = $self->_find_class_in_inc($class);
f96ef30f 931
ffc705f3 932 my $old_class = $self->_upgrading_classes->{$class}
a4b94090 933 if $self->_rewriting;
ffc705f3 934
935 my $old_real_inc_path = $self->_find_class_in_inc($old_class)
936 if $old_class && $old_class ne $class;
937
938 return unless $real_inc_path || $old_real_inc_path;
939
940 if ($real_inc_path) {
941 # If we make it to here, we loaded an external definition
942 warn qq/# Loaded external class definition for '$class'\n/
943 if $self->debug;
944
0dd4099e 945 my $code = $self->_rewrite_old_classnames(scalar slurp $real_inc_path);
ffc705f3 946
947 if ($self->dynamic) { # load the class too
c38ec663 948 eval_without_redefine_warnings($code);
ffc705f3 949 }
b24cb177 950
951 $self->_ext_stmt($class,
952 qq|# These lines were loaded from '$real_inc_path' found in \@INC.\n|
953 .qq|# They are now part of the custom portion of this file\n|
954 .qq|# for you to hand-edit. If you do not either delete\n|
955 .qq|# this section or remove that file from \@INC, this section\n|
956 .qq|# will be repeated redundantly when you re-create this\n|
e770e9ce 957 .qq|# file again via Loader! See skip_load_external to disable\n|
958 .qq|# this feature.\n|
b24cb177 959 );
960 chomp $code;
961 $self->_ext_stmt($class, $code);
962 $self->_ext_stmt($class,
963 qq|# End of lines loaded from '$real_inc_path' |
964 );
996be9ee 965 }
106a976a 966
ffc705f3 967 if ($old_real_inc_path) {
b511f36e 968 my $code = slurp $old_real_inc_path;
969
ffc705f3 970 $self->_ext_stmt($class, <<"EOF");
971
30a4c064 972# These lines were loaded from '$old_real_inc_path',
b08ea624 973# based on the Result class name that would have been created by an older
30a4c064 974# version of the Loader. For a static schema, this happens only once during
e770e9ce 975# upgrade. See skip_load_external to disable this feature.
ffc705f3 976EOF
b24cb177 977
b24cb177 978 $code = $self->_rewrite_old_classnames($code);
979
ffc705f3 980 if ($self->dynamic) {
981 warn <<"EOF";
982
983Detected external content in '$old_real_inc_path', a class name that would have
b08ea624 984been used by an older version of the Loader.
ffc705f3 985
986* PLEASE RENAME THIS CLASS: from '$old_class' to '$class', as that is the
987new name of the Result.
988EOF
c38ec663 989 eval_without_redefine_warnings($code);
ffc705f3 990 }
991
b24cb177 992 chomp $code;
993 $self->_ext_stmt($class, $code);
ffc705f3 994 $self->_ext_stmt($class,
995 qq|# End of lines loaded from '$old_real_inc_path' |
996 );
9e8033c1 997 }
996be9ee 998}
999
1000=head2 load
1001
1002Does the actual schema-construction work.
1003
1004=cut
1005
1006sub load {
1007 my $self = shift;
1008
bfb43060 1009 $self->_load_tables(
1010 $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude })
1011 );
b97c2c1e 1012}
1013
1014=head2 rescan
1015
a60b5b8d 1016Arguments: schema
1017
b511f36e 1018Rescan the database for changes. Returns a list of the newly added table
1019monikers.
a60b5b8d 1020
b511f36e 1021The schema argument should be the schema class or object to be affected. It
1022should probably be derived from the original schema_class used during L</load>.
b97c2c1e 1023
1024=cut
1025
1026sub rescan {
a60b5b8d 1027 my ($self, $schema) = @_;
1028
1029 $self->{schema} = $schema;
7824616e 1030 $self->_relbuilder->{schema} = $schema;
b97c2c1e 1031
1032 my @created;
bfb43060 1033 my @current = $self->_tables_list({ constraint => $self->constraint, exclude => $self->exclude });
0c1d5b47 1034
bfb43060 1035 foreach my $table (@current) {
b97c2c1e 1036 if(!exists $self->{_tables}->{$table}) {
1037 push(@created, $table);
1038 }
1039 }
1040
0c1d5b47 1041 my %current;
1042 @current{@current} = ();
1043 foreach my $table (keys %{ $self->{_tables} }) {
1044 if (not exists $current{$table}) {
1045 $self->_unregister_source_for_table($table);
1046 }
1047 }
1048
b511f36e 1049 delete $self->{_dump_storage};
1050 delete $self->{_relations_started};
1051
1052 my $loaded = $self->_load_tables(@current);
a60b5b8d 1053
b511f36e 1054 return map { $self->monikers->{$_} } @created;
b97c2c1e 1055}
1056
7824616e 1057sub _relbuilder {
1058 my ($self) = @_;
3fed44ca 1059
1060 return if $self->{skip_relationships};
1061
ef372cf4 1062 return $self->{relbuilder} ||= do {
1063
1064 no warnings 'uninitialized';
1065 my $relbuilder_suff =
1066 {qw{
1067 v4 ::Compat::v0_040
1068 v5 ::Compat::v0_05
1069 v6 ::Compat::v0_06
1070 }}
1071 ->{ $self->naming->{relationships}};
1072
1073 my $relbuilder_class = 'DBIx::Class::Schema::Loader::RelBuilder'.$relbuilder_suff;
b622b087 1074 load_class $relbuilder_class;
ef372cf4 1075 $relbuilder_class->new( $self );
a8d229ff 1076
ef372cf4 1077 };
7824616e 1078}
1079
b97c2c1e 1080sub _load_tables {
1081 my ($self, @tables) = @_;
1082
b97c2c1e 1083 # Save the new tables to the tables list
a60b5b8d 1084 foreach (@tables) {
1085 $self->{_tables}->{$_} = 1;
1086 }
f96ef30f 1087
af31090c 1088 $self->_make_src_class($_) for @tables;
27305cc1 1089
27305cc1 1090 # sanity-check for moniker clashes
1091 my $inverse_moniker_idx;
1092 for (keys %{$self->monikers}) {
1093 push @{$inverse_moniker_idx->{$self->monikers->{$_}}}, $_;
1094 }
1095
1096 my @clashes;
1097 for (keys %$inverse_moniker_idx) {
1098 my $tables = $inverse_moniker_idx->{$_};
1099 if (@$tables > 1) {
1100 push @clashes, sprintf ("tables %s reduced to the same source moniker '%s'",
1101 join (', ', map { "'$_'" } @$tables),
1102 $_,
1103 );
1104 }
1105 }
1106
1107 if (@clashes) {
1108 die 'Unable to load schema - chosen moniker/class naming style results in moniker clashes. '
1109 . 'Either change the naming style, or supply an explicit moniker_map: '
1110 . join ('; ', @clashes)
1111 . "\n"
1112 ;
1113 }
1114
1115
f96ef30f 1116 $self->_setup_src_meta($_) for @tables;
1117
e8ad6491 1118 if(!$self->skip_relationships) {
181cc907 1119 # The relationship loader needs a working schema
af31090c 1120 $self->{quiet} = 1;
79193756 1121 local $self->{dump_directory} = $self->{temp_directory};
106a976a 1122 $self->_reload_classes(\@tables);
e8ad6491 1123 $self->_load_relationships($_) for @tables;
8c70d2c7 1124 $self->_relbuilder->cleanup;
af31090c 1125 $self->{quiet} = 0;
79193756 1126
1127 # Remove that temp dir from INC so it doesn't get reloaded
ffc705f3 1128 @INC = grep $_ ne $self->dump_directory, @INC;
e8ad6491 1129 }
1130
f96ef30f 1131 $self->_load_external($_)
75451704 1132 for map { $self->classes->{$_} } @tables;
f96ef30f 1133
106a976a 1134 # Reload without unloading first to preserve any symbols from external
1135 # packages.
1ad8e8c3 1136 $self->_reload_classes(\@tables, { unload => 0 });
996be9ee 1137
5223f24a 1138 # Drop temporary cache
1139 delete $self->{_cache};
1140
c39e3507 1141 return \@tables;
996be9ee 1142}
1143
af31090c 1144sub _reload_classes {
1ad8e8c3 1145 my ($self, $tables, $opts) = @_;
106a976a 1146
1147 my @tables = @$tables;
1ad8e8c3 1148
1149 my $unload = $opts->{unload};
106a976a 1150 $unload = 1 unless defined $unload;
181cc907 1151
4daef04f 1152 # so that we don't repeat custom sections
1153 @INC = grep $_ ne $self->dump_directory, @INC;
1154
181cc907 1155 $self->_dump_to_dir(map { $self->classes->{$_} } @tables);
e9b8719e 1156
1157 unshift @INC, $self->dump_directory;
af31090c 1158
706ef173 1159 my @to_register;
1160 my %have_source = map { $_ => $self->schema->source($_) }
1161 $self->schema->sources;
1162
181cc907 1163 for my $table (@tables) {
1164 my $moniker = $self->monikers->{$table};
1165 my $class = $self->classes->{$table};
0ae6b65d 1166
1167 {
1168 no warnings 'redefine';
942bd5e0 1169 local *Class::C3::reinitialize = sub {}; # to speed things up, reinitialized below
0ae6b65d 1170 use warnings;
1171
01f93238 1172 if (my $mc = $self->_moose_metaclass($class)) {
1173 $mc->make_mutable;
c9cf9b4d 1174 }
106a976a 1175 Class::Unload->unload($class) if $unload;
706ef173 1176 my ($source, $resultset_class);
1177 if (
1178 ($source = $have_source{$moniker})
1179 && ($resultset_class = $source->resultset_class)
1180 && ($resultset_class ne 'DBIx::Class::ResultSet')
1181 ) {
1182 my $has_file = Class::Inspector->loaded_filename($resultset_class);
01f93238 1183 if (my $mc = $self->_moose_metaclass($resultset_class)) {
1184 $mc->make_mutable;
c9cf9b4d 1185 }
106a976a 1186 Class::Unload->unload($resultset_class) if $unload;
1187 $self->_reload_class($resultset_class) if $has_file;
0ae6b65d 1188 }
106a976a 1189 $self->_reload_class($class);
af31090c 1190 }
706ef173 1191 push @to_register, [$moniker, $class];
1192 }
af31090c 1193
706ef173 1194 Class::C3->reinitialize;
1195 for (@to_register) {
1196 $self->schema->register_class(@$_);
af31090c 1197 }
1198}
1199
01f93238 1200sub _moose_metaclass {
1201 return undef unless $INC{'Class/MOP.pm'}; # if CMOP is not loaded the class could not have loaded in the 1st place
1202
0dd4099e 1203 my $class = $_[1];
1204
1205 my $mc = try { Class::MOP::class_of($class) }
01f93238 1206 or return undef;
1207
1208 return $mc->isa('Moose::Meta::Class') ? $mc : undef;
1209}
1210
106a976a 1211# We use this instead of ensure_class_loaded when there are package symbols we
1212# want to preserve.
1213sub _reload_class {
1214 my ($self, $class) = @_;
1215
1216 my $class_path = $self->_class_path($class);
1217 delete $INC{ $class_path };
f53dcdf0 1218
1219# kill redefined warnings
1ad8e8c3 1220 try {
c38ec663 1221 eval_without_redefine_warnings ("require $class");
1ad8e8c3 1222 }
1223 catch {
61d1cca1 1224 my $source = slurp $self->_get_dump_filename($class);
1225 die "Failed to reload class $class: $_.\n\nCLASS SOURCE:\n\n$source";
f53dcdf0 1226 };
106a976a 1227}
1228
996be9ee 1229sub _get_dump_filename {
1230 my ($self, $class) = (@_);
1231
1232 $class =~ s{::}{/}g;
1233 return $self->dump_directory . q{/} . $class . q{.pm};
1234}
1235
1ad8e8c3 1236=head2 get_dump_filename
1237
1238Arguments: class
1239
1240Returns the full path to the file for a class that the class has been or will
1241be dumped to. This is a file in a temp dir for a dynamic schema.
1242
1243=cut
1244
1245sub get_dump_filename {
1246 my ($self, $class) = (@_);
1247
1248 local $self->{dump_directory} = $self->real_dump_directory;
1249
1250 return $self->_get_dump_filename($class);
1251}
1252
996be9ee 1253sub _ensure_dump_subdirs {
1254 my ($self, $class) = (@_);
1255
1256 my @name_parts = split(/::/, $class);
dd03ee1a 1257 pop @name_parts; # we don't care about the very last element,
1258 # which is a filename
1259
996be9ee 1260 my $dir = $self->dump_directory;
7cab3ab7 1261 while (1) {
1262 if(!-d $dir) {
25328cc4 1263 mkdir($dir) or croak "mkdir('$dir') failed: $!";
996be9ee 1264 }
7cab3ab7 1265 last if !@name_parts;
1266 $dir = File::Spec->catdir($dir, shift @name_parts);
996be9ee 1267 }
1268}
1269
1270sub _dump_to_dir {
af31090c 1271 my ($self, @classes) = @_;
996be9ee 1272
fc2b71fd 1273 my $schema_class = $self->schema_class;
9c9c2f2b 1274 my $schema_base_class = $self->schema_base_class || 'DBIx::Class::Schema';
996be9ee 1275
e9b8719e 1276 my $target_dir = $self->dump_directory;
af31090c 1277 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n"
1278 unless $self->{dynamic} or $self->{quiet};
996be9ee 1279
7cab3ab7 1280 my $schema_text =
1281 qq|package $schema_class;\n\n|
b4dcbcc5 1282 . qq|# Created by DBIx::Class::Schema::Loader\n|
1ad8e8c3 1283 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|;
1284
dcaf302a 1285 if ($self->use_moose) {
49643e1d 1286 $schema_text.= qq|use Moose;\nuse namespace::autoclean;\nextends '$schema_base_class';\n\n|;
dcaf302a 1287 }
1288 else {
1ad8e8c3 1289 $schema_text .= qq|use strict;\nuse warnings;\n\nuse base '$schema_base_class';\n\n|;
dcaf302a 1290 }
f44ecc2f 1291
f44ecc2f 1292 if ($self->use_namespaces) {
1293 $schema_text .= qq|__PACKAGE__->load_namespaces|;
1294 my $namespace_options;
2a8e93e9 1295
1296 my @attr = qw/resultset_namespace default_resultset_class/;
1297
1298 unshift @attr, 'result_namespace' unless (not $self->result_namespace) || $self->result_namespace eq 'Result';
1299
1300 for my $attr (@attr) {
f44ecc2f 1301 if ($self->$attr) {
1302 $namespace_options .= qq| $attr => '| . $self->$attr . qq|',\n|
1303 }
1304 }
1305 $schema_text .= qq|(\n$namespace_options)| if $namespace_options;
1306 $schema_text .= qq|;\n|;
1307 }
1308 else {
1309 $schema_text .= qq|__PACKAGE__->load_classes;\n|;
f44ecc2f 1310 }
996be9ee 1311
1c95b304 1312 {
1313 local $self->{version_to_dump} = $self->schema_version_to_dump;
68d49e50 1314 $self->_write_classfile($schema_class, $schema_text, 1);
1c95b304 1315 }
996be9ee 1316
2229729e 1317 my $result_base_class = $self->result_base_class || 'DBIx::Class::Core';
9c9c2f2b 1318
af31090c 1319 foreach my $src_class (@classes) {
7cab3ab7 1320 my $src_text =
1321 qq|package $src_class;\n\n|
b4dcbcc5 1322 . qq|# Created by DBIx::Class::Schema::Loader\n|
1323 . qq|# DO NOT MODIFY THE FIRST PART OF THIS FILE\n\n|
dcaf302a 1324 . qq|use strict;\nuse warnings;\n\n|;
1325 if ($self->use_moose) {
6c2b21a5 1326 $src_text.= qq|use Moose;\nuse MooseX::NonMoose;\nuse namespace::autoclean;|;
1327
1328 # these options 'use base' which is compile time
2b74a06b 1329 if (@{ $self->left_base_classes } || @{ $self->additional_base_classes }) {
6c2b21a5 1330 $src_text .= qq|\nBEGIN { extends '$result_base_class' }\n\n|;
1331 }
1332 else {
1333 $src_text .= qq|\nextends '$result_base_class';\n\n|;
1334 }
dcaf302a 1335 }
1336 else {
1337 $src_text .= qq|use base '$result_base_class';\n\n|;
1338 }
7cab3ab7 1339 $self->_write_classfile($src_class, $src_text);
02356864 1340 }
996be9ee 1341
a4b94090 1342 # remove Result dir if downgrading from use_namespaces, and there are no
1343 # files left.
b5f1b43c 1344 if (my $result_ns = $self->_downgrading_to_load_classes
1345 || $self->_rewriting_result_namespace) {
540a8149 1346 my $result_namespace = $self->_result_namespace(
1347 $schema_class,
1348 $result_ns,
1349 );
a4b94090 1350
540a8149 1351 (my $result_dir = $result_namespace) =~ s{::}{/}g;
a4b94090 1352 $result_dir = $self->dump_directory . '/' . $result_dir;
1353
1354 unless (my @files = glob "$result_dir/*") {
1355 rmdir $result_dir;
1356 }
1357 }
1358
af31090c 1359 warn "Schema dump completed.\n" unless $self->{dynamic} or $self->{quiet};
1360
7cab3ab7 1361}
1362
79193756 1363sub _sig_comment {
1364 my ($self, $version, $ts) = @_;
1365 return qq|\n\n# Created by DBIx::Class::Schema::Loader|
1366 . qq| v| . $version
1367 . q| @ | . $ts
1368 . qq|\n# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:|;
1369}
1370
7cab3ab7 1371sub _write_classfile {
68d49e50 1372 my ($self, $class, $text, $is_schema) = @_;
7cab3ab7 1373
1374 my $filename = $self->_get_dump_filename($class);
1375 $self->_ensure_dump_subdirs($class);
1376
28b4691d 1377 if (-f $filename && $self->really_erase_my_files) {
7cab3ab7 1378 warn "Deleting existing file '$filename' due to "
af31090c 1379 . "'really_erase_my_files' setting\n" unless $self->{quiet};
7cab3ab7 1380 unlink($filename);
8de81918 1381 }
7cab3ab7 1382
8de81918 1383 my ($old_gen, $old_md5, $old_ver, $old_ts, $old_custom)
1384 = $self->_parse_generated_file($filename);
17ca645f 1385
8de81918 1386 if (! $old_gen && -f $filename) {
1387 croak "Cannot overwrite '$filename' without 'really_erase_my_files',"
1388 . " it does not appear to have been generated by Loader"
1389 }
c9cf9b4d 1390
8de81918 1391 my $custom_content = $old_custom || '';
c9cf9b4d 1392
8de81918 1393 # prepend extra custom content from a *renamed* class (singularization effect)
1394 if (my $renamed_class = $self->_upgrading_classes->{$class}) {
1395 my $old_filename = $self->_get_dump_filename($renamed_class);
c9cf9b4d 1396
8de81918 1397 if (-f $old_filename) {
1398 my $extra_custom = ($self->_parse_generated_file ($old_filename))[4];
1399
1400 $extra_custom =~ s/\n\n# You can replace.*\n1;\n//;
1401
1402 $custom_content = join ("\n", '', $extra_custom, $custom_content)
1403 if $extra_custom;
1404
1405 unlink $old_filename;
c9cf9b4d 1406 }
1407 }
1408
49643e1d 1409 $custom_content ||= $self->_default_custom_content($is_schema);
f53dcdf0 1410
8de81918 1411 # If upgrading to use_moose=1 replace default custom content with default Moose custom content.
1412 # If there is already custom content, which does not have the Moose content, add it.
1413 if ($self->use_moose) {
ffc705f3 1414
8de81918 1415 my $non_moose_custom_content = do {
1416 local $self->{use_moose} = 0;
1417 $self->_default_custom_content;
1418 };
f53dcdf0 1419
8de81918 1420 if ($custom_content eq $non_moose_custom_content) {
49643e1d 1421 $custom_content = $self->_default_custom_content($is_schema);
8de81918 1422 }
49643e1d 1423 elsif ($custom_content !~ /\Q@{[$self->_default_moose_custom_content($is_schema)]}\E/) {
1424 $custom_content .= $self->_default_custom_content($is_schema);
f53dcdf0 1425 }
1426 }
22edddda 1427 elsif (defined $self->use_moose && $old_gen) {
1428 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'
1429 if $old_gen =~ /use \s+ MooseX?\b/x;
1430 }
f53dcdf0 1431
b24cb177 1432 $custom_content = $self->_rewrite_old_classnames($custom_content);
1433
7cab3ab7 1434 $text .= qq|$_\n|
1435 for @{$self->{_dump_storage}->{$class} || []};
1436
79193756 1437 # Check and see if the dump is infact differnt
1438
1439 my $compare_to;
1440 if ($old_md5) {
1441 $compare_to = $text . $self->_sig_comment($old_ver, $old_ts);
79193756 1442 if (Digest::MD5::md5_base64($compare_to) eq $old_md5) {
68d49e50 1443 return unless $self->_upgrading_from && $is_schema;
79193756 1444 }
1445 }
1446
1447 $text .= $self->_sig_comment(
01012543 1448 $self->version_to_dump,
79193756 1449 POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime)
1450 );
7cab3ab7 1451
1452 open(my $fh, '>', $filename)
1453 or croak "Cannot open '$filename' for writing: $!";
1454
1455 # Write the top half and its MD5 sum
a4476f41 1456 print $fh $text . Digest::MD5::md5_base64($text) . "\n";
7cab3ab7 1457
1458 # Write out anything loaded via external partial class file in @INC
1459 print $fh qq|$_\n|
1460 for @{$self->{_ext_storage}->{$class} || []};
1461
1eea4fb1 1462 # Write out any custom content the user has added
7cab3ab7 1463 print $fh $custom_content;
1464
1465 close($fh)
e9b8719e 1466 or croak "Error closing '$filename': $!";
7cab3ab7 1467}
1468
c9cf9b4d 1469sub _default_moose_custom_content {
49643e1d 1470 my ($self, $is_schema) = @_;
1471
1472 if (not $is_schema) {
1473 return qq|\n__PACKAGE__->meta->make_immutable;|;
1474 }
1475
1476 return qq|\n__PACKAGE__->meta->make_immutable(inline_constructor => 0);|;
c9cf9b4d 1477}
1478
79193756 1479sub _default_custom_content {
49643e1d 1480 my ($self, $is_schema) = @_;
dcaf302a 1481 my $default = qq|\n\n# You can replace this text with custom|
b8e1a9d5 1482 . qq| code or comments, and it will be preserved on regeneration|;
dcaf302a 1483 if ($self->use_moose) {
49643e1d 1484 $default .= $self->_default_moose_custom_content($is_schema);
dcaf302a 1485 }
1486 $default .= qq|\n1;\n|;
1487 return $default;
79193756 1488}
1489
8de81918 1490sub _parse_generated_file {
1491 my ($self, $fn) = @_;
7cab3ab7 1492
8de81918 1493 return unless -f $fn;
79193756 1494
8de81918 1495 open(my $fh, '<', $fn)
1496 or croak "Cannot open '$fn' for reading: $!";
7cab3ab7 1497
8de81918 1498 my $mark_re =
419a2eeb 1499 qr{^(# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:)([A-Za-z0-9/+]{22})\n};
7cab3ab7 1500
8de81918 1501 my ($md5, $ts, $ver, $gen);
7cab3ab7 1502 while(<$fh>) {
8de81918 1503 if(/$mark_re/) {
1504 my $pre_md5 = $1;
79193756 1505 $md5 = $2;
79193756 1506
8de81918 1507 # Pull out the version and timestamp from the line above
1508 ($ver, $ts) = $gen =~ m/^# Created by DBIx::Class::Schema::Loader v(.*?) @ (.*?)\Z/m;
79193756 1509
8de81918 1510 $gen .= $pre_md5;
1511 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"
1512 if !$self->overwrite_modifications && Digest::MD5::md5_base64($gen) ne $md5;
7cab3ab7 1513
8de81918 1514 last;
7cab3ab7 1515 }
1516 else {
8de81918 1517 $gen .= $_;
7cab3ab7 1518 }
996be9ee 1519 }
1520
8de81918 1521 my $custom = do { local $/; <$fh> }
1522 if $md5;
5ef3c771 1523
8de81918 1524 close ($fh);
5ef3c771 1525
8de81918 1526 return ($gen, $md5, $ver, $ts, $custom);
996be9ee 1527}
1528
1529sub _use {
1530 my $self = shift;
1531 my $target = shift;
1532
1533 foreach (@_) {
cb54990b 1534 warn "$target: use $_;" if $self->debug;
996be9ee 1535 $self->_raw_stmt($target, "use $_;");
996be9ee 1536 }
1537}
1538
1539sub _inject {
1540 my $self = shift;
1541 my $target = shift;
996be9ee 1542
af31090c 1543 my $blist = join(q{ }, @_);
6c2b21a5 1544
1545 return unless $blist;
1546
1547 warn "$target: use base qw/$blist/;" if $self->debug;
1548 $self->_raw_stmt($target, "use base qw/$blist/;");
996be9ee 1549}
1550
540a8149 1551sub _result_namespace {
1552 my ($self, $schema_class, $ns) = @_;
1553 my @result_namespace;
1554
1555 if ($ns =~ /^\+(.*)/) {
1556 # Fully qualified namespace
1557 @result_namespace = ($1)
1558 }
1559 else {
1560 # Relative namespace
1561 @result_namespace = ($schema_class, $ns);
1562 }
1563
1564 return wantarray ? @result_namespace : join '::', @result_namespace;
1565}
1566
f96ef30f 1567# Create class with applicable bases, setup monikers, etc
1568sub _make_src_class {
1569 my ($self, $table) = @_;
996be9ee 1570
a13b2803 1571 my $schema = $self->schema;
1572 my $schema_class = $self->schema_class;
996be9ee 1573
f96ef30f 1574 my $table_moniker = $self->_table2moniker($table);
f44ecc2f 1575 my @result_namespace = ($schema_class);
1576 if ($self->use_namespaces) {
1577 my $result_namespace = $self->result_namespace || 'Result';
540a8149 1578 @result_namespace = $self->_result_namespace(
1579 $schema_class,
1580 $result_namespace,
1581 );
f44ecc2f 1582 }
1583 my $table_class = join(q{::}, @result_namespace, $table_moniker);
996be9ee 1584
805dbe0a 1585 if ((my $upgrading_v = $self->_upgrading_from)
a4b94090 1586 || $self->_rewriting) {
805dbe0a 1587 local $self->naming->{monikers} = $upgrading_v
1588 if $upgrading_v;
1589
1590 my @result_namespace = @result_namespace;
a4b94090 1591 if ($self->_upgrading_from_load_classes) {
1592 @result_namespace = ($schema_class);
1593 }
1594 elsif (my $ns = $self->_downgrading_to_load_classes) {
540a8149 1595 @result_namespace = $self->_result_namespace(
1596 $schema_class,
1597 $ns,
1598 );
1599 }
1600 elsif ($ns = $self->_rewriting_result_namespace) {
1601 @result_namespace = $self->_result_namespace(
1602 $schema_class,
1603 $ns,
1604 );
a4b94090 1605 }
f53dcdf0 1606
1607 my $old_class = join(q{::}, @result_namespace,
1608 $self->_table2moniker($table));
1609
68d49e50 1610 $self->_upgrading_classes->{$table_class} = $old_class
1611 unless $table_class eq $old_class;
f53dcdf0 1612 }
1613
bfb43060 1614# this was a bad idea, should be ok now without it
1615# my $table_normalized = lc $table;
1616# $self->classes->{$table_normalized} = $table_class;
1617# $self->monikers->{$table_normalized} = $table_moniker;
1618
f96ef30f 1619 $self->classes->{$table} = $table_class;
f96ef30f 1620 $self->monikers->{$table} = $table_moniker;
996be9ee 1621
f96ef30f 1622 $self->_use ($table_class, @{$self->additional_classes});
af31090c 1623 $self->_inject($table_class, @{$self->left_base_classes});
996be9ee 1624
8d65c820 1625 my @components = @{ $self->components || [] };
5ad21d3c 1626
1627 push @components, @{ $self->result_component_map->{$table_moniker} }
1628 if exists $self->result_component_map->{$table_moniker};
1629
8d65c820 1630 $self->_dbic_stmt($table_class, 'load_components', @components) if @components;
996be9ee 1631
af31090c 1632 $self->_inject($table_class, @{$self->additional_base_classes});
f96ef30f 1633}
996be9ee 1634
26c54680 1635sub _is_result_class_method {
8d65c820 1636 my ($self, $name, $table_name) = @_;
1637
1638 my $table_moniker = $table_name ? $self->_table2moniker($table_name) : '';
9fdf3d5b 1639
26c54680 1640 if (not $self->_result_class_methods) {
1641 my (@methods, %methods);
1642 my $base = $self->result_base_class || 'DBIx::Class::Core';
5ad21d3c 1643
1644 my @components = @{ $self->components || [] };
1645
1646 push @components, @{ $self->result_component_map->{$table_moniker} }
1647 if exists $self->result_component_map->{$table_moniker};
1648
1649 for my $c (@components) {
1650 $c = $c =~ /^\+/ ? substr($c,1) : "DBIx::Class::$c";
8d65c820 1651 }
9fdf3d5b 1652
26c54680 1653 for my $class ($base, @components, $self->use_moose ? 'Moose::Object' : ()) {
1654 load_class $class;
15c4393b 1655
26c54680 1656 push @methods, @{ Class::Inspector->methods($class) || [] };
1657 }
9fdf3d5b 1658
26c54680 1659 push @methods, @{ Class::Inspector->methods('UNIVERSAL') };
9fdf3d5b 1660
26c54680 1661 @methods{@methods} = ();
9fdf3d5b 1662
26c54680 1663 # futureproof meta
1664 $methods{meta} = undef;
61d1cca1 1665
26c54680 1666 $self->_result_class_methods(\%methods);
a7116285 1667 }
26c54680 1668 my $result_methods = $self->_result_class_methods;
1669
1670 return exists $result_methods->{$name};
a7116285 1671}
1672
1673sub _resolve_col_accessor_collisions {
1674 my ($self, $table, $col_info) = @_;
1675
1676 my $table_name = ref $table ? $$table : $table;
6c2b21a5 1677
9fdf3d5b 1678 while (my ($col, $info) = each %$col_info) {
1679 my $accessor = $info->{accessor} || $col;
1680
c9486c78 1681 next if $accessor eq 'id'; # special case (very common column)
9fdf3d5b 1682
8d65c820 1683 if ($self->_is_result_class_method($accessor, $table_name)) {
15c4393b 1684 my $mapped = 0;
1685
1686 if (my $map = $self->col_collision_map) {
1687 for my $re (keys %$map) {
1688 if (my @matches = $col =~ /$re/) {
1689 $info->{accessor} = sprintf $map->{$re}, @matches;
1690 $mapped = 1;
1691 }
1692 }
1693 }
1694
1695 if (not $mapped) {
1696 warn <<"EOF";
a7116285 1697Column '$col' in table '$table_name' collides with an inherited method.
15c4393b 1698See "COLUMN ACCESSOR COLLISIONS" in perldoc DBIx::Class::Schema::Loader::Base .
1699EOF
1700 $info->{accessor} = undef;
1701 }
9fdf3d5b 1702 }
1703 }
1704}
1705
3fea497f 1706# use the same logic to run moniker_map, col_accessor_map, and
cfc5dce3 1707# relationship_name_map
1708sub _run_user_map {
1709 my ( $self, $map, $default_code, $ident, @extra ) = @_;
1710
1711 my $default_ident = $default_code->( $ident, @extra );
1712 my $new_ident;
1713 if( $map && ref $map eq 'HASH' ) {
1714 $new_ident = $map->{ $ident };
1715 }
1716 elsif( $map && ref $map eq 'CODE' ) {
1717 $new_ident = $map->( $ident, $default_ident, @extra );
1718 }
1719
1720 $new_ident ||= $default_ident;
1721
1722 return $new_ident;
1723}
1724
1725sub _default_column_accessor_name {
1726 my ( $self, $column_name ) = @_;
1727
1728 my $accessor_name = $column_name;
1729 $accessor_name =~ s/\W+/_/g;
1730
61d1cca1 1731 if ((($self->naming->{column_accessors}||'') =~ /(\d+)/ && $1 < 7) || (not $self->preserve_case)) {
cfc5dce3 1732 # older naming just lc'd the col accessor and that's all.
1733 return lc $accessor_name;
1734 }
f3a657ef 1735
cc4f11a2 1736 return join '_', map lc, split_name $column_name;
cfc5dce3 1737
1738}
61d1cca1 1739
cfc5dce3 1740sub _make_column_accessor_name {
1741 my ($self, $column_name, $column_context_info ) = @_;
1742
1743 my $accessor = $self->_run_user_map(
3fea497f 1744 $self->col_accessor_map,
cfc5dce3 1745 sub { $self->_default_column_accessor_name( shift ) },
1746 $column_name,
1747 $column_context_info,
1748 );
1749
1750 return $accessor;
f3a657ef 1751}
1752
af31090c 1753# Set up metadata (cols, pks, etc)
f96ef30f 1754sub _setup_src_meta {
1755 my ($self, $table) = @_;
996be9ee 1756
f96ef30f 1757 my $schema = $self->schema;
1758 my $schema_class = $self->schema_class;
a13b2803 1759
f96ef30f 1760 my $table_class = $self->classes->{$table};
1761 my $table_moniker = $self->monikers->{$table};
996be9ee 1762
ff30991a 1763 my $table_name = $table;
1764 my $name_sep = $self->schema->storage->sql_maker->name_sep;
1765
c177d483 1766 if ($name_sep && $table_name =~ /\Q$name_sep\E/) {
ff30991a 1767 $table_name = \ $self->_quote_table_name($table_name);
1768 }
1769
b1d11550 1770 my $full_table_name = ($self->qualify_objects ? ($self->db_schema . '.') : '') . (ref $table_name ? $$table_name : $table_name);
1771
1772 # be careful to not create refs Data::Dump can "optimize"
1773 $full_table_name = \do {"".$full_table_name} if ref $table_name;
1774
1775 $self->_dbic_stmt($table_class, 'table', $full_table_name);
996be9ee 1776
cfc5dce3 1777 my $cols = $self->_table_columns($table);
45be2ce7 1778 my $col_info = $self->__columns_info_for($table);
df55c5fa 1779
cfc5dce3 1780 ### generate all the column accessor names
df55c5fa 1781 while (my ($col, $info) = each %$col_info) {
cfc5dce3 1782 # hashref of other info that could be used by
1783 # user-defined accessor map functions
1784 my $context = {
1785 table_class => $table_class,
1786 table_moniker => $table_moniker,
1787 table_name => $table_name,
1788 full_table_name => $full_table_name,
1789 schema_class => $schema_class,
1790 column_info => $info,
1791 };
df55c5fa 1792
cfc5dce3 1793 $info->{accessor} = $self->_make_column_accessor_name( $col, $context );
45be2ce7 1794 }
c9373b79 1795
15c4393b 1796 $self->_resolve_col_accessor_collisions($full_table_name, $col_info);
9fdf3d5b 1797
cfc5dce3 1798 # prune any redundant accessor names
1799 while (my ($col, $info) = each %$col_info) {
1800 no warnings 'uninitialized';
1801 delete $info->{accessor} if $info->{accessor} eq $col;
1802 }
1803
45be2ce7 1804 my $fks = $self->_table_fk_info($table);
565335e6 1805
10c0c4f3 1806 foreach my $fkdef (@$fks) {
45be2ce7 1807 for my $col (@{ $fkdef->{local_columns} }) {
1808 $col_info->{$col}{is_foreign_key} = 1;
e7213f4f 1809 }
996be9ee 1810 }
10c0c4f3 1811
1812 my $pks = $self->_table_pk_info($table) || [];
1813
1814 foreach my $pkcol (@$pks) {
1815 $col_info->{$pkcol}{is_nullable} = 0;
1816 }
1817
45be2ce7 1818 $self->_dbic_stmt(
1819 $table_class,
1820 'add_columns',
1821 map { $_, ($col_info->{$_}||{}) } @$cols
1822 );
996be9ee 1823
d70c335f 1824 my %uniq_tag; # used to eliminate duplicate uniqs
1825
f96ef30f 1826 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
1827 : carp("$table has no primary key");
d70c335f 1828 $uniq_tag{ join("\0", @$pks) }++ if @$pks; # pk is a uniq
996be9ee 1829
f96ef30f 1830 my $uniqs = $self->_table_uniq_info($table) || [];
d70c335f 1831 for (@$uniqs) {
1832 my ($name, $cols) = @$_;
1833 next if $uniq_tag{ join("\0", @$cols) }++; # skip duplicates
1834 $self->_dbic_stmt($table_class,'add_unique_constraint', $name, $cols);
1835 }
1836
996be9ee 1837}
1838
d67d058e 1839sub __columns_info_for {
1840 my ($self, $table) = @_;
1841
1842 my $result = $self->_columns_info_for($table);
1843
1844 while (my ($col, $info) = each %$result) {
1845 $info = { %$info, %{ $self->_custom_column_info ($table, $col, $info) } };
1846 $info = { %$info, %{ $self->_datetime_column_info($table, $col, $info) } };
1847
1848 $result->{$col} = $info;
1849 }
1850
1851 return $result;
1852}
1853
996be9ee 1854=head2 tables
1855
1856Returns a sorted list of loaded tables, using the original database table
1857names.
1858
1859=cut
1860
1861sub tables {
1862 my $self = shift;
1863
b97c2c1e 1864 return keys %{$self->_tables};
996be9ee 1865}
1866
1867# Make a moniker from a table
c39e403e 1868sub _default_table2moniker {
66afce69 1869 no warnings 'uninitialized';
c39e403e 1870 my ($self, $table) = @_;
1871
a8d229ff 1872 if ($self->naming->{monikers} eq 'v4') {
1873 return join '', map ucfirst, split /[\W_]+/, lc $table;
1874 }
ecf930e6 1875 elsif ($self->naming->{monikers} eq 'v5') {
1876 return join '', map ucfirst, split /[\W_]+/,
1877 Lingua::EN::Inflect::Number::to_S(lc $table);
1878 }
9990e58f 1879 elsif ($self->naming->{monikers} eq 'v6') {
1880 (my $as_phrase = lc $table) =~ s/_+/ /g;
1881 my $inflected = Lingua::EN::Inflect::Phrase::to_S($as_phrase);
1882
1883 return join '', map ucfirst, split /\W+/, $inflected;
1884 }
1885
cc4f11a2 1886 my @words = map lc, split_name $table;
9990e58f 1887 my $as_phrase = join ' ', @words;
ecf930e6 1888
ecf930e6 1889 my $inflected = Lingua::EN::Inflect::Phrase::to_S($as_phrase);
a8d229ff 1890
ecf930e6 1891 return join '', map ucfirst, split /\W+/, $inflected;
c39e403e 1892}
1893
996be9ee 1894sub _table2moniker {
1895 my ( $self, $table ) = @_;
1896
cfc5dce3 1897 $self->_run_user_map(
1898 $self->moniker_map,
1899 sub { $self->_default_table2moniker( shift ) },
1900 $table
1901 );
996be9ee 1902}
1903
1904sub _load_relationships {
e8ad6491 1905 my ($self, $table) = @_;
996be9ee 1906
e8ad6491 1907 my $tbl_fk_info = $self->_table_fk_info($table);
1908 foreach my $fkdef (@$tbl_fk_info) {
1909 $fkdef->{remote_source} =
1910 $self->monikers->{delete $fkdef->{remote_table}};
996be9ee 1911 }
26f1c8c9 1912 my $tbl_uniq_info = $self->_table_uniq_info($table);
996be9ee 1913
e8ad6491 1914 my $local_moniker = $self->monikers->{$table};
7824616e 1915 my $rel_stmts = $self->_relbuilder->generate_code($local_moniker, $tbl_fk_info, $tbl_uniq_info);
996be9ee 1916
996be9ee 1917 foreach my $src_class (sort keys %$rel_stmts) {
1918 my $src_stmts = $rel_stmts->{$src_class};
1919 foreach my $stmt (@$src_stmts) {
1920 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
1921 }
1922 }
1923}
1924
1925# Overload these in driver class:
1926
1927# Returns an arrayref of column names
1928sub _table_columns { croak "ABSTRACT METHOD" }
1929
1930# Returns arrayref of pk col names
1931sub _table_pk_info { croak "ABSTRACT METHOD" }
1932
1933# Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
1934sub _table_uniq_info { croak "ABSTRACT METHOD" }
1935
1936# Returns an arrayref of foreign key constraints, each
1937# being a hashref with 3 keys:
1938# local_columns (arrayref), remote_columns (arrayref), remote_table
1939sub _table_fk_info { croak "ABSTRACT METHOD" }
1940
1941# Returns an array of lower case table names
1942sub _tables_list { croak "ABSTRACT METHOD" }
1943
1944# Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
1945sub _dbic_stmt {
bf654ab9 1946 my $self = shift;
1947 my $class = shift;
996be9ee 1948 my $method = shift;
bf654ab9 1949
1950 # generate the pod for this statement, storing it with $self->_pod
43b982ea 1951 $self->_make_pod( $class, $method, @_ ) if $self->generate_pod;
bf654ab9 1952
1953 my $args = dump(@_);
1954 $args = '(' . $args . ')' if @_ < 2;
1955 my $stmt = $method . $args . q{;};
1956
1957 warn qq|$class\->$stmt\n| if $self->debug;
1958 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
1959 return;
1960}
1961
1962# generates the accompanying pod for a DBIC class method statement,
1963# storing it with $self->_pod
1964sub _make_pod {
1965 my $self = shift;
1966 my $class = shift;
1967 my $method = shift;
1968
fbcfebdd 1969 if ( $method eq 'table' ) {
1970 my ($table) = @_;
43b982ea 1971 my $pcm = $self->pod_comment_mode;
1972 my ($comment, $comment_overflows, $comment_in_name, $comment_in_desc);
fd97abca 1973 $comment = $self->__table_comment($table);
1974 $comment_overflows = ($comment and length $comment > $self->pod_comment_spillover_length);
1975 $comment_in_name = ($pcm eq 'name' or ($pcm eq 'auto' and !$comment_overflows));
1976 $comment_in_desc = ($pcm eq 'description' or ($pcm eq 'auto' and $comment_overflows));
43b982ea 1977 $self->_pod( $class, "=head1 NAME" );
1978 my $table_descr = $class;
1979 $table_descr .= " - " . $comment if $comment and $comment_in_name;
fbcfebdd 1980 $self->{_class2table}{ $class } = $table;
1981 $self->_pod( $class, $table_descr );
43b982ea 1982 if ($comment and $comment_in_desc) {
1983 $self->_pod( $class, "=head1 DESCRIPTION" );
1984 $self->_pod( $class, $comment );
1985 }
fbcfebdd 1986 $self->_pod_cut( $class );
1987 } elsif ( $method eq 'add_columns' ) {
1988 $self->_pod( $class, "=head1 ACCESSORS" );
79a00530 1989 my $col_counter = 0;
ceb009d3 1990 my @cols = @_;
79a00530 1991 while( my ($name,$attrs) = splice @cols,0,2 ) {
ceb009d3 1992 $col_counter++;
79a00530 1993 $self->_pod( $class, '=head2 ' . $name );
ceb009d3 1994 $self->_pod( $class,
1995 join "\n", map {
1996 my $s = $attrs->{$_};
1997 $s = !defined $s ? 'undef' :
1998 length($s) == 0 ? '(empty string)' :
1999 ref($s) eq 'SCALAR' ? $$s :
2000 ref($s) ? dumper_squashed $s :
2001 looks_like_number($s) ? $s : qq{'$s'};
2002
2003 " $_: $s"
2004 } sort keys %$attrs,
2005 );
4cd5155b 2006 if (my $comment = $self->__column_comment($self->{_class2table}{$class}, $col_counter, $name)) {
ceb009d3 2007 $self->_pod( $class, $comment );
2008 }
fbcfebdd 2009 }
2010 $self->_pod_cut( $class );
2011 } elsif ( $method =~ /^(belongs_to|has_many|might_have)$/ ) {
2012 $self->_pod( $class, "=head1 RELATIONS" ) unless $self->{_relations_started} { $class } ;
2013 my ( $accessor, $rel_class ) = @_;
2014 $self->_pod( $class, "=head2 $accessor" );
2015 $self->_pod( $class, 'Type: ' . $method );
2016 $self->_pod( $class, "Related object: L<$rel_class>" );
2017 $self->_pod_cut( $class );
2018 $self->{_relations_started} { $class } = 1;
2019 }
996be9ee 2020}
2021
fd97abca 2022sub _filter_comment {
2023 my ($self, $txt) = @_;
2024
2025 $txt = '' if not defined $txt;
2026
2027 $txt =~ s/(?:\015?\012|\015\012?)/\n/g;
2028
2029 return $txt;
2030}
2031
2032sub __table_comment {
2033 my $self = shift;
2034
2035 if (my $code = $self->can('_table_comment')) {
2036 return $self->_filter_comment($self->$code(@_));
2037 }
2038
2039 return '';
2040}
2041
2042sub __column_comment {
2043 my $self = shift;
2044
2045 if (my $code = $self->can('_column_comment')) {
2046 return $self->_filter_comment($self->$code(@_));
2047 }
2048
2049 return '';
2050}
2051
fbcfebdd 2052# Stores a POD documentation
2053sub _pod {
2054 my ($self, $class, $stmt) = @_;
2055 $self->_raw_stmt( $class, "\n" . $stmt );
2056}
2057
2058sub _pod_cut {
2059 my ($self, $class ) = @_;
2060 $self->_raw_stmt( $class, "\n=cut\n" );
2061}
2062
996be9ee 2063# Store a raw source line for a class (for dumping purposes)
2064sub _raw_stmt {
2065 my ($self, $class, $stmt) = @_;
af31090c 2066 push(@{$self->{_dump_storage}->{$class}}, $stmt);
996be9ee 2067}
2068
7cab3ab7 2069# Like above, but separately for the externally loaded stuff
2070sub _ext_stmt {
2071 my ($self, $class, $stmt) = @_;
af31090c 2072 push(@{$self->{_ext_storage}->{$class}}, $stmt);
7cab3ab7 2073}
2074
565335e6 2075sub _quote_table_name {
2076 my ($self, $table) = @_;
2077
2078 my $qt = $self->schema->storage->sql_maker->quote_char;
2079
c177d483 2080 return $table unless $qt;
2081
565335e6 2082 if (ref $qt) {
2083 return $qt->[0] . $table . $qt->[1];
2084 }
2085
2086 return $qt . $table . $qt;
2087}
2088
b639d969 2089sub _custom_column_info {
23d1f36b 2090 my ( $self, $table_name, $column_name, $column_info ) = @_;
b639d969 2091
d67d058e 2092 if (my $code = $self->custom_column_info) {
2093 return $code->($table_name, $column_name, $column_info) || {};
b639d969 2094 }
3a368709 2095 return {};
b639d969 2096}
2097
42e785fa 2098sub _datetime_column_info {
23d1f36b 2099 my ( $self, $table_name, $column_name, $column_info ) = @_;
d67d058e 2100 my $result = {};
2101 my $type = $column_info->{data_type} || '';
2102 if ((grep $_, @{ $column_info }{map "inflate_$_", qw/date datetime timestamp/})
2103 or ($type =~ /date|timestamp/i)) {
2104 $result->{timezone} = $self->datetime_timezone if $self->datetime_timezone;
2105 $result->{locale} = $self->datetime_locale if $self->datetime_locale;
42e785fa 2106 }
d67d058e 2107 return $result;
42e785fa 2108}
2109
bc1cb85e 2110sub _lc {
2111 my ($self, $name) = @_;
2112
2113 return $self->preserve_case ? $name : lc($name);
2114}
2115
2116sub _uc {
2117 my ($self, $name) = @_;
2118
2119 return $self->preserve_case ? $name : uc($name);
2120}
2121
0c1d5b47 2122sub _unregister_source_for_table {
2123 my ($self, $table) = @_;
2124
1ad8e8c3 2125 try {
0c1d5b47 2126 local $@;
2127 my $schema = $self->schema;
2128 # in older DBIC it's a private method
2129 my $unregister = $schema->can('unregister_source') || $schema->can('_unregister_source');
2130 $schema->$unregister($self->_table2moniker($table));
2131 delete $self->monikers->{$table};
2132 delete $self->classes->{$table};
2133 delete $self->_upgrading_classes->{$table};
2134 delete $self->{_tables}{$table};
2135 };
2136}
2137
ffc705f3 2138# remove the dump dir from @INC on destruction
2139sub DESTROY {
2140 my $self = shift;
2141
2142 @INC = grep $_ ne $self->dump_directory, @INC;
2143}
2144
996be9ee 2145=head2 monikers
2146
8f9d7ce5 2147Returns a hashref of loaded table to moniker mappings. There will
996be9ee 2148be two entries for each table, the original name and the "normalized"
2149name, in the case that the two are different (such as databases
2150that like uppercase table names, or preserve your original mixed-case
2151definitions, or what-have-you).
2152
2153=head2 classes
2154
8f9d7ce5 2155Returns a hashref of table to class mappings. In some cases it will
996be9ee 2156contain multiple entries per table for the original and normalized table
2157names, as above in L</monikers>.
2158
15c4393b 2159=head1 COLUMN ACCESSOR COLLISIONS
2160
2161Occasionally you may have a column name that collides with a perl method, such
2162as C<can>. In such cases, the default action is to set the C<accessor> of the
2163column spec to C<undef>.
2164
2165You can then name the accessor yourself by placing code such as the following
2166below the md5:
2167
2168 __PACKAGE__->add_column('+can' => { accessor => 'my_can' });
2169
2170Another option is to use the L</col_collision_map> option.
2171
a7116285 2172=head1 RELATIONSHIP NAME COLLISIONS
2173
2174In very rare cases, you may get a collision between a generated relationship
2175name and a method in your Result class, for example if you have a foreign key
2176called C<belongs_to>.
2177
2178This is a problem because relationship names are also relationship accessor
2179methods in L<DBIx::Class>.
2180
2181The default behavior is to append C<_rel> to the relationship name and print
2182out a warning that refers to this text.
2183
2184You can also control the renaming with the L</rel_collision_map> option.
2185
996be9ee 2186=head1 SEE ALSO
2187
2188L<DBIx::Class::Schema::Loader>
2189
be80bba7 2190=head1 AUTHOR
2191
9cc8e7e1 2192See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 2193
2194=head1 LICENSE
2195
2196This library is free software; you can redistribute it and/or modify it under
2197the same terms as Perl itself.
2198
996be9ee 2199=cut
2200
22011;
bfb43060 2202# vim:et sts=4 sw=4 tw=0: