Skip to content

Commit

Permalink
Merge branch 'add-support-for-uuid-primary-keys' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
sskirby committed Nov 25, 2020
2 parents ccd178e + 9a333e9 commit 1d248d5
Show file tree
Hide file tree
Showing 13 changed files with 388 additions and 211 deletions.
35 changes: 30 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Vorpal [![Build Status](https://travis-ci.com/nulogy/vorpal.svg?branch=master)](https://travis-ci.com/nulogy/vorpal) [![Code Climate](https://codeclimate.com/github/nulogy/vorpal/badges/gpa.svg)](https://codeclimate.com/github/nulogy/vorpal) [![Code Coverage](https://codecov.io/gh/nulogy/vorpal/branch/master/graph/badge.svg)](https://codecov.io/gh/nulogy/vorpal/branch/master)
# Vorpal [![Build Status](https://travis-ci.com/nulogy/vorpal.svg?branch=main)](https://travis-ci.com/nulogy/vorpal) [![Code Climate](https://codeclimate.com/github/nulogy/vorpal/badges/gpa.svg)](https://codeclimate.com/github/nulogy/vorpal) [![Code Coverage](https://codecov.io/gh/nulogy/vorpal/branch/main/graph/badge.svg)](https://codecov.io/gh/nulogy/vorpal/branch/main)

Separate your domain model from your persistence mechanism. Some problems call for a really sharp tool.

Expand Down Expand Up @@ -156,9 +156,35 @@ TreeRepository.destroy(dead_tree)
TreeRepository.destroy_by_id(dead_tree_id)
```

### Ids

Vorpal by default will use auto-incrementing Integers from a DB sequence for ids. However, UUID v4 ids are also
supported:

```ruby
Vorpal.define do
# UUID v4 id!
map Tree, primary_key_type: :uuid do
# ..
end

# Also a UUID v4 id, the Rails Way!
map Trunk, id: :uuid do
# ..
end

# If you feel the need to specify an auto-incrementing integer id.
map Branch, primary_key_type: :serial do
# ..
end
end
```

CAVEAT: Vorpal currently does NOT SUPPORT anyone but Vorpal setting the id of an entity!

## API Documentation

http://rubydoc.info/github/nulogy/vorpal/master/frames
http://rubydoc.info/github/nulogy/vorpal/main/frames

## Caveats
It also does not do some things that you might expect from other ORMs:
Expand All @@ -175,9 +201,8 @@ It also does not do some things that you might expect from other ORMs:
1. Only supports PostgreSQL.

## Future Enhancements
* Support for UUID primary keys.
* Support for clients to set UUID-based ids.
* Nicer DSL for specifying attributes that have different names in the domain model than in the DB.
* Show how to implement POROs without using Virtus (it is unsupported and can be crazy slow)
* Aggregate updated_at.
* Better support for value objects.

Expand All @@ -195,7 +220,7 @@ It also does not do some things that you might expect from other ORMs:

**A.** Create a method on a [Repository](http://martinfowler.com/eaaCatalog/repository.html)! They have full access to the DB/ORM so you can use [Arel](https://github.com/rails/arel) and go [crazy](http://asciicasts.com/episodes/239-activerecord-relation-walkthrough) or use direct SQL if you want.

For example, use the [#query](https://rubydoc.info/github/nulogy/vorpal/master/Vorpal/AggregateMapper#query-instance_method) method on the [AggregateMapper](https://rubydoc.info/github/nulogy/vorpal/master/Vorpal/AggregateMapper) to access the underyling [ActiveRecordRelation](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html):
For example, use the [#query](https://rubydoc.info/github/nulogy/vorpal/main/Vorpal/AggregateMapper#query-instance_method) method on the [AggregateMapper](https://rubydoc.info/github/nulogy/vorpal/main/Vorpal/AggregateMapper) to access the underyling [ActiveRecordRelation](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html):

```ruby
def find_special_ones
Expand Down
71 changes: 71 additions & 0 deletions lib/vorpal/config/class_config.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
require 'equalizer'

module Vorpal
module Config
# @private
class ClassConfig
include Equalizer.new(:domain_class, :db_class)
attr_reader :serializer, :deserializer, :domain_class, :db_class, :primary_key_type, :local_association_configs
attr_accessor :has_manys, :belongs_tos, :has_ones

ALLOWED_PRIMARY_KEY_TYPE_OPTIONS = [:serial, :uuid]

def initialize(attrs)
@has_manys = []
@belongs_tos = []
@has_ones = []
@local_association_configs = []

@serializer = attrs[:serializer]
@deserializer = attrs[:deserializer]
@domain_class = attrs[:domain_class]
@db_class = attrs[:db_class]
@primary_key_type = attrs[:primary_key_type]
raise "Invalid primary_key_type: '#{@primary_key_type}'" unless ALLOWED_PRIMARY_KEY_TYPE_OPTIONS.include?(@primary_key_type)
end

def build_db_object(attributes)
db_class.new(attributes)
end

def set_db_object_attributes(db_object, attributes)
db_object.attributes = attributes
end

def get_db_object_attributes(db_object)
symbolize_keys(db_object.attributes)
end

def serialization_required?
domain_class.superclass.name != 'ActiveRecord::Base'
end

def serialize(object)
serializer.serialize(object)
end

def deserialize(db_object)
attributes = get_db_object_attributes(db_object)
serialization_required? ? deserializer.deserialize(domain_class.new, attributes) : db_object
end

def set_attribute(db_object, attribute, value)
db_object.send("#{attribute}=", value)
end

def get_attribute(db_object, attribute)
db_object.send(attribute)
end

private

def symbolize_keys(hash)
result = {}
hash.each_key do |key|
result[key.to_sym] = hash[key]
end
result
end
end
end
end
75 changes: 9 additions & 66 deletions lib/vorpal/configs.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
require 'vorpal/util/hash_initialization'
require 'vorpal/exceptions'
require 'vorpal/config/class_config'
require 'equalizer'

module Vorpal
# @private
class MasterConfig
def initialize(class_configs)
@class_configs = class_configs
initialize_association_configs
class MainConfig
def initialize
@class_configs = []
end

def config_for(clazz)
Expand All @@ -20,7 +20,9 @@ def config_for_db_object(db_object)
@class_configs.detect { |conf| conf.db_class == db_object.class }
end

private
def add_class_config(class_config)
@class_configs << class_config
end

def initialize_association_configs
association_configs = {}
Expand Down Expand Up @@ -50,6 +52,8 @@ def initialize_association_configs
end
end

private

def build_association_config(association_configs, local_config, fk, fk_type)
association_config = AssociationConfig.new(local_config, fk, fk_type)
if association_configs[association_config]
Expand Down Expand Up @@ -126,67 +130,6 @@ def foreign_key_info(remote_class_config)
end
end

# @private
class ClassConfig
include Equalizer.new(:domain_class, :db_class)
attr_reader :serializer, :deserializer, :domain_class, :db_class, :local_association_configs
attr_accessor :has_manys, :belongs_tos, :has_ones

def initialize(attrs)
@has_manys = []
@belongs_tos = []
@has_ones = []
@local_association_configs = []

attrs.each do |k,v|
instance_variable_set("@#{k}", v)
end
end

def build_db_object(attributes)
db_class.new(attributes)
end

def set_db_object_attributes(db_object, attributes)
db_object.attributes = attributes
end

def get_db_object_attributes(db_object)
symbolize_keys(db_object.attributes)
end

def serialization_required?
domain_class.superclass.name != 'ActiveRecord::Base'
end

def serialize(object)
serializer.serialize(object)
end

def deserialize(db_object)
attributes = get_db_object_attributes(db_object)
serialization_required? ? deserializer.deserialize(domain_class.new, attributes) : db_object
end

def set_attribute(db_object, attribute, value)
db_object.send("#{attribute}=", value)
end

def get_attribute(db_object, attribute)
db_object.send(attribute)
end

private

def symbolize_keys(hash)
result = {}
hash.each_key do |key|
result[key.to_sym] = hash[key]
end
result
end
end

# @private
class ForeignKeyInfo
include Equalizer.new(:fk_column, :fk_type_column, :fk_type)
Expand Down
77 changes: 12 additions & 65 deletions lib/vorpal/dsl/config_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,74 +16,32 @@ def initialize(clazz, options, db_driver)
@defaults_generator = DefaultsGenerator.new(clazz, db_driver)
end

# Maps the given attributes to and from the domain object and the DB. Not needed
# if a serializer and deserializer were provided.
# @private
def attributes(*attributes)
@attributes.concat(attributes)
end

# Defines a one-to-many association to another type where the foreign key is stored on the child.
#
# In Object-Oriented programming, associations are *directed*. This means that they can only be
# traversed in one direction: from the type that defines the association (the one with the
# getter) to the type that is associated. They end that defines the association is called the
# 'Parent' and the end that is associated is called the 'Child'.
#
# @param name [String] Name of the association getter.
# @param options [Hash]
# @option options [Boolean] :owned (True) True if the child type belongs to the aggregate. Changes to any object belonging to the aggregate will be persisted when the aggregate is persisted.
# @option options [String] :fk (Parent class name converted to snakecase and appended with a '_id') The name of the DB column on the child that contains the foreign key reference to the parent.
# @option options [String] :fk_type The name of the DB column on the child that contains the parent class name. Only needed when there is an association from the child side that is polymorphic.
# @option options [Class] :child_class (name converted to a Class) The child class.
# @private
def has_many(name, options={})
@has_manys << {name: name}.merge(options)
@has_manys << build_has_many({name: name}.merge(options))
end

# Defines a one-to-one association to another type where the foreign key
# is stored on the child.
#
# In Object-Oriented programming, associations are *directed*. This means that they can only be
# traversed in one direction: from the type that defines the association (the one with the
# getter) to the type that is associated. They end that defines the association is called the
# 'Parent' and the end that is associated is called the 'Child'.
#
# @param name [String] Name of the association getter.
# @param options [Hash]
# @option options [Boolean] :owned (True) True if the child type belongs to the aggregate. Changes to any object belonging to the aggregate will be persisted when the aggregate is persisted.
# @option options [String] :fk (Parent class name converted to snakecase and appended with a '_id') The name of the DB column on the child that contains the foreign key reference to the parent.
# @option options [String] :fk_type The name of the DB column on the child that contains the parent class name. Only needed when there is an association from the child side that is polymorphic.
# @option options [Class] :child_class (name converted to a Class) The child class.
# @private
def has_one(name, options={})
@has_ones << {name: name}.merge(options)
@has_ones << build_has_one({name: name}.merge(options))
end

# Defines a one-to-one association with another type where the foreign key
# is stored on the parent.
#
# This association can be polymorphic. I.E. children can be of different types.
#
# In Object-Oriented programming, associations are *directed*. This means that they can only be
# traversed in one direction: from the type that defines the association (the one with the
# getter) to the type that is associated. They end that defines the association is called the
# 'Parent' and the end that is associated is called the 'Child'.
#
# @param name [String] Name of the association getter.
# @param options [Hash]
# @option options [Boolean] :owned (True) True if the child type belongs to the aggregate. Changes to any object belonging to the aggregate will be persisted when the aggregate is persisted.
# @option options [String] :fk (Child class name converted to snakecase and appended with a '_id') The name of the DB column on the parent that contains the foreign key reference to the child.
# @option options [String] :fk_type The name of the DB column on the parent that contains the child class name. Only needed when the association is polymorphic.
# @option options [Class] :child_class (name converted to a Class) The child class.
# @option options [[Class]] :child_classes The list of possible classes that can be children. This is for polymorphic associations. Takes precedence over `:child_class`.
# @private
def belongs_to(name, options={})
@belongs_tos << {name: name}.merge(options)
@belongs_tos << build_belongs_to({name: name}.merge(options))
end

# @private
def build
class_config = build_class_config
class_config.has_manys = build_has_manys
class_config.has_ones = build_has_ones
class_config.belongs_tos = build_belongs_tos
class_config.has_manys = @has_manys
class_config.has_ones = @has_ones
class_config.belongs_tos = @belongs_tos

class_config
end
Expand All @@ -96,40 +54,29 @@ def attributes_with_id
private

def build_class_config
Vorpal::ClassConfig.new(
Vorpal::Config::ClassConfig.new(
domain_class: @domain_class,
db_class: @class_options[:to] || @defaults_generator.build_db_class(@class_options[:table_name]),
serializer: @class_options[:serializer] || @defaults_generator.serializer(attributes_with_id),
deserializer: @class_options[:deserializer] || @defaults_generator.deserializer(attributes_with_id),
primary_key_type: @class_options[:primary_key_type] || @class_options[:id] || :serial,
)
end

def build_has_manys
@has_manys.map { |options| build_has_many(options) }
end

def build_has_many(options)
options[:child_class] ||= @defaults_generator.child_class(options[:name])
options[:fk] ||= @defaults_generator.foreign_key(@domain_class.name)
options[:owned] = options.fetch(:owned, true)
Vorpal::HasManyConfig.new(options)
end

def build_has_ones
@has_ones.map { |options| build_has_one(options) }
end

def build_has_one(options)
options[:child_class] ||= @defaults_generator.child_class(options[:name])
options[:fk] ||= @defaults_generator.foreign_key(@domain_class.name)
options[:owned] = options.fetch(:owned, true)
Vorpal::HasOneConfig.new(options)
end

def build_belongs_tos
@belongs_tos.map { |options| build_belongs_to(options) }
end

def build_belongs_to(options)
child_class = options[:child_classes] || options[:child_class] || @defaults_generator.child_class(options[:name])
options[:child_classes] = Array(child_class)
Expand Down
Loading

0 comments on commit 1d248d5

Please sign in to comment.