a2d8267 13 years ago
1 contributor
108 lines | 2.287kb
  1. package DBIx::Custom::Order;
  2. use Object::Simple -base;
  3. use overload
  4. 'bool' => sub {1},
  5. '""' => sub { shift->to_string },
  6. fallback => 1;
  7.  
  8. has 'dbi',
  9. orders => sub { [] };
  10.  
  11. sub prepend {
  12. my $self = shift;
  13. foreach my $order (reverse @_) {
  14. if (ref $order eq 'ARRAY') {
  15. my $column = shift @$order;
  16. $column = $self->dbi->_q($column) if defined $column;
  17. my $derection = shift @$order;
  18. $order = $column;
  19. $order .= " $derection" if $derection;
  20. }
  21. unshift @{$self->orders}, $order;
  22. }
  23. return $self;
  24. }
  25.  
  26. sub to_string {
  27. my $self = shift;
  28. my $exists = {};
  29. my @orders;
  30. foreach my $order (@{$self->orders}) {
  31. next unless defined $order;
  32. $order =~ s/^\s+//;
  33. $order =~ s/\s+$//;
  34. my ($column, $direction) = split /\s+/, $order;
  35. push @orders, $order unless $exists->{$column};
  36. $exists->{$column} = 1;
  37. }
  38. return '' unless @orders;
  39. return 'order by ' . join(', ', @orders);
  40. }
  41.  
  42. 1;
  43.  
  44. =head1 NAME
  45.  
  46. DBIx::Custom::Order - Order by EXPERIMENTAL
  47.  
  48. =head1 SYNOPSIS
  49.  
  50. # Result
  51. my $order = DBIx::Custom::Order->new;
  52. $order->prepend('title', 'author desc');
  53. my $order_by = "$order";
  54. =head1 ATTRIBUTES
  55.  
  56. =head2 C<dbi>
  57.  
  58. my $dbi = $order->dbi;
  59. $order = $order->dbi($dbi);
  60.  
  61. L<DBIx::Custom> object.
  62.  
  63. =head2 C<orders>
  64.  
  65. my $orders = $result->orders;
  66. $result = $result->orders(\%orders);
  67.  
  68. Parts of order by clause
  69.  
  70. =head1 METHODS
  71.  
  72. L<DBIx::Custom::Result> inherits all methods from L<Object::Simple>
  73. and implements the following new ones.
  74.  
  75. =head2 C<prepend>
  76.  
  77. $order->prepend('title', 'author desc');
  78.  
  79. Prepend order parts to C<orders>.
  80.  
  81. You can pass array reference, which contain column name and direction.
  82. Column name is quoted properly
  83. # Column name and direction
  84. $order->prepend(['book-title']);
  85. $order->prepend([qw/book-title desc/]);
  86.  
  87. This is expanded to the following way.
  88.  
  89. "book-title"
  90. "book-title" desc
  91.  
  92. =head2 C<to_string>
  93.  
  94. my $order_by = $order->to_string;
  95.  
  96. Create order by clause. If column name is duplicated, First one is used.
  97. C<to_string> override stringification. so you can write the follwoing way.
  98.  
  99. my $order_by = "$order";
  100.  
  101. =cut
  102.