]> git.openstreetmap.org Git - rails.git/blob - app/models/node.rb
Avoid noise on console when running tests
[rails.git] / app / models / node.rb
1 class Node < ActiveRecord::Base
2   require 'xml/libxml'
3
4   include GeoRecord
5   include ConsistencyValidations
6
7   set_table_name 'current_nodes'
8
9   belongs_to :changeset
10
11   has_many :old_nodes, :order => :version
12
13   has_many :way_nodes
14   has_many :ways, :through => :way_nodes
15
16   has_many :node_tags
17   
18   has_many :old_way_nodes
19   has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
20
21   has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
22   has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
23
24   validates_presence_of :id, :on => :update
25   validates_presence_of :timestamp,:version,  :changeset_id
26   validates_uniqueness_of :id
27   validates_inclusion_of :visible, :in => [ true, false ]
28   validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
29   validates_numericality_of :id, :on => :update, :integer_only => true
30   validate :validate_position
31   validates_associated :changeset
32
33   scope :visible, where(:visible => true)
34   scope :invisible, where(:visible => false)
35
36   # Sanity check the latitude and longitude and add an error if it's broken
37   def validate_position
38     errors.add(:base, "Node is not in the world") unless in_world?
39   end
40
41   #
42   # Search for nodes matching tags within bounding_box
43   #
44   # Also adheres to limitations such as within max_number_of_nodes
45   #
46   def self.search(bounding_box, tags = {})
47     min_lon, min_lat, max_lon, max_lat = *bounding_box
48     # @fixme a bit of a hack to search for only visible nodes
49     # couldn't think of another to add to tags condition
50     #conditions_hash = tags.merge({ 'visible' => 1 })
51   
52     # using named placeholders http://www.robbyonrails.com/articles/2005/10/21/using-named-placeholders-in-ruby
53     #keys = []
54     #values = {}
55
56     #conditions_hash.each do |key,value|
57     #  keys <<  "#{key} = :#{key}"
58     #  values[key.to_sym] = value
59     #end 
60     #conditions = keys.join(' AND ')
61  
62     find_by_area(min_lat, min_lon, max_lat, max_lon,
63                     :conditions => {:visible => true},
64                     :limit => MAX_NUMBER_OF_NODES+1)  
65   end
66
67   # Read in xml as text and return it's Node object representation
68   def self.from_xml(xml, create=false)
69     begin
70       p = XML::Parser.string(xml)
71       doc = p.parse
72
73       doc.find('//osm/node').each do |pt|
74         return Node.from_xml_node(pt, create)
75       end
76       raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
77     rescue LibXML::XML::Error, ArgumentError => ex
78       raise OSM::APIBadXMLError.new("node", xml, ex.message)
79     end
80   end
81
82   def self.from_xml_node(pt, create=false)
83     node = Node.new
84     
85     raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
86     raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
87     node.lat = pt['lat'].to_f
88     node.lon = pt['lon'].to_f
89     raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
90     node.changeset_id = pt['changeset'].to_i
91
92     raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
93
94     # version must be present unless creating
95     raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
96     node.version = create ? 0 : pt['version'].to_i
97
98     unless create
99       raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
100       node.id = pt['id'].to_i
101       # .to_i will return 0 if there is no number that can be parsed. 
102       # We want to make sure that there is no id with zero anyway
103       raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
104     end
105
106     # We don't care about the time, as it is explicitly set on create/update/delete
107     # We don't care about the visibility as it is implicit based on the action
108     # and set manually before the actual delete
109     node.visible = true
110
111     pt.find('tag').each do |tag|
112       raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
113       raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
114       node.add_tag_key_val(tag['k'],tag['v'])
115     end
116
117     return node
118   end
119
120   ##
121   # the bounding box around a node, which is used for determining the changeset's
122   # bounding box
123   def bbox
124     [ longitude, latitude, longitude, latitude ]
125   end
126
127   # Should probably be renamed delete_from to come in line with update
128   def delete_with_history!(new_node, user)
129     unless self.visible
130       raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
131     end
132
133     # need to start the transaction here, so that the database can 
134     # provide repeatable reads for the used-by checks. this means it
135     # shouldn't be possible to get race conditions.
136     Node.transaction do
137       self.lock!
138       check_consistency(self, new_node, user)
139       ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
140       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
141       
142       rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
143       raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
144
145       self.changeset_id = new_node.changeset_id
146       self.tags = {}
147       self.visible = false
148       
149       # update the changeset with the deleted position
150       changeset.update_bbox!(bbox)
151       
152       save_with_history!
153     end
154   end
155
156   def update_from(new_node, user)
157     Node.transaction do
158       self.lock!
159       check_consistency(self, new_node, user)
160       
161       # update changeset first
162       self.changeset_id = new_node.changeset_id
163       self.changeset = new_node.changeset
164       
165       # update changeset bbox with *old* position first
166       changeset.update_bbox!(bbox);
167       
168       # FIXME logic needs to be double checked
169       self.latitude = new_node.latitude 
170       self.longitude = new_node.longitude
171       self.tags = new_node.tags
172       self.visible = true
173       
174       # update changeset bbox with *new* position
175       changeset.update_bbox!(bbox);
176       
177       save_with_history!
178     end
179   end
180   
181   def create_with_history(user)
182     check_create_consistency(self, user)
183     self.version = 0
184     self.visible = true
185
186     # update the changeset to include the new location
187     changeset.update_bbox!(bbox)
188
189     save_with_history!
190   end
191
192   def to_xml
193     doc = OSM::API.new.get_xml_doc
194     doc.root << to_xml_node()
195     return doc
196   end
197
198   def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
199     el1 = XML::Node.new 'node'
200     el1['id'] = self.id.to_s
201     el1['lat'] = self.lat.to_s
202     el1['lon'] = self.lon.to_s
203     el1['version'] = self.version.to_s
204     el1['changeset'] = self.changeset_id.to_s
205
206     if changeset_cache.key?(self.changeset_id)
207       # use the cache if available
208     else
209       changeset_cache[self.changeset_id] = self.changeset.user_id
210     end
211
212     user_id = changeset_cache[self.changeset_id]
213
214     if user_display_name_cache.key?(user_id)
215       # use the cache if available
216     elsif self.changeset.user.data_public?
217       user_display_name_cache[user_id] = self.changeset.user.display_name
218     else
219       user_display_name_cache[user_id] = nil
220     end
221
222     if not user_display_name_cache[user_id].nil?
223       el1['user'] = user_display_name_cache[user_id]
224       el1['uid'] = user_id.to_s
225     end
226
227     self.tags.each do |k,v|
228       el2 = XML::Node.new('tag')
229       el2['k'] = k.to_s
230       el2['v'] = v.to_s
231       el1 << el2
232     end
233
234     el1['visible'] = self.visible.to_s
235     el1['timestamp'] = self.timestamp.xmlschema
236     return el1
237   end
238
239   def tags_as_hash
240     return tags
241   end
242
243   def tags
244     unless @tags
245       @tags = {}
246       self.node_tags.each do |tag|
247         @tags[tag.k] = tag.v
248       end
249     end
250     @tags
251   end
252
253   def tags=(t)
254     @tags = t 
255   end 
256
257   def add_tag_key_val(k,v)
258     @tags = Hash.new unless @tags
259
260     # duplicate tags are now forbidden, so we can't allow values
261     # in the hash to be overwritten.
262     raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
263
264     @tags[k] = v
265   end
266
267   ##
268   # are the preconditions OK? this is mainly here to keep the duck
269   # typing interface the same between nodes, ways and relations.
270   def preconditions_ok?
271     in_world?
272   end
273
274   ##
275   # dummy method to make the interfaces of node, way and relation
276   # more consistent.
277   def fix_placeholders!(id_map, placeholder_id = nil)
278     # nodes don't refer to anything, so there is nothing to do here
279   end
280   
281   private
282
283   def save_with_history!
284     t = Time.now.getutc
285     Node.transaction do
286       self.version += 1
287       self.timestamp = t
288       self.save!
289
290       # Create a NodeTag
291       tags = self.tags
292       NodeTag.delete_all(:node_id => self.id)
293       tags.each do |k,v|
294         tag = NodeTag.new
295         tag.node_id = self.id
296         tag.k = k 
297         tag.v = v 
298         tag.save!
299       end 
300
301       # Create an OldNode
302       old_node = OldNode.from_node(self)
303       old_node.timestamp = t
304       old_node.save_with_dependencies!
305
306       # tell the changeset we updated one element only
307       changeset.add_changes! 1
308
309       # save the changeset in case of bounding box updates
310       changeset.save!
311     end
312   end
313   
314 end