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 scope :visible, where(:visible => true)
27 scope :invisible, where(:visible => false)
28 scope :nodes, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Node", :member_id => ids }) }
29 scope :ways, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids }) }
30 scope :relations, lambda { |*ids| joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids }) }
32 TYPES = ["node", "way", "relation"]
34 def self.from_xml(xml, create=false)
36 p = XML::Parser.string(xml)
39 doc.find('//osm/relation').each do |pt|
40 return Relation.from_xml_node(pt, create)
42 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
43 rescue LibXML::XML::Error, ArgumentError => ex
44 raise OSM::APIBadXMLError.new("relation", xml, ex.message)
48 def self.from_xml_node(pt, create=false)
49 relation = Relation.new
51 raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create or not pt['version'].nil?
52 relation.version = pt['version']
53 raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
54 relation.changeset_id = pt['changeset']
57 raise 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 raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
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
69 pt.find('tag').each do |tag|
70 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
71 raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
72 relation.add_tag_keyval(tag['k'], tag['v'])
75 pt.find('member').each do |member|
77 logger.debug "each member"
78 raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
79 logger.debug "after raise"
80 #member_ref = member['ref']
82 member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
83 logger.debug member['role']
84 relation.add_member(member['type'].classify, member['ref'], member['role'])
86 raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
92 doc = OSM::API.new.get_xml_doc
93 doc.root << to_xml_node()
97 def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
98 el1 = XML::Node.new 'relation'
99 el1['id'] = self.id.to_s
100 el1['visible'] = self.visible.to_s
101 el1['timestamp'] = self.timestamp.xmlschema
102 el1['version'] = self.version.to_s
103 el1['changeset'] = self.changeset_id.to_s
105 if changeset_cache.key?(self.changeset_id)
106 # use the cache if available
108 changeset_cache[self.changeset_id] = self.changeset.user_id
111 user_id = changeset_cache[self.changeset_id]
113 if user_display_name_cache.key?(user_id)
114 # use the cache if available
115 elsif self.changeset.user.data_public?
116 user_display_name_cache[user_id] = self.changeset.user.display_name
118 user_display_name_cache[user_id] = nil
121 if not user_display_name_cache[user_id].nil?
122 el1['user'] = user_display_name_cache[user_id]
123 el1['uid'] = user_id.to_s
126 self.relation_members.each do |member|
129 # if there is a list of visible members then use that to weed out deleted segments
130 if visible_members[member.member_type][member.member_id]
134 # otherwise, manually go to the db to check things
135 if member.member.visible?
140 e = XML::Node.new 'member'
141 e['type'] = member.member_type.downcase
142 e['ref'] = member.member_id.to_s
143 e['role'] = member.member_role
148 self.relation_tags.each do |tag|
149 e = XML::Node.new 'tag'
157 # FIXME is this really needed?
161 self.relation_members.each do |member|
162 @members += [[member.member_type,member.member_id,member.member_role]]
171 self.relation_tags.each do |tag|
186 def add_member(type,id,role)
187 @members = Array.new unless @members
188 @members += [[type,id.to_i,role]]
191 def add_tag_keyval(k, v)
192 @tags = Hash.new unless @tags
194 # duplicate tags are now forbidden, so we can't allow values
195 # in the hash to be overwritten.
196 raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
202 # updates the changeset bounding box to contain the bounding box of
203 # the element with given +type+ and +id+. this only works with nodes
204 # and ways at the moment, as they're the only elements to respond to
206 def update_changeset_element(type, id)
207 element = Kernel.const_get(type.capitalize).find(id)
208 changeset.update_bbox! element.bbox
211 def delete_with_history!(new_relation, user)
213 raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
216 # need to start the transaction here, so that the database can
217 # provide repeatable reads for the used-by checks. this means it
218 # shouldn't be possible to get race conditions.
219 Relation.transaction do
221 check_consistency(self, new_relation, user)
222 # This will check to see if this relation is used by another relation
223 rel = RelationMember.find(:first, :joins => :relation,
224 :conditions => [ "visible = ? AND member_type='Relation' and member_id=? ", true, self.id ])
225 raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
227 self.changeset_id = new_relation.changeset_id
235 def update_from(new_relation, user)
236 Relation.transaction do
238 check_consistency(self, new_relation, user)
239 unless new_relation.preconditions_ok?(self.members)
240 raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
242 self.changeset_id = new_relation.changeset_id
243 self.changeset = new_relation.changeset
244 self.tags = new_relation.tags
245 self.members = new_relation.members
251 def create_with_history(user)
252 check_create_consistency(self, user)
253 unless self.preconditions_ok?
254 raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
261 def preconditions_ok?(good_members = [])
262 # These are hastables that store an id in the index of all
263 # the nodes/way/relations that have already been added.
264 # If the member is valid and visible then we add it to the
265 # relevant hash table, with the value true as a cache.
266 # Thus if you have nodes with the ids of 50 and 1 already in the
267 # relation, then the hash table nodes would contain:
268 # => {50=>true, 1=>true}
269 elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
271 # pre-set all existing members to good
272 good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
274 self.members.each do |m|
275 # find the hash for the element type or die
276 hash = elements[m[0].downcase.to_sym] or return false
277 # unless its in the cache already
278 unless hash.key? m[1]
279 # use reflection to look up the appropriate class
280 model = Kernel.const_get(m[0].capitalize)
281 # get the element with that ID
282 element = model.find(:first, :conditions =>["id = ?", m[1]])
284 # and check that it is OK to use.
285 unless element and element.visible? and element.preconditions_ok?
286 raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
295 # Temporary method to match interface to nodes
301 # if any members are referenced by placeholder IDs (i.e: negative) then
302 # this calling this method will fix them using the map from placeholders
304 def fix_placeholders!(id_map, placeholder_id = nil)
305 self.members.map! do |type, id, role|
308 new_id = id_map[type.downcase.to_sym][old_id]
309 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?
319 def save_with_history!
320 Relation.transaction do
321 # have to be a little bit clever here - to detect if any tags
322 # changed then we have to monitor their before and after state.
330 tags = self.tags.clone
331 self.relation_tags.each do |old_tag|
333 # if we can match the tags we currently have to the list
334 # of old tags, then we never set the tags_changed flag. but
335 # if any are different then set the flag and do the DB
338 tags_changed |= (old_tag.v != tags[key])
340 # remove from the map, so that we can expect an empty map
341 # at the end if there are no new tags
345 # this means a tag was deleted
349 # if there are left-over tags then they are new and will have to
351 tags_changed |= (not tags.empty?)
352 RelationTag.delete_all(:id => self.id)
353 self.tags.each do |k,v|
354 tag = RelationTag.new
361 # same pattern as before, but this time we're collecting the
362 # changed members in an array, as the bounding box updates for
363 # elements are per-element, not blanked on/off like for tags.
364 changed_members = Array.new
365 members = self.members.clone
366 self.relation_members.each do |old_member|
367 key = [old_member.member_type, old_member.member_id, old_member.member_role]
368 i = members.index key
370 changed_members << key
375 # any remaining members must be new additions
376 changed_members += members
378 # update the members. first delete all the old members, as the new
379 # members may be in a different order and i don't feel like implementing
380 # a longest common subsequence algorithm to optimise this.
381 members = self.members
382 RelationMember.delete_all(:id => self.id)
383 members.each_with_index do |m,i|
384 mem = RelationMember.new
385 mem.id = [self.id, i]
386 mem.member_type = m[0]
388 mem.member_role = m[2]
392 old_relation = OldRelation.from_relation(self)
393 old_relation.timestamp = t
394 old_relation.save_with_dependencies!
396 # update the bbox of the changeset and save it too.
397 # discussion on the mailing list gave the following definition for
398 # the bounding box update procedure of a relation:
400 # adding or removing nodes or ways from a relation causes them to be
401 # added to the changeset bounding box. adding a relation member or
402 # changing tag values causes all node and way members to be added to the
403 # bounding box. this is similar to how the map call does things and is
404 # reasonable on the assumption that adding or removing members doesn't
405 # materially change the rest of the relation.
407 changed_members.collect { |id,type| type == "relation" }.
408 inject(false) { |b,s| b or s }
410 update_members = if tags_changed or any_relations
411 # add all non-relation bounding boxes to the changeset
412 # FIXME: check for tag changes along with element deletions and
413 # make sure that the deleted element's bounding box is hit.
418 update_members.each do |type, id, role|
419 if type != "Relation"
420 update_changeset_element(type, id)
424 # tell the changeset we updated one element only
425 changeset.add_changes! 1
427 # save the (maybe updated) changeset bounding box