1 class Node < ActiveRecord::Base
5 include ConsistencyValidations
8 self.table_name = "current_nodes"
12 has_many :old_nodes, :order => :version
15 has_many :ways, :through => :way_nodes
19 has_many :old_way_nodes
20 has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
22 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
23 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
25 validates_presence_of :id, :on => :update
26 validates_presence_of :timestamp,:version, :changeset_id
27 validates_uniqueness_of :id
28 validates_inclusion_of :visible, :in => [ true, false ]
29 validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
30 validates_numericality_of :id, :on => :update, :integer_only => true
31 validate :validate_position
32 validates_associated :changeset
34 scope :visible, where(:visible => true)
35 scope :invisible, where(:visible => false)
37 # Sanity check the latitude and longitude and add an error if it's broken
39 errors.add(:base, "Node is not in the world") unless in_world?
43 # Search for nodes matching tags within bounding_box
45 # Also adheres to limitations such as within max_number_of_nodes
47 def self.search(bounding_box, tags = {})
48 # @fixme a bit of a hack to search for only visible nodes
49 # couldn't think of another to add to tags condition
50 #conditions_hash = tags.merge({ 'visible' => 1 })
52 # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
56 #conditions_hash.each do |key,value|
57 # keys << "#{key} = :#{key}"
58 # values[key.to_sym] = value
60 #conditions = keys.join(' AND ')
62 find_by_area(bounding_box, :conditions => {:visible => true},
63 :limit => MAX_NUMBER_OF_NODES+1)
66 # Read in xml as text and return it's Node object representation
67 def self.from_xml(xml, create=false)
69 p = XML::Parser.string(xml)
72 doc.find('//osm/node').each do |pt|
73 return Node.from_xml_node(pt, create)
75 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
76 rescue LibXML::XML::Error, ArgumentError => ex
77 raise OSM::APIBadXMLError.new("node", xml, ex.message)
81 def self.from_xml_node(pt, create=false)
84 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
85 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
86 node.lat = pt['lat'].to_f
87 node.lon = pt['lon'].to_f
88 raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
89 node.changeset_id = pt['changeset'].to_i
91 raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
93 # version must be present unless creating
94 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
95 node.version = create ? 0 : pt['version'].to_i
98 raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
99 node.id = pt['id'].to_i
100 # .to_i will return 0 if there is no number that can be parsed.
101 # We want to make sure that there is no id with zero anyway
102 raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
105 # We don't care about the time, as it is explicitly set on create/update/delete
106 # We don't care about the visibility as it is implicit based on the action
107 # and set manually before the actual delete
113 # Add in any tags from the XML
114 pt.find('tag').each do |tag|
115 raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
116 raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
117 node.add_tag_key_val(tag['k'],tag['v'])
124 # the bounding box around a node, which is used for determining the changeset's
127 BoundingBox.new(longitude, latitude, longitude, latitude)
130 # Should probably be renamed delete_from to come in line with update
131 def delete_with_history!(new_node, user)
133 raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
136 # need to start the transaction here, so that the database can
137 # provide repeatable reads for the used-by checks. this means it
138 # shouldn't be possible to get race conditions.
141 check_consistency(self, new_node, user)
142 ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
143 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
145 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
146 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
148 self.changeset_id = new_node.changeset_id
152 # update the changeset with the deleted position
153 changeset.update_bbox!(bbox)
159 def update_from(new_node, user)
162 check_consistency(self, new_node, user)
164 # update changeset first
165 self.changeset_id = new_node.changeset_id
166 self.changeset = new_node.changeset
168 # update changeset bbox with *old* position first
169 changeset.update_bbox!(bbox);
171 # FIXME logic needs to be double checked
172 self.latitude = new_node.latitude
173 self.longitude = new_node.longitude
174 self.tags = new_node.tags
177 # update changeset bbox with *new* position
178 changeset.update_bbox!(bbox);
184 def create_with_history(user)
185 check_create_consistency(self, user)
189 # update the changeset to include the new location
190 changeset.update_bbox!(bbox)
196 doc = OSM::API.new.get_xml_doc
197 doc.root << to_xml_node()
201 def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
202 el1 = XML::Node.new 'node'
203 el1['id'] = self.id.to_s
204 el1['version'] = self.version.to_s
205 el1['changeset'] = self.changeset_id.to_s
208 el1['lat'] = self.lat.to_s
209 el1['lon'] = self.lon.to_s
212 if changeset_cache.key?(self.changeset_id)
213 # use the cache if available
215 changeset_cache[self.changeset_id] = self.changeset.user_id
218 user_id = changeset_cache[self.changeset_id]
220 if user_display_name_cache.key?(user_id)
221 # use the cache if available
222 elsif self.changeset.user.data_public?
223 user_display_name_cache[user_id] = self.changeset.user.display_name
225 user_display_name_cache[user_id] = nil
228 if not user_display_name_cache[user_id].nil?
229 el1['user'] = user_display_name_cache[user_id]
230 el1['uid'] = user_id.to_s
233 self.tags.each do |k,v|
234 el2 = XML::Node.new('tag')
240 el1['visible'] = self.visible.to_s
241 el1['timestamp'] = self.timestamp.xmlschema
252 self.node_tags.each do |tag|
263 def add_tag_key_val(k,v)
264 @tags = Hash.new unless @tags
266 # duplicate tags are now forbidden, so we can't allow values
267 # in the hash to be overwritten.
268 raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
274 # are the preconditions OK? this is mainly here to keep the duck
275 # typing interface the same between nodes, ways and relations.
276 def preconditions_ok?
281 # dummy method to make the interfaces of node, way and relation
283 def fix_placeholders!(id_map, placeholder_id = nil)
284 # nodes don't refer to anything, so there is nothing to do here
289 def save_with_history!
298 NodeTag.delete_all(:node_id => self.id)
301 tag.node_id = self.id
308 old_node = OldNode.from_node(self)
309 old_node.timestamp = t
310 old_node.save_with_dependencies!
312 # tell the changeset we updated one element only
313 changeset.add_changes! 1
315 # save the changeset in case of bounding box updates