]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Merge remote-tracking branch 'upstream/pull/3264'
[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   include ObjectMetadata
31
32   self.table_name = "current_nodes"
33
34   belongs_to :changeset
35
36   has_many :old_nodes, -> { order(:version) }
37
38   has_many :way_nodes
39   has_many :ways, :through => :way_nodes
40
41   has_many :node_tags
42
43   has_many :old_way_nodes
44   has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
45
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
48
49   validates :id, :uniqueness => true, :presence => { :on => :update },
50                  :numericality => { :on => :update, :only_integer => true }
51   validates :version, :presence => true,
52                       :numericality => { :only_integer => true }
53   validates :changeset_id, :presence => true,
54                            :numericality => { :only_integer => true }
55   validates :latitude, :presence => true,
56                        :numericality => { :only_integer => true }
57   validates :longitude, :presence => true,
58                         :numericality => { :only_integer => true }
59   validates :timestamp, :presence => true
60   validates :changeset, :associated => true
61   validates :visible, :inclusion => [true, false]
62
63   validate :validate_position
64
65   scope :visible, -> { where(:visible => true) }
66   scope :invisible, -> { where(:visible => false) }
67
68   # Sanity check the latitude and longitude and add an error if it's broken
69   def validate_position
70     errors.add(:base, "Node is not in the world") unless in_world?
71   end
72
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)
76     doc = p.parse
77     pt = doc.find_first("//osm/node")
78
79     if pt
80       Node.from_xml_node(pt, :create => create)
81     else
82       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
83     end
84   rescue LibXML::XML::Error, ArgumentError => e
85     raise OSM::APIBadXMLError.new("node", xml, e.message)
86   end
87
88   def self.from_xml_node(pt, create: false)
89     node = Node.new
90
91     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt["lat"].nil?
92     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt["lon"].nil?
93
94     node.lat = OSM.parse_float(pt["lat"], OSM::APIBadXMLError, "node", pt, "lat not a number")
95     node.lon = OSM.parse_float(pt["lon"], OSM::APIBadXMLError, "node", pt, "lon not a number")
96     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt["changeset"].nil?
97
98     node.changeset_id = pt["changeset"].to_i
99
100     raise OSM::APIBadUserInput, "The node is outside this world" unless node.in_world?
101
102     # version must be present unless creating
103     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt["version"].nil?
104
105     node.version = create ? 0 : pt["version"].to_i
106
107     unless create
108       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt["id"].nil?
109
110       node.id = pt["id"].to_i
111       # .to_i will return 0 if there is no number that can be parsed.
112       # We want to make sure that there is no id with zero anyway
113       raise OSM::APIBadUserInput, "ID of node cannot be zero when updating." if node.id.zero?
114     end
115
116     # We don't care about the time, as it is explicitly set on create/update/delete
117     # We don't care about the visibility as it is implicit based on the action
118     # and set manually before the actual delete
119     node.visible = true
120
121     # Start with no tags
122     node.tags = {}
123
124     # Add in any tags from the XML
125     pt.find("tag").each do |tag|
126       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag["k"].nil?
127       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag["v"].nil?
128
129       node.add_tag_key_val(tag["k"], tag["v"])
130     end
131
132     node
133   end
134
135   ##
136   # the bounding box around a node, which is used for determining the changeset's
137   # bounding box
138   def bbox
139     BoundingBox.new(longitude, latitude, longitude, latitude)
140   end
141
142   # Should probably be renamed delete_from to come in line with update
143   def delete_with_history!(new_node, user)
144     raise OSM::APIAlreadyDeletedError.new("node", new_node.id) unless visible
145
146     # need to start the transaction here, so that the database can
147     # provide repeatable reads for the used-by checks. this means it
148     # shouldn't be possible to get race conditions.
149     Node.transaction do
150       lock!
151       check_consistency(self, new_node, user)
152       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
153       raise OSM::APIPreconditionFailedError, "Node #{id} is still used by ways #{ways.collect(&:id).join(',')}." unless ways.empty?
154
155       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
156       raise OSM::APIPreconditionFailedError, "Node #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
157
158       self.changeset_id = new_node.changeset_id
159       self.tags = {}
160       self.visible = false
161
162       # update the changeset with the deleted position
163       changeset.update_bbox!(bbox)
164
165       save_with_history!
166     end
167   end
168
169   def update_from(new_node, user)
170     Node.transaction do
171       lock!
172       check_consistency(self, new_node, user)
173
174       # update changeset first
175       self.changeset_id = new_node.changeset_id
176       self.changeset = new_node.changeset
177
178       # update changeset bbox with *old* position first
179       changeset.update_bbox!(bbox)
180
181       # FIXME: logic needs to be double checked
182       self.latitude = new_node.latitude
183       self.longitude = new_node.longitude
184       self.tags = new_node.tags
185       self.visible = true
186
187       # update changeset bbox with *new* position
188       changeset.update_bbox!(bbox)
189
190       save_with_history!
191     end
192   end
193
194   def create_with_history(user)
195     check_create_consistency(self, user)
196     self.version = 0
197     self.visible = true
198
199     # update the changeset to include the new location
200     changeset.update_bbox!(bbox)
201
202     save_with_history!
203   end
204
205   def tags_as_hash
206     tags
207   end
208
209   def tags
210     @tags ||= node_tags.collect { |t| [t.k, t.v] }.to_h
211   end
212
213   attr_writer :tags
214
215   def add_tag_key_val(k, v)
216     @tags ||= {}
217
218     # duplicate tags are now forbidden, so we can't allow values
219     # in the hash to be overwritten.
220     raise OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
221
222     @tags[k] = v
223   end
224
225   ##
226   # are the preconditions OK? this is mainly here to keep the duck
227   # typing interface the same between nodes, ways and relations.
228   def preconditions_ok?
229     in_world?
230   end
231
232   ##
233   # dummy method to make the interfaces of node, way and relation
234   # more consistent.
235   def fix_placeholders!(_id_map, _placeholder_id = nil)
236     # nodes don't refer to anything, so there is nothing to do here
237   end
238
239   private
240
241   def save_with_history!
242     t = Time.now.getutc
243
244     self.version += 1
245     self.timestamp = t
246
247     Node.transaction do
248       # clone the object before saving it so that the original is
249       # still marked as dirty if we retry the transaction
250       clone.save!
251
252       # Create a NodeTag
253       tags = self.tags
254       NodeTag.where(:node_id => id).delete_all
255       tags.each do |k, v|
256         tag = NodeTag.new
257         tag.node_id = id
258         tag.k = k
259         tag.v = v
260         tag.save!
261       end
262
263       # Create an OldNode
264       old_node = OldNode.from_node(self)
265       old_node.timestamp = t
266       old_node.save_with_dependencies!
267
268       # tell the changeset we updated one element only
269       changeset.add_changes! 1
270
271       # save the changeset in case of bounding box updates
272       changeset.save!
273     end
274   end
275 end