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 = %w(node way relation)
36 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 fail 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)
48 def self.from_xml_node(pt, create = false)
49 relation = Relation.new
51 fail OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create || !pt["version"].nil?
52 relation.version = pt["version"]
53 fail OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt["changeset"].nil?
54 relation.changeset_id = pt["changeset"]
57 fail OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt["id"].nil?
58 relation.id = pt["id"].to_i
59 # .to_i will return 0 if there is no number that can be parsed.
60 # We want to make sure that there is no id with zero anyway
61 fail OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
64 # We don't care about the timestamp nor the visibility as these are either
65 # set explicitly or implicit in the action. The visibility is set to true,
66 # and manually set to false before the actual delete.
67 relation.visible = true
72 # Add in any tags from the XML
73 pt.find("tag").each do |tag|
74 fail OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag["k"].nil?
75 fail OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag["v"].nil?
76 relation.add_tag_keyval(tag["k"], tag["v"])
79 # need to initialise the relation members array explicitly, as if this
80 # isn't done for a new relation then @members attribute will be nil,
81 # and the members will be loaded from the database instead of being
85 pt.find("member").each do |member|
87 logger.debug "each member"
88 fail OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member["type"]
89 logger.debug "after raise"
90 # member_ref = member['ref']
92 member["role"] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
93 logger.debug member["role"]
94 relation.add_member(member["type"].classify, member["ref"], member["role"])
96 fail OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
102 doc = OSM::API.new.get_xml_doc
103 doc.root << to_xml_node
107 def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
108 el = XML::Node.new "relation"
111 add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
113 relation_members.each do |member|
117 # if there is a list of visible members then use that to weed out deleted segments
118 p = 1 if visible_members[member.member_type][member.member_id]
120 # otherwise, manually go to the db to check things
121 p = 1 if member.member.visible?
126 member_el = XML::Node.new "member"
127 member_el["type"] = member.member_type.downcase
128 member_el["ref"] = member.member_id.to_s
129 member_el["role"] = member.member_role
133 add_tags_to_xml_node(el, relation_tags)
138 # FIXME is this really needed?
140 @members ||= relation_members.map do |member|
141 [member.member_type, member.member_id, member.member_role]
146 @tags ||= Hash[relation_tags.collect { |t| [t.k, t.v] }]
153 def add_member(type, id, role)
155 @members << [type, id.to_i, role]
158 def add_tag_keyval(k, v)
159 @tags = {} unless @tags
161 # duplicate tags are now forbidden, so we can't allow values
162 # in the hash to be overwritten.
163 fail OSM::APIDuplicateTagsError.new("relation", id, k) if @tags.include? k
169 # updates the changeset bounding box to contain the bounding box of
170 # the element with given +type+ and +id+. this only works with nodes
171 # and ways at the moment, as they're the only elements to respond to
173 def update_changeset_element(type, id)
174 element = Kernel.const_get(type.capitalize).find(id)
175 changeset.update_bbox! element.bbox
178 def delete_with_history!(new_relation, user)
180 fail OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
183 # need to start the transaction here, so that the database can
184 # provide repeatable reads for the used-by checks. this means it
185 # shouldn't be possible to get race conditions.
186 Relation.transaction do
188 check_consistency(self, new_relation, user)
189 # This will check to see if this relation is used by another relation
190 rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, id).first
191 fail OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
193 self.changeset_id = new_relation.changeset_id
201 def update_from(new_relation, user)
202 Relation.transaction do
204 check_consistency(self, new_relation, user)
205 unless new_relation.preconditions_ok?(members)
206 fail OSM::APIPreconditionFailedError.new("Cannot update relation #{id}: data or member data is invalid.")
208 self.changeset_id = new_relation.changeset_id
209 self.changeset = new_relation.changeset
210 self.tags = new_relation.tags
211 self.members = new_relation.members
217 def create_with_history(user)
218 check_create_consistency(self, user)
219 unless self.preconditions_ok?
220 fail OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
227 def preconditions_ok?(good_members = [])
228 # These are hastables that store an id in the index of all
229 # the nodes/way/relations that have already been added.
230 # If the member is valid and visible then we add it to the
231 # relevant hash table, with the value true as a cache.
232 # Thus if you have nodes with the ids of 50 and 1 already in the
233 # relation, then the hash table nodes would contain:
234 # => {50=>true, 1=>true}
235 elements = { :node => {}, :way => {}, :relation => {} }
237 # pre-set all existing members to good
238 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
241 # find the hash for the element type or die
242 hash = elements[m[0].downcase.to_sym]
243 return false unless hash
245 # unless its in the cache already
246 next if hash.key? m[1]
248 # use reflection to look up the appropriate class
249 model = Kernel.const_get(m[0].capitalize)
250 # get the element with that ID
251 element = model.where(:id => m[1]).first
253 # and check that it is OK to use.
254 unless element && element.visible? && element.preconditions_ok?
255 fail OSM::APIPreconditionFailedError.new("Relation with id #{id} cannot be saved due to #{m[0]} with id #{m[1]}")
263 # Temporary method to match interface to nodes
269 # if any members are referenced by placeholder IDs (i.e: negative) then
270 # this calling this method will fix them using the map from placeholders
272 def fix_placeholders!(id_map, placeholder_id = nil)
273 members.map! do |type, id, role|
276 new_id = id_map[type.downcase.to_sym][old_id]
277 fail OSM::APIBadUserInput.new("Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}.") if new_id.nil?
287 def save_with_history!
288 Relation.transaction do
289 # have to be a little bit clever here - to detect if any tags
290 # changed then we have to monitor their before and after state.
298 tags = self.tags.clone
299 relation_tags.each do |old_tag|
301 # if we can match the tags we currently have to the list
302 # of old tags, then we never set the tags_changed flag. but
303 # if any are different then set the flag and do the DB
306 tags_changed |= (old_tag.v != tags[key])
308 # remove from the map, so that we can expect an empty map
309 # at the end if there are no new tags
313 # this means a tag was deleted
317 # if there are left-over tags then they are new and will have to
319 tags_changed |= (!tags.empty?)
320 RelationTag.delete_all(:relation_id => id)
321 self.tags.each do |k, v|
322 tag = RelationTag.new
329 # same pattern as before, but this time we're collecting the
330 # changed members in an array, as the bounding box updates for
331 # elements are per-element, not blanked on/off like for tags.
333 members = self.members.clone
334 relation_members.each do |old_member|
335 key = [old_member.member_type, old_member.member_id, old_member.member_role]
336 i = members.index key
338 changed_members << key
343 # any remaining members must be new additions
344 changed_members += members
346 # update the members. first delete all the old members, as the new
347 # members may be in a different order and i don't feel like implementing
348 # a longest common subsequence algorithm to optimise this.
349 members = self.members
350 RelationMember.delete_all(:relation_id => id)
351 members.each_with_index do |m, i|
352 mem = RelationMember.new
355 mem.member_type = m[0]
357 mem.member_role = m[2]
361 old_relation = OldRelation.from_relation(self)
362 old_relation.timestamp = t
363 old_relation.save_with_dependencies!
365 # update the bbox of the changeset and save it too.
366 # discussion on the mailing list gave the following definition for
367 # the bounding box update procedure of a relation:
369 # adding or removing nodes or ways from a relation causes them to be
370 # added to the changeset bounding box. adding a relation member or
371 # changing tag values causes all node and way members to be added to the
372 # bounding box. this is similar to how the map call does things and is
373 # reasonable on the assumption that adding or removing members doesn't
374 # materially change the rest of the relation.
376 changed_members.collect { |_id, type| type == "relation" }
377 .inject(false) { |a, e| a || e }
379 update_members = if tags_changed || any_relations
380 # add all non-relation bounding boxes to the changeset
381 # FIXME: check for tag changes along with element deletions and
382 # make sure that the deleted element's bounding box is hit.
387 update_members.each do |type, id, _role|
388 update_changeset_element(type, id) if type != "Relation"
391 # tell the changeset we updated one element only
392 changeset.add_changes! 1
394 # save the (maybe updated) changeset bounding box