From a32b5dd5917d3ff2adfeea65475092d07f88c9ab Mon Sep 17 00:00:00 2001 From: Simon Kollross Date: Sun, 24 Jul 2022 12:30:35 +0200 Subject: [PATCH] Support PostgreSQL --- src/StatsQuery.php | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/StatsQuery.php b/src/StatsQuery.php index 0eb9897..e2d7083 100644 --- a/src/StatsQuery.php +++ b/src/StatsQuery.php @@ -172,6 +172,17 @@ public static function getPeriodDateFormat(string $period): string { $dbDriver = Config::get('database.connections.'.Config::get('database.default', 'mysql').'.driver', 'mysql'); + if ($dbDriver === 'pgsql') { + return match ($period) { + 'year' => "to_char(created_at, 'YYYY')", + 'month' => "to_char(created_at, 'YYYY-MM')", + 'week' => "to_char(created_at, 'IYYYIW')", + 'day' => "to_char(created_at, 'YYYY-MM-DD')", + 'hour' => "to_char(created_at, 'YYYY-MM-DD HH24')", + 'minute' => "to_char(created_at, 'YYYY-MM-DD HH24:MI')", + }; + } + return match ($period) { 'year' => "date_format(created_at,'%Y')", 'month' => "date_format(created_at,'%Y-%m')", @@ -245,11 +256,13 @@ protected function getLatestSetPerPeriod(): EloquentCollection { $periodDateFormat = static::getPeriodDateFormat($this->period); - $statsTable = $this->getStatsTableName(); - $statsKey = $this->getStatsKey(); + $query = $this->queryStats(); + + $statsTable = $query->getGrammar()->wrap($this->getStatsTableName()); + $statsKey = $query->getGrammar()->wrap($this->getStatsKey()); - $rankedSets = $this->queryStats() - ->selectRaw("ROW_NUMBER() OVER (PARTITION BY {$periodDateFormat} ORDER BY `{$statsKey}` DESC) AS rn, `{$statsTable}`.*, {$periodDateFormat} as period") + $rankedSets = $query + ->selectRaw("ROW_NUMBER() OVER (PARTITION BY {$periodDateFormat} ORDER BY {$statsKey} DESC) AS rn, {$statsTable}.*, {$periodDateFormat} as period") ->where('type', DataPoint::TYPE_SET) ->where('created_at', '>=', $this->start) ->where('created_at', '<', $this->end)