Alzabo
view release on metacpan or search on metacpan
lib/Alzabo/MethodMaker.pm view on Meta::CPAN
plural => { optional => 1 },
};
my $name = $self->{opts}{name_maker}->( %p )
or return;
my ($code_name, $debug_name) = ("$p{class}::$name",
"$p{class}\->$name");
if ( $p{class}->can($name) )
{
warn "MethodMaker: Creating $p{type} method $debug_name will override"
. " the method of the same name in the parent class\n";
}
no strict 'refs'; # We use symbolic references here
if ( defined &$code_name )
{
# This should probably always be shown to the user, not just
# when debugging mode is turned on, because name clashes can
# cause confusion - whichever subroutine happens first will
# arbitrarily win.
warn "MethodMaker: skipping $p{type} method $debug_name, subroutine already exists\n";
return;
}
if (Alzabo::Debug::METHODMAKER)
{
my $message = "Making $p{type} method $debug_name";
$message .= ": returns $p{returns}" if $p{returns};
print STDERR "$message\n";
}
*$code_name = $p{code};
return $name;
}
sub _make_fk_method
{
my $self = shift;
my $fk = shift;
my $table_to = $fk->table_to->name;
# The table may be a linking or lookup table. If we are
# supposed to make that kind of method we will and then we'll
# skip to the next foreign table.
$self->make_linking_table_method($fk)
if $self->{opts}{linking_tables};
$self->make_lookup_columns_methods($fk)
if $self->{opts}{lookup_columns};
return unless $self->{opts}{foreign_keys};
if ($fk->is_one_to_many)
{
my $name = $self->_make_method
( type => 'foreign_key',
class => $self->{row_class},
returns => 'row cursor',
code => sub { my $self = shift;
return $self->rows_by_foreign_key( foreign_key => $fk, @_ ); },
foreign_key => $fk,
plural => 1,
) or return;
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that return cursors for foreign keys',
description =>
"returns a cursor containing related rows from the " . $fk->table_to->name . " table",
spec => 'same as Alzabo::Runtime::Table->rows_where',
) );
}
# Singular method name
else
{
my $name = $self->_make_method
( type => 'foreign_key',
class => $self->{row_class},
returns => 'single row',
code => sub { my $self = shift;
return $self->rows_by_foreign_key( foreign_key => $fk, @_ ); },
foreign_key => $fk,
plural => 0,
) or return;
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that return a single row for foreign keys',
description =>
"returns a single related row from the " . $fk->table_to->name . " table",
spec => 'same as Alzabo::Runtime::Table->one_row',
) );
}
}
sub make_self_relation
{
my $self = shift;
my $fk = shift;
my (@pairs, @reverse_pairs);
if ($fk->is_one_to_many)
{
@pairs = map { [ $_->[0], $_->[1]->name ] } $fk->column_pairs;
@reverse_pairs = map { [ $_->[1], $_->[0]->name ] } $fk->column_pairs;
}
else
{
@pairs = map { [ $_->[1], $_->[0]->name ] } $fk->column_pairs;
@reverse_pairs = map { [ $_->[0], $_->[1]->name ] } $fk->column_pairs;
}
my $table = $fk->table_from;
my $name = $self->_make_method
( type => 'self_relation',
class => $self->{row_class},
returns => 'single row',
code => sub { my $self = shift;
my @where = map { [ $_->[0], '=', $self->select( $_->[1] ) ] } @pairs;
return $table->one_row( where => \@where, @_ ); },
foreign_key => $fk,
parent => 1,
) or last;
if ($name)
{
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that return a parent row',
description =>
"a single parent row from the same table",
spec => 'same as Alzabo::Runtime::Table->one_row',
) );
}
$name = $self->_make_method
( type => 'self_relation',
class => $self->{row_class},
returns => 'row cursor',
code =>
sub { my $self = shift;
my %p = @_;
my @where = map { [ $_->[0], '=', $self->select( $_->[1] ) ] } @reverse_pairs;
if ( $p{where} )
{
@where = ( '(', @where, ')' );
push @where,
Alzabo::Utils::is_arrayref( $p{where}->[0] ) ? @{ $p{where} } : $p{where};
delete $p{where};
}
return $table->rows_where( where => \@where,
%p ); },
foreign_key => $fk,
parent => 0,
) or return;
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that return child rows',
description =>
"a row cursor of child rows from the same table",
spec => 'same as Alzabo::Runtime::Table->rows_where',
) );
}
sub make_linking_table_method
{
my $self = shift;
my $fk = shift;
return unless $fk->table_to->primary_key_size == 2;
# Find the foreign key from the linking table to the _other_ table
my $fk_2;
{
my @fk = $fk->table_to->all_foreign_keys;
return unless @fk == 2;
# Get the foreign key that's not the one we already have
$fk_2 = $fk[0]->is_same_relationship_as($fk) ? $fk[1] : $fk[0];
}
return unless $fk_2;
# Not a linking table unless all the PK columns in the linking
# table are part of the link.
return unless $fk->table_to->primary_key_size == $fk->table_to->columns;
# Not a linking table unless the PK in the middle table is the
# same size as the sum of the two table's PK sizes
return unless ( $fk->table_to->primary_key_size ==
( $fk->table_from->primary_key_size + $fk_2->table_to->primary_key_size ) );
my $s = $fk->table_to->schema;
my @t = ( $fk->table_to, $fk_2->table_to );
my $select = [ $t[1] ];
my $name = $self->_make_method
( type => 'linking_table',
class => $self->{row_class},
returns => 'row cursor',
code =>
sub { my $self = shift;
my %p = @_;
if ( $p{where} )
{
$p{where} = [ $p{where} ] unless Alzabo::Utils::is_arrayref( $p{where}[0] );
}
foreach my $pair ( $fk->column_pairs )
{
push @{ $p{where} }, [ $pair->[1], '=', $self->select( $pair->[0]->name ) ];
}
return $s->join( tables => [[@t, $fk_2]],
select => $select,
%p ); },
foreign_key => $fk,
foreign_key_2 => $fk_2,
) or return;
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that follow a linking table',
description =>
"a row cursor of related rows from the " . $fk_2->table_to->name . " table, " .
"via the " . $fk->table_to->name . " linking table",
spec => 'same as Alzabo::Runtime::Table->rows_where',
) );
}
sub make_lookup_columns_methods
{
my $self = shift;
my $fk = shift;
return if $fk->is_one_to_many;
# Make sure the relationship is to the foreign table's primary key
my @to = $fk->columns_to;
return unless ( ( scalar grep { $_->is_primary_key } @to ) == @to &&
( $fk->table_to->primary_key_size == @to ) );
foreach ( sort { $a->name cmp $b->name } $fk->table_to->columns )
{
next if $_->is_primary_key;
my $col_name = $_->name;
my $name = $self->_make_method
( type => 'lookup_columns',
class => $self->{row_class},
returns => 'scalar value of column',
code =>
sub { my $self = shift;
my $row = $self->rows_by_foreign_key( foreign_key => $fk, @_ );
return unless $row;
return $row->select($col_name) },
foreign_key => $fk,
column => $_,
) or next;
$self->{row_class}->add_method_docs
( Alzabo::MethodDocs->new
( name => $name,
group => 'Methods that follow a lookup table',
description =>
"returns the value of " . (join '.', $fk->table_to->name, $col_name) . " for the given row by following the foreign key relationship",
spec => 'same as Alzabo::Runtime::Table->rows_where',
) );
}
}
sub make_hooks
{
my $self = shift;
my $table = shift;
my $type = shift;
my $class = $type eq 'insert' ? $self->{table_class} : $self->{row_class};
my $pre = "pre_$type";
my $post = "post_$type";
return unless $class->can($pre) || $class->can($post);
lib/Alzabo/MethodMaker.pm view on Meta::CPAN
C<pre_insert()> and/or C<post_insert()> method for the generated table
class or this parameter will not do anything. See the
L<HOOKS|/"HOOKS"> section for more details.
=back
=head2 Row object methods
=over 4
=item * row_columns => $bool
This tells MethodMaker to create get/set methods for each column a row
has. These methods take a single optional argument, which if given
will cause that column to be updated for the row.
=item * update_hooks => $bool
Look for hooks to wrap around the C<update> method in
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row>. See L<Loading
Classes> for more details. You have to define a C<pre_update()>
and/or C<post_update()> method for the generated row class or this
parameter will not do anything. See the L<HOOKS|/"HOOKS"> section for
more details.
=item * select_hooks => $bool
Look for hooks to wrap around the C<select> method in
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row>. See L<Loading
Classes> for more details. You have to define either a
C<pre_select()> and/or C<post_select()> method for the generated row
class or this parameter will not do anything. See the
L<HOOKS|/"HOOKS"> section for more details.
=item * delete_hooks => $bool
Look for hooks to wrap around the C<delete> method in
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row>. See L<Loading
Classes> for more details. You have to define either a
C<pre_delete()> and/or C<post_delete()> method for the generated row
class or this parameter will not do anything. See the
L<HOOKS|/"HOOKS"> section for more details.
=item * foreign_keys => $bool
Creates methods in row objects named for the table to which the
relationship exists. These methods return either a single
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row> object or a single
L<C<Alzabo::Runtime::RowCursor>|Alzabo::Runtime::RowCursor> object,
depending on the cardinality of the relationship.
For exa
Movie Credit
--------- --------
movie_id movie_id
title person_id
role_name
This would create a method for Movie row objects called C<Credit()>
which would return a cursor for the associated Credit table rows.
Similarly, Credit row objects would have a method called C<Movie()>
which would return the associated Movie row object.
=item * linking_tables => $bool
A linking table, as defined here, is a table with a two column primary
key, with each column being a foreign key to another table's primary
key. These tables exist to facilitate n..n logical relationships. If
both C<foreign_keys> and C<linking_tables> are true, then methods will
be created that skip the intermediate linking tables.
For example, with the following tables:
User UserGroup Group
------- --------- --------
user_id user_id group_id
user_name group_id group_name
The "UserGroup" table exists solely to facilitate the n..n
relationship between "User" and "Group". User row objects will have a
C<Group()> method, which returns a row cursor of Group row objects.
And Group row objects will have a C<User()> method which returns a row
cursor of User row objects.
=item * lookup_columns => $bool
Lookup columns are columns in foreign tables to which a table has a
many-to-one or one-to-one relationship to the foreign table's primary
key. For example, given the tables below:
Restaurant Cuisine
--------- --------
restaurant_id cuisine_id
restaurant_name (n..1) description
phone spiciness
cuisine_id
In this example, Restaurant row objects would have
C<Cuisine_description()> and C<Cuisine_spiciness> methods which
returned the corresponding values from the C<Cuisine> table.
=item * self_relations => $bool
A self relation is when a table has a parent/child relationship with
itself. Here is an example:
Location
--------
location_id
location_name
parent_location_id
NOTE: If the relationship has a cardinality of 1..1 then no methods
will be created, as this option is really intended for parent/child
relationships. This may change in the future.
In this case, Location row objects will have both C<parent()> and
C<children()> methods. The parent method returns a single row, while
the C<children()> method returns a row cursor of Location rows.
=back
=head1 HOOKS
As was mentioned previously, it is possible to create pre- and
post-execution hooks to wrap around a number of methods. This allows
you to do data validation on inserts and updates as well as giving you
a chance to filter incoming or outgoing data as needed. For example,
this can be used to convert dates to and from a specific RDBMS
format.
All hooks are inside a transaction which is rolled back if any part of
the process fails.
It should be noted that Alzabo uses both the C<<
Alzabo::Runtime::Row->select >> and C<< Alzabo::Runtime::Row->delete >>
methods internally. If their behavior is radically altered through
the use of hooks, then some of Alzabo's functionality may be broken.
Given this, it may be safer to create new methods to fetch and massage
data rather than to create post-select hooks that alter data.
Each of these hooks receives different parameters, documented below:
=head2 Insert Hooks
=over 4
=item * pre_insert
This method receives a hash reference of all the parameters that are
passed to the L<C<< Alzabo::Runtime::Table->insert()
>>|Alzabo::Runtime::Table/insert> method.
These are the actual parameters that will be passed to the C<insert>
method so alterations to this reference will be seen by that method.
This allows you to alter the values that actually end up going into
the database or change any other parameters as you see fit.
=item * post_insert
This method also receives a hash reference containing all of the
parameters passed to the C<insert()> method. In addition, the hash
reference contains an additional key, "row", which contains the newly
created row.
=back
=head2 Update Hooks
=over 4
=item * pre_update
This method receives a hash reference of the parameters that will be
passed to the L<C<< Alzabo::Runtime::Row->update()
>>|Alzabo::Runtime::Row/update> method. Again, alterations to these
parameters will be seen by the C<update> method.
lib/Alzabo/MethodMaker.pm view on Meta::CPAN
=over 4
=item * type => $method_type
This will always be the same as one of the parameters you give to the
import method. It will be one of the following: "foreign_key",
"linking_table", "lookup_columns", "row_column", "self_relation",
"table", "table_column".
=back
The following parameters vary from case to case, depending on the
value of "type".
When the type is "table":
=over 4
=item * table => Alzabo::Table object
This parameter will be passed when the type is C<table>. It is the
table object the schema object's method will return.
=back
When the type is "table_column" or "row_column":
=over 4
=item * column => Alzabo::Column object
When the type is "table_column", this is the column object the method
will return. When the type is "row_column", then it is the column
whose B<value> the method will return.
=back
When the type is "foreign_key", "linking_table", or "self_relation":
=over 4
=item * foreign_key => Alzabo::ForeignKey object
This is the foreign key on which the method is based.
=back
It is possible to create an n..n relationship between a table and
itself, and MethodMaker will attempt to generate linking table methods
for such relationships, so your naming sub may need to take this into
account.
When the type is "foreign_key":
=over 4
=item * plural => $bool
This indicates whether or not the method that is being created will
return a cursor object (true) or a row object (false).
=back
When the type is "linking_table":
=over 4
=item * foreign_key_2 => Alzabo::ForeignKey object
When making a linking table method, two foreign keys are used. The
C<foreign_key> is from the table being linked from to the linking
table. This parameter is the foreign key from the linking table to
the table being linked to.
=back
When the type is "lookup_columns":
=over 4
=item * column => Alzabo::Column object
When making lookup column methods, this column is the column in the
foreign table for which a method is being made.
=back
When the type is "self_relation":
=over 4
=item * parent => $boolean
This indicates whether or not the method being created will return
parent objects (true) or child objects (false).
=back
=head1 NAMING SUB EXAMPLE
Here is an example that covers all of the possible options:
use Lingua::EN::Inflect;
sub namer
{
my %p = @_;
# Table object can be returned from the schema via methods such as $schema->User_t;
return $p{table}->name . '_t' if $p{type} eq 'table';
# Column objects are returned similarly, via $schema->User_t->username_c;
return $p{column}->name . '_c' if $p{type} eq 'table_column';
# If I have a row object, I can get at the columns via their
# names, for example $user->username;
return $p{column}->name if $p{type} eq 'row_column';
# This manipulates the table names a bit to generate names. For
# example, if I have a table called UserRating and a 1..n
# relationship from User to UserRating, I'll end up with a method
# on rows in the User table called ->Ratings which returns a row
# cursor of rows from the UserRating table.
if ( $p{type} eq 'foreign_key' )
{
my $name = $p{foreign_key}->table_to->name;
my $from = $p{foreign_key}->table_from->name;
$name =~ s/$from//;
if ($p{plural})
{
return my_PL( $name );
}
else
{
return $name;
}
}
# This is very similar to how foreign keys are handled. Assume
# we have the tables Restaurant, Cuisine, and RestaurantCuisine.
# If we are generating a method for the link from Restaurant
# through to Cuisine, we'll have a method on Restaurant table
# rows called ->Cuisines, which will return a cursor of rows from
# the Cuisine table.
#
# Note: this will generate a bad name if given a linking table
# that links a table to itself.
if ( $p{type} eq 'linking_table' )
{
my $method = $p{foreign_key}->table_to->name;
my $tname = $p{foreign_key}->table_from->name;
$method =~ s/$tname//;
return my_PL($method);
}
# Lookup columns are columns if foreign tables for which there
# exists a one-to-one or many-to-one relationship. In cases such
# as these, it is often the case that the foreign table is rarely
# used on its own, but rather it primarily used as a lookup table
# for values that should appear to be part of other tables.
#
# For example, an Address table might have a many-to-one
# relationship with a State table. The State table would contain
# the columns 'name' and 'abbreviation'. If we have
# an Address table row, it is convenient to simply be able to say
# $address->state_name and $address->state_abbreviation.
if ( $p{type} eq 'lookup_columns' )
{
return join '_', map { lc $_->name } $p{foreign_key}->table_to, $p{column};
}
# This should be fairly self-explanatory.
return $p{parent} ? 'parent' : 'children'
if $p{type} eq 'self_relation';
# And just to make sure that nothing slips by us we do this.
die "unknown type in call to naming sub: $p{type}\n";
}
# Lingua::EN::Inflect did not handle the word 'hours' properly when this was written
sub my_PL
{
my $name = shift;
return $name if $name =~ /hours$/i;
return Lingua::EN::Inflect::PL($name);
}
=head1 GENERATED DOCUMENTATION
This module keeps track of methods that are generated and can in turn
generate basic POD for those methods.
Any schema that has had methods generated for it by
Alzabo::MethodMaker will have an additional method, C<docs_as_pod>.
This will return documentation for the schema object's methods, as
well as any documentation available for objects that the schema
contains, in this case tables. The tables in turn return their own
documentation plus that of their contained row classes.
It is also possible to call the C<docs_as_pod> method on any generated
( run in 1.059 second using v1.01-cache-2.11-cpan-437f7b0c052 )