Skip to content

Commit

Permalink
Merge pull request #153 from Crecto/pkey_unique_constraints
Browse files Browse the repository at this point in the history
fixed unique constraint on primary key fields
  • Loading branch information
fridgerator committed Apr 22, 2018
2 parents 66f3b41 + 13355ce commit 0ad9b2f
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
13 changes: 13 additions & 0 deletions spec/changeset_spec.cr
@@ -1,3 +1,4 @@
require "uuid"
require "./spec_helper"

describe Crecto do
Expand Down Expand Up @@ -51,6 +52,18 @@ describe Crecto do
changeset.errors[0].should eq({:field => "unique_field", :message => "UNIQUE constraint failed: users.unique_field"})
end
end

it "should check uniqueness on primary_key fields" do
id = UUID.random.to_s

u = UserUUID.new
u.uuid = id
Repo.insert(u).errors.empty?.should be_true

u = UserUUID.new
u.uuid = id
Repo.insert(u).errors.empty?.should be_false
end
end

describe "#validate_required" do
Expand Down
2 changes: 1 addition & 1 deletion spec/migrations/pg_migrations.sql
Expand Up @@ -106,7 +106,7 @@ CREATE TABLE things(
);

CREATE TABLE users_uuid(
uuid character varying NOT NULL,
uuid character varying NOT NULL PRIMARY KEY,
name character varying,
created_at timestamp without time zone,
updated_at timestamp without time zone
Expand Down
7 changes: 7 additions & 0 deletions src/crecto/changeset/changeset.cr
Expand Up @@ -59,6 +59,7 @@ module Crecto
end

def check_unique_constraint_from_exception!(e : Exception, queryable_instance)
return false unless UNIQUE_FIELDS[@class_key]?
message = e.message.to_s

# Postgres
Expand All @@ -69,6 +70,8 @@ module Crecto
return true
end
end
self.add_error("_base", message)
return true
end

# Mysql
Expand All @@ -79,6 +82,8 @@ module Crecto
return true
end
end
self.add_error("_base", message)
return true
end

# Sqlite
Expand All @@ -89,6 +94,8 @@ module Crecto
return true
end
end
self.add_error("_base", message)
return true
end

false
Expand Down
1 change: 1 addition & 0 deletions src/crecto/schema.cr
Expand Up @@ -167,6 +167,7 @@ module Crecto
{% if CRECTO_USE_PRIMARY_KEY %}
{% mapping.push(CRECTO_PRIMARY_KEY_FIELD.id.stringify + ": {type: #{CRECTO_PRIMARY_KEY_FIELD_TYPE.id}, nilable: true}") %}
CRECTO_MODEL_FIELDS.push({name: {{CRECTO_PRIMARY_KEY_FIELD.id.symbolize}}, type: {{CRECTO_PRIMARY_KEY_FIELD_TYPE}}})
unique_constraint(CRECTO_PRIMARY_KEY_FIELD_SYMBOL)
{% end %}

{% unless CRECTO_CREATED_AT_FIELD == nil %}
Expand Down

0 comments on commit 0ad9b2f

Please sign in to comment.