1 class Relation < ActiveRecord::Base
4 include ConsistencyValidations
6 set_table_name 'current_relations'
10 has_many :old_relations, :foreign_key => 'id', :order => 'version'
12 has_many :relation_members, :foreign_key => 'id', :order => 'sequence_id'
13 has_many :relation_tags, :foreign_key => 'id'
15 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
16 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
18 validates_presence_of :id, :on => :update
19 validates_presence_of :timestamp,:version, :changeset_id
20 validates_uniqueness_of :id
21 validates_inclusion_of :visible, :in => [ true, false ]
22 validates_numericality_of :id, :on => :update, :integer_only => true
23 validates_numericality_of :changeset_id, :version, :integer_only => true
24 validates_associated :changeset
26 TYPES = ["node", "way", "relation"]
28 def self.from_xml(xml, create=false)
34 doc.find('//osm/relation').each do |pt|
35 return Relation.from_xml_node(pt, create)
37 rescue LibXML::XML::Error => ex
38 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
42 def self.from_xml_node(pt, create=false)
43 relation = Relation.new
45 if !create and pt['id'] != '0'
46 relation.id = pt['id'].to_i
49 raise OSM::APIBadXMLError.new("relation", pt, "You are missing the required changeset in the relation") if pt['changeset'].nil?
50 relation.changeset_id = pt['changeset']
53 relation.timestamp = Time.now
54 relation.visible = true
58 relation.timestamp = Time.parse(pt['timestamp'])
60 relation.version = pt['version']
63 pt.find('tag').each do |tag|
64 relation.add_tag_keyval(tag['k'], tag['v'])
67 pt.find('member').each do |member|
69 logger.debug "each member"
70 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
71 logger.debug "after raise"
72 #member_ref = member['ref']
74 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
75 logger.debug member['role']
76 relation.add_member(member['type'], member['ref'], member['role'])
78 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
84 doc = OSM::API.new.get_xml_doc
85 doc.root << to_xml_node()
89 def to_xml_node(user_display_name_cache = nil)
90 el1 = XML::Node.new 'relation'
91 el1['id'] = self.id.to_s
92 el1['visible'] = self.visible.to_s
93 el1['timestamp'] = self.timestamp.xmlschema
94 el1['version'] = self.version.to_s
95 el1['changeset'] = self.changeset_id.to_s
97 user_display_name_cache = {} if user_display_name_cache.nil?
99 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
100 # use the cache if available
101 elsif self.changeset.user.data_public?
102 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
104 user_display_name_cache[self.changeset.user_id] = nil
107 if not user_display_name_cache[self.changeset.user_id].nil?
108 el1['user'] = user_display_name_cache[self.changeset.user_id]
109 el1['uid'] = self.changeset.user_id.to_s
112 self.relation_members.each do |member|
115 # # if there is a list of visible members then use that to weed out deleted segments
116 # if visible_members[member.member_type][member.member_id]
120 # otherwise, manually go to the db to check things
121 if member.member.visible?
126 e = XML::Node.new 'member'
127 e['type'] = member.member_type
128 e['ref'] = member.member_id.to_s
129 e['role'] = member.member_role
134 self.relation_tags.each do |tag|
135 e = XML::Node.new 'tag'
143 def self.find_for_nodes(ids, options = {})
147 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'node' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
148 return self.find(:all, options)
153 def self.find_for_ways(ids, options = {})
157 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'way' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
158 return self.find(:all, options)
163 def self.find_for_relations(ids, options = {})
167 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members ON current_relation_members.id = current_relations.id", :conditions => "current_relation_members.member_type = 'relation' AND current_relation_members.member_id IN (#{ids.join(',')})" }) do
168 return self.find(:all, options)
173 # FIXME is this really needed?
177 self.relation_members.each do |member|
178 @members += [[member.member_type,member.member_id,member.member_role]]
187 self.relation_tags.each do |tag|
202 def add_member(type,id,role)
203 @members = Array.new unless @members
204 @members += [[type,id,role]]
207 def add_tag_keyval(k, v)
208 @tags = Hash.new unless @tags
210 # duplicate tags are now forbidden, so we can't allow values
211 # in the hash to be overwritten.
212 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
218 # updates the changeset bounding box to contain the bounding box of
219 # the element with given +type+ and +id+. this only works with nodes
220 # and ways at the moment, as they're the only elements to respond to
222 def update_changeset_element(type, id)
223 element = Kernel.const_get(type.capitalize).find(id)
224 changeset.update_bbox! element.bbox
227 def delete_with_history!(new_relation, user)
229 raise OSM::APIAlreadyDeletedError.new
232 # need to start the transaction here, so that the database can
233 # provide repeatable reads for the used-by checks. this means it
234 # shouldn't be possible to get race conditions.
235 Relation.transaction do
236 check_consistency(self, new_relation, user)
237 # This will check to see if this relation is used by another relation
238 if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id", :conditions => [ "visible = ? AND member_type='relation' and member_id=? ", true, self.id ])
239 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is a used in another relation")
241 self.changeset_id = new_relation.changeset_id
249 def update_from(new_relation, user)
250 check_consistency(self, new_relation, user)
251 if !new_relation.preconditions_ok?
252 raise OSM::APIPreconditionFailedError.new
254 self.changeset_id = new_relation.changeset_id
255 self.tags = new_relation.tags
256 self.members = new_relation.members
261 def create_with_history(user)
262 check_create_consistency(self, user)
263 if !self.preconditions_ok?
264 raise OSM::APIPreconditionFailedError.new
271 def preconditions_ok?
272 # These are hastables that store an id in the index of all
273 # the nodes/way/relations that have already been added.
274 # If the member is valid and visible then we add it to the
275 # relevant hash table, with the value true as a cache.
276 # Thus if you have nodes with the ids of 50 and 1 already in the
277 # relation, then the hash table nodes would contain:
278 # => {50=>true, 1=>true}
279 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
280 self.members.each do |m|
281 # find the hash for the element type or die
282 hash = elements[m[0].to_sym] or return false
284 # unless its in the cache already
285 unless hash.key? m[1]
286 # use reflection to look up the appropriate class
287 model = Kernel.const_get(m[0].capitalize)
289 # get the element with that ID
290 element = model.find(m[1])
292 # and check that it is OK to use.
293 unless element and element.visible? and element.preconditions_ok?
305 # Temporary method to match interface to nodes
311 # if any members are referenced by placeholder IDs (i.e: negative) then
312 # this calling this method will fix them using the map from placeholders
314 def fix_placeholders!(id_map)
315 self.members.map! do |type, id, role|
318 new_id = id_map[type.to_sym][old_id]
319 raise "invalid placeholder" if new_id.nil?
329 def save_with_history!
330 Relation.transaction do
331 # have to be a little bit clever here - to detect if any tags
332 # changed then we have to monitor their before and after state.
341 self.relation_tags.each do |old_tag|
343 # if we can match the tags we currently have to the list
344 # of old tags, then we never set the tags_changed flag. but
345 # if any are different then set the flag and do the DB
348 # rails 2.1 dirty handling should take care of making this
349 # somewhat efficient... hopefully...
350 old_tag.v = tags[key]
351 tags_changed |= old_tag.changed?
354 # remove from the map, so that we can expect an empty map
355 # at the end if there are no new tags
359 # this means a tag was deleted
361 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
364 # if there are left-over tags then they are new and will have to
366 tags_changed |= (not tags.empty?)
368 tag = RelationTag.new
375 # same pattern as before, but this time we're collecting the
376 # changed members in an array, as the bounding box updates for
377 # elements are per-element, not blanked on/off like for tags.
378 changed_members = Array.new
380 self.members.each do |m|
381 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
382 members[[m[1], m[0]]] = m[2]
384 relation_members.each do |old_member|
385 key = [old_member.member_id.to_s, old_member.member_type]
386 if members.has_key? key
389 changed_members << key
392 # any remaining members must be new additions
393 changed_members += members.keys
395 # update the members. first delete all the old members, as the new
396 # members may be in a different order and i don't feel like implementing
397 # a longest common subsequence algorithm to optimise this.
398 members = self.members
399 RelationMember.delete_all(:id => self.id)
400 members.each_with_index do |m,i|
401 mem = RelationMember.new
402 mem.id = [self.id, i]
403 mem.member_type = m[0]
405 mem.member_role = m[2]
409 old_relation = OldRelation.from_relation(self)
410 old_relation.timestamp = t
411 old_relation.save_with_dependencies!
413 # update the bbox of the changeset and save it too.
414 # discussion on the mailing list gave the following definition for
415 # the bounding box update procedure of a relation:
417 # adding or removing nodes or ways from a relation causes them to be
418 # added to the changeset bounding box. adding a relation member or
419 # changing tag values causes all node and way members to be added to the
420 # bounding box. this is similar to how the map call does things and is
421 # reasonable on the assumption that adding or removing members doesn't
422 # materially change the rest of the relation.
424 changed_members.collect { |id,type| type == "relation" }.
425 inject(false) { |b,s| b or s }
427 if tags_changed or any_relations
428 # add all non-relation bounding boxes to the changeset
429 # FIXME: check for tag changes along with element deletions and
430 # make sure that the deleted element's bounding box is hit.
431 self.members.each do |type, id, role|
432 if type != "relation"
433 update_changeset_element(type, id)
437 # add only changed members to the changeset
438 changed_members.each do |id, type|
439 update_changeset_element(type, id)
443 # tell the changeset we updated one element only
444 changeset.add_changes! 1
446 # save the (maybe updated) changeset bounding box