karthikv / model_schema

Enforced, Annotated Schema for Ruby Sequel Models
MIT License
41 stars 0 forks source link

Getting confused on primary key? #2

Closed jacquescrocker closed 6 years ago

jacquescrocker commented 6 years ago

I'm seeing the following error on my specs. I'm running rake test:prepare first.

An error occurred while loading ./spec/models/user_spec.rb.
Failure/Error:
  model_schema do
    primary_key :id
    column :email, "text", null: false
    column :created_at, DateTime
    column :updated_at, DateTime

ModelSchema::SchemaError:
  Table users does not match the expected schema.

  Table users has mismatched columns:

    actual:    Integer :id, :null=>false
    expected:  primary_key :id

Here's whats in my schema.rb

    create_table(:users) do
      column :id, "integer", :null=>false
      column :email, "text", :null=>false
      column :created_at, "timestamp with time zone"
      column :updated_at, "timestamp with time zone"

      primary_key [:id]

    end
karthikv commented 6 years ago

See http://sequel.jeremyevans.net/rdoc/files/doc/schema_modification_rdoc.html#label-primary_key

In create_table blocks, you generally use primary_key :id to represent the entire id column (i.e. you don't need to separately specify column :id, Integer).

The difference is that primary_key :id creates an auto-incrementing primary key, which isn't the case for column :id, Integer followed by primary_key [:id]

karthikv commented 6 years ago

Also, to clarify the issue in your example, there's a distinction between primary_key :id and primary_key [:id]. The former means that there's an auto-incrementing id column with a primary key constraint. The latter means there's a primary key constraint on an existing column named :id (which must be specified separately by column :id).

Your model_schema block specifies primary_key :id, whereas your create_table block specifies primary_key [:id]. That's why you're getting the error; these two are different, because the :id column being referred to in the create_table block is not auto-incrementing.