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