[Question] Whether it is possible to receive a name of the field in which a sql error?
AlexanderMint opened this issue · comments
Example:
def create_user(params)
UserRepository.new.create(params)
rescue Hanami::Model::UniqueConstraintViolationError
# Error: "PG::UniqueViolation: ERROR: duplicate key value violates unique constraint 'users_email_key'
# DETAIL: Key (email)=(name@example.com) already exists."
# How to receive a name not of the unique field?
end
@AlexanderMint we have an idea to improve UniqueConstraintViolationError
getting the table, column and constraint so we'll be able to access them and could be used in params using something like params.errors.add(e.column, e.message)
FWIW, unique validations should be done before data goes to a database. Of course, there is small (most likely) chance of getting a constraint violation error but such errors should be handled in another way, by rescuing and retrying the whole transaction including the validation step. Another possible option is using the ON CONFLICT
statement introduced in recent PG versions