Alzabo

 view release on metacpan or  search on metacpan

lib/Alzabo/Runtime/Table.pm  view on Meta::CPAN


    params_exception
        'Incorrect number of pk values provided.  ' . scalar @pk . ' are needed.'
            if ref $pk_val && @pk != scalar keys %$pk_val;

    if (@pk > 1)
    {
        params_exception
            ( 'Primary key for ' . $self->name . ' is more than one column.' .
              '  Please provide multiple key values as a hashref.' )
                unless ref $pk_val;

        foreach my $pk (@pk)
        {
            params_exception 'No value provided for primary key ' . $pk->name . '.'
                unless defined $pk_val->{ $pk->name };
        }
    }

    return $self->_make_row( %p,
                             table => $self,
                           );
}

sub _make_row
{
    my $self = shift;
    my %p = @_;

    my $class = $p{row_class} ? delete $p{row_class} : $self->_row_class;

    return $class->new(%p);
}

sub _row_class { 'Alzabo::Runtime::Row' }

sub row_by_id
{
    my $self = shift;
    my %p = @_;
    validate( @_, { row_id => { type => SCALAR },
                    ( map { $_ => { optional => 1 } } keys %p ) } );

    my (undef, undef, %pk) = split ';:;_;:;', delete $p{row_id};

    return $self->row_by_pk( %p, pk => \%pk );
}

sub rows_where
{
    my $self = shift;
    my %p = @_;

    my $sql = $self->_make_sql(%p);

    Alzabo::Runtime::process_where_clause( $sql, $p{where} ) if exists $p{where};

    $sql->debug(\*STDERR) if Alzabo::Debug::SQL;
    print STDERR Devel::StackTrace->new if Alzabo::Debug::TRACE;

    return $self->_cursor_by_sql( %p, sql => $sql );
}

sub one_row
{
    my $self = shift;
    my %p = @_;

    my $sql = $self->_make_sql(%p);

    Alzabo::Runtime::process_where_clause( $sql, $p{where} ) if exists $p{where};

    Alzabo::Runtime::process_order_by_clause( $sql, $p{order_by} ) if exists $p{order_by};

    if ( exists $p{limit} )
    {
        $sql->limit( ref $p{limit} ? @{ $p{limit} } : $p{limit} );
    }

    $sql->debug(\*STDERR) if Alzabo::Debug::SQL;
    print STDERR Devel::StackTrace->new if Alzabo::Debug::TRACE;

    my @return = $self->schema->driver->one_row( sql => $sql->sql,
                                                 bind => $sql->bind )
        or return;

    my @pk = $self->primary_key;

    my (%pk, %prefetch);

    @pk{ map { $_->name } @pk } = splice @return, 0, scalar @pk;

    # Must be some prefetch pieces
    if (@return)
    {
        @prefetch{ $self->prefetch } = @return;
    }

    return $self->row_by_pk( pk => \%pk,
                             prefetch => \%prefetch,
                           );
}

sub all_rows
{
    my $self = shift;

    my $sql = $self->_make_sql;

    $sql->debug(\*STDERR) if Alzabo::Debug::SQL;
    print STDERR Devel::StackTrace->new if Alzabo::Debug::TRACE;

    return $self->_cursor_by_sql( @_, sql => $sql );
}

sub _make_sql
{
    my $self = shift;
    my %p = @_;

    logic_exception "Can't make rows for tables without a primary key"
        unless $self->primary_key;

    my $sql = ( Alzabo::Runtime::sqlmaker( $self->schema, \%p )->
                select( $self->primary_key,
                        $self->prefetch ? $self->columns( $self->prefetch ) : () )->
                from( $self ) );

    return $sql;
}

sub _cursor_by_sql
{
    my $self = shift;

    my %p = @_;
    validate( @_, { sql => { isa => 'Alzabo::SQLMaker' },
                    order_by => { type => ARRAYREF | HASHREF | OBJECT,
                                  optional => 1 },
                    limit => { type => SCALAR | ARRAYREF,
                               optional => 1 },
                    ( map { $_ => { optional => 1 } } keys %p ) } );

    Alzabo::Runtime::process_order_by_clause( $p{sql}, $p{order_by} ) if exists $p{order_by};

    if ( exists $p{limit} )
    {
        $p{sql}->limit( ref $p{limit} ? @{ $p{limit} } : $p{limit} );
    }

    my $statement = $self->schema->driver->statement( sql => $p{sql}->sql,
                                                      bind => $p{sql}->bind,
                                                      limit => $p{sql}->get_limit );

    return Alzabo::Runtime::RowCursor->new( statement => $statement,
                                            table => $self,
                                          );
}

