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)
30 p = XML::Parser.string(xml)
33 doc.find('//osm/relation').each do |pt|
34 return Relation.from_xml_node(pt, create)
36 rescue LibXML::XML::Error, ArgumentError => ex
37 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
41 def self.from_xml_node(pt, create=false)
42 relation = Relation.new
44 if !create and pt['id'] != '0'
45 relation.id = pt['id'].to_i
48 raise OSM::APIBadXMLError.new("relation", pt, "You are missing the required changeset in the relation") if pt['changeset'].nil?
49 relation.changeset_id = pt['changeset']
51 # The follow block does not need to be executed because they are dealt with
52 # in create_with_history, update_from and delete_with_history
54 relation.timestamp = Time.now.getutc
55 relation.visible = true
59 relation.timestamp = Time.parse(pt['timestamp'])
61 relation.version = pt['version']
64 pt.find('tag').each do |tag|
65 relation.add_tag_keyval(tag['k'], tag['v'])
68 pt.find('member').each do |member|
70 logger.debug "each member"
71 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
72 logger.debug "after raise"
73 #member_ref = member['ref']
75 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
76 logger.debug member['role']
77 relation.add_member(member['type'].classify, member['ref'], member['role'])
79 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
85 doc = OSM::API.new.get_xml_doc
86 doc.root << to_xml_node()
90 def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
91 el1 = XML::Node.new 'relation'
92 el1['id'] = self.id.to_s
93 el1['visible'] = self.visible.to_s
94 el1['timestamp'] = self.timestamp.xmlschema
95 el1['version'] = self.version.to_s
96 el1['changeset'] = self.changeset_id.to_s
98 if changeset_cache.key?(self.changeset_id)
99 # use the cache if available
101 changeset_cache[self.changeset_id] = self.changeset.user_id
104 user_id = changeset_cache[self.changeset_id]
106 if user_display_name_cache.key?(user_id)
107 # use the cache if available
108 elsif self.changeset.user.data_public?
109 user_display_name_cache[user_id] = self.changeset.user.display_name
111 user_display_name_cache[user_id] = nil
114 if not user_display_name_cache[user_id].nil?
115 el1['user'] = user_display_name_cache[user_id]
116 el1['uid'] = user_id.to_s
119 self.relation_members.each do |member|
122 # if there is a list of visible members then use that to weed out deleted segments
123 if visible_members[member.member_type][member.member_id]
127 # otherwise, manually go to the db to check things
128 if member.member.visible?
133 e = XML::Node.new 'member'
134 e['type'] = member.member_type.downcase
135 e['ref'] = member.member_id.to_s
136 e['role'] = member.member_role
141 self.relation_tags.each do |tag|
142 e = XML::Node.new 'tag'
150 def self.find_for_nodes(ids, options = {})
154 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members AS crm ON crm.id = current_relations.id", :conditions => "crm.member_type = 'Node' AND crm.member_id IN (#{ids.join(',')})" }) do
155 return self.find(:all, options)
160 def self.find_for_ways(ids, options = {})
164 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members AS crm ON crm.id = current_relations.id", :conditions => "crm.member_type = 'Way' AND crm.member_id IN (#{ids.join(',')})" }) do
165 return self.find(:all, options)
170 def self.find_for_relations(ids, options = {})
174 self.with_scope(:find => { :joins => "INNER JOIN current_relation_members AS crm ON crm.id = current_relations.id", :conditions => "crm.member_type = 'Relation' AND crm.member_id IN (#{ids.join(',')})" }) do
175 return self.find(:all, options)
180 # FIXME is this really needed?
184 self.relation_members.each do |member|
185 @members += [[member.member_type,member.member_id,member.member_role]]
194 self.relation_tags.each do |tag|
209 def add_member(type,id,role)
210 @members = Array.new unless @members
211 @members += [[type,id,role]]
214 def add_tag_keyval(k, v)
215 @tags = Hash.new unless @tags
217 # duplicate tags are now forbidden, so we can't allow values
218 # in the hash to be overwritten.
219 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
225 # updates the changeset bounding box to contain the bounding box of
226 # the element with given +type+ and +id+. this only works with nodes
227 # and ways at the moment, as they're the only elements to respond to
229 def update_changeset_element(type, id)
230 element = Kernel.const_get(type.capitalize).find(id)
231 changeset.update_bbox! element.bbox
234 def delete_with_history!(new_relation, user)
236 raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
239 # need to start the transaction here, so that the database can
240 # provide repeatable reads for the used-by checks. this means it
241 # shouldn't be possible to get race conditions.
242 Relation.transaction do
243 check_consistency(self, new_relation, user)
244 # This will check to see if this relation is used by another relation
245 rel = RelationMember.find(:first, :joins => :relation,
246 :conditions => [ "visible = ? AND member_type='Relation' and member_id=? ", true, self.id ])
247 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
249 self.changeset_id = new_relation.changeset_id
257 def update_from(new_relation, user)
258 check_consistency(self, new_relation, user)
259 unless new_relation.preconditions_ok?(self.members)
260 raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
262 self.changeset_id = new_relation.changeset_id
263 self.changeset = new_relation.changeset
264 self.tags = new_relation.tags
265 self.members = new_relation.members
270 def create_with_history(user)
271 check_create_consistency(self, user)
272 unless self.preconditions_ok?
273 raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
280 def preconditions_ok?(good_members = [])
281 # These are hastables that store an id in the index of all
282 # the nodes/way/relations that have already been added.
283 # If the member is valid and visible then we add it to the
284 # relevant hash table, with the value true as a cache.
285 # Thus if you have nodes with the ids of 50 and 1 already in the
286 # relation, then the hash table nodes would contain:
287 # => {50=>true, 1=>true}
288 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
290 # pre-set all existing members to good
291 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
293 self.members.each do |m|
294 # find the hash for the element type or die
295 hash = elements[m[0].downcase.to_sym] or return false
296 # unless its in the cache already
297 unless hash.key? m[1]
298 # use reflection to look up the appropriate class
299 model = Kernel.const_get(m[0].capitalize)
300 # get the element with that ID
301 element = model.find(:first, :conditions =>["id = ?", m[1]])
303 # and check that it is OK to use.
304 unless element and element.visible? and element.preconditions_ok?
305 raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
314 # Temporary method to match interface to nodes
320 # if any members are referenced by placeholder IDs (i.e: negative) then
321 # this calling this method will fix them using the map from placeholders
323 def fix_placeholders!(id_map, placeholder_id = nil)
324 self.members.map! do |type, id, role|
327 new_id = id_map[type.downcase.to_sym][old_id]
328 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?
338 def save_with_history!
339 Relation.transaction do
340 # have to be a little bit clever here - to detect if any tags
341 # changed then we have to monitor their before and after state.
349 tags = self.tags.clone
350 self.relation_tags.each do |old_tag|
352 # if we can match the tags we currently have to the list
353 # of old tags, then we never set the tags_changed flag. but
354 # if any are different then set the flag and do the DB
357 tags_changed |= (old_tag.v != tags[key])
359 # remove from the map, so that we can expect an empty map
360 # at the end if there are no new tags
364 # this means a tag was deleted
368 # if there are left-over tags then they are new and will have to
370 tags_changed |= (not tags.empty?)
371 RelationTag.delete_all(:id => self.id)
372 self.tags.each do |k,v|
373 tag = RelationTag.new
380 # same pattern as before, but this time we're collecting the
381 # changed members in an array, as the bounding box updates for
382 # elements are per-element, not blanked on/off like for tags.
383 changed_members = Array.new
385 self.members.each do |m|
386 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
387 members[[m[1], m[0]]] = m[2]
389 relation_members.each do |old_member|
390 key = [old_member.member_id.to_s, old_member.member_type]
391 if members.has_key? key
394 changed_members << key
397 # any remaining members must be new additions
398 changed_members += members.keys
400 # update the members. first delete all the old members, as the new
401 # members may be in a different order and i don't feel like implementing
402 # a longest common subsequence algorithm to optimise this.
403 members = self.members
404 RelationMember.delete_all(:id => self.id)
405 members.each_with_index do |m,i|
406 mem = RelationMember.new
407 mem.id = [self.id, i]
408 mem.member_type = m[0]
410 mem.member_role = m[2]
414 old_relation = OldRelation.from_relation(self)
415 old_relation.timestamp = t
416 old_relation.save_with_dependencies!
418 # update the bbox of the changeset and save it too.
419 # discussion on the mailing list gave the following definition for
420 # the bounding box update procedure of a relation:
422 # adding or removing nodes or ways from a relation causes them to be
423 # added to the changeset bounding box. adding a relation member or
424 # changing tag values causes all node and way members to be added to the
425 # bounding box. this is similar to how the map call does things and is
426 # reasonable on the assumption that adding or removing members doesn't
427 # materially change the rest of the relation.
429 changed_members.collect { |id,type| type == "relation" }.
430 inject(false) { |b,s| b or s }
432 if tags_changed or any_relations
433 # add all non-relation bounding boxes to the changeset
434 # FIXME: check for tag changes along with element deletions and
435 # make sure that the deleted element's bounding box is hit.
436 self.members.each do |type, id, role|
437 if type != "Relation"
438 update_changeset_element(type, id)
442 # add only changed members to the changeset
443 changed_members.each do |id, type|
444 if type != "Relation"
445 update_changeset_element(type, id)
450 # tell the changeset we updated one element only
451 changeset.add_changes! 1
453 # save the (maybe updated) changeset bounding box