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