1 package DBIx::Class::Schema::Loader::Base;
5 use base qw/Class::Accessor::Fast/;
7 use Carp::Clan qw/^DBIx::Class::Schema::Loader/;
8 use UNIVERSAL::require;
9 use DBIx::Class::Schema::Loader::RelBuilder;
10 use Data::Dump qw/ dump /;
14 __PACKAGE__->mk_ro_accessors(qw/
21 additional_base_classes
33 legacy_default_inflections
43 DBIx::Class::Schema::Loader::Base - Base DBIx::Class::Schema::Loader Implementation.
47 See L<DBIx::Class::Schema::Loader>
51 This is the base class for the storage-specific C<DBIx::Class::Schema::*>
52 classes, and implements the common functionality between them.
54 =head1 CONSTRUCTOR OPTIONS
56 These constructor options are the base options for
57 L<DBIx::Class::Schema::Loader/loader_opts>. Available constructor options are:
61 Try to automatically detect/setup has_a and has_many relationships.
65 If set to true, each constructive L<DBIx::Class> statement the loader
66 decides to execute will be C<warn>-ed before execution.
70 Set the name of the schema to load (schema in the sense that your database
71 vendor means it). Does not currently support loading more than one schema
76 Only load tables matching regex. Best specified as a qr// regex.
80 Exclude tables matching regex. Best specified as a qr// regex.
84 Overrides the default table name to moniker translation. Can be either
85 a hashref of table keys and moniker values, or a coderef for a translator
86 function taking a single scalar table name argument and returning
87 a scalar moniker. If the hash entry does not exist, or the function
88 returns a false value, the code falls back to default behavior
91 The default behavior is: C<join '', map ucfirst, split /[\W_]+/, lc $table>,
92 which is to say: lowercase everything, split up the table name into chunks
93 anywhere a non-alpha-numeric character occurs, change the case of first letter
94 of each chunk to upper case, and put the chunks back together. Examples:
96 Table Name | Moniker Name
97 ---------------------------
99 luser_group | LuserGroup
100 luser-opts | LuserOpts
102 =head2 inflect_plural
104 Just like L</moniker_map> above (can be hash/code-ref, falls back to default
105 if hash key does not exist or coderef returns false), but acts as a map
106 for pluralizing relationship names. The default behavior is to utilize
107 L<Lingua::EN::Inflect::Number/to_PL>.
109 =head2 inflect_singular
111 As L</inflect_plural> above, but for singularizing relationship names.
112 Default behavior is to utilize L<Lingua::EN::Inflect::Number/to_S>.
114 =head2 additional_base_classes
116 List of additional base classes all of your table classes will use.
118 =head2 left_base_classes
120 List of additional base classes all of your table classes will use
121 that need to be leftmost.
123 =head2 additional_classes
125 List of additional classes which all of your table classes will use.
129 List of additional components to be loaded into all of your table
130 classes. A good example would be C<ResultSetManager>.
132 =head2 resultset_components
134 List of additional ResultSet components to be loaded into your table
135 classes. A good example would be C<AlwaysRS>. Component
136 C<ResultSetManager> will be automatically added to the above
137 C<components> list if this option is set.
139 =head2 legacy_default_inflections
141 Setting this option changes the default fallback for L</inflect_plural> to
142 utilize L<Lingua::EN::Inflect/PL>, and L</inflect_singular> to a no-op.
143 Those choices produce substandard results, but might be necessary to support
144 your existing code if you started developing on a version prior to 0.03 and
145 don't wish to go around updating all your relationship names to the new
148 This option will continue to be supported until at least version 0.05xxx,
149 but may dissappear sometime thereafter. It is recommended that you update
150 your code to use the newer-style inflections when you have the time.
152 =head2 dump_directory
154 This option is designed to be a tool to help you transition from this
155 loader to a manually-defined schema when you decide it's time to do so.
157 The value of this option is a perl libdir pathname. Within
158 that directory this module will create a baseline manual
159 L<DBIx::Class::Schema> module set, based on what it creates at runtime
162 The created schema class will have the same classname as the one on
163 which you are setting this option (and the ResultSource classes will be
164 based on this name as well). Therefore it is wise to note that if you
165 point the C<dump_directory> option of a schema class at the live libdir
166 where that class is currently located, it will overwrite itself with a
167 manual version of itself. This might be a really good or bad thing
168 depending on your situation and perspective.
170 Normally you wouldn't hard-code this setting in your schema class, as it
171 is meant for one-time manual usage.
173 See L<DBIx::Class::Schema::Loader/dump_to_dir> for examples of the
174 recommended way to access this functionality.
176 =head2 dump_overwrite
178 If set to a true value, the dumping code will overwrite existing files.
179 The default is false, which means the dumping code will die if it encounters
182 =head1 DEPRECATED CONSTRUCTOR OPTIONS
184 B<These will be removed in version 0.04000 !!!>
188 Equivalent to L</inflect_plural>.
192 Equivalent to L</inflect_plural>.
194 =head2 connect_info, dsn, user, password, options
196 You connect these schemas the same way you would any L<DBIx::Class::Schema>,
197 which is by calling either C<connect> or C<connection> on a schema class
198 or object. These options are only supported via the deprecated
199 C<load_from_connection> interface, which is also being removed in 0.04000.
203 None of these methods are intended for direct invocation by regular
204 users of L<DBIx::Class::Schema::Loader>. Anything you can find here
205 can also be found via standard L<DBIx::Class::Schema> methods somehow.
209 # ensure that a peice of object data is a valid arrayref, creating
210 # an empty one or encapsulating whatever's there.
211 sub _ensure_arrayref {
216 $self->{$_} = [ $self->{$_} ]
217 unless ref $self->{$_} eq 'ARRAY';
223 Constructor for L<DBIx::Class::Schema::Loader::Base>, used internally
224 by L<DBIx::Class::Schema::Loader>.
229 my ( $class, %args ) = @_;
231 my $self = { %args };
233 bless $self => $class;
235 $self->{db_schema} ||= '';
236 $self->_ensure_arrayref(qw/additional_classes
237 additional_base_classes
243 push(@{$self->{components}}, 'ResultSetManager')
244 if @{$self->{resultset_components}};
246 $self->{monikers} = {};
247 $self->{classes} = {};
249 # Support deprecated arguments
250 for(qw/inflect_map inflect/) {
251 warn "Argument $_ is deprecated in favor of 'inflect_plural'"
252 . ", and will be removed in 0.04000"
255 $self->{inflect_plural} ||= $self->{inflect_map} || $self->{inflect};
257 $self->{schema_class} ||= ( ref $self->{schema} || $self->{schema} );
258 $self->{schema} ||= $self->{schema_class};
266 foreach my $table_class (values %{$self->classes}) {
267 $table_class->require;
268 if($@ && $@ !~ /^Can't locate /) {
269 croak "Failed to load external class definition"
270 . " for '$table_class': $@";
272 next if $@; # "Can't locate" error
274 # If we make it to here, we loaded an external definition
275 warn qq/# Loaded external class definition for '$table_class'\n/
278 if($self->dump_directory) {
279 my $class_path = $table_class;
280 $class_path =~ s{::}{/}g;
281 $class_path .= '.pm';
282 my $filename = $INC{$class_path};
283 croak 'Failed to locate actual external module file for '
286 open(my $fh, '<', $filename)
287 or croak "Failed to open $filename for reading: $!";
288 $self->_raw_stmt($table_class,
289 q|# These lines loaded from user-supplied external file: |
293 $self->_raw_stmt($table_class, $_);
295 $self->_raw_stmt($table_class,
296 q|# End of lines loaded from user-supplied external file |
299 or croak "Failed to close $filename: $!";
306 Does the actual schema-construction work.
313 $self->_load_classes;
314 $self->_load_relationships if $self->relationships;
315 $self->_load_external;
316 $self->_dump_to_dir if $self->dump_directory;
318 # Drop temporary cache
319 delete $self->{_cache};
324 sub _get_dump_filename {
325 my ($self, $class) = (@_);
328 return $self->dump_directory . q{/} . $class . q{.pm};
331 sub _ensure_dump_subdirs {
332 my ($self, $class) = (@_);
334 my @name_parts = split(/::/, $class);
336 my $dir = $self->dump_directory;
337 foreach (@name_parts) {
340 mkdir($dir) or croak "mkdir('$dir') failed: $!";
348 my $target_dir = $self->dump_directory;
350 my $schema_class = $self->schema_class;
352 croak "Must specify target directory for dumping!" if ! $target_dir;
354 warn "Dumping manual schema for $schema_class to directory $target_dir ...\n";
356 if(! -d $target_dir) {
357 mkdir($target_dir) or croak "mkdir('$target_dir') failed: $!";
360 my $verstr = $DBIx::Class::Schema::Loader::VERSION;
361 my $datestr = POSIX::strftime('%Y-%m-%d %H:%M:%S', localtime);
362 my $tagline = qq|# Created by DBIx::Class::Schema::Loader v$verstr @ $datestr|;
364 $self->_ensure_dump_subdirs($schema_class);
366 my $schema_fn = $self->_get_dump_filename($schema_class);
367 croak "$schema_fn exists, will not overwrite"
368 if -f $schema_fn && !$self->dump_overwrite;
369 sysopen(my $schema_fh, '>', $schema_fn)
370 or croak "Cannot open $schema_fn for writing: $!";
371 print $schema_fh qq|package $schema_class;\n\n$tagline\n\n|;
372 print $schema_fh qq|use strict;\nuse warnings;\n\n|;
373 print $schema_fh qq|use base 'DBIx::Class::Schema';\n\n|;
374 print $schema_fh qq|__PACKAGE__->load_classes;\n|;
375 print $schema_fh qq|\n1;\n\n|;
377 or croak "Cannot close $schema_fn: $!";
379 foreach my $src_class (sort keys %{$self->{_dump_storage}}) {
380 $self->_ensure_dump_subdirs($src_class);
381 my $src_fn = $self->_get_dump_filename($src_class);
382 croak "$src_fn exists, will not overwrite"
383 if -f $src_fn && !$self->dump_overwrite;
384 open(my $src_fh, '>', $src_fn)
385 or croak "Cannot open $src_fn for writing: $!";
386 print $src_fh qq|package $src_class;\n\n$tagline\n\n|;
387 print $src_fh qq|use strict;\nuse warnings;\n\n|;
388 print $src_fh qq|use base 'DBIx::Class';\n\n|;
389 print $src_fh qq|$_\n|
390 for @{$self->{_dump_storage}->{$src_class}};
391 print $src_fh qq|\n1;\n\n|;
393 or croak "Cannot close $src_fn: $!";
396 warn "Schema dump completed.\n";
404 $_->require or croak ($_ . "->require: $@");
405 $self->_raw_stmt($target, "use $_;");
406 warn "$target: use $_" if $self->debug;
407 eval "package $target; use $_;";
408 croak "use $_: $@" if $@;
415 my $schema_class = $self->schema_class;
417 my $blist = join(q{ }, @_);
418 $self->_raw_stmt($target, "use base qw/ $blist /;") if @_;
419 warn "$target: use base qw/ $blist /" if $self->debug && @_;
421 $_->require or croak ($_ . "->require: $@");
422 $schema_class->inject_base($target, $_);
426 # Load and setup classes
430 my $schema = $self->schema;
431 my $schema_class = $self->schema_class;
432 my $constraint = $self->constraint;
433 my $exclude = $self->exclude;
434 my @tables = sort $self->_tables_list;
436 warn "No tables found in database, nothing to load" if !@tables;
439 @tables = grep { /$constraint/ } @tables if $constraint;
440 @tables = grep { ! /$exclude/ } @tables if $exclude;
442 warn "All tables excluded by constraint/exclude, nothing to load"
446 $self->{_tables} = \@tables;
448 foreach my $table (@tables) {
449 my $table_moniker = $self->_table2moniker($table);
450 my $table_class = $schema_class . q{::} . $table_moniker;
452 my $table_normalized = lc $table;
453 $self->classes->{$table} = $table_class;
454 $self->classes->{$table_normalized} = $table_class;
455 $self->monikers->{$table} = $table_moniker;
456 $self->monikers->{$table_normalized} = $table_moniker;
458 no warnings 'redefine';
459 local *Class::C3::reinitialize = sub { };
462 { no strict 'refs'; @{"${table_class}::ISA"} = qw/DBIx::Class/ }
464 $self->_use ($table_class, @{$self->additional_classes});
465 $self->_inject($table_class, @{$self->additional_base_classes});
467 $self->_dbic_stmt($table_class, 'load_components', @{$self->components}, qw/PK::Auto Core/);
469 $self->_dbic_stmt($table_class, 'load_resultset_components', @{$self->resultset_components})
470 if @{$self->resultset_components};
471 $self->_inject($table_class, @{$self->left_base_classes});
474 Class::C3::reinitialize;
476 foreach my $table (@tables) {
477 my $table_class = $self->classes->{$table};
478 my $table_moniker = $self->monikers->{$table};
480 $self->_dbic_stmt($table_class,'table',$table);
482 my $cols = $self->_table_columns($table);
484 eval { $col_info = $schema->storage->columns_info_for($table) };
486 $self->_dbic_stmt($table_class,'add_columns',@$cols);
490 foreach my $col (@$cols) {
491 $cols_hash{$col} = \%{($col_info->{$col})};
493 $self->_dbic_stmt($table_class,'add_columns',%cols_hash);
496 my $pks = $self->_table_pk_info($table) || [];
497 @$pks ? $self->_dbic_stmt($table_class,'set_primary_key',@$pks)
498 : carp("$table has no primary key");
500 my $uniqs = $self->_table_uniq_info($table) || [];
501 $self->_dbic_stmt($table_class,'add_unique_constraint',@$_) for (@$uniqs);
503 $schema_class->register_class($table_moniker, $table_class);
504 $schema->register_class($table_moniker, $table_class) if $schema ne $schema_class;
510 Returns a sorted list of loaded tables, using the original database table
518 return @{$self->_tables};
521 # Make a moniker from a table
523 my ( $self, $table ) = @_;
527 if( ref $self->moniker_map eq 'HASH' ) {
528 $moniker = $self->moniker_map->{$table};
530 elsif( ref $self->moniker_map eq 'CODE' ) {
531 $moniker = $self->moniker_map->($table);
534 $moniker ||= join '', map ucfirst, split /[\W_]+/, lc $table;
539 sub _load_relationships {
542 # Construct the fk_info RelBuilder wants to see, by
543 # translating table names to monikers in the _fk_info output
545 foreach my $table ($self->tables) {
546 my $tbl_fk_info = $self->_table_fk_info($table);
547 foreach my $fkdef (@$tbl_fk_info) {
548 $fkdef->{remote_source} =
549 $self->monikers->{delete $fkdef->{remote_table}};
551 my $moniker = $self->monikers->{$table};
552 $fk_info{$moniker} = $tbl_fk_info;
555 my $relbuilder = DBIx::Class::Schema::Loader::RelBuilder->new(
556 $self->schema_class, \%fk_info, $self->inflect_plural,
557 $self->inflect_singular
560 my $rel_stmts = $relbuilder->generate_code;
561 foreach my $src_class (sort keys %$rel_stmts) {
562 my $src_stmts = $rel_stmts->{$src_class};
563 foreach my $stmt (@$src_stmts) {
564 $self->_dbic_stmt($src_class,$stmt->{method},@{$stmt->{args}});
569 # Overload these in driver class:
571 # Returns an arrayref of column names
572 sub _table_columns { croak "ABSTRACT METHOD" }
574 # Returns arrayref of pk col names
575 sub _table_pk_info { croak "ABSTRACT METHOD" }
577 # Returns an arrayref of uniqs [ [ foo => [ col1, col2 ] ], [ bar => [ ... ] ] ]
578 sub _table_uniq_info { croak "ABSTRACT METHOD" }
580 # Returns an arrayref of foreign key constraints, each
581 # being a hashref with 3 keys:
582 # local_columns (arrayref), remote_columns (arrayref), remote_table
583 sub _table_fk_info { croak "ABSTRACT METHOD" }
585 # Returns an array of lower case table names
586 sub _tables_list { croak "ABSTRACT METHOD" }
588 # Execute a constructive DBIC class method, with debug/dump_to_dir hooks.
594 if(!$self->debug && !$self->dump_directory) {
600 $args = '(' . $args . ')' if @_ < 2;
601 my $stmt = $method . $args . q{;};
603 warn qq|$class\->$stmt\n| if $self->debug;
605 $self->_raw_stmt($class, '__PACKAGE__->' . $stmt);
608 # Store a raw source line for a class (for dumping purposes)
610 my ($self, $class, $stmt) = @_;
611 push(@{$self->{_dump_storage}->{$class}}, $stmt) if $self->dump_directory;
616 Returns a hashref of loaded table to moniker mappings. There will
617 be two entries for each table, the original name and the "normalized"
618 name, in the case that the two are different (such as databases
619 that like uppercase table names, or preserve your original mixed-case
620 definitions, or what-have-you).
624 Returns a hashref of table to class mappings. In some cases it will
625 contain multiple entries per table for the original and normalized table
626 names, as above in L</monikers>.
630 L<DBIx::Class::Schema::Loader>