Unify the MSSQL and DB2 RNO implementations - they are the same
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / MSSQL.pm
index 2db2af7..28b87f2 100644 (file)
@@ -178,6 +178,41 @@ sub _execute {
 
 sub last_insert_id { shift->_identity }
 
+#
+# MSSQL is retarded wrt ordered subselects. One needs to add a TOP 100%
+# to *all* subqueries, do it here.
+#
+sub _select_args_to_query {
+  my $self = shift;
+
+  # _select_args does some shady action at a distance
+  # see DBI.pm for more info
+  my $sql_maker = $self->sql_maker;
+  my ($op, $bind, $ident, $bind_attrs, $select, $cond, $order, $rows, $offset);
+  {
+    local $sql_maker->{_dbic_rs_attrs};
+    ($op, $bind, $ident, $bind_attrs, $select, $cond, $order, $rows, $offset) = $self->_select_args(@_);
+  }
+
+  if (
+    ($rows || $offset)
+      ||
+    not scalar $sql_maker->_order_by_chunks ($order->{order_by})
+  ) {
+    # either limited RS or no ordering, just short circuit
+    return $self->next::method (@_);
+  }
+
+  my ($sql, $prep_bind, @rest) = $self->next::method (@_);
+  $sql =~ s/^ \s* SELECT \s/SELECT TOP 100 PERCENT /xi;
+
+  return wantarray
+    ? ($sql, $prep_bind, @rest)
+    : \[ "($sql)", @$prep_bind ]
+  ;
+}
+
+
 # savepoint syntax is the same as in Sybase ASE
 
 sub _svp_begin {
@@ -212,7 +247,7 @@ sub _sql_maker_opts {
     $self->{_sql_maker_opts} = { %$opts };
   }
 
-  return { limit_dialect => 'Top', %{$self->{_sql_maker_opts}||{}} };
+  return { limit_dialect => 'RowNumberOver', %{$self->{_sql_maker_opts}||{}} };
 }
 
 1;