Golang SQLBoiler returns nothing when running orderby

900 Views Asked by At

I'm using SqlBoiler on Go to send requests to a PostgreSQL db, but when trying to order the database by one of the fields it returns 0 rows.

At first i run a count (like detailed below) and if the count returns more than or equal to one row then i query the database for all the results.

This returns the correct row count:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
    ).Count(CTX, DB)

This returns no rows, despite the query params being exactly the same:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy(`mt_mas`),
    ).Count(CTX, DB)

This is how I get all the rows after checking the row count:

res, err := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy(`mt_mas`),
    ).All(CTX, DB)

When reading the error from the request above, it prints out <nil> and everything seems fine.

The database is, as mentioned Postgres (version PostgreSQL 13.3), and the columns are as follows:

  • mt_mas (integer)
    This column holds the uid of the owner of this row.
  • mt_mem (character varying [1000])
    This column holds a JSON list of user members uid:s.
  • mt_group (boolean)
    This column shows of this row is a group of not.

Example of database row:
| mt_mas | mt_mem | mt_group | | :----: | :----: | :------: | | 1 | {"1", "2"} | false |

1

There are 1 best solutions below

0
On BEST ANSWER

Okay, the solution was simpler than expected. @Gari Singh (https://stackoverflow.com/users/5529712/gari-singh) actually pointed this out in the comments above, but i figured i would write it here so the question registers as solved.

The solution is to simply not order in the query that counts the results. So the correct code for counting should only be:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
    ).Count(CTX, DB)

And then running the query to get the actual rows with the order, like this:

res, err := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy("mt_mas"),
    ).All(CTX, DB)

Thank you for your help! :)