Search code examples
rubysinatrasequelpadrino

Trapping constraint errors in Sequel ORM before the server


I have a Ruby/Padrino project using Sequel ORM to access a legacy database in MySQL. The problem I am having is that several of the tables have a user editable column that is also a Primary Key.

I am trying to set up Sequel to catch any duplication errors within the application itself before MySQL can throw an error. I assumed that the validation helpers in Sequel could help me do that, but it appears they do not kick in before the data is saved.

My SQL table is defined as:

CREATE TABLE `dblocations` (
  `code` varchar(3) NOT NULL,
  `description` varchar(100) NOT NULL,
  PRIMARY KEY (`code`)
)

and my Sequel models are defined as follows:

class Location < Sequel::Model(:dblocations)
  plugins :validation_helpers
  def validate
    super
    validates_presence [:code, :description]
    validates_unique :code
  end
end

the problem is now, when I try the following code to insert Location Code 'ABC' into the database (when there is already another row in there with the Code 'ABC'), Ruby throws the following error:

Location.insert(:code => "ABC", :description => "Test Location")

ERROR -  Mysql2::Error: Duplicate entry 'ABC' for key 'PRIMARY': INSERT INTO `dblocations` (`code`, `description`) VALUES ('ABC', 'Test Location')
Sequel::UniqueConstraintViolation: Mysql2::Error: Duplicate entry 'ABC' for key 'PRIMARY'

Have I misconfigured my validations or is there another plugin I need to invoke?


Solution

  • insert is a dataset-level method, validations are model level. You probably want to use create instead of insert.