1 class Relation < ActiveRecord::Base
4 include ConsistencyValidations
6 set_table_name 'current_relations'
10 has_many :old_relations, :foreign_key => 'id', :order => 'version'
12 has_many :relation_members, :foreign_key => 'id', :order => 'sequence_id'
13 has_many :relation_tags, :foreign_key => 'id'
15 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
16 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
18 validates_presence_of :id, :on => :update
19 validates_presence_of :timestamp,:version, :changeset_id
20 validates_uniqueness_of :id
21 validates_inclusion_of :visible, :in => [ true, false ]
22 validates_numericality_of :id, :on => :update, :integer_only => true
23 validates_numericality_of :changeset_id, :version, :integer_only => true
24 validates_associated :changeset
26 TYPES = ["node", "way", "relation"]
28 def self.from_xml(xml, create=false)
34 doc.find('//osm/relation').each do |pt|
35 return Relation.from_xml_node(pt, create)
37 rescue LibXML::XML::Error => ex
38 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
42 def self.from_xml_node(pt, create=false)
43 relation = Relation.new
45 if !create and pt['id'] != '0'
46 relation.id = pt['id'].to_i
49 raise OSM::APIBadXMLError.new("relation", pt, "You are missing the required changeset in the relation") if pt['changeset'].nil?
50 relation.changeset_id = pt['changeset']
52 # The follow block does not need to be executed because they are dealt with
53 # in create_with_history, update_from and delete_with_history
55 relation.timestamp = Time.now
56 relation.visible = true
60 relation.timestamp = Time.parse(pt['timestamp'])
62 relation.version = pt['version']
65 pt.find('tag').each do |tag|
66 relation.add_tag_keyval(tag['k'], tag['v'])
69 pt.find('member').each do |member|
71 logger.debug "each member"
72 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
73 logger.debug "after raise"
74 #member_ref = member['ref']
76 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
77 logger.debug member['role']
78 relation.add_member(member['type'], member['ref'], member['role'])
80 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
86 doc = OSM::API.new.get_xml_doc
87 doc.root << to_xml_node()
91 def to_xml_node(user_display_name_cache = nil)
92 el1 = XML::Node.new 'relation'
93 el1['id'] = self.id.to_s
94 el1['visible'] = self.visible.to_s
95 el1['timestamp'] = self.timestamp.xmlschema
96 el1['version'] = self.version.to_s
97 el1['changeset'] = self.changeset_id.to_s
99 user_display_name_cache = {} if user_display_name_cache.nil?
101 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
102 # use the cache if available
103 elsif self.changeset.user.data_public?
104 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
106 user_display_name_cache[self.changeset.user_id] = nil
109 if not user_display_name_cache[self.changeset.user_id].nil?
110 el1['user'] = user_display_name_cache[self.changeset.user_id]
111 el1['uid'] = self.changeset.user_id.to_s
114 self.relation_members.each do |member|
117 # # if there is a list of visible members then use that to weed out deleted segments
118 # if visible_members[member.member_type][member.member_id]
122 # otherwise, manually go to the db to check things
123 if member.member.visible?
128 e = XML::Node.new 'member'
129 e['type'] = member.member_type
130 e['ref'] = member.member_id.to_s
131 e['role'] = member.member_role
136 self.relation_tags.each do |tag|
137 e = XML::Node.new 'tag'
145 def self.find_for_nodes(ids, options = {})
149 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'node' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
150 return self.find(:all, options)
155 def self.find_for_ways(ids, options = {})
159 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'way' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
160 return self.find(:all, options)
165 def self.find_for_relations(ids, options = {})
169 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'relation' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
170 return self.find(:all, options)
175 # FIXME is this really needed?
179 self.relation_members.each do |member|
180 @members += [[member.member_type,member.member_id,member.member_role]]
189 self.relation_tags.each do |tag|
204 def add_member(type,id,role)
205 @members = Array.new unless @members
206 @members += [[type,id,role]]
209 def add_tag_keyval(k, v)
210 @tags = Hash.new unless @tags
212 # duplicate tags are now forbidden, so we can't allow values
213 # in the hash to be overwritten.
214 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
220 # updates the changeset bounding box to contain the bounding box of
221 # the element with given +type+ and +id+. this only works with nodes
222 # and ways at the moment, as they're the only elements to respond to
224 def update_changeset_element(type, id)
225 element = Kernel.const_get(type.capitalize).find(id)
226 changeset.update_bbox! element.bbox
229 def delete_with_history!(new_relation, user)
231 raise OSM::APIAlreadyDeletedError.new
234 # need to start the transaction here, so that the database can
235 # provide repeatable reads for the used-by checks. this means it
236 # shouldn't be possible to get race conditions.
237 Relation.transaction do
238 check_consistency(self, new_relation, user)
239 # This will check to see if this relation is used by another relation
240 if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id", :conditions => [ "visible = ? AND member_type='relation' and member_id=? ", true, self.id ])
241 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is a used in another relation")
243 self.changeset_id = new_relation.changeset_id
251 def update_from(new_relation, user)
252 check_consistency(self, new_relation, user)
253 if !new_relation.preconditions_ok?
254 raise OSM::APIPreconditionFailedError.new
256 self.changeset_id = new_relation.changeset_id
257 self.tags = new_relation.tags
258 self.members = new_relation.members
263 def create_with_history(user)
264 check_create_consistency(self, user)
265 if !self.preconditions_ok?
266 raise OSM::APIPreconditionFailedError.new
273 def preconditions_ok?
274 # These are hastables that store an id in the index of all
275 # the nodes/way/relations that have already been added.
276 # If the member is valid and visible then we add it to the
277 # relevant hash table, with the value true as a cache.
278 # Thus if you have nodes with the ids of 50 and 1 already in the
279 # relation, then the hash table nodes would contain:
280 # => {50=>true, 1=>true}
281 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
282 self.members.each do |m|
283 # find the hash for the element type or die
284 hash = elements[m[0].to_sym] or return false
286 # unless its in the cache already
287 unless hash.key? m[1]
288 # use reflection to look up the appropriate class
289 model = Kernel.const_get(m[0].capitalize)
291 # get the element with that ID
292 element = model.find(m[1])
294 # and check that it is OK to use.
295 unless element and element.visible? and element.preconditions_ok?
307 # Temporary method to match interface to nodes
313 # if any members are referenced by placeholder IDs (i.e: negative) then
314 # this calling this method will fix them using the map from placeholders
316 def fix_placeholders!(id_map)
317 self.members.map! do |type, id, role|
320 new_id = id_map[type.to_sym][old_id]
321 raise "invalid placeholder" if new_id.nil?
331 def save_with_history!
332 Relation.transaction do
333 # have to be a little bit clever here - to detect if any tags
334 # changed then we have to monitor their before and after state.
343 self.relation_tags.each do |old_tag|
345 # if we can match the tags we currently have to the list
346 # of old tags, then we never set the tags_changed flag. but
347 # if any are different then set the flag and do the DB
350 # rails 2.1 dirty handling should take care of making this
351 # somewhat efficient... hopefully...
352 old_tag.v = tags[key]
353 tags_changed |= old_tag.changed?
356 # remove from the map, so that we can expect an empty map
357 # at the end if there are no new tags
361 # this means a tag was deleted
363 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
366 # if there are left-over tags then they are new and will have to
368 tags_changed |= (not tags.empty?)
370 tag = RelationTag.new
377 # same pattern as before, but this time we're collecting the
378 # changed members in an array, as the bounding box updates for
379 # elements are per-element, not blanked on/off like for tags.
380 changed_members = Array.new
382 self.members.each do |m|
383 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
384 members[[m[1], m[0]]] = m[2]
386 relation_members.each do |old_member|
387 key = [old_member.member_id.to_s, old_member.member_type]
388 if members.has_key? key
391 changed_members << key
394 # any remaining members must be new additions
395 changed_members += members.keys
397 # update the members. first delete all the old members, as the new
398 # members may be in a different order and i don't feel like implementing
399 # a longest common subsequence algorithm to optimise this.
400 members = self.members
401 RelationMember.delete_all(:id => self.id)
402 members.each_with_index do |m,i|
403 mem = RelationMember.new
404 mem.id = [self.id, i]
405 mem.member_type = m[0]
407 mem.member_role = m[2]
411 old_relation = OldRelation.from_relation(self)
412 old_relation.timestamp = t
413 old_relation.save_with_dependencies!
415 # update the bbox of the changeset and save it too.
416 # discussion on the mailing list gave the following definition for
417 # the bounding box update procedure of a relation:
419 # adding or removing nodes or ways from a relation causes them to be
420 # added to the changeset bounding box. adding a relation member or
421 # changing tag values causes all node and way members to be added to the
422 # bounding box. this is similar to how the map call does things and is
423 # reasonable on the assumption that adding or removing members doesn't
424 # materially change the rest of the relation.
426 changed_members.collect { |id,type| type == "relation" }.
427 inject(false) { |b,s| b or s }
429 if tags_changed or any_relations
430 # add all non-relation bounding boxes to the changeset
431 # FIXME: check for tag changes along with element deletions and
432 # make sure that the deleted element's bounding box is hit.
433 self.members.each do |type, id, role|
434 if type != "relation"
435 update_changeset_element(type, id)
439 # add only changed members to the changeset
440 changed_members.each do |id, type|
441 update_changeset_element(type, id)
445 # tell the changeset we updated one element only
446 changeset.add_changes! 1
448 # save the (maybe updated) changeset bounding box