1 # frozen_string_literal: true
3 # == Schema Information
5 # Table name: current_ways
7 # id :bigint not null, primary key
8 # changeset_id :bigint not null
9 # timestamp :datetime not null
10 # visible :boolean not null
11 # version :bigint not null
15 # current_ways_timestamp_idx (timestamp)
19 # current_ways_changeset_id_fkey (changeset_id => changesets.id)
22 class Way < ApplicationRecord
25 include ConsistencyValidations
28 self.table_name = "current_ways"
32 has_many :old_ways, -> { order(:version) }, :inverse_of => :current_way
34 has_many :way_nodes, -> { order(:sequence_id) }, :inverse_of => :way
35 has_many :nodes, :through => :way_nodes
37 has_many :element_tags, :class_name => "WayTag"
39 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
40 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
42 validates :id, :uniqueness => true, :presence => { :on => :update },
43 :numericality => { :on => :update, :only_integer => true }
44 validates :version, :presence => true,
45 :numericality => { :only_integer => true }
46 validates :timestamp, :presence => true
47 validates :changeset, :associated => true
48 validates :visible, :inclusion => [true, false]
50 scope :visible, -> { where(:visible => true) }
51 scope :invisible, -> { where(:visible => false) }
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)
57 pt = doc.find_first("//osm/way")
60 Way.from_xml_node(pt, :create => create)
62 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
64 rescue LibXML::XML::Error, ArgumentError => e
65 raise OSM::APIBadXMLError.new("way", xml, e.message)
68 def self.from_xml_node(pt, create: false)
71 raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt["version"].nil?
73 way.version = pt["version"]
74 raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt["changeset"].nil?
76 way.changeset_id = pt["changeset"]
79 raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt["id"].nil?
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?
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.
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?
100 way.add_tag_keyval(tag["k"], tag["v"])
103 pt.find("nd").each do |nd|
104 way.add_nd_num(nd["ref"])
111 @nds ||= way_nodes.collect(&:node_id)
115 @tags ||= element_tags.to_h { |t| [t.k, t.v] }
118 attr_writer :nds, :tags
125 def add_tag_keyval(k, v)
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
136 # the integer coords (i.e: unscaled) bounding box of the way, assuming
137 # straight line segments.
139 lons = nodes.collect(&:longitude)
140 lats = nodes.collect(&:latitude)
141 BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
144 def update_from(new_way, user)
147 check_update_element_consistency(self, new_way, user)
148 raise OSM::APIPreconditionFailedError, "Cannot update way #{id}: data is invalid." unless new_way.preconditions_ok?(nds)
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
155 changeset.num_modified_ways += 1
160 def create_with_history(user)
161 check_create_element_consistency(self, user)
162 raise OSM::APIPreconditionFailedError, "Cannot create way: data is invalid." unless preconditions_ok?
166 changeset.num_created_ways += 1
170 def preconditions_ok?(old_nodes = [])
171 return false if nds.empty?
172 raise OSM::APITooManyWayNodesError.new(id, nds.length, Settings.max_number_of_way_nodes) if nds.length > Settings.max_number_of_way_nodes
174 # check only the new nodes, for efficiency - old nodes having been checked last time and can't
175 # be deleted when they're in-use.
176 new_nds = (nds - old_nodes).sort.uniq
178 unless new_nds.empty?
179 # NOTE: nodes are locked here to ensure they can't be deleted before
180 # the current transaction commits.
181 db_nds = Node.where(:id => new_nds, :visible => true).lock("for share")
183 if db_nds.length < new_nds.length
184 missing = new_nds - db_nds.collect(&:id)
185 raise OSM::APIPreconditionFailedError, "Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible."
192 def delete_with_history!(new_way, user)
193 raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible
195 # need to start the transaction here, so that the database can
196 # provide repeatable reads for the used-by checks. this means it
197 # shouldn't be possible to get race conditions.
200 check_update_element_consistency(self, new_way, user)
201 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
202 raise OSM::APIPreconditionFailedError, "Way #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
204 self.changeset_id = new_way.changeset_id
205 self.changeset = new_way.changeset
210 changeset.num_deleted_ways += 1
216 # if any referenced nodes are placeholder IDs (i.e: are negative) then
217 # this calling this method will fix them using the map from placeholders
219 def fix_placeholders!(id_map, placeholder_id = nil)
220 nds.map! do |node_id|
222 new_id = id_map[:node][node_id]
223 raise OSM::APIBadUserInput, "Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}" if new_id.nil?
234 def save_with_history!
240 # update the bounding box, note that this has to be done both before
241 # and after the save, so that nodes from both versions are included in the
242 # bbox. we use a copy of the changeset so that it isn't reloaded
245 cs.update_bbox!(bbox) unless nodes.empty?
248 # clone the object before saving it so that the original is
249 # still marked as dirty if we retry the transaction
253 WayTag.where(:way_id => id).delete_all
263 WayNode.where(:way_id => id).delete_all
267 nd.id = [id, sequence]
273 old_way = OldWay.from_way(self)
274 old_way.timestamp = t
275 old_way.save_with_dependencies!
277 # reload the way so that the nodes array points to the correct
281 # update and commit the bounding box, now that way nodes
282 # have been updated and we're in a transaction.
283 cs.update_bbox!(bbox) unless nodes.empty?
285 # tell the changeset we updated one element only