Added as_sql and as_subselect as wrappers around as_query
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / ResultSetColumn.pm
index 167cd02..5e8e727 100644 (file)
@@ -40,10 +40,13 @@ sub new {
   my $attrs = $new_parent_rs->_resolved_attrs;
   $new_parent_rs->{attrs}->{$_} = undef for qw(prefetch include_columns +select +as); # prefetch, include_columns, +select, +as cause additional columns to be fetched
 
+  # If $column can be found in the 'as' list of the parent resultset, use the
+  # corresponding element of its 'select' list (to keep any custom column
+  # definition set up with 'select' or '+select' attrs), otherwise use $column
+  # (to create a new column definition on-the-fly).
   my $as_list = $attrs->{as} || [];
   my $select_list = $attrs->{select} || [];
   my $as_index = List::Util::first { ($as_list->[$_] || "") eq $column } 0..$#$as_list;
-
   my $select = defined $as_index ? $select_list->[$as_index] : $column;
 
   my $new = bless { _select => $select, _as => $column, _parent_resultset => $new_parent_rs }, $class;
@@ -51,6 +54,69 @@ sub new {
   return $new;
 }
 
+=head2 as_query
+
+=over 4
+
+=item Arguments: none
+
+=item Return Value: \[ $sql, @bind ]
+
+=back
+
+Returns the SQL query and bind vars associated with the invocant.
+
+=cut
+
+sub as_query { return shift->_resultset->as_query }
+
+=head2 as_subselect
+
+=over 4
+
+=item Arguments: none
+
+=item Return Value: \[ $sql, @bind ]
+
+=back
+
+Returns the SQL query and bind vars associated with the invocant.
+
+The SQL will be wrapped in parentheses, ready for use as a subselect.
+
+=cut
+
+sub as_subselect {
+  my $self = shift;
+  my $arr = ${$self->as_query(@_)};
+  $arr->[0] = '( ' . $arr->[0] . ' )';
+  return \$arr;
+}
+
+=head2 as_query
+
+=over 4
+
+=item Arguments: none
+
+=item Return Value: $sql
+
+=back
+
+Returns the SQL query associated with the invocant. All bind vars
+will have been bound using C<< DBI->quote() >>.
+
+=cut
+
+sub as_sql {
+  my $self = shift;
+  my $arr = ${$self->as_query(@_)};
+  my $sql = shift @$arr;
+  my $dbh = $self->_resultset->result_source->schema->storage->dbh;
+  $sql =~ s/\?/$dbh->quote((shift @$arr)->[1])/eg;
+  return $sql
+}
+
 =head2 next
 
 =over 4
@@ -275,7 +341,6 @@ sub _resultset {
   );
 }
 
-
 1;
 
 =head1 AUTHORS