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 TYPES = ["node", "way", "relation"]
20 def self.from_xml(xml, create=false)
26 doc.find('//osm/relation').each do |pt|
27 return Relation.from_xml_node(pt, create)
29 rescue LibXML::XML::Error => ex
31 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
35 def self.from_xml_node(pt, create=false)
36 relation = Relation.new
38 if !create and pt['id'] != '0'
39 relation.id = pt['id'].to_i
42 relation.version = pt['version']
43 relation.changeset_id = pt['changeset']
46 relation.timestamp = Time.now
47 relation.visible = true
50 relation.timestamp = Time.parse(pt['timestamp'])
54 pt.find('tag').each do |tag|
55 relation.add_tag_keyval(tag['k'], tag['v'])
58 pt.find('member').each do |member|
60 logger.debug "each member"
61 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
62 logger.debug "after raise"
63 #member_ref = member['ref']
65 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
66 logger.debug member['role']
67 relation.add_member(member['type'], member['ref'], member['role'])
69 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
75 doc = OSM::API.new.get_xml_doc
76 doc.root << to_xml_node()
80 def to_xml_node(user_display_name_cache = nil)
81 el1 = XML::Node.new 'relation'
82 el1['id'] = self.id.to_s
83 el1['visible'] = self.visible.to_s
84 el1['timestamp'] = self.timestamp.xmlschema
85 el1['version'] = self.version.to_s
86 el1['changeset'] = self.changeset_id.to_s
88 user_display_name_cache = {} if user_display_name_cache.nil?
90 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
91 # use the cache if available
92 elsif self.changeset.user.data_public?
93 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
95 user_display_name_cache[self.changeset.user_id] = nil
98 if not user_display_name_cache[self.changeset.user_id].nil?
99 el1['user'] = user_display_name_cache[self.changeset.user_id]
100 el1['uid'] = self.changeset.user_id.to_s
103 self.relation_members.each do |member|
106 # # if there is a list of visible members then use that to weed out deleted segments
107 # if visible_members[member.member_type][member.member_id]
111 # otherwise, manually go to the db to check things
112 if member.member.visible?
117 e = XML::Node.new 'member'
118 e['type'] = member.member_type
119 e['ref'] = member.member_id.to_s
120 e['role'] = member.member_role
125 self.relation_tags.each do |tag|
126 e = XML::Node.new 'tag'
134 def self.find_for_nodes(ids, options = {})
138 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
139 return self.find(:all, options)
144 def self.find_for_ways(ids, options = {})
148 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
149 return self.find(:all, options)
154 def self.find_for_relations(ids, options = {})
158 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
159 return self.find(:all, options)
164 # FIXME is this really needed?
168 self.relation_members.each do |member|
169 @members += [[member.member_type,member.member_id,member.member_role]]
178 self.relation_tags.each do |tag|
193 def add_member(type,id,role)
194 @members = Array.new unless @members
195 @members += [[type,id,role]]
198 def add_tag_keyval(k, v)
199 @tags = Hash.new unless @tags
201 # duplicate tags are now forbidden, so we can't allow values
202 # in the hash to be overwritten.
203 raise OSM::APIDuplicateTagsError.new if @tags.include? k
208 def save_with_history!
209 Relation.transaction do
210 # have to be a little bit clever here - to detect if any tags
211 # changed then we have to monitor their before and after state.
220 self.relation_tags.each do |old_tag|
222 # if we can match the tags we currently have to the list
223 # of old tags, then we never set the tags_changed flag. but
224 # if any are different then set the flag and do the DB
227 # rails 2.1 dirty handling should take care of making this
228 # somewhat efficient... hopefully...
229 old_tag.v = tags[key]
230 tags_changed |= old_tag.changed?
233 # remove from the map, so that we can expect an empty map
234 # at the end if there are no new tags
238 # this means a tag was deleted
240 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
243 # if there are left-over tags then they are new and will have to
245 tags_changed |= (not tags.empty?)
247 tag = RelationTag.new
254 # same pattern as before, but this time we're collecting the
255 # changed members in an array, as the bounding box updates for
256 # elements are per-element, not blanked on/off like for tags.
257 changed_members = Array.new
259 self.members.each do |m|
260 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
261 members[[m[1], m[0]]] = m[2]
263 relation_members.each do |old_member|
264 key = [old_member.member_id.to_s, old_member.member_type]
265 if members.has_key? key
268 changed_members << key
271 # any remaining members must be new additions
272 changed_members += members.keys
274 # update the members. first delete all the old members, as the new
275 # members may be in a different order and i don't feel like implementing
276 # a longest common subsequence algorithm to optimise this.
277 members = self.members
278 RelationMember.delete_all(:id => self.id)
279 members.each_with_index do |m,i|
280 mem = RelationMember.new
281 mem.id = [self.id, i]
282 mem.member_type = m[0]
284 mem.member_role = m[2]
288 old_relation = OldRelation.from_relation(self)
289 old_relation.timestamp = t
290 old_relation.save_with_dependencies!
292 # update the bbox of the changeset and save it too.
293 # discussion on the mailing list gave the following definition for
294 # the bounding box update procedure of a relation:
296 # adding or removing nodes or ways from a relation causes them to be
297 # added to the changeset bounding box. adding a relation member or
298 # changing tag values causes all node and way members to be added to the
299 # bounding box. this is similar to how the map call does things and is
300 # reasonable on the assumption that adding or removing members doesn't
301 # materially change the rest of the relation.
303 changed_members.collect { |id,type| type == "relation" }.
304 inject(false) { |b,s| b or s }
306 if tags_changed or any_relations
307 # add all non-relation bounding boxes to the changeset
308 # FIXME: check for tag changes along with element deletions and
309 # make sure that the deleted element's bounding box is hit.
310 self.members.each do |type, id, role|
311 if type != "relation"
312 update_changeset_element(type, id)
316 # add only changed members to the changeset
317 changed_members.each do |id, type|
318 update_changeset_element(type, id)
322 # tell the changeset we updated one element only
323 changeset.add_changes! 1
325 # save the (maybe updated) changeset bounding box
331 # updates the changeset bounding box to contain the bounding box of
332 # the element with given +type+ and +id+. this only works with nodes
333 # and ways at the moment, as they're the only elements to respond to
335 def update_changeset_element(type, id)
336 element = Kernel.const_get(type.capitalize).find(id)
337 changeset.update_bbox! element.bbox
340 def delete_with_history!(new_relation, user)
342 check_consistency(self, new_relation, user)
343 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 ])
344 raise OSM::APIPreconditionFailedError.new
346 self.changeset_id = new_relation.changeset_id
353 raise OSM::APIAlreadyDeletedError.new
357 def update_from(new_relation, user)
358 check_consistency(self, new_relation, user)
359 if !new_relation.preconditions_ok?
360 raise OSM::APIPreconditionFailedError.new
362 self.changeset_id = new_relation.changeset_id
363 self.tags = new_relation.tags
364 self.members = new_relation.members
369 def create_with_history(user)
370 check_create_consistency(self, user)
371 if !self.preconditions_ok?
372 raise OSM::APIPreconditionFailedError.new
379 def preconditions_ok?
380 # These are hastables that store an id in the index of all
381 # the nodes/way/relations that have already been added.
382 # If the member is valid and visible then we add it to the
383 # relevant hash table, with the value true as a cache.
384 # Thus if you have nodes with the ids of 50 and 1 already in the
385 # relation, then the hash table nodes would contain:
386 # => {50=>true, 1=>true}
387 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
388 self.members.each do |m|
389 # find the hash for the element type or die
390 hash = elements[m[0].to_sym] or return false
392 # unless its in the cache already
393 unless hash.key? m[1]
394 # use reflection to look up the appropriate class
395 model = Kernel.const_get(m[0].capitalize)
397 # get the element with that ID
398 element = model.find(m[1])
400 # and check that it is OK to use.
401 unless element and element.visible? and element.preconditions_ok?
413 # Temporary method to match interface to nodes
419 # if any members are referenced by placeholder IDs (i.e: negative) then
420 # this calling this method will fix them using the map from placeholders
422 def fix_placeholders!(id_map)
423 self.members.map! do |type, id, role|
426 new_id = id_map[type.to_sym][old_id]
427 raise "invalid placeholder" if new_id.nil?