Having difficulty catching postgresql exception in sequel/ruby
- by mhd
I have postgresql table that has somekind of unique constraint.
I have ruby script that will update this table.
The ruby script should be able to switch to UPDATE instead of INSERT
when this kind of error occured:
PGError: ERROR: duplicate key value violates unique constraint
CMIIW, sequel seems cannot catch this exception??
Anyway,sample code below is something that I would like to see to work but apparently not:
@myarray.each do |x|
fresh_ds = DB["INSERT INTO mytable (id, col_foo) values ('#{x}' ,'#{myhash[x]}')"]
result = fresh_ds.insert
catch Sequel::Error do
fresh_ds = DB["UPDATE mytable set col_foo = '#{myhash[x]} where id = #{x}"]
result = fresh_ds.update
end
end
Maybe my ruby code is wrong or I missed something I don't know.
Any solution?
Thanks.
UPDATE:
code below works, the error is caught when unique constraint is violated.
@myarray.each do |x|
begin
# INSERT CODE
rescue Sequel::Error
# UPDATE CODE
end
end