Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

5.5 CRUD basics

DataMapper as an ORM is intended to create, retrieve, update, and delete records from a repository through interactions with Ruby objects. This means that we don’t have to write SQL statements through the normal course of usage. In fact, DataMapper’s versatility, intelligence, and performance will probably leave you never needing to write a single SQL statement in your entire application.

Throughout this section, we will assume the existence of the following model:

class BlogEntry
  include DataMapper::Resource

  property :id, Serial
  property :live, TrueClass
  property :title, String
  property :text, Text
end

5.5.1 Creating records

The creation of DataMapper records is a two-step process. The first step is the creation of a new model object. This is as simple as initializing with the new method. This method can also take an attributes hash that will set the model object’s properties. The second step of this process is the saving of the object’s data into the database as a record. This is done via the save method. Below we create a new blog entry and then save it immediately after.

blog_entry = BlogEntry.new(:title => "Model Magic!",
  :text => "Persistently cool.")

blog_entry.save

At the end, this issues a SQL insert command, saving the data in our database. However, let’s take a look first at the most superficial methods inside the DataMapper that make this work:

module DataMapper::Resource
  def save

    # ... association related

    saved = new_record? ? create : update

    if saved
      original_values.clear
    end

    # ... association related

    (saved | associations_saved) == true
  end

  def new_record?
    !defined?(@new_record) || @new_record
  end

  protected

  def create
    return false if new_record? &&
      !dirty? && !model.key.any? { |p| p.serial? }

    # set defaults for new resource
    properties.each do |property|
      next if attribute_loaded?(property.name)
      property.set(self, property.default_for(self))
    end

    return false unless repository.create([ self ]) == 1

    @repository = repository
    @new_record = false

    # ... IdentityMap related

    true
  end

  private

  def initialize(attributes = {})
    assert_valid_model
    self.attributes = attributes
  end

end

As you can see, the default initialize has been overridden so that it can set attributes. You’ll also spot a method assert_valid_model, but it isn’t of much interest since all it does is confirm that the model class does in fact have properties defined. Moving on to the save method, you’ll find that it first checks to see if the model object should be a new record. To do this it uses the public method new_record?, which is also available to you should you need it as an application or plugin developer. Then, given that our record is new, it invokes the protected method create. This method effectively cascades through the resource’s repository object down to an adapter, where a SQL create statement is executed.

Alternatively, you can shorten this process to a single step by using the class method create defined within the Model module. Here we use it just as we did before:

blog_entry = BlogEntry.create(:title => 'Models Rule!',
  :text => 'Persistently cool.')

Taking a peek at the source code, we find that the class method create does exactly what we did ourselves before but returns the model object for our convenience:

module DataMapper::Model

  def create(attributes = {})
    resource = new(attributes)
    resource.save
    resource
  end

end

5.5.2 Retrieving records

The retrieval of model records is principally done through the two methods all and first. These two methods pull up a collection of records or access a single record, respectively. They can easily be chained, allowing for the refining of the data to be retrieved. Let’s take a look at some basic examples:

user = User.first(:login => 'foysavas')
groups = Group.all(:name => '%Ruby%')
admin_groups = groups.all(:user => user)

The first line looks up a user by login, the second retrieves all groups with the word Ruby in them, and the third refines the collection of the second to only those where the user is the admin. Let’s look at the source behind the methods first and all to get an understanding of how they work:

module DataMapper::Model

  def all(query = {})
    query = scoped_query(query)
    query.repository.read_many(query)
  end

  def first(*args)
    query = args.last.respond_to?(:merge) ?
      args.pop : {}

      query = scoped_query(
        query.merge(:limit => args.first || 1))

    if args.any?
      query.repository.read_many(query)
    else
      query.repository.read_one(query)
    end
  end

end

Both all and first use the method scoped_query to integrate new query parameters with any preexisting ones that may exist higher up on a collection on which the method may be acting:

module DataMapper::Model

  private

  def scoped_query(query = self.query)
    assert_kind_of 'query', query, Query, Hash

    return self.query if query == self.query

    query = if query.kind_of?(Hash)
      Query.new(query.has_key?(:repository) ?
        query.delete(:repository) :
        self.repository, self, query)
    else
      query
    end

    if self.query
      self.query.merge(query)
    else
      merge_with_default_scope(query)
    end
  end

