1 class Node < ActiveRecord::Base
5 include ConsistencyValidations
7 set_table_name 'current_nodes'
11 has_many :old_nodes, :order => :version
14 has_many :ways, :through => :way_nodes
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 scope :visible, where(:visible => true)
34 scope :invisible, where(:visible => false)
36 # Sanity check the latitude and longitude and add an error if it's broken
38 errors.add(:base, "Node is not in the world") unless in_world?
42 # Search for nodes matching tags within bounding_box
44 # Also adheres to limitations such as within max_number_of_nodes
46 def self.search(bounding_box, tags = {})
47 # @fixme a bit of a hack to search for only visible nodes
48 # couldn't think of another to add to tags condition
49 #conditions_hash = tags.merge({ 'visible' => 1 })
51 # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
55 #conditions_hash.each do |key,value|
56 # keys << "#{key} = :#{key}"
57 # values[key.to_sym] = value
59 #conditions = keys.join(' AND ')
61 find_by_area(bounding_box, :conditions => {:visible => true},
62 :limit => MAX_NUMBER_OF_NODES+1)
65 # Read in xml as text and return it's Node object representation
66 def self.from_xml(xml, create=false)
68 p = XML::Parser.string(xml)
71 doc.find('//osm/node').each do |pt|
72 return Node.from_xml_node(pt, create)
74 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
75 rescue LibXML::XML::Error, ArgumentError => ex
76 raise OSM::APIBadXMLError.new("node", xml, ex.message)
80 def self.from_xml_node(pt, create=false)
83 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
84 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
85 node.lat = pt['lat'].to_f
86 node.lon = pt['lon'].to_f
87 raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
88 node.changeset_id = pt['changeset'].to_i
90 raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
92 # version must be present unless creating
93 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
94 node.version = create ? 0 : pt['version'].to_i
97 raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
98 node.id = pt['id'].to_i
99 # .to_i will return 0 if there is no number that can be parsed.
100 # We want to make sure that there is no id with zero anyway
101 raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
104 # We don't care about the time, as it is explicitly set on create/update/delete
105 # We don't care about the visibility as it is implicit based on the action
106 # and set manually before the actual delete
109 pt.find('tag').each do |tag|
110 raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
111 raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
112 node.add_tag_key_val(tag['k'],tag['v'])
119 # the bounding box around a node, which is used for determining the changeset's
122 BoundingBox.new(longitude, latitude, longitude, latitude)
125 # Should probably be renamed delete_from to come in line with update
126 def delete_with_history!(new_node, user)
128 raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
131 # need to start the transaction here, so that the database can
132 # provide repeatable reads for the used-by checks. this means it
133 # shouldn't be possible to get race conditions.
136 check_consistency(self, new_node, user)
137 ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
138 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
140 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
141 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
143 self.changeset_id = new_node.changeset_id
147 # update the changeset with the deleted position
148 changeset.update_bbox!(bbox)
154 def update_from(new_node, user)
157 check_consistency(self, new_node, user)
159 # update changeset first
160 self.changeset_id = new_node.changeset_id
161 self.changeset = new_node.changeset
163 # update changeset bbox with *old* position first
164 changeset.update_bbox!(bbox);
166 # FIXME logic needs to be double checked
167 self.latitude = new_node.latitude
168 self.longitude = new_node.longitude
169 self.tags = new_node.tags
172 # update changeset bbox with *new* position
173 changeset.update_bbox!(bbox);
179 def create_with_history(user)
180 check_create_consistency(self, user)
184 # update the changeset to include the new location
185 changeset.update_bbox!(bbox)
191 doc = OSM::API.new.get_xml_doc
192 doc.root << to_xml_node()
196 def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
197 el1 = XML::Node.new 'node'
198 el1['id'] = self.id.to_s
199 el1['lat'] = self.lat.to_s
200 el1['lon'] = self.lon.to_s
201 el1['version'] = self.version.to_s
202 el1['changeset'] = self.changeset_id.to_s
204 if changeset_cache.key?(self.changeset_id)
205 # use the cache if available
207 changeset_cache[self.changeset_id] = self.changeset.user_id
210 user_id = changeset_cache[self.changeset_id]
212 if user_display_name_cache.key?(user_id)
213 # use the cache if available
214 elsif self.changeset.user.data_public?
215 user_display_name_cache[user_id] = self.changeset.user.display_name
217 user_display_name_cache[user_id] = nil
220 if not user_display_name_cache[user_id].nil?
221 el1['user'] = user_display_name_cache[user_id]
222 el1['uid'] = user_id.to_s
225 self.tags.each do |k,v|
226 el2 = XML::Node.new('tag')
232 el1['visible'] = self.visible.to_s
233 el1['timestamp'] = self.timestamp.xmlschema
244 self.node_tags.each do |tag|
255 def add_tag_key_val(k,v)
256 @tags = Hash.new unless @tags
258 # duplicate tags are now forbidden, so we can't allow values
259 # in the hash to be overwritten.
260 raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
266 # are the preconditions OK? this is mainly here to keep the duck
267 # typing interface the same between nodes, ways and relations.
268 def preconditions_ok?
273 # dummy method to make the interfaces of node, way and relation
275 def fix_placeholders!(id_map, placeholder_id = nil)
276 # nodes don't refer to anything, so there is nothing to do here
281 def save_with_history!
290 NodeTag.delete_all(:node_id => self.id)
293 tag.node_id = self.id
300 old_node = OldNode.from_node(self)
301 old_node.timestamp = t
302 old_node.save_with_dependencies!
304 # tell the changeset we updated one element only
305 changeset.add_changes! 1
307 # save the changeset in case of bounding box updates