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'
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 def self.from_xml(xml, create=false)
24 doc.find('//osm/relation').each do |pt|
25 return Relation.from_xml_node(pt, create)
32 def self.from_xml_node(pt, create=false)
33 relation = Relation.new
35 if !create and pt['id'] != '0'
36 relation.id = pt['id'].to_i
39 relation.version = pt['version']
40 relation.changeset_id = pt['changeset']
43 relation.timestamp = Time.now
44 relation.visible = true
47 relation.timestamp = Time.parse(pt['timestamp'])
51 pt.find('tag').each do |tag|
52 relation.add_tag_keyval(tag['k'], tag['v'])
55 pt.find('member').each do |member|
56 relation.add_member(member['type'], member['ref'], member['role'])
63 doc = OSM::API.new.get_xml_doc
64 doc.root << to_xml_node()
68 def to_xml_node(user_display_name_cache = nil)
69 el1 = XML::Node.new 'relation'
70 el1['id'] = self.id.to_s
71 el1['visible'] = self.visible.to_s
72 el1['timestamp'] = self.timestamp.xmlschema
73 el1['version'] = self.version.to_s
74 el1['changeset'] = self.changeset_id.to_s
76 user_display_name_cache = {} if user_display_name_cache.nil?
78 if user_display_name_cache and user_display_name_cache.key?(self.changeset.user_id)
79 # use the cache if available
80 elsif self.changeset.user.data_public?
81 user_display_name_cache[self.changeset.user_id] = self.changeset.user.display_name
83 user_display_name_cache[self.changeset.user_id] = nil
86 el1['user'] = user_display_name_cache[self.changeset.user_id] unless user_display_name_cache[self.changeset.user_id].nil?
88 self.relation_members.each do |member|
91 # # if there is a list of visible members then use that to weed out deleted segments
92 # if visible_members[member.member_type][member.member_id]
96 # otherwise, manually go to the db to check things
97 if member.member.visible?
102 e = XML::Node.new 'member'
103 e['type'] = member.member_type
104 e['ref'] = member.member_id.to_s
105 e['role'] = member.member_role
110 self.relation_tags.each do |tag|
111 e = XML::Node.new 'tag'
119 def self.find_for_nodes(ids, options = {})
123 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
124 return self.find(:all, options)
129 def self.find_for_ways(ids, options = {})
133 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
134 return self.find(:all, options)
139 def self.find_for_relations(ids, options = {})
143 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
144 return self.find(:all, options)
149 # FIXME is this really needed?
153 self.relation_members.each do |member|
154 @members += [[member.member_type,member.member_id,member.member_role]]
163 self.relation_tags.each do |tag|
178 def add_member(type,id,role)
179 @members = Array.new unless @members
180 @members += [[type,id,role]]
183 def add_tag_keyval(k, v)
184 @tags = Hash.new unless @tags
186 # duplicate tags are now forbidden, so we can't allow values
187 # in the hash to be overwritten.
188 raise OSM::APIDuplicateTagsError.new if @tags.include? k
193 def save_with_history!
194 Relation.transaction do
195 # have to be a little bit clever here - to detect if any tags
196 # changed then we have to monitor their before and after state.
205 self.relation_tags.each do |old_tag|
207 # if we can match the tags we currently have to the list
208 # of old tags, then we never set the tags_changed flag. but
209 # if any are different then set the flag and do the DB
212 # rails 2.1 dirty handling should take care of making this
213 # somewhat efficient... hopefully...
214 old_tag.v = tags[key]
215 tags_changed |= old_tag.changed?
218 # remove from the map, so that we can expect an empty map
219 # at the end if there are no new tags
223 # this means a tag was deleted
225 RelationTag.delete_all ['id = ? and k = ?', self.id, old_tag.k]
228 # if there are left-over tags then they are new and will have to
230 tags_changed |= (not tags.empty?)
232 tag = RelationTag.new
239 # same pattern as before, but this time we're collecting the
240 # changed members in an array, as the bounding box updates for
241 # elements are per-element, not blanked on/off like for tags.
242 changed_members = Array.new
243 members = self.members_as_hash
244 relation_members.each do |old_member|
245 key = [old_member.member_id.to_s, old_member.member_type]
246 if members.has_key? key
247 # i'd love to rely on rails' dirty handling here, but the
248 # relation members are always dirty because of the member_class
250 if members[key] != old_member.member_role
251 old_member.member_role = members[key]
252 changed_members << key
258 changed_members << key
259 RelationMember.delete_all ['id = ? and member_id = ? and member_type = ?', self.id, old_member.member_id, old_member.member_type]
262 # any remaining members must be new additions
263 changed_members += members.keys
264 members.each do |k,v|
265 mem = RelationMember.new
267 mem.member_type = k[1];
268 mem.member_id = k[0];
273 old_relation = OldRelation.from_relation(self)
274 old_relation.timestamp = t
275 old_relation.save_with_dependencies!
277 # update the bbox of the changeset and save it too.
278 # discussion on the mailing list gave the following definition for
279 # the bounding box update procedure of a relation:
281 # adding or removing nodes or ways from a relation causes them to be
282 # added to the changeset bounding box. adding a relation member or
283 # changing tag values causes all node and way members to be added to the
284 # bounding box. this is similar to how the map call does things and is
285 # reasonable on the assumption that adding or removing members doesn't
286 # materially change the rest of the relation.
288 changed_members.collect { |id,type| type == "relation" }.
289 inject(false) { |b,s| b or s }
291 if tags_changed or any_relations
292 # add all non-relation bounding boxes to the changeset
293 # FIXME: check for tag changes along with element deletions and
294 # make sure that the deleted element's bounding box is hit.
295 self.members.each do |type, id, role|
296 if type != "relation"
297 update_changeset_element(type, id)
301 # add only changed members to the changeset
302 changed_members.each do |id, type|
303 update_changeset_element(type, id)
307 # save the (maybe updated) changeset bounding box
313 # updates the changeset bounding box to contain the bounding box of
314 # the element with given +type+ and +id+. this only works with nodes
315 # and ways at the moment, as they're the only elements to respond to
317 def update_changeset_element(type, id)
318 element = Kernel.const_get(type.capitalize).find(id)
319 changeset.update_bbox! element.bbox
322 def delete_with_history!(new_relation, user)
324 check_consistency(self, new_relation, user)
325 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 ])
326 raise OSM::APIPreconditionFailedError.new
328 self.changeset_id = new_relation.changeset_id
335 raise OSM::APIAlreadyDeletedError.new
339 def update_from(new_relation, user)
340 check_consistency(self, new_relation, user)
341 if !new_relation.preconditions_ok?
342 raise OSM::APIPreconditionFailedError.new
344 self.changeset_id = new_relation.changeset_id
345 self.tags = new_relation.tags
346 self.members = new_relation.members
351 def create_with_history(user)
352 check_create_consistency(self, user)
353 if !self.preconditions_ok?
354 raise OSM::APIPreconditionFailedError.new
361 def preconditions_ok?
362 # These are hastables that store an id in the index of all
363 # the nodes/way/relations that have already been added.
364 # Once we know the id of the node/way/relation exists
365 # we check to see if it is already existing in the hashtable
366 # if it does, then we return false. Otherwise
367 # we add it to the relevant hash table, with the value true..
368 # Thus if you have nodes with the ids of 50 and 1 already in the
369 # relation, then the hash table nodes would contain:
370 # => {50=>true, 1=>true}
374 self.members.each do |m|
376 n = Node.find(:first, :conditions => ["id = ?", m[1]])
377 unless n and n.visible
385 elsif (m[0] == "way")
386 w = Way.find(:first, :conditions => ["id = ?", m[1]])
387 unless w and w.visible and w.preconditions_ok?
395 elsif (m[0] == "relation")
396 e = Relation.find(:first, :conditions => ["id = ?", m[1]])
397 unless e and e.visible and e.preconditions_ok?
403 relations[m[1]] = true
415 # members in a hash table [id,type] => role
419 # should be: h[[m.id, m.type]] = m.role, but someone prefers arrays
420 h[[m[1], m[0]]] = m[2]
425 # Temporary method to match interface to nodes
431 # if any members are referenced by placeholder IDs (i.e: negative) then
432 # this calling this method will fix them using the map from placeholders
434 def fix_placeholders!(id_map)
435 self.members.map! do |type, id, role|
438 new_id = id_map[type.to_sym][old_id]
439 raise "invalid placeholder" if new_id.nil?