#959 suggestion
Ashley Moran

Repository#save

Reported by Ashley Moran | July 7th, 2009 @ 08:30 AM

This is a ticket to represent the thread on the DataMapper group: http://groups.google.com/group/datamapper/t/a80a60b7a3663ef5

What I would ideally like is for Repository to be the central place to handle persistence, much like SQLAlchemy, as described on their docs: http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-a-session

I suspect the useful methods would be:
* Repository#<< - mark a new resource for saving * Repository#save - save all (unsaved) resources * Repository#valid? - true if all object graphs in the repository are valid * Repository#dirty? - true if any resource in an object graph in the repository is dirty * Repository#saved? - true if all resources in an object graph in the repository are saved

In fact, I imagine most of not all of the Resource methods could be extended to repository.

One point to make about Resource#save: it ideally needs to walk the object graphs to find all unsaved objects. The reason is that the Resource#save described in #940 has to stop at non-dirty objects, which means branches of the object graph may not be reached. (We have a real case of this.) And it would be much more convenient if these resources could be found automatically, rather than needing to use Repository#<<.

I made a quick code spike to see how feasible this would all be. The ugly, but somewhat useful, code is here:

module DataMapper
  class Repository
    module SessionOperations
      def <<(resource)
        new_resources << resource
        new_resources
      end
      
      def save
        success = new_resources.all? { |resource|
          saved = resource.save
          saved
        } &&
        @identity_maps.all? { |model, identity_map|
          identity_map.all? { |key, resource|
            resource.new? || resource.dirty? ? resource.save : true
          }
        }
        new_resources.delete_if { |resource| resource.saved? }
        success
      end
      
      private
      
      def new_resources
        @new_resources ||= [ ]
      end
    end
    
    include SessionOperations
  end
end

I hope this is a useful starting point.

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket

Pages