end

DataMapper uses the method assert_kind_of as a way of enforcing types and throws errors when types do not match. Thus, above, we see that scoped_query accepts only queries and hashes. The hashes are really just cases of yet-to-be-initiated queries coming from the parameters of some method like all or first. If both new query parameters and an existing query exist, the two are merged. The model’s default scope (typically having no conditions and all non-lazy model fields) is used to merge in further conditions.

The method Query#merge duplicates the query and then seeks to update it. Below we see this method as it leads into Query#update.

class DataMapper::Query

  def update(other)
    assert_kind_of 'other', other, self.class, Hash

    assert_valid_other(other)

    if other.kind_of?(Hash)
      return self if other.empty?
      other = self.class.new(@repository, model, other)
    end

    return self if self == other

    @reload = other.reload?
      unless other.reload? == false
    @unique = other.unique?
      unless other.unique? == false
    @offset = other.offset
      if other.reload? || other.offset != 0
    @limit = other.limit
      unless other.limit == nil
    @order = other.order
      unless other.order == model.default_order
    @add_reversed = other.add_reversed?
      unless other.add_reversed? == false
    @fields = other.fields
      unless other.fields == @properties.defaults
    @links = other.links
      unless other.links == []
    @includes = other.includes
      unless other.includes == []

    update_conditions(other)

    self
  end

  def merge(other)
    dup.update(other)
  end

end

Note that the method update picks out special query parameters before updating the conditions and finally returning itself.

5.5.2.1 Special query parameters

The parameters passed into all and first are mostly understood simply as conditions upon parameters. However, certain keys are understood as special query parameters that shape the query in other ways. The following list should make the use of each of these clear:

  • add_reversed—reverses the order in which objects are added to the collection. Defaults to false.
  • conditions—allows SQL conditions to be set directly using an array of strings. Conditions are appended to conditions specified elsewhere.
  • fields—sets the fields to fetch as an array of symbols or properties. Defaults to all of a model’s non-lazy properties.
  • includes—includes other model data specified as a list of DataMapper property paths.
  • limit—limits the number of records returned. Defaults to 1 in the case of first and is otherwise not set.
  • links—links in related model data specified by an array of symbols, strings, or associations.
  • offset—the offset of the query, essential for paging. Defaults to 0.
  • order—the query order specified as an array or properties (or symbols) modified by the two direction methods desc and asc.
  • reload—causes the reloading of the entire data set. Defaults to false.
  • unique—groups by the fields specified, resulting in a unique collection. Defaults to false.

5.5.2.2 Lazy loading of collections

DataMapper does not load collections or issue database queries until the data is absolutely needed. The major benefit here is that application developers can worry less about the database side of things once again, knowing that unless they actually use the data of a resource, no database query will be executed. With Merb, we’ve also found that this means simpler controller code, since we can use chained relationships or pagination inside the view. With any other ORM, this may be extremely bad form, given that it implies littering the view with lines of supporting code as well as incurring performance penalties based on the retrieval of possibly unused data. Below we present the practical application of collection lazy loading.

# Posts Controller
# app/controllers/posts.rb

class Posts
  before :set_page

  def index
    @posts = Post.all
    render
  end

  private

  def set_page
    @p = params[:page] > 0 ?
      params[:page] : 1
  end
end

# Posts Index View
# app/views/posts/index.html.haml
- @posts.all(:limit => 10, :offset => 10*@p).each do |i|
  .post
    = @posts.name

Note that this executes only one database query, specifically at the each. To see how and why this works, we need to take a look at some of the code in the parent class of Collection, LazyArray:

