1 class Relation < ActiveRecord::Base
4 include ConsistencyValidations
7 self.table_name = "current_relations"
11 has_many :old_relations, :order => 'version'
13 has_many :relation_members, :order => 'sequence_id'
14 has_many :relation_tags
16 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
17 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
19 validates_presence_of :id, :on => :update
20 validates_presence_of :timestamp,:version, :changeset_id
21 validates_uniqueness_of :id
22 validates_inclusion_of :visible, :in => [ true, false ]
23 validates_numericality_of :id, :on => :update, :integer_only => true
24 validates_numericality_of :changeset_id, :version, :integer_only => true
25 validates_associated :changeset
27 scope :visible, where(:visible => true)
28 scope :invisible, where(:visible => false)
29 scope :nodes, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids }) }
30 scope :ways, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids }) }
31 scope :relations, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids }) }
33 TYPES = ["node", "way", "relation"]
35 def self.from_xml(xml, create=false)
37 p = XML::Parser.string(xml)
40 doc.find('//osm/relation').each do |pt|
41 return Relation.from_xml_node(pt, create)
43 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
44 rescue LibXML::XML::Error, ArgumentError => ex
45 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
49 def self.from_xml_node(pt, create=false)
50 relation = Relation.new
52 raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create or not pt['version'].nil?
53 relation.version = pt['version']
54 raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
55 relation.changeset_id = pt['changeset']
58 raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil?
59 relation.id = pt['id'].to_i
60 # .to_i will return 0 if there is no number that can be parsed.
61 # We want to make sure that there is no id with zero anyway
62 raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
65 # We don't care about the timestamp nor the visibility as these are either
66 # set explicitly or implicit in the action. The visibility is set to true,
67 # and manually set to false before the actual delete.
68 relation.visible = true
71 relation.tags = Hash.new
73 # Add in any tags from the XML
74 pt.find('tag').each do |tag|
75 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
76 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
77 relation.add_tag_keyval(tag['k'], tag['v'])
80 # need to initialise the relation members array explicitly, as if this
81 # isn't done for a new relation then @members attribute will be nil,
82 # and the members will be loaded from the database instead of being
84 relation.members = Array.new
86 pt.find('member').each do |member|
88 logger.debug "each member"
89 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
90 logger.debug "after raise"
91 #member_ref = member['ref']
93 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
94 logger.debug member['role']
95 relation.add_member(member['type'].classify, member['ref'], member['role'])
97 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
103 doc = OSM::API.new.get_xml_doc
104 doc.root << to_xml_node()
108 def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
109 el1 = XML::Node.new 'relation'
110 el1['id'] = self.id.to_s
111 el1['visible'] = self.visible.to_s
112 el1['timestamp'] = self.timestamp.xmlschema
113 el1['version'] = self.version.to_s
114 el1['changeset'] = self.changeset_id.to_s
116 if changeset_cache.key?(self.changeset_id)
117 # use the cache if available
119 changeset_cache[self.changeset_id] = self.changeset.user_id
122 user_id = changeset_cache[self.changeset_id]
124 if user_display_name_cache.key?(user_id)
125 # use the cache if available
126 elsif self.changeset.user.data_public?
127 user_display_name_cache[user_id] = self.changeset.user.display_name
129 user_display_name_cache[user_id] = nil
132 if not user_display_name_cache[user_id].nil?
133 el1['user'] = user_display_name_cache[user_id]
134 el1['uid'] = user_id.to_s
137 self.relation_members.each do |member|
140 # if there is a list of visible members then use that to weed out deleted segments
141 if visible_members[member.member_type][member.member_id]
145 # otherwise, manually go to the db to check things
146 if member.member.visible?
151 e = XML::Node.new 'member'
152 e['type'] = member.member_type.downcase
153 e['ref'] = member.member_id.to_s
154 e['role'] = member.member_role
159 self.relation_tags.each do |tag|
160 e = XML::Node.new 'tag'
168 # FIXME is this really needed?
172 self.relation_members.each do |member|
173 @members += [[member.member_type,member.member_id,member.member_role]]
182 self.relation_tags.each do |tag|
197 def add_member(type,id,role)
198 @members = Array.new unless @members
199 @members += [[type,id.to_i,role]]
202 def add_tag_keyval(k, v)
203 @tags = Hash.new unless @tags
205 # duplicate tags are now forbidden, so we can't allow values
206 # in the hash to be overwritten.
207 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
213 # updates the changeset bounding box to contain the bounding box of
214 # the element with given +type+ and +id+. this only works with nodes
215 # and ways at the moment, as they're the only elements to respond to
217 def update_changeset_element(type, id)
218 element = Kernel.const_get(type.capitalize).find(id)
219 changeset.update_bbox! element.bbox
222 def delete_with_history!(new_relation, user)
224 raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
227 # need to start the transaction here, so that the database can
228 # provide repeatable reads for the used-by checks. this means it
229 # shouldn't be possible to get race conditions.
230 Relation.transaction do
232 check_consistency(self, new_relation, user)
233 # This will check to see if this relation is used by another relation
234 rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, self.id).first
235 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
237 self.changeset_id = new_relation.changeset_id
245 def update_from(new_relation, user)
246 Relation.transaction do
248 check_consistency(self, new_relation, user)
249 unless new_relation.preconditions_ok?(self.members)
250 raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
252 self.changeset_id = new_relation.changeset_id
253 self.changeset = new_relation.changeset
254 self.tags = new_relation.tags
255 self.members = new_relation.members
261 def create_with_history(user)
262 check_create_consistency(self, user)
263 unless self.preconditions_ok?
264 raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
271 def preconditions_ok?(good_members = [])
272 # These are hastables that store an id in the index of all
273 # the nodes/way/relations that have already been added.
274 # If the member is valid and visible then we add it to the
275 # relevant hash table, with the value true as a cache.
276 # Thus if you have nodes with the ids of 50 and 1 already in the
277 # relation, then the hash table nodes would contain:
278 # => {50=>true, 1=>true}
279 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
281 # pre-set all existing members to good
282 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
284 self.members.each do |m|
285 # find the hash for the element type or die
286 hash = elements[m[0].downcase.to_sym] or return false
287 # unless its in the cache already
288 unless hash.key? m[1]
289 # use reflection to look up the appropriate class
290 model = Kernel.const_get(m[0].capitalize)
291 # get the element with that ID
292 element = model.where(:id => m[1]).first
294 # and check that it is OK to use.
295 unless element and element.visible? and element.preconditions_ok?
296 raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
305 # Temporary method to match interface to nodes
311 # if any members are referenced by placeholder IDs (i.e: negative) then
312 # this calling this method will fix them using the map from placeholders
314 def fix_placeholders!(id_map, placeholder_id = nil)
315 self.members.map! do |type, id, role|
318 new_id = id_map[type.downcase.to_sym][old_id]
319 raise OSM::APIBadUserInput.new("Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}.") if new_id.nil?
329 def save_with_history!
330 Relation.transaction do
331 # have to be a little bit clever here - to detect if any tags
332 # changed then we have to monitor their before and after state.
340 tags = self.tags.clone
341 self.relation_tags.each do |old_tag|
343 # if we can match the tags we currently have to the list
344 # of old tags, then we never set the tags_changed flag. but
345 # if any are different then set the flag and do the DB
348 tags_changed |= (old_tag.v != tags[key])
350 # remove from the map, so that we can expect an empty map
351 # at the end if there are no new tags
355 # this means a tag was deleted
359 # if there are left-over tags then they are new and will have to
361 tags_changed |= (not tags.empty?)
362 RelationTag.delete_all(:relation_id => self.id)
363 self.tags.each do |k,v|
364 tag = RelationTag.new
365 tag.relation_id = self.id
371 # same pattern as before, but this time we're collecting the
372 # changed members in an array, as the bounding box updates for
373 # elements are per-element, not blanked on/off like for tags.
374 changed_members = Array.new
375 members = self.members.clone
376 self.relation_members.each do |old_member|
377 key = [old_member.member_type, old_member.member_id, old_member.member_role]
378 i = members.index key
380 changed_members << key
385 # any remaining members must be new additions
386 changed_members += members
388 # update the members. first delete all the old members, as the new
389 # members may be in a different order and i don't feel like implementing
390 # a longest common subsequence algorithm to optimise this.
391 members = self.members
392 RelationMember.delete_all(:relation_id => self.id)
393 members.each_with_index do |m,i|
394 mem = RelationMember.new
395 mem.relation_id = self.id
397 mem.member_type = m[0]
399 mem.member_role = m[2]
403 old_relation = OldRelation.from_relation(self)
404 old_relation.timestamp = t
405 old_relation.save_with_dependencies!
407 # update the bbox of the changeset and save it too.
408 # discussion on the mailing list gave the following definition for
409 # the bounding box update procedure of a relation:
411 # adding or removing nodes or ways from a relation causes them to be
412 # added to the changeset bounding box. adding a relation member or
413 # changing tag values causes all node and way members to be added to the
414 # bounding box. this is similar to how the map call does things and is
415 # reasonable on the assumption that adding or removing members doesn't
416 # materially change the rest of the relation.
418 changed_members.collect { |id,type| type == "relation" }.
419 inject(false) { |b,s| b or s }
421 update_members = if tags_changed or any_relations
422 # add all non-relation bounding boxes to the changeset
423 # FIXME: check for tag changes along with element deletions and
424 # make sure that the deleted element's bounding box is hit.
429 update_members.each do |type, id, role|
430 if type != "Relation"
431 update_changeset_element(type, id)
435 # tell the changeset we updated one element only
436 changeset.add_changes! 1
438 # save the (maybe updated) changeset bounding box