1 # frozen_string_literal: true
3 # == Schema Information
5 # Table name: current_nodes
7 # id :bigint not null, primary key
8 # latitude :integer not null
9 # longitude :integer not null
10 # changeset_id :bigint not null
11 # visible :boolean not null
12 # timestamp :datetime not null
13 # tile :bigint not null
14 # version :bigint not null
18 # current_nodes_tile_idx (tile)
19 # current_nodes_timestamp_idx (timestamp)
23 # current_nodes_changeset_id_fkey (changeset_id => changesets.id)
26 class Node < ApplicationRecord
30 include ConsistencyValidations
33 self.table_name = "current_nodes"
37 has_many :old_nodes, -> { order(:version) }, :inverse_of => :current_node
40 has_many :ways, :through => :way_nodes
42 has_many :element_tags, :class_name => "NodeTag"
44 has_many :old_way_nodes
45 has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
47 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
48 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
50 validates :id, :uniqueness => true, :presence => { :on => :update },
51 :numericality => { :on => :update, :only_integer => true }
52 validates :version, :presence => true,
53 :numericality => { :only_integer => true }
54 validates :latitude, :presence => true,
55 :numericality => { :only_integer => true }
56 validates :longitude, :presence => true,
57 :numericality => { :only_integer => true }
58 validates :timestamp, :presence => true
59 validates :changeset, :associated => true
60 validates :visible, :inclusion => [true, false]
62 validate :validate_position
64 scope :visible, -> { where(:visible => true) }
65 scope :invisible, -> { where(:visible => false) }
67 # Sanity check the latitude and longitude and add an error if it's broken
69 errors.add(:base, "Node is not in the world") unless in_world?
72 # Read in xml as text and return it's Node object representation
73 def self.from_xml(xml, create: false)
74 p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
76 pt = doc.find_first("//osm/node")
79 Node.from_xml_node(pt, :create => create)
81 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
83 rescue LibXML::XML::Error, ArgumentError => e
84 raise OSM::APIBadXMLError.new("node", xml, e.message)
87 def self.from_xml_node(pt, create: false)
90 raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt["lat"].nil?
91 raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt["lon"].nil?
93 node.lat = OSM.parse_float(pt["lat"], OSM::APIBadXMLError, "node", pt, "lat not a number")
94 node.lon = OSM.parse_float(pt["lon"], OSM::APIBadXMLError, "node", pt, "lon not a number")
95 raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt["changeset"].nil?
97 node.changeset_id = pt["changeset"].to_i
99 raise OSM::APIBadUserInput, "The node is outside this world" unless node.in_world?
101 # version must be present unless creating
102 raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
104 node.version = create ? 0 : pt["version"].to_i
107 raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
109 node.id = pt["id"].to_i
110 # .to_i will return 0 if there is no number that can be parsed.
111 # We want to make sure that there is no id with zero anyway
112 raise OSM::APIBadUserInput, "ID of node cannot be zero when updating." if node.id.zero?
115 # We don't care about the time, as it is explicitly set on create/update/delete
116 # We don't care about the visibility as it is implicit based on the action
117 # and set manually before the actual delete
123 # Add in any tags from the XML
124 pt.find("tag").each do |tag|
125 raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag["k"].nil?
126 raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag["v"].nil?
128 node.add_tag_key_val(tag["k"], tag["v"])
135 # the bounding box around a node, which is used for determining the changeset's
138 BoundingBox.new(longitude, latitude, longitude, latitude)
141 # Should probably be renamed delete_from to come in line with update
142 def delete_with_history!(new_node, user)
143 raise OSM::APIAlreadyDeletedError.new("node", new_node.id) unless visible
145 # need to start the transaction here, so that the database can
146 # provide repeatable reads for the used-by checks. this means it
147 # shouldn't be possible to get race conditions.
150 check_update_element_consistency(self, new_node, user)
151 ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
152 raise OSM::APIPreconditionFailedError, "Node #{id} is still used by ways #{ways.collect(&:id).join(',')}." unless ways.empty?
154 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
155 raise OSM::APIPreconditionFailedError, "Node #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
157 self.changeset_id = new_node.changeset_id
161 # update the changeset with the deleted position
162 changeset.update_bbox!(bbox)
164 changeset.num_deleted_nodes += 1
170 def update_from(new_node, user)
173 check_update_element_consistency(self, new_node, user)
175 # update changeset first
176 self.changeset_id = new_node.changeset_id
177 self.changeset = new_node.changeset
179 # update changeset bbox with *old* position first
180 changeset.update_bbox!(bbox)
182 # FIXME: logic needs to be double checked
183 self.latitude = new_node.latitude
184 self.longitude = new_node.longitude
185 self.tags = new_node.tags
188 # update changeset bbox with *new* position
189 changeset.update_bbox!(bbox)
191 changeset.num_modified_nodes += 1
197 def create_with_history(user)
198 check_create_element_consistency(self, user)
202 # update the changeset to include the new location
203 changeset.update_bbox!(bbox)
205 changeset.num_created_nodes += 1
211 @tags ||= element_tags.to_h { |t| [t.k, t.v] }
216 def add_tag_key_val(k, v)
219 # duplicate tags are now forbidden, so we can't allow values
220 # in the hash to be overwritten.
221 raise OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
227 # are the preconditions OK? this is mainly here to keep the duck
228 # typing interface the same between nodes, ways and relations.
229 def preconditions_ok?
234 # dummy method to make the interfaces of node, way and relation
236 def fix_placeholders!(_id_map, _placeholder_id = nil)
237 # nodes don't refer to anything, so there is nothing to do here
242 def save_with_history!
249 # clone the object before saving it so that the original is
250 # still marked as dirty if we retry the transaction
255 NodeTag.where(:node_id => id).delete_all
265 old_node = OldNode.from_node(self)
266 old_node.timestamp = t
267 old_node.save_with_dependencies!
269 # tell the changeset we updated one element only
270 changeset.add_changes! 1
272 # save the changeset in case of bounding box updates