class LazyArray # borrowed partially from StrokeDB
  instance_methods.each { |m|
    undef_method m unless %w[
      _ _id_ _ _ _send_ _ send class dup object_id
      kind_of? respond_to? equal? assert_kind_of
      should should_not instance_variable_set
      instance_variable_get extend ].include?(m.to_s)
  }

  # add proxies for all Array and Enumerable methods
  ((Array.instance_methods(false)
    | Enumerable.instance_methods(false)).map { |m|
      m.to_s
    } - %w[ taguri= ]).each do |method|

    class_eval <<-EOS, _ _FILE_ _, _ _LINE_ _
      def #{method}(*args, &block)
        lazy_load
        results = @array.#{method}(*args, &block)
        results.equal?(@array) ? self : results
      end
    EOS

  end


  def load_with(&block)
    @load_with_proc = block
    self
  end

  # ...

  private

  def lazy_load
    return if loaded?
    mark_loaded
    @load_with_proc[self]
    @array.unshift(*@head)
    @array.concat(@tail)
    @head = @tail = nil
    @reapers.each { |r|
      @array.delete_if(&r)
    } if @reapers
    @array.freeze if frozen?
  end

  # ...

end

Starting at the top, we can see that all but the quintessence methods are undefined. This is because LazyArray is meant to emulate the primitive Array class, and starting off with a slate that is as blank as possible helps us get there. The next few lines define various instance methods from both Array and Enumerable, essentially making LazyArray a proxy to a real array but prefacing the call of any array method with lazy_load. The lazy_load method itself either simply returns true if already loaded, or uses a Proc defined through the load_with method to populate the array. All in all, the lazy loading of LazyArray has a profound impact on the DataMapper API, arguably serving as the foundation for the elegance and straightforwardness of the query algebra.

5.5.2.3 Lazy loading of properties

Some property data is not automatically retrieved when a model object is loaded. For instance, by default, text properties are not loaded unless you specifically request them. This form of lazy loading is facilitated by code with the Resource module and PropertySet class. Let’s see it in action before taking an in-depth look at how it has been put together:

# app/models/post.rb
class Post
  include DataMapper::Resource

  property :id, Serial
  property :title, String
  property :body, Text
end

# Example Merb Interaction
> post = Post.first
 ~ SELECT "id", "title", "is_basic" FROM "posts" ORDER BY
   "id" LIMIT 1
 => #<Post id=1 title="First Post!" body=<not loaded>>
> post.body
 ~ SELECT "body", "id" FROM "posts" WHERE ("id" = 1) ORDER BY "id"
 => "Nothing to see here"

Note that if we had multiple text properties, they would all have been loaded by the second line of interaction. To prevent this from happening, you can define lazy contexts on properties, thus segmenting the retrieval of lazy property data:

# app/models/post.rb
class Article
  include DataMapper::Resource

  property :id, Serial
  property :title, String, :lazy => true
  property :abstract, Text, :lazy => [:summary, :full]
  property :body, Text, :lazy => [:full]
end

It’s time to see how this is done. We’ll have to open up Resource and PropertySet, with the insight that a property when either get or set calls the method Resource#lazy_load:

module DataMapper::Resource

  def lazy_load(name)
    reload_attributes(
      *properties.lazy_load_context(name) -
      loaded_attributes)
  end

end


class DataMapper::PropertySet

  # ...

  def property_contexts(name)
    contexts = []
    lazy_contexts.each do |context,property_names|
      contexts << context
        if property_names.include?(name)
    end
    contexts
  end

  def lazy_load_context(names)
    if names.kind_of?(Array) && names.empty?
      raise ArgumentError, '+names+ cannot be empty',
        caller
    end

    result = []

    Array(names).each do |name|
      contexts = property_contexts(name)
      if contexts.empty?
        result << name # not lazy
      else
        result |= lazy_contexts.values_at(*contexts).
          flatten.uniq
      end
    end
    result
  end
end

The methods of PropertySet aren’t anything special, but seeing how they work certainly clears up any ambiguity that may have existed within the concept of lazy load contexts.

5.5.2.4 Strategic eager loading

If you’ve used ActiveRecord before, you’ve probably trained yourself to avoid N+1 queries. These come up frequently in ActiveRecord since iteration over the associates of a model object usually forces you to make a query for each associate. Add in the original query for the model itself, and you have N+1 queries in total. However, DataMapper prevents this from happening and instead issues only two queries. Let’s take a look at an example in a view to make this more concrete:

<% Post.all.each do |post| %>
  <div class="post">
    <h1><%= post.title ></h1>
    <h2>by <%= post.author.name %></h2>
  </div>
