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