From b716260a53683a915e9d00ccdcc7da60082d0046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sun, 12 Aug 2018 21:45:27 +0200 Subject: [PATCH] Fix very slow table display when filled with ugly data --- app/Models/Row.php | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/app/Models/Row.php b/app/Models/Row.php index c88f090..caa0b82 100644 --- a/app/Models/Row.php +++ b/app/Models/Row.php @@ -31,17 +31,30 @@ class Row extends BaseModel public function scopeSortByCol(Builder $query, Column $column, $dir="asc") { $q = "data->>'".$column->id."'"; - if ($column->type == 'int' || $column->type == 'float') { - $q = "CAST($q AS INTEGER)"; - } - else if ($column->type == 'float') { - $q = "CAST($q AS FLOAT)"; - } - if ($dir == 'asc') { - $q .= ' ASC'; - } else { - $q .= ' DESC'; + $dir = strtoupper($dir); + + switch ($column->type) { + case 'int': + $q = "CAST($q AS INTEGER) $dir"; + break; + + case 'float': + $q = "CAST($q AS FLOAT) $dir"; + break; + + case 'string': + // Without a size restriction and a cast, this query becomes VERY slow + $q = "CAST($q AS CHAR(25)) $dir, data->>'_id' $dir"; + // added _id as a fallback to ensure the order is the same between revisions + break; + + case 'bool': + $q = "CAST($q AS boolean) $dir"; + break; + + default: + throw new \LogicException("Missing SQL cast for column type $column->type, performance will suffer."); } return $query->orderByRaw($q);