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