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