From e7da8fa66854585a71845ac2cc8665eb5ccc6afc Mon Sep 17 00:00:00 2001 From: Kailash Nadh Date: Sun, 5 Jul 2020 19:23:45 +0530 Subject: [PATCH] Fix ordering of records on the subscribers page --- queries.sql | 3 ++- subscribers.go | 12 ++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/queries.sql b/queries.sql index 7b124fc..6542525 100644 --- a/queries.sql +++ b/queries.sql @@ -224,6 +224,7 @@ SELECT (SELECT email FROM prof) as email, -- there's a COUNT() OVER() that still returns the total result count -- for pagination in the frontend, albeit being a field that'll repeat -- with every resultant row. +-- %s = arbitrary expression, %s = order by field, %s = order direction SELECT COUNT(*) OVER () AS total, subscribers.* FROM subscribers LEFT JOIN subscriber_lists ON ( @@ -233,7 +234,7 @@ SELECT COUNT(*) OVER () AS total, subscribers.* FROM subscribers ) WHERE subscriber_lists.list_id = ALL($1::INT[]) %s - ORDER BY $2 DESC OFFSET $3 LIMIT $4; + ORDER BY %s %s OFFSET $2 LIMIT $3; -- name: query-subscribers-template -- raw: true diff --git a/subscribers.go b/subscribers.go index 71e90e4..c76d8d9 100644 --- a/subscribers.go +++ b/subscribers.go @@ -101,12 +101,16 @@ func handleQuerySubscribers(c echo.Context) error { } // There's an arbitrary query condition from the frontend. - cond := "" + var ( + cond = "" + ordBy = "updated_at" + ord = "DESC" + ) if query != "" { cond = " AND " + query } - stmt := fmt.Sprintf(app.queries.QuerySubscribers, cond) + stmt := fmt.Sprintf(app.queries.QuerySubscribers, cond, ordBy, ord) // Create a readonly transaction to prevent mutations. tx, err := app.db.BeginTxx(context.Background(), &sql.TxOptions{ReadOnly: true}) @@ -117,8 +121,8 @@ func handleQuerySubscribers(c echo.Context) error { } defer tx.Rollback() - // Run the query. - if err := tx.Select(&out.Results, stmt, listIDs, "updaated_at", pg.Offset, pg.Limit); err != nil { + // Run the query. stmt is the raw SQL query. + if err := tx.Select(&out.Results, stmt, listIDs, pg.Offset, pg.Limit); err != nil { return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Error querying subscribers: %v", pqErrMsg(err))) }