]> git.openstreetmap.org Git - rails.git/blob - app/models/way.rb
Merge remote-tracking branch 'upstream/pull/4720'
[rails.git] / app / models / way.rb
1 # == Schema Information
2 #
3 # Table name: current_ways
4 #
5 #  id           :bigint(8)        not null, primary key
6 #  changeset_id :bigint(8)        not null
7 #  timestamp    :datetime         not null
8 #  visible      :boolean          not null
9 #  version      :bigint(8)        not null
10 #
11 # Indexes
12 #
13 #  current_ways_timestamp_idx  (timestamp)
14 #
15 # Foreign Keys
16 #
17 #  current_ways_changeset_id_fkey  (changeset_id => changesets.id)
18 #
19
20 class Way < ApplicationRecord
21   require "xml/libxml"
22
23   include ConsistencyValidations
24   include NotRedactable
25
26   self.table_name = "current_ways"
27
28   belongs_to :changeset
29
30   has_many :old_ways, -> { order(:version) }, :inverse_of => :current_way
31
32   has_many :way_nodes, -> { order(:sequence_id) }, :inverse_of => :way
33   has_many :nodes, :through => :way_nodes
34
35   has_many :way_tags
36
37   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
38   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
39
40   validates :id, :uniqueness => true, :presence => { :on => :update },
41                  :numericality => { :on => :update, :only_integer => true }
42   validates :version, :presence => true,
43                       :numericality => { :only_integer => true }
44   validates :timestamp, :presence => true
45   validates :changeset, :associated => true
46   validates :visible, :inclusion => [true, false]
47
48   scope :visible, -> { where(:visible => true) }
49   scope :invisible, -> { where(:visible => false) }
50
51   # Read in xml as text and return it's Way object representation
52   def self.from_xml(xml, create: false)
53     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
54     doc = p.parse
55     pt = doc.find_first("//osm/way")
56
57     if pt
58       Way.from_xml_node(pt, :create => create)
59     else
60       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
61     end
62   rescue LibXML::XML::Error, ArgumentError => e
63     raise OSM::APIBadXMLError.new("way", xml, e.message)
64   end
65
66   def self.from_xml_node(pt, create: false)
67     way = Way.new
68
69     raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt["version"].nil?
70
71     way.version = pt["version"]
72     raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt["changeset"].nil?
73
74     way.changeset_id = pt["changeset"]
75
76     unless create
77       raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt["id"].nil?
78
79       way.id = pt["id"].to_i
80       # .to_i will return 0 if there is no number that can be parsed.
81       # We want to make sure that there is no id with zero anyway
82       raise OSM::APIBadUserInput, "ID of way cannot be zero when updating." if way.id.zero?
83     end
84
85     # We don't care about the timestamp nor the visibility as these are either
86     # set explicitly or implicit in the action. The visibility is set to true,
87     # and manually set to false before the actual delete.
88     way.visible = true
89
90     # Start with no tags
91     way.tags = {}
92
93     # Add in any tags from the XML
94     pt.find("tag").each do |tag|
95       raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag["k"].nil?
96       raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag["v"].nil?
97
98       way.add_tag_keyval(tag["k"], tag["v"])
99     end
100
101     pt.find("nd").each do |nd|
102       way.add_nd_num(nd["ref"])
103     end
104
105     way
106   end
107
108   def nds
109     @nds ||= way_nodes.collect(&:node_id)
110   end
111
112   def tags
113     @tags ||= way_tags.to_h { |t| [t.k, t.v] }
114   end
115
116   attr_writer :nds, :tags
117
118   def add_nd_num(n)
119     @nds ||= []
120     @nds << n.to_i
121   end
122
123   def add_tag_keyval(k, v)
124     @tags ||= {}
125
126     # duplicate tags are now forbidden, so we can't allow values
127     # in the hash to be overwritten.
128     raise OSM::APIDuplicateTagsError.new("way", id, k) if @tags.include? k
129
130     @tags[k] = v
131   end
132
133   ##
134   # the integer coords (i.e: unscaled) bounding box of the way, assuming
135   # straight line segments.
136   def bbox
137     lons = nodes.collect(&:longitude)
138     lats = nodes.collect(&:latitude)
139     BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
140   end
141
142   def update_from(new_way, user)
143     Way.transaction do
144       lock!
145       check_update_element_consistency(self, new_way, user)
146       raise OSM::APIPreconditionFailedError, "Cannot update way #{id}: data is invalid." unless new_way.preconditions_ok?(nds)
147
148       self.changeset_id = new_way.changeset_id
149       self.changeset = new_way.changeset
150       self.tags = new_way.tags
151       self.nds = new_way.nds
152       self.visible = true
153       save_with_history!
154     end
155   end
156
157   def create_with_history(user)
158     check_create_element_consistency(self, user)
159     raise OSM::APIPreconditionFailedError, "Cannot create way: data is invalid." unless preconditions_ok?
160
161     self.version = 0
162     self.visible = true
163     save_with_history!
164   end
165
166   def preconditions_ok?(old_nodes = [])
167     return false if nds.empty?
168     raise OSM::APITooManyWayNodesError.new(id, nds.length, Settings.max_number_of_way_nodes) if nds.length > Settings.max_number_of_way_nodes
169
170     # check only the new nodes, for efficiency - old nodes having been checked last time and can't
171     # be deleted when they're in-use.
172     new_nds = (nds - old_nodes).sort.uniq
173
174     unless new_nds.empty?
175       # NOTE: nodes are locked here to ensure they can't be deleted before
176       # the current transaction commits.
177       db_nds = Node.where(:id => new_nds, :visible => true).lock("for share")
178
179       if db_nds.length < new_nds.length
180         missing = new_nds - db_nds.collect(&:id)
181         raise OSM::APIPreconditionFailedError, "Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible."
182       end
183     end
184
185     true
186   end
187
188   def delete_with_history!(new_way, user)
189     raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible
190
191     # need to start the transaction here, so that the database can
192     # provide repeatable reads for the used-by checks. this means it
193     # shouldn't be possible to get race conditions.
194     Way.transaction do
195       lock!
196       check_update_element_consistency(self, new_way, user)
197       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
198       raise OSM::APIPreconditionFailedError, "Way #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
199
200       self.changeset_id = new_way.changeset_id
201       self.changeset = new_way.changeset
202
203       self.tags = []
204       self.nds = []
205       self.visible = false
206       save_with_history!
207     end
208   end
209
210   ##
211   # if any referenced nodes are placeholder IDs (i.e: are negative) then
212   # this calling this method will fix them using the map from placeholders
213   # to IDs +id_map+.
214   def fix_placeholders!(id_map, placeholder_id = nil)
215     nds.map! do |node_id|
216       if node_id.negative?
217         new_id = id_map[:node][node_id]
218         raise OSM::APIBadUserInput, "Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}" if new_id.nil?
219
220         new_id
221       else
222         node_id
223       end
224     end
225   end
226
227   private
228
229   def save_with_history!
230     t = Time.now.utc
231
232     self.version += 1
233     self.timestamp = t
234
235     # update the bounding box, note that this has to be done both before
236     # and after the save, so that nodes from both versions are included in the
237     # bbox. we use a copy of the changeset so that it isn't reloaded
238     # later in the save.
239     cs = changeset
240     cs.update_bbox!(bbox) unless nodes.empty?
241
242     Way.transaction do
243       # clone the object before saving it so that the original is
244       # still marked as dirty if we retry the transaction
245       clone.save!
246
247       tags = self.tags
248       WayTag.where(:way_id => id).delete_all
249       tags.each do |k, v|
250         tag = WayTag.new
251         tag.way_id = id
252         tag.k = k
253         tag.v = v
254         tag.save!
255       end
256
257       nds = self.nds
258       WayNode.where(:way_id => id).delete_all
259       sequence = 1
260       nds.each do |n|
261         nd = WayNode.new
262         nd.id = [id, sequence]
263         nd.node_id = n
264         nd.save!
265         sequence += 1
266       end
267
268       old_way = OldWay.from_way(self)
269       old_way.timestamp = t
270       old_way.save_with_dependencies!
271
272       # reload the way so that the nodes array points to the correct
273       # new set of nodes.
274       reload
275
276       # update and commit the bounding box, now that way nodes
277       # have been updated and we're in a transaction.
278       cs.update_bbox!(bbox) unless nodes.empty?
279
280       # tell the changeset we updated one element only
281       cs.add_changes! 1
282
283       cs.save!
284     end
285   end
286 end