]> git.openstreetmap.org Git - rails.git/blob - app/models/way.rb
Fix OldRelation.tags
[rails.git] / app / models / way.rb
1 class Way < ActiveRecord::Base
2   require 'xml/libxml'
3   
4   include ConsistencyValidations
5   include NotRedactable
6   include ObjectMetadata
7
8   self.table_name = "current_ways"
9   
10   belongs_to :changeset
11
12   has_many :old_ways, -> { order(:version) }
13
14   has_many :way_nodes, -> { order(:sequence_id) }
15   has_many :nodes, -> { order("sequence_id") }, :through => :way_nodes
16
17   has_many :way_tags
18
19   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
20   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
21
22   validates_presence_of :id, :on => :update
23   validates_presence_of :changeset_id,:version,  :timestamp
24   validates_uniqueness_of :id
25   validates_inclusion_of :visible, :in => [ true, false ]
26   validates_numericality_of :changeset_id, :version, :integer_only => true
27   validates_numericality_of :id, :on => :update, :integer_only => true
28   validates_associated :changeset
29
30   scope :visible, -> { where(:visible => true) }
31     scope :invisible, -> { where(:visible => false) }
32
33   # Read in xml as text and return it's Way object representation
34   def self.from_xml(xml, create=false)
35     begin
36       p = XML::Parser.string(xml)
37       doc = p.parse
38
39       doc.find('//osm/way').each do |pt|
40         return Way.from_xml_node(pt, create)
41       end
42       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
43     rescue LibXML::XML::Error, ArgumentError => ex
44       raise OSM::APIBadXMLError.new("way", xml, ex.message)
45     end
46   end
47
48   def self.from_xml_node(pt, create=false)
49     way = Way.new
50
51     raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create or not pt['version'].nil?
52     way.version = pt['version']
53     raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt['changeset'].nil?
54     way.changeset_id = pt['changeset']
55
56     unless create
57       raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt['id'].nil?
58       way.id = pt['id'].to_i
59       # .to_i will return 0 if there is no number that can be parsed. 
60       # We want to make sure that there is no id with zero anyway
61       raise OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0
62     end
63
64     # We don't care about the timestamp nor the visibility as these are either
65     # set explicitly or implicit in the action. The visibility is set to true, 
66     # and manually set to false before the actual delete.
67     way.visible = true
68
69     # Start with no tags
70     way.tags = Hash.new
71
72     # Add in any tags from the XML
73     pt.find('tag').each do |tag|
74       raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag['k'].nil?
75       raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag['v'].nil?
76       way.add_tag_keyval(tag['k'], tag['v'])
77     end
78
79     pt.find('nd').each do |nd|
80       way.add_nd_num(nd['ref'])
81     end
82
83     return way
84   end
85
86   # Find a way given it's ID, and in a single SQL call also grab its nodes
87   #
88   
89   # You can't pull in all the tags too unless we put a sequence_id on the way_tags table and have a multipart key
90   def self.find_eager(id)
91     way = Way.find(id, :include => {:way_nodes => :node})
92     #If waytag had a multipart key that was real, you could do this:
93     #way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
94   end
95
96   # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
97   def to_xml
98     doc = OSM::API.new.get_xml_doc
99     doc.root << to_xml_node()
100     return doc
101   end
102
103   def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
104     el = XML::Node.new 'way'
105     el['id'] = self.id.to_s
106
107     add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
108
109     # make sure nodes are output in sequence_id order
110     ordered_nodes = []
111     self.way_nodes.each do |nd|
112       if visible_nodes
113         # if there is a list of visible nodes then use that to weed out deleted nodes
114         if visible_nodes[nd.node_id]
115           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
116         end
117       else
118         # otherwise, manually go to the db to check things
119         if nd.node and nd.node.visible?
120           ordered_nodes[nd.sequence_id] = nd.node_id.to_s
121         end
122       end
123     end
124
125     ordered_nodes.each do |nd_id|
126       if nd_id and nd_id != '0'
127         node_el = XML::Node.new 'nd'
128         node_el['ref'] = nd_id
129         el << node_el
130       end
131     end
132
133     add_tags_to_xml_node(el, self.way_tags)
134
135     return el
136   end 
137
138   def nds
139     unless @nds
140       @nds = Array.new
141       self.way_nodes.each do |nd|
142         @nds += [nd.node_id]
143       end
144     end
145     @nds
146   end
147
148   def tags
149     unless @tags
150       @tags = {}
151       self.way_tags.each do |tag|
152         @tags[tag.k] = tag.v
153       end
154     end
155     @tags
156   end
157
158   def nds=(s)
159     @nds = s
160   end
161
162   def tags=(t)
163     @tags = t
164   end
165
166   def add_nd_num(n)
167     @nds = Array.new unless @nds
168     @nds << n.to_i
169   end
170
171   def add_tag_keyval(k, v)
172     @tags = Hash.new unless @tags
173
174     # duplicate tags are now forbidden, so we can't allow values
175     # in the hash to be overwritten.
176     raise OSM::APIDuplicateTagsError.new("way", self.id, k) if @tags.include? k
177
178     @tags[k] = v
179   end
180
181   ##
182   # the integer coords (i.e: unscaled) bounding box of the way, assuming
183   # straight line segments.
184   def bbox
185     lons = nodes.collect { |n| n.longitude }
186     lats = nodes.collect { |n| n.latitude }
187     BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
188   end
189
190   def update_from(new_way, user)
191     Way.transaction do
192       self.lock!
193       check_consistency(self, new_way, user)
194       unless new_way.preconditions_ok?(self.nds)
195         raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.")
196       end
197       
198       self.changeset_id = new_way.changeset_id
199       self.changeset = new_way.changeset
200       self.tags = new_way.tags
201       self.nds = new_way.nds
202       self.visible = true
203       save_with_history!
204     end
205   end
206
207   def create_with_history(user)
208     check_create_consistency(self, user)
209     unless self.preconditions_ok?
210       raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
211     end
212     self.version = 0
213     self.visible = true
214     save_with_history!
215   end
216
217   def preconditions_ok?(old_nodes = [])
218     return false if self.nds.empty?
219     if self.nds.length > MAX_NUMBER_OF_WAY_NODES
220       raise OSM::APITooManyWayNodesError.new(self.id, self.nds.length, MAX_NUMBER_OF_WAY_NODES)
221     end
222
223     # check only the new nodes, for efficiency - old nodes having been checked last time and can't
224     # be deleted when they're in-use.
225     new_nds = (self.nds - old_nodes).sort.uniq
226
227     unless new_nds.empty?
228       db_nds = Node.where(:id => new_nds, :visible => true)
229
230       if db_nds.length < new_nds.length
231         missing = new_nds - db_nds.collect { |n| n.id }
232         raise OSM::APIPreconditionFailedError.new("Way #{self.id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.")
233       end
234     end
235
236     return true
237   end
238
239   def delete_with_history!(new_way, user)
240     unless self.visible
241       raise OSM::APIAlreadyDeletedError.new("way", new_way.id)
242     end
243     
244     # need to start the transaction here, so that the database can 
245     # provide repeatable reads for the used-by checks. this means it
246     # shouldn't be possible to get race conditions.
247     Way.transaction do
248       self.lock!
249       check_consistency(self, new_way, user)
250       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
251       raise OSM::APIPreconditionFailedError.new("Way #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
252
253       self.changeset_id = new_way.changeset_id
254       self.changeset = new_way.changeset
255
256       self.tags = []
257       self.nds = []
258       self.visible = false
259       save_with_history!
260     end
261   end
262
263   # Temporary method to match interface to nodes
264   def tags_as_hash
265     return self.tags
266   end
267
268   ##
269   # if any referenced nodes are placeholder IDs (i.e: are negative) then
270   # this calling this method will fix them using the map from placeholders 
271   # to IDs +id_map+. 
272   def fix_placeholders!(id_map, placeholder_id = nil)
273     self.nds.map! do |node_id|
274       if node_id < 0
275         new_id = id_map[:node][node_id]
276         raise OSM::APIBadUserInput.new("Placeholder node not found for reference #{node_id} in way #{self.id.nil? ? placeholder_id : self.id}") if new_id.nil?
277         new_id
278       else
279         node_id
280       end
281     end
282   end
283
284   private
285   
286   def save_with_history!
287     t = Time.now.getutc
288
289     # update the bounding box, note that this has to be done both before 
290     # and after the save, so that nodes from both versions are included in the 
291     # bbox. we use a copy of the changeset so that it isn't reloaded
292     # later in the save.
293     cs = self.changeset
294     cs.update_bbox!(bbox) unless nodes.empty?
295
296     Way.transaction do
297       self.version += 1
298       self.timestamp = t
299       self.save!
300
301       tags = self.tags
302       WayTag.delete_all(:way_id => self.id)
303       tags.each do |k,v|
304         tag = WayTag.new
305         tag.way_id = self.id
306         tag.k = k
307         tag.v = v
308         tag.save!
309       end
310
311       nds = self.nds
312       WayNode.delete_all(:way_id => self.id)
313       sequence = 1
314       nds.each do |n|
315         nd = WayNode.new
316         nd.id = [self.id, sequence]
317         nd.node_id = n
318         nd.save!
319         sequence += 1
320       end
321
322       old_way = OldWay.from_way(self)
323       old_way.timestamp = t
324       old_way.save_with_dependencies!
325
326       # reload the way so that the nodes array points to the correct
327       # new set of nodes.
328       self.reload
329
330       # update and commit the bounding box, now that way nodes 
331       # have been updated and we're in a transaction.
332       cs.update_bbox!(bbox) unless nodes.empty?
333
334       # tell the changeset we updated one element only
335       cs.add_changes! 1
336
337       cs.save!
338     end
339   end
340 end