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(user_display_name_cache = nil)
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 user_display_name_cache = {} if user_display_name_cache.nil?
100 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
101 # use the cache if available
102 elsif self.changeset.user.data_public?
103 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
105 user_display_name_cache[self.changeset.user_id] = nil
108 if not user_display_name_cache[self.changeset.user_id].nil?
109 el1['user'] = user_display_name_cache[self.changeset.user_id]
110 el1['uid'] = self.changeset.user_id.to_s
113 self.relation_members.each do |member|
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]
121 # otherwise, manually go to the db to check things
122 if member.member.visible?
127 e = XML::Node.new 'member'
128 e['type'] = member.member_type.downcase
129 e['ref'] = member.member_id.to_s
130 e['role'] = member.member_role
135 self.relation_tags.each do |tag|
136 e = XML::Node.new 'tag'
144 def self.find_for_nodes(ids, options = {})
148 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
149 return self.find(:all, options)
154 def self.find_for_ways(ids, options = {})
158 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
159 return self.find(:all, options)
164 def self.find_for_relations(ids, options = {})
168 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
169 return self.find(:all, options)
174 # FIXME is this really needed?
178 self.relation_members.each do |member|
179 @members += [[member.member_type,member.member_id,member.member_role]]
188 self.relation_tags.each do |tag|
203 def add_member(type,id,role)
204 @members = Array.new unless @members
205 @members += [[type,id,role]]
208 def add_tag_keyval(k, v)
209 @tags = Hash.new unless @tags
211 # duplicate tags are now forbidden, so we can't allow values
212 # in the hash to be overwritten.
213 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
219 # updates the changeset bounding box to contain the bounding box of
220 # the element with given +type+ and +id+. this only works with nodes
221 # and ways at the moment, as they're the only elements to respond to
223 def update_changeset_element(type, id)
224 element = Kernel.const_get(type.capitalize).find(id)
225 changeset.update_bbox! element.bbox
228 def delete_with_history!(new_relation, user)
230 raise OSM::APIAlreadyDeletedError.new
233 # need to start the transaction here, so that the database can
234 # provide repeatable reads for the used-by checks. this means it
235 # shouldn't be possible to get race conditions.
236 Relation.transaction do
237 check_consistency(self, new_relation, user)
238 # This will check to see if this relation is used by another relation
239 rel = 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 ])
240 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is a used in relation #{rel.id}.") unless rel.nil?
242 self.changeset_id = new_relation.changeset_id
250 def update_from(new_relation, user)
251 check_consistency(self, new_relation, user)
252 unless preconditions_ok?
253 raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
255 self.changeset_id = new_relation.changeset_id
256 self.changeset = new_relation.changeset
257 self.tags = new_relation.tags
258 self.members = new_relation.members
263 def create_with_history(user)
264 check_create_consistency(self, user)
265 unless self.preconditions_ok?
266 raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
273 def preconditions_ok?
274 # These are hastables that store an id in the index of all
275 # the nodes/way/relations that have already been added.
276 # If the member is valid and visible then we add it to the
277 # relevant hash table, with the value true as a cache.
278 # Thus if you have nodes with the ids of 50 and 1 already in the
279 # relation, then the hash table nodes would contain:
280 # => {50=>true, 1=>true}
281 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
282 self.members.each do |m|
283 # find the hash for the element type or die
285 hash = elements[m[0].downcase.to_sym] or return false
286 # unless its in the cache already
287 unless hash.key? m[1]
288 # use reflection to look up the appropriate class
289 model = Kernel.const_get(m[0].capitalize)
290 # get the element with that ID
291 element = model.find(m[1])
293 # and check that it is OK to use.
294 unless element and element.visible? and element.preconditions_ok?
306 # Temporary method to match interface to nodes
312 # if any members are referenced by placeholder IDs (i.e: negative) then
313 # this calling this method will fix them using the map from placeholders
315 def fix_placeholders!(id_map)
316 self.members.map! do |type, id, role|
319 new_id = id_map[type.downcase.to_sym][old_id]
320 raise "invalid placeholder" if new_id.nil?
330 def save_with_history!
331 Relation.transaction do
332 # have to be a little bit clever here - to detect if any tags
333 # changed then we have to monitor their before and after state.
342 self.relation_tags.each do |old_tag|
344 # if we can match the tags we currently have to the list
345 # of old tags, then we never set the tags_changed flag. but
346 # if any are different then set the flag and do the DB
349 # rails 2.1 dirty handling should take care of making this
350 # somewhat efficient... hopefully...
351 old_tag.v = tags[key]
352 tags_changed |= old_tag.changed?
355 # remove from the map, so that we can expect an empty map
356 # at the end if there are no new tags
360 # this means a tag was deleted
362 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
365 # if there are left-over tags then they are new and will have to
367 tags_changed |= (not tags.empty?)
369 tag = RelationTag.new
376 # reload, so that all of the members are accessible in their
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