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