1 class Relation < ActiveRecord::Base
4 include ConsistencyValidations
8 self.table_name = "current_relations"
12 has_many :old_relations, -> { order(:version) }
14 has_many :relation_members, -> { order(:sequence_id) }
15 has_many :relation_tags
17 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
18 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
20 validates_presence_of :id, :on => :update
21 validates_presence_of :timestamp,:version, :changeset_id
22 validates_uniqueness_of :id
23 validates_inclusion_of :visible, :in => [ true, false ]
24 validates_numericality_of :id, :on => :update, :integer_only => true
25 validates_numericality_of :changeset_id, :version, :integer_only => true
26 validates_associated :changeset
28 scope :visible, -> { where(:visible => true) }
29 scope :invisible, -> { where(:visible => false) }
30 scope :nodes, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids.flatten }) }
31 scope :ways, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids.flatten }) }
32 scope :relations, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids.flatten }) }
34 TYPES = ["node", "way", "relation"]
36 def self.from_xml(xml, create=false)
38 p = XML::Parser.string(xml)
41 doc.find('//osm/relation').each do |pt|
42 return Relation.from_xml_node(pt, create)
44 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
45 rescue LibXML::XML::Error, ArgumentError => ex
46 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
50 def self.from_xml_node(pt, create=false)
51 relation = Relation.new
53 raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create or not pt['version'].nil?
54 relation.version = pt['version']
55 raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
56 relation.changeset_id = pt['changeset']
59 raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil?
60 relation.id = pt['id'].to_i
61 # .to_i will return 0 if there is no number that can be parsed.
62 # We want to make sure that there is no id with zero anyway
63 raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
66 # We don't care about the timestamp nor the visibility as these are either
67 # set explicitly or implicit in the action. The visibility is set to true,
68 # and manually set to false before the actual delete.
69 relation.visible = true
72 relation.tags = Hash.new
74 # Add in any tags from the XML
75 pt.find('tag').each do |tag|
76 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
77 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
78 relation.add_tag_keyval(tag['k'], tag['v'])
81 # need to initialise the relation members array explicitly, as if this
82 # isn't done for a new relation then @members attribute will be nil,
83 # and the members will be loaded from the database instead of being
85 relation.members = Array.new
87 pt.find('member').each do |member|
89 logger.debug "each member"
90 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
91 logger.debug "after raise"
92 #member_ref = member['ref']
94 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
95 logger.debug member['role']
96 relation.add_member(member['type'].classify, member['ref'], member['role'])
98 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
104 doc = OSM::API.new.get_xml_doc
105 doc.root << to_xml_node()
109 def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
110 el = XML::Node.new 'relation'
111 el['id'] = self.id.to_s
113 add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
115 self.relation_members.each do |member|
118 # if there is a list of visible members then use that to weed out deleted segments
119 if visible_members[member.member_type][member.member_id]
123 # otherwise, manually go to the db to check things
124 if member.member.visible?
129 member_el = XML::Node.new 'member'
130 member_el['type'] = member.member_type.downcase
131 member_el['ref'] = member.member_id.to_s
132 member_el['role'] = member.member_role
137 add_tags_to_xml_node(el, self.relation_tags)
142 # FIXME is this really needed?
144 @members ||= self.relation_members.map do |member|
145 [member.member_type, member.member_id, member.member_role]
150 @tags ||= Hash[self.relation_tags.collect { |t| [t.k, t.v] }]
161 def add_member(type, id, role)
163 @members << [type, id.to_i, role]
166 def add_tag_keyval(k, v)
167 @tags = Hash.new unless @tags
169 # duplicate tags are now forbidden, so we can't allow values
170 # in the hash to be overwritten.
171 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
177 # updates the changeset bounding box to contain the bounding box of
178 # the element with given +type+ and +id+. this only works with nodes
179 # and ways at the moment, as they're the only elements to respond to
181 def update_changeset_element(type, id)
182 element = Kernel.const_get(type.capitalize).find(id)
183 changeset.update_bbox! element.bbox
186 def delete_with_history!(new_relation, user)
188 raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
191 # need to start the transaction here, so that the database can
192 # provide repeatable reads for the used-by checks. this means it
193 # shouldn't be possible to get race conditions.
194 Relation.transaction do
196 check_consistency(self, new_relation, user)
197 # This will check to see if this relation is used by another relation
198 rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, self.id).first
199 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
201 self.changeset_id = new_relation.changeset_id
209 def update_from(new_relation, user)
210 Relation.transaction do
212 check_consistency(self, new_relation, user)
213 unless new_relation.preconditions_ok?(self.members)
214 raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
216 self.changeset_id = new_relation.changeset_id
217 self.changeset = new_relation.changeset
218 self.tags = new_relation.tags
219 self.members = new_relation.members
225 def create_with_history(user)
226 check_create_consistency(self, user)
227 unless self.preconditions_ok?
228 raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
235 def preconditions_ok?(good_members = [])
236 # These are hastables that store an id in the index of all
237 # the nodes/way/relations that have already been added.
238 # If the member is valid and visible then we add it to the
239 # relevant hash table, with the value true as a cache.
240 # Thus if you have nodes with the ids of 50 and 1 already in the
241 # relation, then the hash table nodes would contain:
242 # => {50=>true, 1=>true}
243 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
245 # pre-set all existing members to good
246 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
248 self.members.each do |m|
249 # find the hash for the element type or die
250 hash = elements[m[0].downcase.to_sym] or return false
251 # unless its in the cache already
252 unless hash.key? m[1]
253 # use reflection to look up the appropriate class
254 model = Kernel.const_get(m[0].capitalize)
255 # get the element with that ID
256 element = model.where(:id => m[1]).first
258 # and check that it is OK to use.
259 unless element and element.visible? and element.preconditions_ok?
260 raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
269 # Temporary method to match interface to nodes
275 # if any members are referenced by placeholder IDs (i.e: negative) then
276 # this calling this method will fix them using the map from placeholders
278 def fix_placeholders!(id_map, placeholder_id = nil)
279 self.members.map! do |type, id, role|
282 new_id = id_map[type.downcase.to_sym][old_id]
283 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?
293 def save_with_history!
294 Relation.transaction do
295 # have to be a little bit clever here - to detect if any tags
296 # changed then we have to monitor their before and after state.
304 tags = self.tags.clone
305 self.relation_tags.each do |old_tag|
307 # if we can match the tags we currently have to the list
308 # of old tags, then we never set the tags_changed flag. but
309 # if any are different then set the flag and do the DB
312 tags_changed |= (old_tag.v != tags[key])
314 # remove from the map, so that we can expect an empty map
315 # at the end if there are no new tags
319 # this means a tag was deleted
323 # if there are left-over tags then they are new and will have to
325 tags_changed |= (not tags.empty?)
326 RelationTag.delete_all(:relation_id => self.id)
327 self.tags.each do |k,v|
328 tag = RelationTag.new
329 tag.relation_id = self.id
335 # same pattern as before, but this time we're collecting the
336 # changed members in an array, as the bounding box updates for
337 # elements are per-element, not blanked on/off like for tags.
338 changed_members = Array.new
339 members = self.members.clone
340 self.relation_members.each do |old_member|
341 key = [old_member.member_type, old_member.member_id, old_member.member_role]
342 i = members.index key
344 changed_members << key
349 # any remaining members must be new additions
350 changed_members += members
352 # update the members. first delete all the old members, as the new
353 # members may be in a different order and i don't feel like implementing
354 # a longest common subsequence algorithm to optimise this.
355 members = self.members
356 RelationMember.delete_all(:relation_id => self.id)
357 members.each_with_index do |m,i|
358 mem = RelationMember.new
359 mem.relation_id = self.id
361 mem.member_type = m[0]
363 mem.member_role = m[2]
367 old_relation = OldRelation.from_relation(self)
368 old_relation.timestamp = t
369 old_relation.save_with_dependencies!
371 # update the bbox of the changeset and save it too.
372 # discussion on the mailing list gave the following definition for
373 # the bounding box update procedure of a relation:
375 # adding or removing nodes or ways from a relation causes them to be
376 # added to the changeset bounding box. adding a relation member or
377 # changing tag values causes all node and way members to be added to the
378 # bounding box. this is similar to how the map call does things and is
379 # reasonable on the assumption that adding or removing members doesn't
380 # materially change the rest of the relation.
382 changed_members.collect { |id,type| type == "relation" }.
383 inject(false) { |b,s| b or s }
385 update_members = if tags_changed or any_relations
386 # add all non-relation bounding boxes to the changeset
387 # FIXME: check for tag changes along with element deletions and
388 # make sure that the deleted element's bounding box is hit.
393 update_members.each do |type, id, role|
394 if type != "Relation"
395 update_changeset_element(type, id)
399 # tell the changeset we updated one element only
400 changeset.add_changes! 1
402 # save the (maybe updated) changeset bounding box