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