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