close
The Wayback Machine - https://web.archive.org/web/20230131214955/https://dev.to/schmijos/serial-in-sqlite-mgc

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Josua Schmid
Josua Schmid

Posted on

SERIAL in SQLite

Today I received the following error when creating a new Rails ActiveRecord with CourseStatus.create!(name: 'Klettern fΓΌr AnfΓ€nger') in a SQLite database:

SQLite3::ConstraintException: NOT NULL constraint failed: course_statuses.id
Enter fullscreen mode Exit fullscreen mode

The problem was that the schema.rb defined the primary key as serial (originally created by a Rails 5.0 migration):

create_table "course_statuses", id: :serial do |t|
  t.string "name", limit: 255
  t.datetime "created_at"
  t.datetime "updated_at"
end
Enter fullscreen mode Exit fullscreen mode

Since SQLite is dynamically typed, the id primary key will simply be declared with the non-existent type serial. And this means that the SQLite adapter will not mark the primary key to be auto-incrementable. Only INTEGER types can be auto-incremented in SQLite.

The solution is to remove all id: :serial from the schema.rb (then db:schema:load db:schema:dump) and leave the decision about how to create the tables completely up to the database adapter.

Top comments (0)

Build Anything...

Image
Use any Linode offering to create something for the DEV x Linode Hackathon 2022. A variety of prizes are up for grabs, inculding $1,000 USD. πŸ‘€

β†’ Join the Hackathon <-