sub potential_row
{
    my $self = shift;
    my %p = @_;

    logic_exception "Can't make rows for tables without a primary key"
        unless $self->primary_key;

    my $class = $p{row_class} ? delete $p{row_class} : $self->_row_class;

    return $class->new( %p,
                        state => 'Alzabo::Runtime::RowState::Potential',
                        table => $self,
                      );
}

sub row_count
{
    my $self = shift;
    my %p = @_;

    my $count = Alzabo::Runtime::sqlmaker( $self->schema, \%p )->COUNT('*');

    return $self->function( select => $count, %p );
}

sub function
{
    my $self = shift;
    my %p = @_;

    my $sql = $self->_select_sql(%p);

lib/Alzabo/Runtime/Table.pm  view on Meta::CPAN

        # not previously cloned
        unless ( $col->table eq $self )
        {
            # replace our copy of this column with a clone
            $col = $col->alias_clone( table => $self );
            my $index = $self->{columns}->Indices($name);
            $self->{columns}->Replace( $index, $col, $name );

            Scalar::Util::weaken( $col->{table} );

            delete $self->{pk_array} if $col->is_primary_key;
        }

        return $col;
    }
    else
    {
        return $self->SUPER::column(@_);
    }
}

sub alias_name
{
    # intentionally don't call $_[0]->name for a noticeable
    # performance boost
    return $_[0]->{alias_name} || $_[0]->{name};
}

sub real_table
{
    return $_[0]->{real_table} || $_[0];
}

# This gets called a _lot_ so doing this sort of 'memoization' helps
sub primary_key
{
    my $self = shift;

    $self->{pk_array} ||= [ $self->SUPER::primary_key ];

    return ( wantarray ?
             @{ $self->{pk_array} } :
             $self->{pk_array}->[0]
           );
}

1;

__END__

=head1 NAME

Alzabo::Runtime::Table - Table objects

=head1 SYNOPSIS

  my $table = $schema->table('foo');

  my $row = $table->row_by_pk( pk => 1 );

  my $row_cursor =
      $table->rows_where
          ( where =>
            [ Alzabo::Column object, '=', 5 ] );

=head1 DESCRIPTION

This object is able to create rows, either by making objects based on
existing data or inserting new data to make new rows.

This object also implements a method of lazy column evaluation that
can be used to save memory and database wear and tear.  Please see the
L<LAZY COLUMN LOADING> section for details.

=head1 INHERITS FROM

C<Alzabo::Table>

=for pod_merge merged

=head1 METHODS

=head2 Methods that return an C<Alzabo::Runtime::Row> object

All of these methods accept the "no_cache" parameter, which will be
passed on to C<< Alzabo::Runtime::Row->new >>.

=head2 insert

Inserts the given values into the table.  If no value is given for a
primary key column and the column is
L<"sequenced"|Alzabo::Column/sequenced> then the primary key will be
auto-generated.

It takes the following parameters:

=over 4

=item * values => $hashref

The hashref contains column names and values for the new row.  This
parameter is optional.  If no values are specified, then the default
values will be used.

=back

This methods return a new
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row> object.

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::NotNullable>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 row_by_pk

The primary key can be either a simple scalar, as when the table has a
single primary key, or a hash reference of column names to primary key
values, for multi-column primary keys.

It takes the following parameters:

lib/Alzabo/Runtime/Table.pm  view on Meta::CPAN

 WHERE foo = 5 AND ( foo > 10 OR bar < 50 )

Make sure that your parentheses balance out or an exception will be
thrown.

You can also use the SQL functions (L<Using SQL
functions|Alzabo::Intro/Using SQL functions>) exported from the
SQLMaker subclass you are using.  For example:

 [ LENGTH($foo_col), '<', 10 ]

would generate something like:

 WHERE LENGTH(foo) < 10

=item * order_by => see below

This parameter can take one of two different values.  The simplest
form is to just give it a single column object or SQL function.
Alternatively, you can give it an array reference to a list of column
objects, SQL functions and strings like this:

  order_by => [ $col1, COUNT('*'), $col2, 'DESC', $col3, 'ASC' ]

It is important to note that you cannot simply use any arbitrary SQL
function as part of your order by clause.  You need to use a function
that is exactly the same as one that was given as part of the "select"
parameter.

=item * group_by => see below

This parameter can take either a single column object or an array of
column objects.

=item * having => same as "where"

This parameter is specified in the same way as the "where" parameter.

=item * limit => $limit or [ $limit, $offset ]

For databases that support LIMIT clauses, this incorporates such a
clause into the SQL.

For databases that don't, the limit will be implemented
programatically as rows are being requested.  If an offset is given,
this will be the number of rows skipped in the result set before the
first one is returned.

=back

=head2 Methods that return an C<Alzabo::Runtime::RowCursor> object

