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
39 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
43 def self.from_xml_node(pt, create=false)
44 relation = Relation.new
46 if !create and pt['id'] != '0'
47 relation.id = pt['id'].to_i
50 relation.version = pt['version']
51 relation.changeset_id = pt['changeset']
54 relation.timestamp = Time.now
55 relation.visible = true
58 relation.timestamp = Time.parse(pt['timestamp'])
62 pt.find('tag').each do |tag|
63 relation.add_tag_keyval(tag['k'], tag['v'])
66 pt.find('member').each do |member|
68 logger.debug "each member"
69 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
70 logger.debug "after raise"
71 #member_ref = member['ref']
73 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
74 logger.debug member['role']
75 relation.add_member(member['type'], member['ref'], member['role'])
77 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
83 doc = OSM::API.new.get_xml_doc
84 doc.root << to_xml_node()
88 def to_xml_node(user_display_name_cache = nil)
89 el1 = XML::Node.new 'relation'
90 el1['id'] = self.id.to_s
91 el1['visible'] = self.visible.to_s
92 el1['timestamp'] = self.timestamp.xmlschema
93 el1['version'] = self.version.to_s
94 el1['changeset'] = self.changeset_id.to_s
96 user_display_name_cache = {} if user_display_name_cache.nil?
98 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
99 # use the cache if available
100 elsif self.changeset.user.data_public?
101 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
103 user_display_name_cache[self.changeset.user_id] = nil
106 if not user_display_name_cache[self.changeset.user_id].nil?
107 el1['user'] = user_display_name_cache[self.changeset.user_id]
108 el1['uid'] = self.changeset.user_id.to_s
111 self.relation_members.each do |member|
114 # # if there is a list of visible members then use that to weed out deleted segments
115 # if visible_members[member.member_type][member.member_id]
119 # otherwise, manually go to the db to check things
120 if member.member.visible?
125 e = XML::Node.new 'member'
126 e['type'] = member.member_type
127 e['ref'] = member.member_id.to_s
128 e['role'] = member.member_role
133 self.relation_tags.each do |tag|
134 e = XML::Node.new 'tag'
142 def self.find_for_nodes(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 = 'node' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
147 return self.find(:all, options)
152 def self.find_for_ways(ids, options = {})
156 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
157 return self.find(:all, options)
162 def self.find_for_relations(ids, options = {})
166 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
167 return self.find(:all, options)
172 # FIXME is this really needed?
176 self.relation_members.each do |member|
177 @members += [[member.member_type,member.member_id,member.member_role]]
186 self.relation_tags.each do |tag|
201 def add_member(type,id,role)
202 @members = Array.new unless @members
203 @members += [[type,id,role]]
206 def add_tag_keyval(k, v)
207 @tags = Hash.new unless @tags
209 # duplicate tags are now forbidden, so we can't allow values
210 # in the hash to be overwritten.
211 raise OSM::APIDuplicateTagsError.new if @tags.include? k
216 def save_with_history!
217 Relation.transaction do
218 # have to be a little bit clever here - to detect if any tags
219 # changed then we have to monitor their before and after state.
228 self.relation_tags.each do |old_tag|
230 # if we can match the tags we currently have to the list
231 # of old tags, then we never set the tags_changed flag. but
232 # if any are different then set the flag and do the DB
235 # rails 2.1 dirty handling should take care of making this
236 # somewhat efficient... hopefully...
237 old_tag.v = tags[key]
238 tags_changed |= old_tag.changed?
241 # remove from the map, so that we can expect an empty map
242 # at the end if there are no new tags
246 # this means a tag was deleted
248 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
251 # if there are left-over tags then they are new and will have to
253 tags_changed |= (not tags.empty?)
255 tag = RelationTag.new
262 # same pattern as before, but this time we're collecting the
263 # changed members in an array, as the bounding box updates for
264 # elements are per-element, not blanked on/off like for tags.
265 changed_members = Array.new
267 self.members.each do |m|
268 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
269 members[[m[1], m[0]]] = m[2]
271 relation_members.each do |old_member|
272 key = [old_member.member_id.to_s, old_member.member_type]
273 if members.has_key? key
276 changed_members << key
279 # any remaining members must be new additions
280 changed_members += members.keys
282 # update the members. first delete all the old members, as the new
283 # members may be in a different order and i don't feel like implementing
284 # a longest common subsequence algorithm to optimise this.
285 members = self.members
286 RelationMember.delete_all(:id => self.id)
287 members.each_with_index do |m,i|
288 mem = RelationMember.new
289 mem.id = [self.id, i]
290 mem.member_type = m[0]
292 mem.member_role = m[2]
296 old_relation = OldRelation.from_relation(self)
297 old_relation.timestamp = t
298 old_relation.save_with_dependencies!
300 # update the bbox of the changeset and save it too.
301 # discussion on the mailing list gave the following definition for
302 # the bounding box update procedure of a relation:
304 # adding or removing nodes or ways from a relation causes them to be
305 # added to the changeset bounding box. adding a relation member or
306 # changing tag values causes all node and way members to be added to the
307 # bounding box. this is similar to how the map call does things and is
308 # reasonable on the assumption that adding or removing members doesn't
309 # materially change the rest of the relation.
311 changed_members.collect { |id,type| type == "relation" }.
312 inject(false) { |b,s| b or s }
314 if tags_changed or any_relations
315 # add all non-relation bounding boxes to the changeset
316 # FIXME: check for tag changes along with element deletions and
317 # make sure that the deleted element's bounding box is hit.
318 self.members.each do |type, id, role|
319 if type != "relation"
320 update_changeset_element(type, id)
324 # add only changed members to the changeset
325 changed_members.each do |id, type|
326 update_changeset_element(type, id)
330 # tell the changeset we updated one element only
331 changeset.add_changes! 1
333 # save the (maybe updated) changeset bounding box
339 # updates the changeset bounding box to contain the bounding box of
340 # the element with given +type+ and +id+. this only works with nodes
341 # and ways at the moment, as they're the only elements to respond to
343 def update_changeset_element(type, id)
344 element = Kernel.const_get(type.capitalize).find(id)
345 changeset.update_bbox! element.bbox
348 def delete_with_history!(new_relation, user)
350 check_consistency(self, new_relation, user)
351 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 ])
352 raise OSM::APIPreconditionFailedError.new
354 self.changeset_id = new_relation.changeset_id
361 raise OSM::APIAlreadyDeletedError.new
365 def update_from(new_relation, user)
366 check_consistency(self, new_relation, user)
367 if !new_relation.preconditions_ok?
368 raise OSM::APIPreconditionFailedError.new
370 self.changeset_id = new_relation.changeset_id
371 self.tags = new_relation.tags
372 self.members = new_relation.members
377 def create_with_history(user)
378 check_create_consistency(self, user)
379 if !self.preconditions_ok?
380 raise OSM::APIPreconditionFailedError.new
387 def preconditions_ok?
388 # These are hastables that store an id in the index of all
389 # the nodes/way/relations that have already been added.
390 # If the member is valid and visible then we add it to the
391 # relevant hash table, with the value true as a cache.
392 # Thus if you have nodes with the ids of 50 and 1 already in the
393 # relation, then the hash table nodes would contain:
394 # => {50=>true, 1=>true}
395 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
396 self.members.each do |m|
397 # find the hash for the element type or die
398 hash = elements[m[0].to_sym] or return false
400 # unless its in the cache already
401 unless hash.key? m[1]
402 # use reflection to look up the appropriate class
403 model = Kernel.const_get(m[0].capitalize)
405 # get the element with that ID
406 element = model.find(m[1])
408 # and check that it is OK to use.
409 unless element and element.visible? and element.preconditions_ok?
421 # Temporary method to match interface to nodes
427 # if any members are referenced by placeholder IDs (i.e: negative) then
428 # this calling this method will fix them using the map from placeholders
430 def fix_placeholders!(id_map)
431 self.members.map! do |type, id, role|
434 new_id = id_map[type.to_sym][old_id]
435 raise "invalid placeholder" if new_id.nil?