+ # check only the new nodes, for efficiency - old nodes having been checked last time and can't
+ # be deleted when they're in-use.
+ new_nds = (nds - old_nodes).sort.uniq
+
+ unless new_nds.empty?
+ # NOTE: nodes are locked here to ensure they can't be deleted before
+ # the current transaction commits.
+ db_nds = Node.where(:id => new_nds, :visible => true).lock("for share")
+
+ if db_nds.length < new_nds.length
+ missing = new_nds - db_nds.collect(&:id)
+ raise OSM::APIPreconditionFailedError, "Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible."
+ end
+ end
+
+ true
+ end
+
+ def delete_with_history!(new_way, user)
+ raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible
+
+ # need to start the transaction here, so that the database can
+ # provide repeatable reads for the used-by checks. this means it
+ # shouldn't be possible to get race conditions.
+ Way.transaction do
+ lock!
+ check_update_element_consistency(self, new_way, user)
+ rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
+ raise OSM::APIPreconditionFailedError, "Way #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty?
+
+ self.changeset_id = new_way.changeset_id
+ self.changeset = new_way.changeset
+
+ self.tags = []
+ self.nds = []
+ self.visible = false
+ save_with_history!
+ end
+ end
+
+ ##
+ # if any referenced nodes are placeholder IDs (i.e: are negative) then
+ # this calling this method will fix them using the map from placeholders
+ # to IDs +id_map+.
+ def fix_placeholders!(id_map, placeholder_id = nil)
+ nds.map! do |node_id|
+ if node_id.negative?
+ new_id = id_map[:node][node_id]
+ raise OSM::APIBadUserInput, "Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}" if new_id.nil?
+
+ new_id
+ else
+ node_id
+ end
+ end
+ end
+
+ private
+
+ def save_with_history!
+ t = Time.now.utc
+
+ self.version += 1
+ self.timestamp = t
+
+ # update the bounding box, note that this has to be done both before
+ # and after the save, so that nodes from both versions are included in the
+ # bbox. we use a copy of the changeset so that it isn't reloaded
+ # later in the save.
+ cs = changeset
+ cs.update_bbox!(bbox) unless nodes.empty?
+
+ Way.transaction do
+ # clone the object before saving it so that the original is
+ # still marked as dirty if we retry the transaction
+ clone.save!
+
+ tags = self.tags
+ WayTag.where(:way_id => id).delete_all
+ tags.each do |k, v|