The C<rows_where()> and C<all_rows()> methods both return an
L<C<Alzabo::Runtime::RowCursor>|Alzabo::Runtime::RowCursor> object
representing the results of the query.  This is the case even for
queries that end up returning one or zero rows, because Alzabo cannot
know in advance how many rows these queries will return.

=head2 rows_where

This method provides a simple way to retrieve a row cursor based on
one or more colum values.

It takes the following parameters, all of which were described in the
L<Common Parameters|Alzabo::Runtime::Table/Common Parameters> section.

=over 4

=item * where

=item * order_by

=item * limit

=back

It returns n
L<C<Alzabo::Runtime::RowCursor>|Alzabo::Runtime::RowCursor> object
representing the query.

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 all_rows

This method simply returns all the rows in the table.

It takes the following parameters:

=over 4

=item * order_by

=item * limit

=back

It returns an
L<C<Alzabo::Runtime::RowCursor>|Alzabo::Runtime::RowCursor> object
representing the query.

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 one_row

This method takes the exact same parameters as the
L<C<rows_where()>|Alzabo::Runtime::table/rows_where> method but
instead of returning a cursor, it returns a single row.  This row
represents the first row returned by the database.

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 potential_row

This method is used to create a new
L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row> object, in the
"potential" state.

It takes the following parameters.

=over 4

=item * values => \%values

This should be a hash reference containing column names, just as is
given to L<insert()|/insert>.

It is ok to omit columns that are normally not nullable, but they
cannot be B<explicitly> set to null.

Any values given will be set in the new potential row object.  If a
column has a default, and a value for that column is not given, then
the default will be used.

Unlike the L<insert()\/insert> method, you cannot use SQL functions as
values here.

=back

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 Other Methods

This method returns a count of the rows in the table.  It takes the
following parameters:

=head2 row_count

=over 4

=item * where

=back

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head2 function and select

These two methods differ only in their return values.

They both take the following parameters:

=over 4

=item * select => $function or [ scalars, SQL functions and/or C<Alzabo::Column> objects ]

If you pass an array reference for this parameter, it may contain
scalars, SQL functions, or column objects.  For example:

  $table->function( select =>
                    [ 1,
                      $foo->column('name'),
                      LENGTH( $foo->column('name') ) ] );

This is equivalent to the following SQL:

  SELECT 1, foo.name, LENGTH( foo.name )
    FROM foo

=item * where

=item * order_by

=item * group_by

=item * limit

=back

This method is used to call arbitrary SQL functions such as 'AVG' or
'MAX', or to select arbitrary column data.  The function (or
functions) should be the return values from the functions exported by
the SQLMaker subclass that you are using.  Please see L<Using SQL
functions|Alzabo/Using SQL functions> for more details.

Throws: L<C<Alzabo::Exception::Logic>|Alzabo::Exceptions>,
L<C<Alzabo::Exception::Params>|Alzabo::Exceptions>

=head3 function() return values

The return value of this method is highly context sensitive.

If you only requested a single element in your "select" parameter,
such as "DISTINCT(foo)", then it returns the first value in scalar
context and all the values as an array in list context.

If you requested multiple functions such as "AVG(foo), MAX(foo)", then
it returns a single array reference, the first row of values, in
scalar context and a list of array references in list context.

=head3 select() return values

This method always returns a new
L<C<Alzabo::DriverStatement>|Alzabo::Driver/Alzabo::DriverStatement>
object containing the results of the query.  This object has an
interface very similar to the Alzabo cursor interface, and has methods
such as C<next()>, C<next_as_hash()>, etc.

=head2 alias

This returns an object which can be used in joins to allow a
particular table to be involved in the join under multiple aliases.
This allows for self-joins as well as more complex joins involving
multiple aliases to a given table.

The object returned by this method is more or less identical to a
table object in terms of the methods it supports.  This includes
methods that were generated by C<Alzabo::MethodMaker>.

However, B<this object should not be used outside the context of a
join query> because the results will be unpredictable.  In addition,
B<the column objects that the aliased table object returns should also
not be used outside of the context of a join>.

=for pod_merge schema

=for pod_merge name

=for pod_merge column

=for pod_merge columns

=for pod_merge has_column

=for pod_merge primary_key

=for pod_merge primary_key_size

=for pod_merge column_is_primary_key

=for pod_merge foreign_keys

=for pod_merge foreign_keys_by_table

=for pod_merge foreign_keys_by_column

=for pod_merge all_foreign_keys

=for pod_merge index

=for pod_merge has_index

=for pod_merge indexes

=for pod_merge attributes

=for pod_merge has_attribute

=for pod_merge comment

=head1 LAZY COLUMN LOADING

This concept was taken directly from Michael Schwern's Class::DBI
module (credit where it is due).

By default, L<C<Alzabo::Runtime::Row>|Alzabo::Runtime::Row> objects



( run in 1.044 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )