Improve the Select translation query.

See http://drupal.org/node/436868 for details.

We use a ORDER BY CASE tecnique to simplify the final query.

Signed-off-by: Antonio Ospite <ospite@studenti.unina.it>

Index: select_translation_filter_handler.inc
===================================================================
--- select_translation_filter_handler.inc.orig
+++ select_translation_filter_handler.inc
@@ -67,32 +67,49 @@
       }
     }
     $list = array_unique($list);
-    
-    // Now build the query. For every option, we need to exclude
-    // the previous ones to ensure only one node gets selected in the end.
+
     $alias = $this->query->ensure_table('node');
-    $query = "node.tnid = 0";
-    $exclude = array();
+    $query = "$alias.tnid IS NULL OR $alias.tnid = 0";
+
+    /* build the body for the CASE statement we use below to
+     * enforce the language preference order
+     */
     foreach ($list as $i => $v) {
+
       if ($v == 'original') {
-        $add = "$alias.nid = $alias.tnid";
-        $exc = "lmfh_node.tnid = lmfh_node.nid";
-      } else {
-        $add = "$alias.language = '$v'";
-        $exc = "lmfh_node.language = '$v'";
-      }
-      
-      if (count($exclude)) {
-        $add = $add ." AND
-          0 = (SELECT count(lmfh_node.nid)
-                 FROM {node} AS lmfh_node
-                WHERE lmfh_node.tnid = node.tnid AND
-                      ((".implode(') OR (', $exclude).")))";
+        $else = $i;
+        continue;
       }
-      $exclude[] = $exc;
+
+      $when = "'$v'";
+      $then = $i;
         
-      $query = $query."\n OR ($add)";
+      $cases .= "WHEN $when THEN $then\n";
+    }
+
+    /* We have handle the case when _only_ the original version is
+     * requested, as the CASE statement wants at least one WHEN,
+     * use a dummy one if needed.
+     */
+    if (empty($cases)) {
+      $cases = "WHEN '__not_a_language__' THEN -1";
     }
+
+    /* We order by language preference, the original language case will be
+     * handled automatically in the ELSE part.
+     *
+     * stfh stands for  Select Translation Filter Handle
+     */
+    $query .= " OR $alias.nid=(
+      SELECT nid FROM node AS stfh_node
+      WHERE stfh_node.tnid=$alias.tnid
+      ORDER BY
+        CASE stfh_node.language
+          $cases
+          ELSE $else
+        END
+      LIMIT 1
+      )";
     
     $this->query->add_where($this->options['group'], $query);
   }
