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?
42 # Read in xml as text and return it's Node object representation
43 def self.from_xml(xml, create=false)
45 p = XML::Parser.string(xml)
48 doc.find('//osm/node').each do |pt|
49 return Node.from_xml_node(pt, create)
51 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
52 rescue LibXML::XML::Error, ArgumentError => ex
53 raise OSM::APIBadXMLError.new("node", xml, ex.message)
57 def self.from_xml_node(pt, create=false)
60 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
61 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
62 node.lat = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number")
63 node.lon = OSM.parse_float(pt['lon'], OSM::APIBadXMLError, "node", pt, "lon not a number")
64 raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
65 node.changeset_id = pt['changeset'].to_i
67 raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
69 # version must be present unless creating
70 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
71 node.version = create ? 0 : pt['version'].to_i
74 raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
75 node.id = pt['id'].to_i
76 # .to_i will return 0 if there is no number that can be parsed.
77 # We want to make sure that there is no id with zero anyway
78 raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
81 # We don't care about the time, as it is explicitly set on create/update/delete
82 # We don't care about the visibility as it is implicit based on the action
83 # and set manually before the actual delete
89 # Add in any tags from the XML
90 pt.find('tag').each do |tag|
91 raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
92 raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
93 node.add_tag_key_val(tag['k'],tag['v'])
100 # the bounding box around a node, which is used for determining the changeset's
103 BoundingBox.new(longitude, latitude, longitude, latitude)
106 # Should probably be renamed delete_from to come in line with update
107 def delete_with_history!(new_node, user)
109 raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
112 # need to start the transaction here, so that the database can
113 # provide repeatable reads for the used-by checks. this means it
114 # shouldn't be possible to get race conditions.
117 check_consistency(self, new_node, user)
118 ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
119 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
121 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
122 raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
124 self.changeset_id = new_node.changeset_id
128 # update the changeset with the deleted position
129 changeset.update_bbox!(bbox)
135 def update_from(new_node, user)
138 check_consistency(self, new_node, user)
140 # update changeset first
141 self.changeset_id = new_node.changeset_id
142 self.changeset = new_node.changeset
144 # update changeset bbox with *old* position first
145 changeset.update_bbox!(bbox);
147 # FIXME logic needs to be double checked
148 self.latitude = new_node.latitude
149 self.longitude = new_node.longitude
150 self.tags = new_node.tags
153 # update changeset bbox with *new* position
154 changeset.update_bbox!(bbox);
160 def create_with_history(user)
161 check_create_consistency(self, user)
165 # update the changeset to include the new location
166 changeset.update_bbox!(bbox)
172 doc = OSM::API.new.get_xml_doc
173 doc.root << to_xml_node()
177 def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
178 el1 = XML::Node.new 'node'
179 el1['id'] = self.id.to_s
180 el1['version'] = self.version.to_s
181 el1['changeset'] = self.changeset_id.to_s
184 el1['lat'] = self.lat.to_s
185 el1['lon'] = self.lon.to_s
188 if changeset_cache.key?(self.changeset_id)
189 # use the cache if available
191 changeset_cache[self.changeset_id] = self.changeset.user_id
194 user_id = changeset_cache[self.changeset_id]
196 if user_display_name_cache.key?(user_id)
197 # use the cache if available
198 elsif self.changeset.user.data_public?
199 user_display_name_cache[user_id] = self.changeset.user.display_name
201 user_display_name_cache[user_id] = nil
204 if not user_display_name_cache[user_id].nil?
205 el1['user'] = user_display_name_cache[user_id]
206 el1['uid'] = user_id.to_s
209 self.tags.each do |k,v|
210 el2 = XML::Node.new('tag')
216 el1['visible'] = self.visible.to_s
217 el1['timestamp'] = self.timestamp.xmlschema
228 self.node_tags.each do |tag|
239 def add_tag_key_val(k,v)
240 @tags = Hash.new unless @tags
242 # duplicate tags are now forbidden, so we can't allow values
243 # in the hash to be overwritten.
244 raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
250 # are the preconditions OK? this is mainly here to keep the duck
251 # typing interface the same between nodes, ways and relations.
252 def preconditions_ok?
257 # dummy method to make the interfaces of node, way and relation
259 def fix_placeholders!(id_map, placeholder_id = nil)
260 # nodes don't refer to anything, so there is nothing to do here
265 def save_with_history!
274 NodeTag.delete_all(:node_id => self.id)
277 tag.node_id = self.id
284 old_node = OldNode.from_node(self)
285 old_node.timestamp = t
286 old_node.save_with_dependencies!
288 # tell the changeset we updated one element only
289 changeset.add_changes! 1
291 # save the changeset in case of bounding box updates