Skip to content

Commit

Permalink
Merge pull request hirocaster#16 from hirocaster/primary-key-not-set
Browse files Browse the repository at this point in the history
Add MissingPrimaryKey Error
  • Loading branch information
hirocaster committed Dec 16, 2015
2 parents 53340b2 + c244ee7 commit d2ed72d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/active_record/sharding/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ class Error < ::StandardError

class MissingShardingKeyAttribute < Error
end

class MissingPrimaryKey < Error
end
end
end
10 changes: 9 additions & 1 deletion lib/active_record/sharding/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ module Sharding
module Model
extend ActiveSupport::Concern

included do
included do |base|
base.before_create :validate_id!

class_attribute :cluster_router, instance_writer: false
class_attribute :shard_repository, instance_writer: false
class_attribute :sharding_key, instance_writer: false
Expand Down Expand Up @@ -61,6 +63,12 @@ def define_parent_methods(&block)
instance_eval(&block)
end
end

private

def validate_id!
raise ActiveRecord::Sharding::MissingPrimaryKey if attributes[self.class.primary_key].nil?
end
end
end
end
38 changes: 38 additions & 0 deletions spec/active_record/sharding/model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,42 @@ def find_from_all_by_name(name)
expect(record.name).to eq("foo")
end
end

describe "Irregular use case" do
context "Not write before_put block" do
let!(:model) do
Class.new(ActiveRecord::Base) do
def self.name
"User"
end

def self.sequence_id
@sequence_id ||= 0
end

class << self
attr_writer :sequence_id
end

def self.next_sequence_id
self.sequence_id += 1
end

include ActiveRecord::Sharding::Model
use_sharding :user, :modulo
define_sharding_key :id

define_parent_methods do
def find_from_all_by_name(name)
all_shards.map { |m| m.find_by(name: name) }.compact.first
end
end
end
end

it "Raise MissingPrimaryKey at #save" do
expect { model.shard_for(1).new.save }.to raise_error ActiveRecord::Sharding::MissingPrimaryKey
end
end
end
end

0 comments on commit d2ed72d

Please sign in to comment.