From d4a597fd4bb2713b8f828211db6caa1b44c46faf Mon Sep 17 00:00:00 2001 From: Angie Byron Date: Fri, 11 Sep 2009 02:47:11 +0000 Subject: #561104 by Crell: Added support for random ordering in dynamic select queries. --- includes/database/pgsql/query.inc | 10 ++++++++++ includes/database/select.inc | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) (limited to 'includes/database') diff --git a/includes/database/pgsql/query.inc b/includes/database/pgsql/query.inc index 9005a1a83..ac5072c76 100644 --- a/includes/database/pgsql/query.inc +++ b/includes/database/pgsql/query.inc @@ -173,3 +173,13 @@ class UpdateQuery_pgsql extends UpdateQuery { return $stmt->rowCount(); } } + +class SelectQuery_pgsql extends SelectQuery { + + public function orderRandom() { + $alias = $this->addExpression('RANDOM()', 'random_field'); + $this->orderBy($alias); + return $this; + } + +} diff --git a/includes/database/select.inc b/includes/database/select.inc index a4c4ed3e4..55eecf586 100644 --- a/includes/database/select.inc +++ b/includes/database/select.inc @@ -347,6 +347,28 @@ interface SelectQueryInterface extends QueryConditionInterface, QueryAlterableIn */ public function orderBy($field, $direction = 'ASC'); + /** + * Orders the result set by a random value. + * + * This may be stacked with other orderBy() calls. If so, the query will order + * by each specified field, including this one, in the order called. Although + * this method may be called multiple times on the same query, doing so + * is not particularly useful. + * + * Note: The method used by most drivers may not scale to very large result + * sets. If you need to work with extremely large data sets, you may create + * your own database driver by subclassing off of an existing driver and + * implementing your own randomization mechanism. See + * + * http://jan.kneschke.de/projects/mysql/order-by-rand/ + * + * for an example of such an alternate sorting mechanism. + * + * @return + * The called object + */ + public function orderRandom(); + /** * Restricts a query to a given range in the result set. * @@ -643,6 +665,11 @@ class SelectQueryExtender implements SelectQueryInterface { return $this; } + public function orderRandom() { + $this->query->orderRandom(); + return $this; + } + public function range($start = NULL, $length = NULL) { $this->query->range($start, $length); return $this; @@ -1182,6 +1209,12 @@ class SelectQuery extends Query implements SelectQueryInterface { return $this; } + public function orderRandom() { + $alias = $this->addExpression('RAND()', 'random_field'); + $this->orderBy($alias); + return $this; + } + public function range($start = NULL, $length = NULL) { $this->range = func_num_args() ? array('start' => $start, 'length' => $length) : array(); return $this; -- cgit v1.2.3