crystal-sqlite3 icon indicating copy to clipboard operation
crystal-sqlite3 copied to clipboard

Data from `db.query` is not populated until `rs.move_next` is called

Open OpenSauce04 opened this issue 11 months ago • 0 comments
trafficstars

When not using the rs.each block to read each row sequentially, it is seemingly necessary for rs.move_next to be called before the returned data can be accessed. This doesn't seem to be documented in any visible fashion and lead to half an hour of staring at my query trying to figure out what was wrong with my code.

As an example, the following causes read the column <column> returned a Nil but a Int64 was expected.:

DB.open <uri> do |db|
  db.query "SELECT <column> FROM <table> WHERE <column> = <value>" do |rs|
    puts rs.read(Int32)
  end
end

By contrast, this code returns the expected value, even if the table only has a single row:

DB.open <uri> do |db|
  db.query "SELECT <column> FROM <table> WHERE <column> = <value>" do |rs|
    rs.move_next # <-- Added line
    puts rs.read(Int32)
  end
end

As I mentioned before, this seems to imply that calling rs.move_next or use of the rs.each block is mandatory for the query results to be populated, which unless I'm misunderstanding something seems a unintuitive. If this intended, please document it somewhere easily visible to save future trial and error sessions from other potential users.

OpenSauce04 avatar Dec 18 '24 20:12 OpenSauce04