]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Fix new rubocop warnings
[rails.git] / app / models / node.rb
1 # == Schema Information
2 #
3 # Table name: current_nodes
4 #
5 #  id           :bigint(8)        not null, primary key
6 #  latitude     :integer          not null
7 #  longitude    :integer          not null
8 #  changeset_id :bigint(8)        not null
9 #  visible      :boolean          not null
10 #  timestamp    :datetime         not null
11 #  tile         :bigint(8)        not null
12 #  version      :bigint(8)        not null
13 #
14 # Indexes
15 #
16 #  current_nodes_tile_idx       (tile)
17 #  current_nodes_timestamp_idx  (timestamp)
18 #
19 # Foreign Keys
20 #
21 #  current_nodes_changeset_id_fkey  (changeset_id => changesets.id)
22 #
23
24 class Node < ApplicationRecord
25   require "xml/libxml"
26
27   include GeoRecord
28   include ConsistencyValidations
29   include NotRedactable
30
31   self.table_name = "current_nodes"
32
33   belongs_to :changeset
34
35   has_many :old_nodes, -> { order(:version) }
36
37   has_many :way_nodes
38   has_many :ways, :through => :way_nodes
39
40   has_many :node_tags
41
42   has_many :old_way_nodes
43   has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
44
45   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
46   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
47
48   validates :id, :uniqueness => true, :presence => { :on => :update },
49                  :numericality => { :on => :update, :only_integer => true }
50   validates :version, :presence => true,
51                       :numericality => { :only_integer => true }
52   validates :changeset_id, :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_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       save_with_history!
165     end
166   end
167
168   def update_from(new_node, user)
169     Node.transaction do
170       lock!
171       check_consistency(self, new_node, user)
172
173       # update changeset first
174       self.changeset_id = new_node.changeset_id
175       self.changeset = new_node.changeset
176
177       # update changeset bbox with *old* position first
178       changeset.update_bbox!(bbox)
179
180       # FIXME: logic needs to be double checked
181       self.latitude = new_node.latitude
182       self.longitude = new_node.longitude
183       self.tags = new_node.tags
184       self.visible = true
185
186       # update changeset bbox with *new* position
187       changeset.update_bbox!(bbox)
188
189       save_with_history!
190     end
191   end
192
193   def create_with_history(user)
194     check_create_consistency(self, user)
195     self.version = 0
196     self.visible = true
197
198     # update the changeset to include the new location
199     changeset.update_bbox!(bbox)
200
201     save_with_history!
202   end
203
204   def tags_as_hash
205     tags
206   end
207
208   def tags
209     @tags ||= node_tags.to_h { |t| [t.k, t.v] }
210   end
211
212   attr_writer :tags
213
214   def add_tag_key_val(k, v)
215     @tags ||= {}
216
217     # duplicate tags are now forbidden, so we can't allow values
218     # in the hash to be overwritten.
219     raise OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
220
221     @tags[k] = v
222   end
223
224   ##
225   # are the preconditions OK? this is mainly here to keep the duck
226   # typing interface the same between nodes, ways and relations.
227   def preconditions_ok?
228     in_world?
229   end
230
231   ##
232   # dummy method to make the interfaces of node, way and relation
233   # more consistent.
234   def fix_placeholders!(_id_map, _placeholder_id = nil)
235     # nodes don't refer to anything, so there is nothing to do here
236   end
237
238   private
239
240   def save_with_history!
241     t = Time.now.getutc
242
243     self.version += 1
244     self.timestamp = t
245
246     Node.transaction do
247       # clone the object before saving it so that the original is
248       # still marked as dirty if we retry the transaction
249       clone.save!
250
251       # Create a NodeTag
252       tags = self.tags
253       NodeTag.where(:node_id => id).delete_all
254       tags.each do |k, v|
255         tag = NodeTag.new
256         tag.node_id = id
257         tag.k = k
258         tag.v = v
259         tag.save!
260       end
261
262       # Create an OldNode
263       old_node = OldNode.from_node(self)
264       old_node.timestamp = t
265       old_node.save_with_dependencies!
266
267       # tell the changeset we updated one element only
268       changeset.add_changes! 1
269
270       # save the changeset in case of bounding box updates
271       changeset.save!
272     end
273   end
274 end