]> git.openstreetmap.org Git - rails.git/blob - app/models/relation.rb
Merge remote-tracking branch 'upstream/pull/3264'
[rails.git] / app / models / relation.rb
1 # == Schema Information
2 #
3 # Table name: current_relations
4 #
5 #  id           :bigint(8)        not null, primary key
6 #  changeset_id :bigint(8)        not null
7 #  timestamp    :datetime         not null
8 #  visible      :boolean          not null
9 #  version      :bigint(8)        not null
10 #
11 # Indexes
12 #
13 #  current_relations_timestamp_idx  (timestamp)
14 #
15 # Foreign Keys
16 #
17 #  current_relations_changeset_id_fkey  (changeset_id => changesets.id)
18 #
19
20 class Relation < ApplicationRecord
21   require "xml/libxml"
22
23   include ConsistencyValidations
24   include NotRedactable
25   include ObjectMetadata
26
27   self.table_name = "current_relations"
28
29   belongs_to :changeset
30
31   has_many :old_relations, -> { order(:version) }
32
33   has_many :relation_members, -> { order(:sequence_id) }
34   has_many :relation_tags
35
36   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
37   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
38
39   validates :id, :uniqueness => true, :presence => { :on => :update },
40                  :numericality => { :on => :update, :only_integer => true }
41   validates :version, :presence => true,
42                       :numericality => { :only_integer => true }
43   validates :changeset_id, :presence => true,
44                            :numericality => { :only_integer => true }
45   validates :timestamp, :presence => true
46   validates :changeset, :associated => true
47   validates :visible, :inclusion => [true, false]
48
49   scope :visible, -> { where(:visible => true) }
50   scope :invisible, -> { where(:visible => false) }
51   scope :nodes, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids.flatten }) }
52   scope :ways, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids.flatten }) }
53   scope :relations, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids.flatten }) }
54
55   TYPES = %w[node way relation].freeze
56
57   def self.from_xml(xml, create: false)
58     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
59     doc = p.parse
60     pt = doc.find_first("//osm/relation")
61
62     if pt
63       Relation.from_xml_node(pt, :create => create)
64     else
65       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
66     end
67   rescue LibXML::XML::Error, ArgumentError => e
68     raise OSM::APIBadXMLError.new("relation", xml, e.message)
69   end
70
71   def self.from_xml_node(pt, create: false)
72     relation = Relation.new
73
74     raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create || !pt["version"].nil?
75
76     relation.version = pt["version"]
77     raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt["changeset"].nil?
78
79     relation.changeset_id = pt["changeset"]
80
81     unless create
82       raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt["id"].nil?
83
84       relation.id = pt["id"].to_i
85       # .to_i will return 0 if there is no number that can be parsed.
86       # We want to make sure that there is no id with zero anyway
87       raise OSM::APIBadUserInput, "ID of relation cannot be zero when updating." if relation.id.zero?
88     end
89
90     # We don't care about the timestamp nor the visibility as these are either
91     # set explicitly or implicit in the action. The visibility is set to true,
92     # and manually set to false before the actual delete.
93     relation.visible = true
94
95     # Start with no tags
96     relation.tags = {}
97
98     # Add in any tags from the XML
99     pt.find("tag").each do |tag|
100       raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag["k"].nil?
101       raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag["v"].nil?
102
103       relation.add_tag_keyval(tag["k"], tag["v"])
104     end
105
106     # need to initialise the relation members array explicitly, as if this
107     # isn't done for a new relation then @members attribute will be nil,
108     # and the members will be loaded from the database instead of being
109     # empty, as intended.
110     relation.members = []
111
112     pt.find("member").each do |member|
113       # member_type =
114       raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member["type"]
115
116       # member_ref = member['ref']
117       # member_role
118       member["role"] ||= "" # Allow  the upload to not include this, in which case we default to an empty string.
119       relation.add_member(member["type"].classify, member["ref"], member["role"])
120     end
121     raise OSM::APIBadUserInput, "Some bad xml in relation" if relation.nil?
122
123     relation
124   end
125
126   # FIXME: is this really needed?
127   def members
128     @members ||= relation_members.map do |member|
129       [member.member_type, member.member_id, member.member_role]
130     end
131   end
132
133   def tags
134     @tags ||= relation_tags.collect { |t| [t.k, t.v] }.to_h
135   end
136
137   attr_writer :members, :tags
138
139   def add_member(type, id, role)
140     @members ||= []
141     @members << [type, id.to_i, role]
142   end
143
144   def add_tag_keyval(k, v)
145     @tags ||= {}
146
147     # duplicate tags are now forbidden, so we can't allow values
148     # in the hash to be overwritten.
149     raise OSM::APIDuplicateTagsError.new("relation", id, k) if @tags.include? k
150
151     @tags[k] = v
152   end
153
154   ##
155   # updates the changeset bounding box to contain the bounding box of
156   # the element with given +type+ and +id+. this only works with nodes
157   # and ways at the moment, as they're the only elements to respond to
158   # the :bbox call.
159   def update_changeset_element(type, id)
160     element = Kernel.const_get(type.capitalize).find(id)
161     changeset.update_bbox! element.bbox
162   end
163
164   def delete_with_history!(new_relation, user)
165     raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id) unless visible
166
167     # need to start the transaction here, so that the database can
168     # provide repeatable reads for the used-by checks. this means it
169     # shouldn't be possible to get race conditions.
170     Relation.transaction do
171       lock!
172       check_consistency(self, new_relation, user)
173       # This will check to see if this relation is used by another relation
174       rel = RelationMember.joins(:relation).find_by("visible = ? AND member_type = 'Relation' and member_id = ? ", true, id)
175       raise OSM::APIPreconditionFailedError, "The relation #{new_relation.id} is used in relation #{rel.relation.id}." unless rel.nil?
176
177       self.changeset_id = new_relation.changeset_id
178       self.tags = {}
179       self.members = []
180       self.visible = false
181       save_with_history!
182     end
183   end
184
185   def update_from(new_relation, user)
186     Relation.transaction do
187       lock!
188       check_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)
190
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
195       self.visible = true
196       save_with_history!
197     end
198   end
199
200   def create_with_history(user)
201     check_create_consistency(self, user)
202     raise OSM::APIPreconditionFailedError, "Cannot create relation: data or member data is invalid." unless preconditions_ok?
203
204     self.version = 0
205     self.visible = true
206     save_with_history!
207   end
208
209   def preconditions_ok?(good_members = [])
210     # These are hastables that store an id in the index of all
211     # the nodes/way/relations that have already been added.
212     # If the member is valid and visible then we add it to the
213     # relevant hash table, with the value true as a cache.
214     # Thus if you have nodes with the ids of 50 and 1 already in the
215     # relation, then the hash table nodes would contain:
216     # => {50=>true, 1=>true}
217     elements = { :node => {}, :way => {}, :relation => {} }
218
219     # pre-set all existing members to good
220     good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
221
222     members.each do |m|
223       # find the hash for the element type or die
224       hash = elements[m[0].downcase.to_sym]
225       return false unless hash
226
227       # unless its in the cache already
228       next if hash.key? m[1]
229
230       # use reflection to look up the appropriate class
231       model = Kernel.const_get(m[0].capitalize)
232       # get the element with that ID. and, if found, lock the element to
233       # ensure it can't be deleted until after the current transaction
234       # commits.
235       element = model.lock("for share").find_by(:id => m[1])
236
237       # and check that it is OK to use.
238       raise OSM::APIPreconditionFailedError, "Relation with id #{id} cannot be saved due to #{m[0]} with id #{m[1]}" unless element&.visible? && element&.preconditions_ok?
239
240       hash[m[1]] = true
241     end
242
243     true
244   end
245
246   ##
247   # if any members are referenced by placeholder IDs (i.e: negative) then
248   # this calling this method will fix them using the map from placeholders
249   # to IDs +id_map+.
250   def fix_placeholders!(id_map, placeholder_id = nil)
251     members.map! do |type, id, role|
252       old_id = id.to_i
253       if old_id.negative?
254         new_id = id_map[type.downcase.to_sym][old_id]
255         raise OSM::APIBadUserInput, "Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}." if new_id.nil?
256
257         [type, new_id, role]
258       else
259         [type, id, role]
260       end
261     end
262   end
263
264   private
265
266   def save_with_history!
267     t = Time.now.getutc
268
269     self.version += 1
270     self.timestamp = t
271
272     Relation.transaction do
273       # have to be a little bit clever here - to detect if any tags
274       # changed then we have to monitor their before and after state.
275       tags_changed = false
276
277       # clone the object before saving it so that the original is
278       # still marked as dirty if we retry the transaction
279       clone.save!
280
281       tags = self.tags.clone
282       relation_tags.each do |old_tag|
283         key = old_tag.k
284         # if we can match the tags we currently have to the list
285         # of old tags, then we never set the tags_changed flag. but
286         # if any are different then set the flag and do the DB
287         # update.
288         if tags.key? key
289           tags_changed |= (old_tag.v != tags[key])
290
291           # remove from the map, so that we can expect an empty map
292           # at the end if there are no new tags
293           tags.delete key
294
295         else
296           # this means a tag was deleted
297           tags_changed = true
298         end
299       end
300       # if there are left-over tags then they are new and will have to
301       # be added.
302       tags_changed |= !tags.empty?
303       RelationTag.where(:relation_id => id).delete_all
304       self.tags.each do |k, v|
305         tag = RelationTag.new
306         tag.relation_id = id
307         tag.k = k
308         tag.v = v
309         tag.save!
310       end
311
312       # same pattern as before, but this time we're collecting the
313       # changed members in an array, as the bounding box updates for
314       # elements are per-element, not blanked on/off like for tags.
315       changed_members = []
316       members = self.members.clone
317       relation_members.each do |old_member|
318         key = [old_member.member_type, old_member.member_id, old_member.member_role]
319         i = members.index key
320         if i.nil?
321           changed_members << key
322         else
323           members.delete_at i
324         end
325       end
326       # any remaining members must be new additions
327       changed_members += members
328
329       # update the members. first delete all the old members, as the new
330       # members may be in a different order and i don't feel like implementing
331       # a longest common subsequence algorithm to optimise this.
332       members = self.members
333       RelationMember.where(:relation_id => id).delete_all
334       members.each_with_index do |m, i|
335         mem = RelationMember.new
336         mem.relation_id = id
337         mem.sequence_id = i
338         mem.member_type = m[0]
339         mem.member_id = m[1]
340         mem.member_role = m[2]
341         mem.save!
342       end
343
344       old_relation = OldRelation.from_relation(self)
345       old_relation.timestamp = t
346       old_relation.save_with_dependencies!
347
348       # update the bbox of the changeset and save it too.
349       # discussion on the mailing list gave the following definition for
350       # the bounding box update procedure of a relation:
351       #
352       # adding or removing nodes or ways from a relation causes them to be
353       # added to the changeset bounding box. adding a relation member or
354       # changing tag values causes all node and way members to be added to the
355       # bounding box. this is similar to how the map call does things and is
356       # reasonable on the assumption that adding or removing members doesn't
357       # materially change the rest of the relation.
358       any_relations =
359         changed_members.collect { |type, _id, _role| type == "Relation" }
360                        .inject(false) { |acc, elem| acc || elem }
361
362       # if the relation is being deleted tags_changed will be true and members empty
363       # so we need to use changed_members to create a correct bounding box
364       update_members = if visible && (tags_changed || any_relations)
365                          # add all non-relation bounding boxes to the changeset
366                          # FIXME: check for tag changes along with element deletions and
367                          # make sure that the deleted element's bounding box is hit.
368                          self.members
369                        else
370                          changed_members
371                        end
372       update_members.each do |type, id, _role|
373         update_changeset_element(type, id) if type != "Relation"
374       end
375
376       # tell the changeset we updated one element only
377       changeset.add_changes! 1
378
379       # save the (maybe updated) changeset bounding box
380       changeset.save!
381     end
382   end
383 end