1 # == Schema Information
3 # Table name: current_nodes
5 # id :integer not null, primary key
6 # latitude :integer not null
7 # longitude :integer not null
8 # changeset_id :integer not null
9 # visible :boolean not null
10 # timestamp :datetime not null
11 # tile :integer not null
12 # version :integer not null
16 # current_nodes_tile_idx (tile)
17 # current_nodes_timestamp_idx (timestamp)
21 # current_nodes_changeset_id_fkey (changeset_id => changesets.id)
24 class Node < ActiveRecord::Base
28 include ConsistencyValidations
30 include ObjectMetadata
32 self.table_name = "current_nodes"
36 has_many :old_nodes, -> { order(:version) }
39 has_many :ways, :through => :way_nodes
43 has_many :old_way_nodes
44 has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
46 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
47 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
49 validates :id, :uniqueness => true, :presence => { :on => :update },
50 :numericality => { :on => :update, :integer_only => true }
51 validates :version, :presence => true,
52 :numericality => { :integer_only => true }
53 validates :changeset_id, :presence => true,
54 :numericality => { :integer_only => true }
55 validates :latitude, :presence => true,
56 :numericality => { :integer_only => true }
57 validates :longitude, :presence => true,
58 :numericality => { :integer_only => true }
59 validates :timestamp, :presence => true
60 validates :changeset, :associated => true
61 validates :visible, :inclusion => [true, false]
63 validate :validate_position
65 scope :visible, -> { where(:visible => true) }
66 scope :invisible, -> { where(:visible => false) }
68 # Sanity check the latitude and longitude and add an error if it's broken
70 errors.add(:base, "Node is not in the world") unless in_world?
73 # Read in xml as text and return it's Node object representation
74 def self.from_xml(xml, create = false)
75 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
78 doc.find("//osm/node").each do |pt|
79 return Node.from_xml_node(pt, create)
81 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
82 rescue LibXML::XML::Error, ArgumentError => ex
83 raise OSM::APIBadXMLError.new("node", xml, ex.message)
86 def self.from_xml_node(pt, create = false)
89 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt["lat"].nil?
90 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt["lon"].nil?
91 node.lat = OSM.parse_float(pt["lat"], OSM::APIBadXMLError, "node", pt, "lat not a number")
92 node.lon = OSM.parse_float(pt["lon"], OSM::APIBadXMLError, "node", pt, "lon not a number")
93 raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt["changeset"].nil?
94 node.changeset_id = pt["changeset"].to_i
96 raise OSM::APIBadUserInput, "The node is outside this world" unless node.in_world?
98 # version must be present unless creating
99 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
100 node.version = create ? 0 : pt["version"].to_i
103 raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
104 node.id = pt["id"].to_i
105 # .to_i will return 0 if there is no number that can be parsed.
106 # We want to make sure that there is no id with zero anyway
107 raise OSM::APIBadUserInput, "ID of node cannot be zero when updating." if node.id.zero?
110 # We don't care about the time, as it is explicitly set on create/update/delete
111 # We don't care about the visibility as it is implicit based on the action
112 # and set manually before the actual delete
118 # Add in any tags from the XML
119 pt.find("tag").each do |tag|
120 raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag["k"].nil?
121 raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag["v"].nil?
122 node.add_tag_key_val(tag["k"], tag["v"])
129 # the bounding box around a node, which is used for determining the changeset's
132 BoundingBox.new(longitude, latitude, longitude, latitude)
135 # Should probably be renamed delete_from to come in line with update
136 def delete_with_history!(new_node, user)
137 raise OSM::APIAlreadyDeletedError.new("node", new_node.id) unless visible
139 # need to start the transaction here, so that the database can
140 # provide repeatable reads for the used-by checks. this means it
141 # shouldn't be possible to get race conditions.
144 check_consistency(self, new_node, user)
145 ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
146 raise OSM::APIPreconditionFailedError, "Node #{id} is still used by ways #{ways.collect(&:id).join(',')}." unless ways.empty?
148 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
149 raise OSM::APIPreconditionFailedError, "Node #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
151 self.changeset_id = new_node.changeset_id
155 # update the changeset with the deleted position
156 changeset.update_bbox!(bbox)
162 def update_from(new_node, user)
165 check_consistency(self, new_node, user)
167 # update changeset first
168 self.changeset_id = new_node.changeset_id
169 self.changeset = new_node.changeset
171 # update changeset bbox with *old* position first
172 changeset.update_bbox!(bbox)
174 # FIXME: logic needs to be double checked
175 self.latitude = new_node.latitude
176 self.longitude = new_node.longitude
177 self.tags = new_node.tags
180 # update changeset bbox with *new* position
181 changeset.update_bbox!(bbox)
187 def create_with_history(user)
188 check_create_consistency(self, user)
192 # update the changeset to include the new location
193 changeset.update_bbox!(bbox)
199 doc = OSM::API.new.get_xml_doc
200 doc.root << to_xml_node
204 def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
205 el = XML::Node.new "node"
208 add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
215 add_tags_to_xml_node(el, node_tags)
225 @tags ||= Hash[node_tags.collect { |t| [t.k, t.v] }]
230 def add_tag_key_val(k, v)
233 # duplicate tags are now forbidden, so we can't allow values
234 # in the hash to be overwritten.
235 raise OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
241 # are the preconditions OK? this is mainly here to keep the duck
242 # typing interface the same between nodes, ways and relations.
243 def preconditions_ok?
248 # dummy method to make the interfaces of node, way and relation
250 def fix_placeholders!(_id_map, _placeholder_id = nil)
251 # nodes don't refer to anything, so there is nothing to do here
256 def save_with_history!
263 # clone the object before saving it so that the original is
264 # still marked as dirty if we retry the transaction
269 NodeTag.where(:node_id => id).delete_all
279 old_node = OldNode.from_node(self)
280 old_node.timestamp = t
281 old_node.save_with_dependencies!
283 # tell the changeset we updated one element only
284 changeset.add_changes! 1
286 # save the changeset in case of bounding box updates