Postgrex count result - reading big vs small values

Hi. I’m trying to assign a database table row count to a variable.

Using:
Postgrex.query!(pid, "select count(*) from sometable", [])

If the table has few rows, eg 73, the result is an ascii character in a list:

%Postgrex.Result{
  columns: ["c"],
  command: :select,
  connection_id: 103477,
  messages: [],
  num_rows: 1,
  rows: ['I'] 
}

If the table has many rows the result is an integer in a nested list:

%Postgrex.Result{
  columns: ["count"],
  command: :select,
  connection_id: 103477,
  messages: [],
  num_rows: 1,
  rows: [[1632691]]
}

The results are seemingly inconsistent, and my theories (charlist related) to explain them are no better.
Firstly, why?

Secondly, which function should I use for accessing the values consistently across both scenarios.
Eg Using hd/1 is no good as it differs for each case: hd(small_result) vs hd(hd(big_result))

Thanks.

congrats on reaching this level of “elixir” expertise… we all go through this little gotcha.

it’s only outputted in iex as a letter since it’s valid ascii… see this thread [7, 8, 9] in iex returns '\a\b\t' Why? - #4 by hauleth

edit:
for pattern matching:

result = %Postgrex.Result{
  columns: ["count"],
  command: :select,
  connection_id: 103477,
  messages: [],
  num_rows: 1,
  rows: [[1632691]]
}

[[count]] = result.rows
3 Likes

Ah, thanks. It was the second question that had me really baffled - “we’re supposed to write code to handle whether the number is big or small?!” I get the impression that default is not as helpful as intended - I’ve changed it according to IEX - char printing - odd behavior - #2 by Nicd Back on track.

1 Like