1 # == Schema Information
3 # Table name: current_ways
5 # id :integer not null, primary key
6 # changeset_id :integer not null
7 # timestamp :datetime not null
8 # visible :boolean not null
9 # version :integer not null
13 # current_ways_timestamp_idx (timestamp)
17 # current_ways_changeset_id_fkey (changeset_id => changesets.id)
20 class Way < ActiveRecord::Base
23 include ConsistencyValidations
25 include ObjectMetadata
27 self.table_name = "current_ways"
31 has_many :old_ways, -> { order(:version) }
33 has_many :way_nodes, -> { order(:sequence_id) }
34 has_many :nodes, :through => :way_nodes
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
41 validates :id, :uniqueness => true, :presence => { :on => :update },
42 :numericality => { :on => :update, :integer_only => true }
43 validates :version, :presence => true,
44 :numericality => { :integer_only => true }
45 validates :changeset_id, :presence => true,
46 :numericality => { :integer_only => true }
47 validates :timestamp, :presence => true
48 validates :changeset, :associated => true
49 validates :visible, :inclusion => [true, false]
51 scope :visible, -> { where(:visible => true) }
52 scope :invisible, -> { where(:visible => false) }
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)
59 doc.find("//osm/way").each do |pt|
60 return Way.from_xml_node(pt, create)
62 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
63 rescue LibXML::XML::Error, ArgumentError => ex
64 raise OSM::APIBadXMLError.new("way", xml, ex.message)
67 def self.from_xml_node(pt, create = false)
70 raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt["version"].nil?
71 way.version = pt["version"]
72 raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt["changeset"].nil?
73 way.changeset_id = pt["changeset"]
76 raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt["id"].nil?
77 way.id = pt["id"].to_i
78 # .to_i will return 0 if there is no number that can be parsed.
79 # We want to make sure that there is no id with zero anyway
80 raise OSM::APIBadUserInput, "ID of way cannot be zero when updating." if way.id.zero?
83 # We don't care about the timestamp nor the visibility as these are either
84 # set explicitly or implicit in the action. The visibility is set to true,
85 # and manually set to false before the actual delete.
91 # Add in any tags from the XML
92 pt.find("tag").each do |tag|
93 raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag["k"].nil?
94 raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag["v"].nil?
95 way.add_tag_keyval(tag["k"], tag["v"])
98 pt.find("nd").each do |nd|
99 way.add_nd_num(nd["ref"])
105 # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
107 doc = OSM::API.new.get_xml_doc
108 doc.root << to_xml_node
112 def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
113 el = XML::Node.new "way"
116 add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
118 # make sure nodes are output in sequence_id order
120 way_nodes.each do |nd|
122 # if there is a list of visible nodes then use that to weed out deleted nodes
123 ordered_nodes[nd.sequence_id] = nd.node_id.to_s if visible_nodes[nd.node_id]
125 # otherwise, manually go to the db to check things
126 ordered_nodes[nd.sequence_id] = nd.node_id.to_s if nd.node && nd.node.visible?
130 ordered_nodes.each do |nd_id|
131 next unless nd_id && nd_id != "0"
133 node_el = XML::Node.new "nd"
134 node_el["ref"] = nd_id
138 add_tags_to_xml_node(el, way_tags)
144 @nds ||= way_nodes.collect(&:node_id)
148 @tags ||= Hash[way_tags.collect { |t| [t.k, t.v] }]
160 def add_tag_keyval(k, v)
163 # duplicate tags are now forbidden, so we can't allow values
164 # in the hash to be overwritten.
165 raise OSM::APIDuplicateTagsError.new("way", id, k) if @tags.include? k
171 # the integer coords (i.e: unscaled) bounding box of the way, assuming
172 # straight line segments.
174 lons = nodes.collect(&:longitude)
175 lats = nodes.collect(&:latitude)
176 BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
179 def update_from(new_way, user)
182 check_consistency(self, new_way, user)
183 raise OSM::APIPreconditionFailedError, "Cannot update way #{id}: data is invalid." unless new_way.preconditions_ok?(nds)
185 self.changeset_id = new_way.changeset_id
186 self.changeset = new_way.changeset
187 self.tags = new_way.tags
188 self.nds = new_way.nds
194 def create_with_history(user)
195 check_create_consistency(self, user)
196 raise OSM::APIPreconditionFailedError, "Cannot create way: data is invalid." unless preconditions_ok?
202 def preconditions_ok?(old_nodes = [])
203 return false if nds.empty?
204 raise OSM::APITooManyWayNodesError.new(id, nds.length, MAX_NUMBER_OF_WAY_NODES) if nds.length > MAX_NUMBER_OF_WAY_NODES
206 # check only the new nodes, for efficiency - old nodes having been checked last time and can't
207 # be deleted when they're in-use.
208 new_nds = (nds - old_nodes).sort.uniq
210 unless new_nds.empty?
211 # NOTE: nodes are locked here to ensure they can't be deleted before
212 # the current transaction commits.
213 db_nds = Node.where(:id => new_nds, :visible => true).lock("for share")
215 if db_nds.length < new_nds.length
216 missing = new_nds - db_nds.collect(&:id)
217 raise OSM::APIPreconditionFailedError, "Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible."
224 def delete_with_history!(new_way, user)
225 raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible
227 # need to start the transaction here, so that the database can
228 # provide repeatable reads for the used-by checks. this means it
229 # shouldn't be possible to get race conditions.
232 check_consistency(self, new_way, user)
233 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
234 raise OSM::APIPreconditionFailedError, "Way #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
236 self.changeset_id = new_way.changeset_id
237 self.changeset = new_way.changeset
247 # if any referenced nodes are placeholder IDs (i.e: are negative) then
248 # this calling this method will fix them using the map from placeholders
250 def fix_placeholders!(id_map, placeholder_id = nil)
251 nds.map! do |node_id|
253 new_id = id_map[:node][node_id]
254 raise OSM::APIBadUserInput, "Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}" if new_id.nil?
264 def save_with_history!
270 # update the bounding box, note that this has to be done both before
271 # and after the save, so that nodes from both versions are included in the
272 # bbox. we use a copy of the changeset so that it isn't reloaded
275 cs.update_bbox!(bbox) unless nodes.empty?
278 # clone the object before saving it so that the original is
279 # still marked as dirty if we retry the transaction
283 WayTag.where(:way_id => id).delete_all
293 WayNode.where(:way_id => id).delete_all
297 nd.id = [id, sequence]
303 old_way = OldWay.from_way(self)
304 old_way.timestamp = t
305 old_way.save_with_dependencies!
307 # reload the way so that the nodes array points to the correct
311 # update and commit the bounding box, now that way nodes
312 # have been updated and we're in a transaction.
313 cs.update_bbox!(bbox) unless nodes.empty?
315 # tell the changeset we updated one element only