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 def self.from_xml(xml, create=false)
24 doc.find('//osm/relation').each do |pt|
25 return Relation.from_xml_node(pt, create)
32 def self.from_xml_node(pt, create=false)
33 relation = Relation.new
35 if !create and pt['id'] != '0'
36 relation.id = pt['id'].to_i
39 relation.version = pt['version']
40 relation.changeset_id = pt['changeset']
43 relation.timestamp = Time.now
44 relation.visible = true
47 relation.timestamp = Time.parse(pt['timestamp'])
51 pt.find('tag').each do |tag|
52 relation.add_tag_keyval(tag['k'], tag['v'])
55 pt.find('member').each do |member|
56 relation.add_member(member['type'], member['ref'], member['role'])
63 doc = OSM::API.new.get_xml_doc
64 doc.root << to_xml_node()
68 def to_xml_node(user_display_name_cache = nil)
69 el1 = XML::Node.new 'relation'
70 el1['id'] = self.id.to_s
71 el1['visible'] = self.visible.to_s
72 el1['timestamp'] = self.timestamp.xmlschema
73 el1['version'] = self.version.to_s
74 el1['changeset'] = self.changeset_id.to_s
76 user_display_name_cache = {} if user_display_name_cache.nil?
78 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
79 # use the cache if available
80 elsif self.changeset.user.data_public?
81 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
83 user_display_name_cache[self.changeset.user_id] = nil
86 if not user_display_name_cache[self.changeset.user_id].nil?
87 el1['user'] = user_display_name_cache[self.changeset.user_id]
88 el1['uid'] = self.changeset.user_id.to_s
91 self.relation_members.each do |member|
94 # # if there is a list of visible members then use that to weed out deleted segments
95 # if visible_members[member.member_type][member.member_id]
99 # otherwise, manually go to the db to check things
100 if member.member.visible?
105 e = XML::Node.new 'member'
106 e['type'] = member.member_type
107 e['ref'] = member.member_id.to_s
108 e['role'] = member.member_role
113 self.relation_tags.each do |tag|
114 e = XML::Node.new 'tag'
122 def self.find_for_nodes(ids, options = {})
126 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
127 return self.find(:all, options)
132 def self.find_for_ways(ids, options = {})
136 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
137 return self.find(:all, options)
142 def self.find_for_relations(ids, options = {})
146 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
147 return self.find(:all, options)
152 # FIXME is this really needed?
156 self.relation_members.each do |member|
157 @members += [[member.member_type,member.member_id,member.member_role]]
166 self.relation_tags.each do |tag|
181 def add_member(type,id,role)
182 @members = Array.new unless @members
183 @members += [[type,id,role]]
186 def add_tag_keyval(k, v)
187 @tags = Hash.new unless @tags
189 # duplicate tags are now forbidden, so we can't allow values
190 # in the hash to be overwritten.
191 raise OSM::APIDuplicateTagsError.new if @tags.include? k
196 def save_with_history!
197 Relation.transaction do
198 # have to be a little bit clever here - to detect if any tags
199 # changed then we have to monitor their before and after state.
208 self.relation_tags.each do |old_tag|
210 # if we can match the tags we currently have to the list
211 # of old tags, then we never set the tags_changed flag. but
212 # if any are different then set the flag and do the DB
215 # rails 2.1 dirty handling should take care of making this
216 # somewhat efficient... hopefully...
217 old_tag.v = tags[key]
218 tags_changed |= old_tag.changed?
221 # remove from the map, so that we can expect an empty map
222 # at the end if there are no new tags
226 # this means a tag was deleted
228 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
231 # if there are left-over tags then they are new and will have to
233 tags_changed |= (not tags.empty?)
235 tag = RelationTag.new
242 # same pattern as before, but this time we're collecting the
243 # changed members in an array, as the bounding box updates for
244 # elements are per-element, not blanked on/off like for tags.
245 changed_members = Array.new
247 self.members.each do |m|
248 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
249 members[[m[1], m[0]]] = m[2]
251 relation_members.each do |old_member|
252 key = [old_member.member_id.to_s, old_member.member_type]
253 if members.has_key? key
256 changed_members << key
259 # any remaining members must be new additions
260 changed_members += members.keys
262 # update the members. first delete all the old members, as the new
263 # members may be in a different order and i don't feel like implementing
264 # a longest common subsequence algorithm to optimise this.
265 members = self.members
266 RelationMember.delete_all(:id => self.id)
267 members.each_with_index do |m,i|
268 mem = RelationMember.new
269 mem.id = [self.id, i]
270 mem.member_type = m[0]
272 mem.member_role = m[2]
276 old_relation = OldRelation.from_relation(self)
277 old_relation.timestamp = t
278 old_relation.save_with_dependencies!
280 # update the bbox of the changeset and save it too.
281 # discussion on the mailing list gave the following definition for
282 # the bounding box update procedure of a relation:
284 # adding or removing nodes or ways from a relation causes them to be
285 # added to the changeset bounding box. adding a relation member or
286 # changing tag values causes all node and way members to be added to the
287 # bounding box. this is similar to how the map call does things and is
288 # reasonable on the assumption that adding or removing members doesn't
289 # materially change the rest of the relation.
291 changed_members.collect { |id,type| type == "relation" }.
292 inject(false) { |b,s| b or s }
294 if tags_changed or any_relations
295 # add all non-relation bounding boxes to the changeset
296 # FIXME: check for tag changes along with element deletions and
297 # make sure that the deleted element's bounding box is hit.
298 self.members.each do |type, id, role|
299 if type != "relation"
300 update_changeset_element(type, id)
304 # add only changed members to the changeset
305 changed_members.each do |id, type|
306 update_changeset_element(type, id)
310 # tell the changeset we updated one element only
311 changeset.add_changes! 1
313 # save the (maybe updated) changeset bounding box
319 # updates the changeset bounding box to contain the bounding box of
320 # the element with given +type+ and +id+. this only works with nodes
321 # and ways at the moment, as they're the only elements to respond to
323 def update_changeset_element(type, id)
324 element = Kernel.const_get(type.capitalize).find(id)
325 changeset.update_bbox! element.bbox
328 def delete_with_history!(new_relation, user)
330 check_consistency(self, new_relation, user)
331 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 ])
332 raise OSM::APIPreconditionFailedError.new
334 self.changeset_id = new_relation.changeset_id
341 raise OSM::APIAlreadyDeletedError.new
345 def update_from(new_relation, user)
346 check_consistency(self, new_relation, user)
347 if !new_relation.preconditions_ok?
348 raise OSM::APIPreconditionFailedError.new
350 self.changeset_id = new_relation.changeset_id
351 self.tags = new_relation.tags
352 self.members = new_relation.members
357 def create_with_history(user)
358 check_create_consistency(self, user)
359 if !self.preconditions_ok?
360 raise OSM::APIPreconditionFailedError.new
367 def preconditions_ok?
368 # These are hastables that store an id in the index of all
369 # the nodes/way/relations that have already been added.
370 # If the member is valid and visible then we add it to the
371 # relevant hash table, with the value true as a cache.
372 # Thus if you have nodes with the ids of 50 and 1 already in the
373 # relation, then the hash table nodes would contain:
374 # => {50=>true, 1=>true}
375 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
376 self.members.each do |m|
377 # find the hash for the element type or die
378 hash = elements[m[0].to_sym] or return false
380 # unless its in the cache already
381 unless hash.key? m[1]
382 # use reflection to look up the appropriate class
383 model = Kernel.const_get(m[0].capitalize)
385 # get the element with that ID
386 element = model.find(m[1])
388 # and check that it is OK to use.
389 unless element and element.visible? and element.preconditions_ok?
401 # Temporary method to match interface to nodes
407 # if any members are referenced by placeholder IDs (i.e: negative) then
408 # this calling this method will fix them using the map from placeholders
410 def fix_placeholders!(id_map)
411 self.members.map! do |type, id, role|
414 new_id = id_map[type.to_sym][old_id]
415 raise "invalid placeholder" if new_id.nil?