luislavena/sqlite3-ruby — Issue #58: ConstraintException not telling if column is not unique
Author: fphilipe
Created: 2011-12-14 08:12:58+00:00
State: open

In ActiveRecord, when used with SQLite, `ActiveRecord::RecordNotUnique` is not raised when violating a unique constraint. ActiveRecord raises `ActiveRecord::RecordNotUnique` when the raised `SQLite3::ConstraintException` exception contains the string `unique` in its message.
I tracked this down and it has to do with the prepared statements and bindings.

```ruby
sql = 'INSERT INTO "some_table" ("a_unique_column") VALUES ("a_duplicate_value")'
db = SQLite3::Database.new('some_db.sqlite3')

# prepare does not tell why the constraint failed:
db.execute sql # => SQLite3::ConstraintException: column name is not unique
db.prepare(sql).to_a # => SQLite3::ConstraintException: constraint failed

# It does work though from the second time on:
stmt = db.prepare(sql)
stmt.to_a # => SQLite3::ConstraintException: constraint failed
stmt.to_a # => SQLite3::ConstraintException: column name is not unique
stmt.to_a # => SQLite3::ConstraintException: column name is not unique
```

This the source of numerous bugs in rails:

* https://github.com/rails/rails/issues/3277
* https://github.com/rails/rails/issues/2965