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