QueryTorrents for postgreSQL - fix loading more torrents

This commit is contained in:
Michał Gątkowski 2022-08-05 01:16:48 +02:00
parent 345901583c
commit fd2ee88e5d

View File

@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
"net/url" "net/url"
"text/template"
"time" "time"
"unicode/utf8" "unicode/utf8"
@ -205,20 +206,50 @@ func (db *postgresDatabase) QueryTorrents(
return nil, fmt.Errorf("lastOrderedValue and lastID should be supplied together, if supplied") return nil, fmt.Errorf("lastOrderedValue and lastID should be supplied together, if supplied")
} }
//doJoin := query != "" firstPage := lastID == nil
//firstPage := lastID == nil
// executeTemplate is used to prepare the SQL query, WITH PLACEHOLDERS FOR USER INPUT. // executeTemplate is used to prepare the SQL query, WITH PLACEHOLDERS FOR USER INPUT.
rows, err := db.conn.Query(` sqlQuery := executeTemplate(`
SELECT id SELECT id
, info_hash , info_hash
, name , name
, total_size , total_size
, discovered_on , discovered_on
, (SELECT COUNT(*) FROM files WHERE torrents.id = files.torrent_id) AS n_files , (SELECT COUNT(*) FROM files WHERE torrents.id = files.torrent_id) AS n_files
FROM torrents FROM torrents {{ if not .FirstPage }}
LIMIT $1;`, limit) WHERE {{.OrderOn}} {{GTEorLTE .Ascending}} {{.LastOrderedValue}} {{ end }}
ORDER BY {{.OrderOn}} {{AscOrDesc .Ascending}}
LIMIT {{.Limit}};
`, struct {
FirstPage bool
OrderOn string
Ascending bool
Limit uint
LastOrderedValue *float64
}{
FirstPage: firstPage,
OrderOn: orderOn(orderBy),
Ascending: ascending,
Limit: limit,
LastOrderedValue: lastOrderedValue,
}, template.FuncMap{
"GTEorLTE": func(ascending bool) string {
if ascending {
return ">"
} else {
return "<"
}
},
"AscOrDesc": func(ascending bool) string {
if ascending {
return "ASC"
} else {
return "DESC"
}
},
})
rows, err := db.conn.Query(sqlQuery)
defer db.closeRows(rows) defer db.closeRows(rows)
if err != nil { if err != nil {
zap.L().Error(fmt.Sprint(err)) zap.L().Error(fmt.Sprint(err))