]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Add frozen_string_literal comments to ruby files
[rails.git] / app / models / node.rb
1 # frozen_string_literal: true
2
3 # == Schema Information
4 #
5 # Table name: current_nodes
6 #
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
15 #
16 # Indexes
17 #
18 #  current_nodes_tile_idx       (tile)
19 #  current_nodes_timestamp_idx  (timestamp)
20 #
21 # Foreign Keys
22 #
23 #  current_nodes_changeset_id_fkey  (changeset_id => changesets.id)
24 #
25
26 class Node < ApplicationRecord
27   require "xml/libxml"
28
29   include GeoRecord
30   include ConsistencyValidations
31   include NotRedactable
32
33   self.table_name = "current_nodes"
34
35   belongs_to :changeset
36
37   has_many :old_nodes, -> { order(:version) }, :inverse_of => :current_node
38
39   has_many :way_nodes
40   has_many :ways, :through => :way_nodes
41
42   has_many :element_tags, :class_name => "NodeTag"
43
44   has_many :old_way_nodes
45   has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
46
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
49
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]
61
62   validate :validate_position
63
64   scope :visible, -> { where(:visible => true) }
65   scope :invisible, -> { where(:visible => false) }
66
67   # Sanity check the latitude and longitude and add an error if it's broken
68   def validate_position
69     errors.add(:base, "Node is not in the world") unless in_world?
70   end
71
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)
75     doc = p.parse
76     pt = doc.find_first("//osm/node")
77
78     if pt
79       Node.from_xml_node(pt, :create => create)
80     else
81       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
82     end
83   rescue LibXML::XML::Error, ArgumentError => e
84     raise OSM::APIBadXMLError.new("node", xml, e.message)
85   end
86
87   def self.from_xml_node(pt, create: false)
88     node = Node.new
89
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?
92
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?
96
97     node.changeset_id = pt["changeset"].to_i
98
99     raise OSM::APIBadUserInput, "The node is outside this world" unless node.in_world?
100
101     # version must be present unless creating
102     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
103
104     node.version = create ? 0 : pt["version"].to_i
105
106     unless create
107       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
108
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?
113     end
114
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
118     node.visible = true
119
120     # Start with no tags
121     node.tags = {}
122
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?
127
128       node.add_tag_key_val(tag["k"], tag["v"])
129     end
130
131     node
132   end
133
134   ##
135   # the bounding box around a node, which is used for determining the changeset's
136   # bounding box
137   def bbox
138     BoundingBox.new(longitude, latitude, longitude, latitude)
139   end
140
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
144
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.
148     Node.transaction do
149       lock!
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?
153
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?
156
157       self.changeset_id = new_node.changeset_id
158       self.tags = {}
159       self.visible = false
160
161       # update the changeset with the deleted position
162       changeset.update_bbox!(bbox)
163
164       changeset.num_deleted_nodes += 1
165
166       save_with_history!
167     end
168   end
169
170   def update_from(new_node, user)
171     Node.transaction do
172       lock!
173       check_update_element_consistency(self, new_node, user)
174
175       # update changeset first
176       self.changeset_id = new_node.changeset_id
177       self.changeset = new_node.changeset
178
179       # update changeset bbox with *old* position first
180       changeset.update_bbox!(bbox)
181
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
186       self.visible = true
187
188       # update changeset bbox with *new* position
189       changeset.update_bbox!(bbox)
190
191       changeset.num_modified_nodes += 1
192
193       save_with_history!
194     end
195   end
196
197   def create_with_history(user)
198     check_create_element_consistency(self, user)
199     self.version = 0
200     self.visible = true
201
202     # update the changeset to include the new location
203     changeset.update_bbox!(bbox)
204
205     changeset.num_created_nodes += 1
206
207     save_with_history!
208   end
209
210   def tags
211     @tags ||= element_tags.to_h { |t| [t.k, t.v] }
212   end
213
214   attr_writer :tags
215
216   def add_tag_key_val(k, v)
217     @tags ||= {}
218
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
222
223     @tags[k] = v
224   end
225
226   ##
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?
230     in_world?
231   end
232
233   ##
234   # dummy method to make the interfaces of node, way and relation
235   # more consistent.
236   def fix_placeholders!(_id_map, _placeholder_id = nil)
237     # nodes don't refer to anything, so there is nothing to do here
238   end
239
240   private
241
242   def save_with_history!
243     t = Time.now.utc
244
245     self.version += 1
246     self.timestamp = t
247
248     Node.transaction do
249       # clone the object before saving it so that the original is
250       # still marked as dirty if we retry the transaction
251       clone.save!
252
253       # Create a NodeTag
254       tags = self.tags
255       NodeTag.where(:node_id => id).delete_all
256       tags.each do |k, v|
257         tag = NodeTag.new
258         tag.node_id = id
259         tag.k = k
260         tag.v = v
261         tag.save!
262       end
263
264       # Create an OldNode
265       old_node = OldNode.from_node(self)
266       old_node.timestamp = t
267       old_node.save_with_dependencies!
268
269       # tell the changeset we updated one element only
270       changeset.add_changes! 1
271
272       # save the changeset in case of bounding box updates
273       changeset.save!
274     end
275   end
276 end