1 # frozen_string_literal: true
3 # == Schema Information
5 # Table name: current_relations
7 # id :bigint not null, primary key
8 # changeset_id :bigint not null
9 # timestamp :datetime not null
10 # visible :boolean not null
11 # version :bigint not null
15 # current_relations_timestamp_idx (timestamp)
19 # current_relations_changeset_id_fkey (changeset_id => changesets.id)
22 class Relation < ApplicationRecord
25 include ConsistencyValidations
28 self.table_name = "current_relations"
32 has_many :old_relations, -> { order(:version) }, :inverse_of => :current_relation
34 has_many :relation_members, -> { order(:sequence_id) }, :inverse_of => :relation
35 has_many :element_tags, :class_name => "RelationTag"
37 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
38 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
40 validates :id, :uniqueness => true, :presence => { :on => :update },
41 :numericality => { :on => :update, :only_integer => true }
42 validates :version, :presence => true,
43 :numericality => { :only_integer => true }
44 validates :timestamp, :presence => true
45 validates :changeset, :associated => true
46 validates :visible, :inclusion => [true, false]
48 scope :visible, -> { where(:visible => true) }
49 scope :invisible, -> { where(:visible => false) }
50 scope :nodes, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids.flatten }) }
51 scope :ways, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids.flatten }) }
52 scope :relations, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids.flatten }) }
54 TYPES = %w[node way relation].freeze
56 def self.from_xml(xml, create: false)
57 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
59 pt = doc.find_first("//osm/relation")
62 Relation.from_xml_node(pt, :create => create)
64 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
66 rescue LibXML::XML::Error, ArgumentError => e
67 raise OSM::APIBadXMLError.new("relation", xml, e.message)
70 def self.from_xml_node(pt, create: false)
71 relation = Relation.new
73 raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create || !pt["version"].nil?
75 relation.version = pt["version"]
76 raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt["changeset"].nil?
78 relation.changeset_id = pt["changeset"]
81 raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt["id"].nil?
83 relation.id = pt["id"].to_i
84 # .to_i will return 0 if there is no number that can be parsed.
85 # We want to make sure that there is no id with zero anyway
86 raise OSM::APIBadUserInput, "ID of relation cannot be zero when updating." if relation.id.zero?
89 # We don't care about the timestamp nor the visibility as these are either
90 # set explicitly or implicit in the action. The visibility is set to true,
91 # and manually set to false before the actual delete.
92 relation.visible = true
97 # Add in any tags from the XML
98 pt.find("tag").each do |tag|
99 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag["k"].nil?
100 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag["v"].nil?
102 relation.add_tag_keyval(tag["k"], tag["v"])
105 # need to initialise the relation members array explicitly, as if this
106 # isn't done for a new relation then @members attribute will be nil,
107 # and the members will be loaded from the database instead of being
108 # empty, as intended.
109 relation.members = []
111 pt.find("member").each do |member|
113 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member["type"]
115 # member_ref = member['ref']
117 member["role"] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
118 relation.add_member(member["type"].classify, member["ref"], member["role"])
120 raise OSM::APIBadUserInput, "Some bad xml in relation" if relation.nil?
125 # FIXME: is this really needed?
127 @members ||= relation_members.map do |member|
128 [member.member_type, member.member_id, member.member_role]
133 @tags ||= element_tags.to_h { |t| [t.k, t.v] }
136 attr_writer :members, :tags
138 def add_member(type, id, role)
140 @members << [type, id.to_i, role]
143 def add_tag_keyval(k, v)
146 # duplicate tags are now forbidden, so we can't allow values
147 # in the hash to be overwritten.
148 raise OSM::APIDuplicateTagsError.new("relation", id, k) if @tags.include? k
154 # updates the changeset bounding box to contain the bounding box of
155 # the element with given +type+ and +id+. this only works with nodes
156 # and ways at the moment, as they're the only elements to respond to
158 def update_changeset_element(type, id)
159 element = Kernel.const_get(type.capitalize).find(id)
160 changeset.update_bbox! element.bbox
163 def delete_with_history!(new_relation, user)
164 raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id) unless visible
166 # need to start the transaction here, so that the database can
167 # provide repeatable reads for the used-by checks. this means it
168 # shouldn't be possible to get race conditions.
169 Relation.transaction do
171 check_update_element_consistency(self, new_relation, user)
172 # This will check to see if this relation is used by another relation
173 rel = RelationMember.joins(:relation).find_by("visible = ? AND member_type = 'Relation' and member_id = ? ", true, id)
174 raise OSM::APIPreconditionFailedError, "The relation #{new_relation.id} is used in relation #{rel.relation.id}." unless rel.nil?
176 self.changeset_id = new_relation.changeset_id
180 changeset.num_deleted_relations += 1
185 def update_from(new_relation, user)
186 Relation.transaction do
188 check_update_element_consistency(self, new_relation, user)
189 raise OSM::APIPreconditionFailedError, "Cannot update relation #{id}: data or member data is invalid." unless new_relation.preconditions_ok?(members)
191 self.changeset_id = new_relation.changeset_id
192 self.changeset = new_relation.changeset
193 self.tags = new_relation.tags
194 self.members = new_relation.members
196 changeset.num_modified_relations += 1
201 def create_with_history(user)
202 check_create_element_consistency(self, user)
203 raise OSM::APIPreconditionFailedError, "Cannot create relation: data or member data is invalid." unless preconditions_ok?
207 changeset.num_created_relations += 1
211 def preconditions_ok?(good_members = [])
212 raise OSM::APITooManyRelationMembersError.new(id, members.length, Settings.max_number_of_relation_members) if members.length > Settings.max_number_of_relation_members
214 # These are hastables that store an id in the index of all
215 # the nodes/way/relations that have already been added.
216 # If the member is valid and visible then we add it to the
217 # relevant hash table, with the value true as a cache.
218 # Thus if you have nodes with the ids of 50 and 1 already in the
219 # relation, then the hash table nodes would contain:
220 # => {50=>true, 1=>true}
221 elements = { :node => {}, :way => {}, :relation => {} }
223 # pre-set all existing members to good
224 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
227 # find the hash for the element type or die
228 hash = elements[m[0].downcase.to_sym]
229 return false unless hash
231 # unless its in the cache already
232 next if hash.key? m[1]
234 # use reflection to look up the appropriate class
235 model = Kernel.const_get(m[0].capitalize)
236 # get the element with that ID. and, if found, lock the element to
237 # ensure it can't be deleted until after the current transaction
239 element = model.lock("for share").find_by(:id => m[1])
241 # and check that it is OK to use.
242 raise OSM::APIPreconditionFailedError, "Relation with id #{id} cannot be saved due to #{m[0]} with id #{m[1]}" unless element&.visible? && element.preconditions_ok?
251 # if any members are referenced by placeholder IDs (i.e: negative) then
252 # this calling this method will fix them using the map from placeholders
254 def fix_placeholders!(id_map, placeholder_id = nil)
255 members.map! do |type, id, role|
258 new_id = id_map[type.downcase.to_sym][old_id]
259 raise OSM::APIBadUserInput, "Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}." if new_id.nil?
270 def save_with_history!
276 Relation.transaction do
277 # have to be a little bit clever here - to detect if any tags
278 # changed then we have to monitor their before and after state.
281 # clone the object before saving it so that the original is
282 # still marked as dirty if we retry the transaction
285 tags = self.tags.clone
286 element_tags.each do |old_tag|
288 # if we can match the tags we currently have to the list
289 # of old tags, then we never set the tags_changed flag. but
290 # if any are different then set the flag and do the DB
293 tags_changed |= (old_tag.v != tags[key])
295 # remove from the map, so that we can expect an empty map
296 # at the end if there are no new tags
300 # this means a tag was deleted
304 # if there are left-over tags then they are new and will have to
306 tags_changed |= !tags.empty?
307 RelationTag.where(:relation_id => id).delete_all
308 self.tags.each do |k, v|
309 tag = RelationTag.new
316 # same pattern as before, but this time we're collecting the
317 # changed members in an array, as the bounding box updates for
318 # elements are per-element, not blanked on/off like for tags.
320 members = self.members.clone
321 relation_members.each do |old_member|
322 key = [old_member.member_type, old_member.member_id, old_member.member_role]
323 i = members.index key
325 changed_members << key
330 # any remaining members must be new additions
331 changed_members += members
333 # update the members. first delete all the old members, as the new
334 # members may be in a different order and i don't feel like implementing
335 # a longest common subsequence algorithm to optimise this.
336 members = self.members
337 RelationMember.where(:relation_id => id).delete_all
338 members.each_with_index do |m, i|
339 mem = RelationMember.new
342 mem.member_type = m[0]
344 mem.member_role = m[2]
348 old_relation = OldRelation.from_relation(self)
349 old_relation.timestamp = t
350 old_relation.save_with_dependencies!
352 # update the bbox of the changeset and save it too.
353 # discussion on the mailing list gave the following definition for
354 # the bounding box update procedure of a relation:
356 # adding or removing nodes or ways from a relation causes them to be
357 # added to the changeset bounding box. adding a relation member or
358 # changing tag values causes all node and way members to be added to the
359 # bounding box. this is similar to how the map call does things and is
360 # reasonable on the assumption that adding or removing members doesn't
361 # materially change the rest of the relation.
363 changed_members.collect { |type, _id, _role| type == "Relation" }
364 .inject(false) { |acc, elem| acc || elem }
366 # if the relation is being deleted tags_changed will be true and members empty
367 # so we need to use changed_members to create a correct bounding box
368 update_members = if visible && (tags_changed || any_relations)
369 # add all non-relation bounding boxes to the changeset
370 # FIXME: check for tag changes along with element deletions and
371 # make sure that the deleted element's bounding box is hit.
376 update_members.each do |type, id, _role|
377 update_changeset_element(type, id) if type != "Relation"
380 # tell the changeset we updated one element only
381 changeset.add_changes! 1
383 # save the (maybe updated) changeset bounding box