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 :id, :uniqueness => true, :presence => { :on => :update },
21 :numericality => { :on => :update, :integer_only => true }
22 validates :version, :presence => true,
23 :numericality => { :integer_only => true }
24 validates :changeset_id, :presence => true,
25 :numericality => { :integer_only => true }
26 validates :timestamp, :presence => true
27 validates :changeset, :associated => true
28 validates :visible, :inclusion => [true, false]
30 scope :visible, -> { where(:visible => true) }
31 scope :invisible, -> { where(:visible => false) }
32 scope :nodes, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids.flatten }) }
33 scope :ways, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids.flatten }) }
34 scope :relations, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids.flatten }) }
36 TYPES = %w(node way relation)
38 def self.from_xml(xml, create = false)
39 p = XML::Parser.string(xml)
42 doc.find("//osm/relation").each do |pt|
43 return Relation.from_xml_node(pt, create)
45 fail OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
46 rescue LibXML::XML::Error, ArgumentError => ex
47 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
50 def self.from_xml_node(pt, create = false)
51 relation = Relation.new
53 fail OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create || !pt["version"].nil?
54 relation.version = pt["version"]
55 fail OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt["changeset"].nil?
56 relation.changeset_id = pt["changeset"]
59 fail 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 fail 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
74 # Add in any tags from the XML
75 pt.find("tag").each do |tag|
76 fail OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag["k"].nil?
77 fail 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
87 pt.find("member").each do |member|
89 logger.debug "each member"
90 fail 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 fail 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"
113 add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
115 relation_members.each do |member|
119 # if there is a list of visible members then use that to weed out deleted segments
120 p = 1 if visible_members[member.member_type][member.member_id]
122 # otherwise, manually go to the db to check things
123 p = 1 if member.member.visible?
128 member_el = XML::Node.new "member"
129 member_el["type"] = member.member_type.downcase
130 member_el["ref"] = member.member_id.to_s
131 member_el["role"] = member.member_role
135 add_tags_to_xml_node(el, relation_tags)
140 # FIXME: is this really needed?
142 @members ||= relation_members.map do |member|
143 [member.member_type, member.member_id, member.member_role]
148 @tags ||= Hash[relation_tags.collect { |t| [t.k, t.v] }]
155 def add_member(type, id, role)
157 @members << [type, id.to_i, role]
160 def add_tag_keyval(k, v)
161 @tags = {} unless @tags
163 # duplicate tags are now forbidden, so we can't allow values
164 # in the hash to be overwritten.
165 fail OSM::APIDuplicateTagsError.new("relation", id, k) if @tags.include? k
171 # updates the changeset bounding box to contain the bounding box of
172 # the element with given +type+ and +id+. this only works with nodes
173 # and ways at the moment, as they're the only elements to respond to
175 def update_changeset_element(type, id)
176 element = Kernel.const_get(type.capitalize).find(id)
177 changeset.update_bbox! element.bbox
180 def delete_with_history!(new_relation, user)
182 fail OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
185 # need to start the transaction here, so that the database can
186 # provide repeatable reads for the used-by checks. this means it
187 # shouldn't be possible to get race conditions.
188 Relation.transaction do
190 check_consistency(self, new_relation, user)
191 # This will check to see if this relation is used by another relation
192 rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, id).first
193 fail OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
195 self.changeset_id = new_relation.changeset_id
203 def update_from(new_relation, user)
204 Relation.transaction do
206 check_consistency(self, new_relation, user)
207 unless new_relation.preconditions_ok?(members)
208 fail OSM::APIPreconditionFailedError.new("Cannot update relation #{id}: data or member data is invalid.")
210 self.changeset_id = new_relation.changeset_id
211 self.changeset = new_relation.changeset
212 self.tags = new_relation.tags
213 self.members = new_relation.members
219 def create_with_history(user)
220 check_create_consistency(self, user)
221 unless self.preconditions_ok?
222 fail OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
229 def preconditions_ok?(good_members = [])
230 # These are hastables that store an id in the index of all
231 # the nodes/way/relations that have already been added.
232 # If the member is valid and visible then we add it to the
233 # relevant hash table, with the value true as a cache.
234 # Thus if you have nodes with the ids of 50 and 1 already in the
235 # relation, then the hash table nodes would contain:
236 # => {50=>true, 1=>true}
237 elements = { :node => {}, :way => {}, :relation => {} }
239 # pre-set all existing members to good
240 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
243 # find the hash for the element type or die
244 hash = elements[m[0].downcase.to_sym]
245 return false unless hash
247 # unless its in the cache already
248 next if hash.key? m[1]
250 # use reflection to look up the appropriate class
251 model = Kernel.const_get(m[0].capitalize)
252 # get the element with that ID
253 element = model.where(:id => m[1]).first
255 # and check that it is OK to use.
256 unless element && element.visible? && element.preconditions_ok?
257 fail OSM::APIPreconditionFailedError.new("Relation with id #{id} cannot be saved due to #{m[0]} with id #{m[1]}")
265 # Temporary method to match interface to nodes
271 # if any members are referenced by placeholder IDs (i.e: negative) then
272 # this calling this method will fix them using the map from placeholders
274 def fix_placeholders!(id_map, placeholder_id = nil)
275 members.map! do |type, id, role|
278 new_id = id_map[type.downcase.to_sym][old_id]
279 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?
289 def save_with_history!
290 Relation.transaction do
291 # have to be a little bit clever here - to detect if any tags
292 # changed then we have to monitor their before and after state.
300 tags = self.tags.clone
301 relation_tags.each do |old_tag|
303 # if we can match the tags we currently have to the list
304 # of old tags, then we never set the tags_changed flag. but
305 # if any are different then set the flag and do the DB
308 tags_changed |= (old_tag.v != tags[key])
310 # remove from the map, so that we can expect an empty map
311 # at the end if there are no new tags
315 # this means a tag was deleted
319 # if there are left-over tags then they are new and will have to
321 tags_changed |= (!tags.empty?)
322 RelationTag.delete_all(:relation_id => id)
323 self.tags.each do |k, v|
324 tag = RelationTag.new
331 # same pattern as before, but this time we're collecting the
332 # changed members in an array, as the bounding box updates for
333 # elements are per-element, not blanked on/off like for tags.
335 members = self.members.clone
336 relation_members.each do |old_member|
337 key = [old_member.member_type, old_member.member_id, old_member.member_role]
338 i = members.index key
340 changed_members << key
345 # any remaining members must be new additions
346 changed_members += members
348 # update the members. first delete all the old members, as the new
349 # members may be in a different order and i don't feel like implementing
350 # a longest common subsequence algorithm to optimise this.
351 members = self.members
352 RelationMember.delete_all(:relation_id => id)
353 members.each_with_index do |m, i|
354 mem = RelationMember.new
357 mem.member_type = m[0]
359 mem.member_role = m[2]
363 old_relation = OldRelation.from_relation(self)
364 old_relation.timestamp = t
365 old_relation.save_with_dependencies!
367 # update the bbox of the changeset and save it too.
368 # discussion on the mailing list gave the following definition for
369 # the bounding box update procedure of a relation:
371 # adding or removing nodes or ways from a relation causes them to be
372 # added to the changeset bounding box. adding a relation member or
373 # changing tag values causes all node and way members to be added to the
374 # bounding box. this is similar to how the map call does things and is
375 # reasonable on the assumption that adding or removing members doesn't
376 # materially change the rest of the relation.
378 changed_members.collect { |_id, type| type == "relation" }
379 .inject(false) { |a, e| a || e }
381 update_members = if tags_changed || any_relations
382 # add all non-relation bounding boxes to the changeset
383 # FIXME: check for tag changes along with element deletions and
384 # make sure that the deleted element's bounding box is hit.
389 update_members.each do |type, id, _role|
390 update_changeset_element(type, id) if type != "Relation"
393 # tell the changeset we updated one element only
394 changeset.add_changes! 1
396 # save the (maybe updated) changeset bounding box