Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created September 15, 2021 19:45
Show Gist options
  • Save JoshCheek/aea565773b51b1e99612edec6ce1c378 to your computer and use it in GitHub Desktop.
Save JoshCheek/aea565773b51b1e99612edec6ce1c378 to your computer and use it in GitHub Desktop.
PG cursors must be in transactions, so can't be seen from other connections
require 'pg'
db1 = PG.connect
db2 = PG.connect
db3 = PG.connect
# setup (db1)
db1.exec "drop table if exists strs;"
db1.exec "create table strs(val text);"
1.upto(100) { |i| db1.exec_params "insert into strs(val) values ($1)", [i.to_s] };
# create the cursor (db2)
db2.exec "begin;"
db2.exec "declare my_cursor cursor for select * from strs order by val::integer;"
db2.exec("fetch 5 from my_cursor;").to_a
# => [{"val"=>"1"}, {"val"=>"2"}, {"val"=>"3"}, {"val"=>"4"}, {"val"=>"5"}]
# attempt to read the cursor from a different connection (db3)
db3.exec("fetch 5 from my_cursor;").to_a # => PG::InvalidCursorName: ERROR: cursor "my_cursor" does not exist\n
# ~> PG::InvalidCursorName
# ~> ERROR: cursor "my_cursor" does not exist
# ~>
# ~> program.rb:18:in `exec'
# ~> program.rb:18:in `<main>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment