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