1 class Node < ActiveRecord::Base
5 include ConsistencyValidations
7 set_table_name 'current_nodes'
11 has_many :old_nodes, :foreign_key => :id
14 has_many :ways, :through => :way_nodes
16 has_many :node_tags, :foreign_key => :id
18 has_many :old_way_nodes
19 has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
21 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
22 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
24 validates_presence_of :id, :on => :update
25 validates_presence_of :timestamp,:version, :changeset_id
26 validates_uniqueness_of :id
27 validates_inclusion_of :visible, :in => [ true, false ]
28 validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
29 validates_numericality_of :id, :on => :update, :integer_only => true
30 validate :validate_position
31 validates_associated :changeset
33 # Sanity check the latitude and longitude and add an error if it's broken
35 errors.add_to_base("Node is not in the world") unless in_world?
39 # Search for nodes matching tags within bounding_box
41 # Also adheres to limitations such as within max_number_of_nodes
43 def self.search(bounding_box, tags = {})
44 min_lon, min_lat, max_lon, max_lat = *bounding_box
45 # @fixme a bit of a hack to search for only visible nodes
46 # couldn't think of another to add to tags condition
47 #conditions_hash = tags.merge({ 'visible' => 1 })
49 # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
53 #conditions_hash.each do |key,value|
54 # keys << "#{key} = :#{key}"
55 # values[key.to_sym] = value
57 #conditions = keys.join(' AND ')
59 find_by_area(min_lat, min_lon, max_lat, max_lon,
60 :conditions => {:visible => true},
61 :limit => APP_CONFIG['max_number_of_nodes']+1)
64 # Read in xml as text and return it's Node object representation
65 def self.from_xml(xml, create=false)
67 p = XML::Parser.string(xml)
70 doc.find('//osm/node').each do |pt|
71 return Node.from_xml_node(pt, create)
73 rescue LibXML::XML::Error, ArgumentError => ex
74 raise OSM::APIBadXMLError.new("node", xml, ex.message)
78 def self.from_xml_node(pt, create=false)
81 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
82 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
83 node.lat = pt['lat'].to_f
84 node.lon = pt['lon'].to_f
85 raise OSM::APIBadXMLError.new("node", pt, "changeset id missing") if pt['changeset'].nil?
86 node.changeset_id = pt['changeset'].to_i
88 raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
90 # version must be present unless creating
91 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
92 node.version = create ? 0 : pt['version'].to_i
96 node.id = pt['id'].to_i
100 # visible if it says it is, or as the default if the attribute
102 # Don't need to set the visibility, when it is set explicitly in the create/update/delete
103 #node.visible = pt['visible'].nil? or pt['visible'] == 'true'
105 # We don't care about the time, as it is explicitly set on create/update/delete
109 pt.find('tag').each do |tag|
110 node.add_tag_key_val(tag['k'],tag['v'])
117 # the bounding box around a node, which is used for determining the changeset's
120 [ longitude, latitude, longitude, latitude ]
123 # Should probably be renamed delete_from to come in line with update
124 def delete_with_history!(new_node, user)
126 raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
129 # need to start the transaction here, so that the database can
130 # provide repeatable reads for the used-by checks. this means it
131 # shouldn't be possible to get race conditions.
133 check_consistency(self, new_node, user)
134 way = WayNode.find(:first, :joins => "INNER JOIN current_ways ON current_ways.id = current_way_nodes.id",
135 :conditions => [ "current_ways.visible = ? AND current_way_nodes.node_id = ?", true, self.id ])
136 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by way #{way.id}.") unless way.nil?
138 rel = RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id",
139 :conditions => [ "visible = ? AND member_type='Node' and member_id=? ", true, self.id])
140 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relation #{rel.relation.id}.") unless rel.nil?
142 self.changeset_id = new_node.changeset_id
145 # update the changeset with the deleted position
146 changeset.update_bbox!(bbox)
152 # As above but doesn't throw an error if node is used elsewhere - instead, just silently
153 # returns without deleting the node. Potlatch needs this in case you ask to delete an
154 # off-screen node while deleting a way - it doesn't know whether the node is used
156 def delete_with_history_unless_used!(new_node, user)
158 raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
162 check_consistency(self, new_node, user)
163 way = WayNode.find(:first, :joins => "INNER JOIN current_ways ON current_ways.id = current_way_nodes.id",
164 :conditions => [ "current_ways.visible = ? AND current_way_nodes.node_id = ?", true, self.id ])
165 rel = RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id",
166 :conditions => [ "visible = ? AND member_type='Node' and member_id=? ", true, self.id])
167 if way.nil? and rel.nil?
168 self.changeset_id = new_node.changeset_id
170 changeset.update_bbox!(bbox)
176 def update_from(new_node, user)
177 check_consistency(self, new_node, user)
179 # update changeset first
180 self.changeset_id = new_node.changeset_id
181 self.changeset = new_node.changeset
183 # update changeset bbox with *old* position first
184 changeset.update_bbox!(bbox);
186 # FIXME logic needs to be double checked
187 self.latitude = new_node.latitude
188 self.longitude = new_node.longitude
189 self.tags = new_node.tags
192 # update changeset bbox with *new* position
193 changeset.update_bbox!(bbox);
198 def create_with_history(user)
199 check_create_consistency(self, user)
203 # update the changeset to include the new location
204 changeset.update_bbox!(bbox)
210 doc = OSM::API.new.get_xml_doc
211 doc.root << to_xml_node()
215 def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
216 el1 = XML::Node.new 'node'
217 el1['id'] = self.id.to_s
218 el1['lat'] = self.lat.to_s
219 el1['lon'] = self.lon.to_s
220 el1['version'] = self.version.to_s
221 el1['changeset'] = self.changeset_id.to_s
223 if changeset_cache.key?(self.changeset_id)
224 # use the cache if available
226 changeset_cache[self.changeset_id] = self.changeset.user_id
229 user_id = changeset_cache[self.changeset_id]
231 if user_display_name_cache.key?(user_id)
232 # use the cache if available
233 elsif self.changeset.user.data_public?
234 user_display_name_cache[user_id] = self.changeset.user.display_name
236 user_display_name_cache[user_id] = nil
239 if not user_display_name_cache[user_id].nil?
240 el1['user'] = user_display_name_cache[user_id]
241 el1['uid'] = user_id.to_s
244 self.tags.each do |k,v|
245 el2 = XML::Node.new('tag')
251 el1['visible'] = self.visible.to_s
252 el1['timestamp'] = self.timestamp.xmlschema
263 self.node_tags.each do |tag|
274 def add_tag_key_val(k,v)
275 @tags = Hash.new unless @tags
277 # duplicate tags are now forbidden, so we can't allow values
278 # in the hash to be overwritten.
279 raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
285 # are the preconditions OK? this is mainly here to keep the duck
286 # typing interface the same between nodes, ways and relations.
287 def preconditions_ok?
292 # dummy method to make the interfaces of node, way and relation
294 def fix_placeholders!(id_map, placeholder_id = nil)
295 # nodes don't refer to anything, so there is nothing to do here
300 def save_with_history!
309 NodeTag.delete_all(['id = ?', self.id])
319 old_node = OldNode.from_node(self)
320 old_node.timestamp = t
321 old_node.save_with_dependencies!
323 # tell the changeset we updated one element only
324 changeset.add_changes! 1
326 # save the changeset in case of bounding box updates