generate sql statement dynamically

This commit is contained in:
Danny 2018-06-01 13:21:54 +02:00
parent 8c6e07255f
commit a72df6274f
2 changed files with 10 additions and 8 deletions

View File

@ -31,7 +31,8 @@ func (db *sqlstore) UpdateReferrerStats(s *models.ReferrerStats) error {
func (db *sqlstore) GetAggregatedReferrerStats(startDate time.Time, endDate time.Time, limit int) ([]*models.ReferrerStats, error) {
var result []*models.ReferrerStats
query := db.Rebind(`
sql := `
SELECT
MIN(hostname) AS hostname,
MIN(pathname) AS pathname,
@ -42,7 +43,14 @@ func (db *sqlstore) GetAggregatedReferrerStats(startDate time.Time, endDate time
COALESCE(ROUND(SUM(avg_duration*pageviews)/SUM(pageviews), 4), 0.00) AS avg_duration
FROM daily_referrer_stats
WHERE date >= ? AND date <= ?
GROUP BY COALESCE(NULLIF(groupname, ""), hostname || pathname) ORDER BY pageviews DESC LIMIT ?`)
GROUP BY COALESCE(NULLIF(groupname, ""), `
if db.Config.Driver == "sqlite3" {
sql = sql + `hostname || pathname`
} else {
sql = sql + ` CONCAT(hostname, pathname)`
}
sql = sql + `) ORDER BY pageviews DESC LIMIT ?`
query := db.Rebind(sql)
err := db.Select(&result, query, startDate.Format("2006-01-02"), endDate.Format("2006-01-02"), limit)
return result, err

View File

@ -29,12 +29,6 @@ func New(c *Config) *sqlstore {
// write log statement
log.Infof("Connected to %s database: %s", c.Driver, c.Name)
// Driver specific database options
if c.Driver == "mysql" {
// Because SQLite doesn't have CONCAT, tell MySQL to accept pipes for concatenating string columns
db.Exec("SET sql_mode=PIPES_AS_CONCAT;")
}
// run migrations
db.Migrate()