<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package DBIx::Custom::Order;
use Object::Simple -base;
use DBIx::Custom::Util '_deprecate';

use overload
  'bool'   =&gt; sub {1},
  '""'     =&gt; sub { shift-&gt;to_string },
  fallback =&gt; 1;

has 'dbi',
  orders =&gt; sub { [] };

sub prepend {
  my $self = shift;
  
  for my $order (reverse @_) {
    if (ref $order eq 'ARRAY') {
      _deprecate('0.24', "prepend method receiving array reference is DEPRECATED! " .
        "use q method to quote column name.");
      my $column = shift @$order;
      $column = $self-&gt;dbi-&gt;q($column) if defined $column;
      my $derection = shift @$order;
      $order = $column;
      $order .= " $derection" if $derection;
    }
    unshift @{$self-&gt;orders}, $order;
  }
  
  return $self;
}

sub to_string {
  my $self = shift;
  
  my $exists = {};
  my @orders;
  for my $order (@{$self-&gt;orders}) {
    next unless defined $order;
    $order =~ s/^\s+//;
    $order =~ s/\s+$//;
    my ($column, $direction) = split /\s+/, $order;
    push @orders, $order unless $exists-&gt;{$column};
    $exists-&gt;{$column} = 1;
  }
  
  return '' unless @orders;
  return 'order by ' . join(', ', @orders);
}

1;

=head1 NAME

DBIx::Custom::Order - Order by clause

=head1 SYNOPSIS

  # Result
  my $order = DBIx::Custom::Order-&gt;new;
  $order-&gt;prepend('title', 'author desc');
  my $order_by = "$order";
  
=head1 ATTRIBUTES

=head2 dbi

  my $dbi = $order-&gt;dbi;
  $order = $order-&gt;dbi($dbi);

L&lt;DBIx::Custom&gt; object.

=head2 orders

  my $orders = $result-&gt;orders;
  $result = $result-&gt;orders(\%orders);

Parts of order by clause

=head1 METHODS

L&lt;DBIx::Custom::Result&gt; inherits all methods from L&lt;Object::Simple&gt;
and implements the following new ones.

=head2 prepend

  $order-&gt;prepend('title', 'author desc');

Prepend order parts to C&lt;orders&gt;.

=head2 to_string

  my $order_by = $order-&gt;to_string;

Create order by clause. If column name is duplicated, First one is used.
C&lt;to_string&gt; override stringification. so you can write the follwoing way.

  my $order_by = "$order";

=cut

</pre></body></html>