Fey::Role::HasAliasName - A role for objects that bring an alias with them


Fey documentation Contained in the Fey distribution.

Index


Code Index:

NAME

Top

Fey::Role::HasAliasName - A role for objects that bring an alias with them

VERSION

Top

version 0.40

SYNOPSIS

Top

  package My::Thing;

  use Moose;
  with 'Fey::Role::HasAliasName'
      => { generated_alias_prefix => 'THING' };

DESCRIPTION

Top

This role adds an alias_name attribute to objects, as well as some methods for making use of that alias.

PARAMETERS

Top

generated_alias_prefix

The prefix that generated aliases will have, e.g. LITERAL, FUNCTION, etc. Required.

sql_needs_parens

If true, sql_with_alias() will wrap the output of sql() when generating its own output. Default is false.

METHODS

Top

$obj->alias_name()

Returns the current alias name, if any.

$obj->set_alias_name()

  $obj->set_alias_name('my object');

Sets the current alias name.

$obj->alias()

  $obj->alias('my object')->do_something_else(...);

Sets the current alias name, then returns the object.

$obj->sql_with_alias()

$obj->sql_or_alias()

Returns the appropriate SQL snippet. sql_with_alias will generate an alias if one has not been set (using generated_alias_prefix, above).

BUGS

Top

See Fey for details on how to report bugs.

AUTHOR

Top

Dave Rolsky <autarch@urth.org>

COPYRIGHT AND LICENSE

Top


Fey documentation Contained in the Fey distribution.

package Fey::Role::HasAliasName;
BEGIN {
  $Fey::Role::HasAliasName::VERSION = '0.40';
}

use strict;
use warnings;
use namespace::autoclean;

use Fey::Types qw( Bool Str );

use MooseX::Role::Parameterized;

parameter 'generated_alias_prefix' => (
    isa      => Str,
    required => 1,
);

parameter 'sql_needs_parens' => (
    isa     => Bool,
    default => 0,
);

has 'alias_name' => (
    is     => 'rw',
    isa    => Str,
    writer => 'set_alias_name',
);

requires 'sql';

sub alias {
    $_[0]->set_alias_name( $_[1] );
    return $_[0];
}

sub sql_with_alias {
    $_[0]->_make_alias()
        unless $_[0]->alias_name();

    my $sql = $_[0]->_sql_for_alias( $_[1] );

    $sql .= ' AS ';
    $sql .= $_[1]->quote_identifier( $_[0]->alias_name() );

    return $sql;
}

sub sql_or_alias {
    return $_[1]->quote_identifier( $_[0]->alias_name() )
        if $_[0]->alias_name();

    return $_[0]->sql( $_[1] );
}

role {
    my $p = shift;

    my $parens = $p->sql_needs_parens();

    method _sql_for_alias => sub {
        my $sql = $_[0]->sql( $_[1] );
        $sql = "( $sql )" if $parens;
        return $sql;
    };

    my $prefix = $p->generated_alias_prefix();
    my $num    = 0;

    method '_make_alias' => sub {
        my $self = shift;
        $self->set_alias_name( $prefix . $num++ );
    };

};

1;

# ABSTRACT: A role for objects that bring an alias with them




__END__