<% end %>

With the code above, all posts and the names of their authors are outputted using only two queries: the first to get the posts and the second to get their authors. This kind of elimination of N+1 queries is called strategic eager loading and is possible thanks to a combination of many different DataMapper implementation decisions. To get an idea of how strategic eager loading works, let’s take a look at some code inside the Relationship class that would have been used in the previous example:

class DataMapper::Associations::Relationship

  # ...

  # @api private
  def get_parent(child, parent = nil)
    child_value = child_key.get(child)
    return nil if child_value.any? { |v| v.nil? }

    with_repository(parent || parent_model) do
      parent_identity_map = (parent || parent_model).
        repository.identity_map(parent_model.base_model)
      child_identity_map = child.
        repository.identity_map(child_model.base_model)

      if parent = parent_identity_map[child_value]
        return parent
      end

      children = child_identity_map.values
      children << child
        unless child_identity_map[child.key]

      bind_values = children.map {
        |c| child_key.get(c) }.uniq
      query_values = bind_values.reject {
        |k| parent_identity_map[k] }

      bind_values = query_values
        unless query_values.empty?
      query = parent_key.zip(bind_values.transpose).
        to_hash
      association_accessor =
        "#{self.name}_association"

      collection = parent_model.send(:all, query)
      unless collection.empty?
        collection.send(:lazy_load)
        children.each do |c|
          c.send(association_accessor).
            instance_variable_set(
              :@parent,
              collection.get(*child_key.get(c)))
        end
        child.send(association_accessor).
          instance_variable_get(:@parent)
      end
    end
  end


end

From this we learn that in the process of getting a parent resource, DataMapper pulls up the identity map of the parent model and child model to see if the resource has already been loaded. If it has, DataMapper short-circuits any retrieval and simply returns the appropriate parent. Most important, if the resource is not already loaded, DataMapper uses the parent keys from all the relevant children within a collection query. The results are then loaded immediately, and after all children are connected with their parents, the parent requested is returned.

5.5.3 Updating records

Resources can be updated by using the save method similarly to how it was used with record creation. However, for saving to have any effect, it is necessary that at least one property value be recently set. This causes DataMapper to mark certain properties as dirty and use them during the creation of an update statement. Below we display the two ways of setting a property value and causing it to be marked as dirty.

post = Post.first
post.title = "New Title"
post.attribute_set(:body, "New Body")
post.save

However, note that the second method attribute_set is typically reserved for use inside override writer methods. Note that save, in the case of non-new records, cascades to the calling of update. Thus we have the option of using that method directly if we want:

post.update

5.5.3.1 Using update_attributes

There is one other way to invoke the updating of attributes. This is to use the method update_attributes, which accepts an arbitrary hash and then an optional constraining property array. Consequently, it works well with form parameters a user may have passed in:

class Users
  def update
    if @user.update_attributes(params[:user],
      [:name, :email, :description])
      redirect resource(@user)
    else
      render :edit
    end
  end
end

Here we have constrained the user to being able to update only name, email, and description.

5.5.3.2 Original and dirty attribute values

You may at some point want to enhance model logic through the comparison of original and dirty attribute values. Here we do so within the method update_speed:

class Position
  property :id, Serial
  property :vertical_position, Integer
  property :horizontal_position, Integer
  property :speed, Float

  belongs_to :player

  before :save, :update_speed

  private

  def update_speed
    dy = 0
    dx = 0
    if original_values[:vertical_position]
      dy = vertical_position -
        original_values[:vertical_position]
    end
    if original_values[:horizontal_position]
      dx = horizontal_position -
        original_values[:horizontal_position]
    end
    v = Math.sqrt(dx*dx + dy*dy)
    attribute_set(:speed, v)
  end

end

You may notice that we use a before hook here. We’ll cover hooks in the next section.

5.5.4 Destroying records

Records can be deleted by using the destroy method. Alternatively, if you’re looking to delete a full collection of resources, you can use the method destroy!:

User.first(:id => 2).destroy
Post.all(:user_id => 2).destroy!
  • + Share This
  • 🔖 Save To Your Account