1

I failing to understand why I can not scan single value to "count" variable.
Could anyone explain what am i doing wrong? Single column value is returned and I try to scan it to integer variable.

query := `
SELECT COUNT('*') FROM "some-table"
WHERE (("state" = 'state') AND ("id" = 1))`

rows, err := s.conn.Query(ctx, query)
defer rows.Close()
var count int
err = rows.Scan(&count)
if err != nil {
    return false, fmt.Errorf("execute query: %w", err)
    }

Returns error: execute query: number of field descriptions must equal number of values, got 1 and 0"

UPDATE: I made workaround with thing below, but not sure it the right way:

count, err := pgx.CollectOneRow(rows, pgx.RowTo[int])
Archirk
  • 427
  • 7
  • 25
  • 1
    remove the double quotes around the count paylod – nbk Aug 11 '23 at 13:03
  • changed here for single quotes. it's valid query and returns expected result in psql CLI. furthermore its for demo purpouses. i use goqu go build queries – Archirk Aug 11 '23 at 13:32
  • there can't be any quotes, this will search for the string * the coamnd is `COUNT(*)` without any quotes at all – nbk Aug 11 '23 at 13:38
  • if don't bileve me and you know better and you have time you can go and test by yourself. I have 1 colum count with result in cell. – Archirk Aug 11 '23 at 13:40
  • 1
    In PostgreSQL double quotes delimit identifiers, single quotes represent a string constant. `SELECT COUNT("*") FROM "some-table"` can work ONLY IF `some-table` has a column named `*` (which is possible but not recommended). `SELECT COUNT('*') FROM "some-table"` will work just fine, however this is unconventional and smells. `SELECT COUNT(*) FROM "some-table"` is the most common variant. – mkopriva Aug 11 '23 at 16:18
  • 1
    Note that, when executing queries that return a single row, it is recommended to use `QueryRow` instead of `Query`... Regarding the error; my guess is that the reason you are having problems with your query is because you are using `Query` and then `Scan` but **without first calling `Next`** in between. Note also that doing `defer rows.Close()` before checking the error returned by `Query` is going to crash your program eventually. **In 99% of cases, you should never touch the primary return value of a function/method call before first checking the error return value.** – mkopriva Aug 11 '23 at 16:30

0 Answers0