]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/db_ops.py
3c5c56323af6d916c71537918e704c8ee607ad82
[nominatim.git] / test / bdd / steps / db_ops.py
1 import base64
2 import random
3 import string
4 import re
5 from nose.tools import * # for assert functions
6 import psycopg2.extras
7
8 class PlaceColumn:
9
10     def __init__(self, context, force_name):
11         self.columns = { 'admin_level' : 100}
12         self.force_name = force_name
13         self.context = context
14         self.geometry = None
15
16     def add(self, key, value):
17         if hasattr(self, 'set_key_' + key):
18             getattr(self, 'set_key_' + key)(value)
19         elif key.startswith('name+'):
20             self.add_hstore('name', key[5:], value)
21         elif key.startswith('extra+'):
22             self.add_hstore('extratags', key[6:], value)
23         else:
24             assert_in(key, ('class', 'type', 'street', 'addr_place',
25                             'isin', 'postcode'))
26             self.columns[key] = None if value == '' else value
27
28     def set_key_name(self, value):
29         self.add_hstore('name', 'name', value)
30
31     def set_key_osm(self, value):
32         assert_in(value[0], 'NRW')
33         ok_(value[1:].isdigit())
34
35         self.columns['osm_type'] = value[0]
36         self.columns['osm_id'] = int(value[1:])
37
38     def set_key_admin(self, value):
39         self.columns['admin_level'] = int(value)
40
41     def set_key_housenr(self, value):
42         self.columns['housenumber'] = None if value == '' else value
43
44     def set_key_country(self, value):
45         self.columns['country_code'] = None if value == '' else value
46
47     def set_key_geometry(self, value):
48         self.geometry = self.context.osm.parse_geometry(value, self.context.scene)
49         assert_is_not_none(self.geometry)
50
51     def add_hstore(self, column, key, value):
52         if column in self.columns:
53             self.columns[column][key] = value
54         else:
55             self.columns[column] = { key : value }
56
57     def db_insert(self, cursor):
58         assert_in('osm_type', self.columns)
59         if self.force_name and 'name' not in self.columns:
60             self.add_hstore('name', 'name', ''.join(random.choice(string.printable)
61                                            for _ in range(int(random.random()*30))))
62
63         if self.columns['osm_type'] == 'N' and self.geometry is None:
64             self.geometry = "ST_SetSRID(ST_Point(%f, %f), 4326)" % (
65                             random.random()*360 - 180, random.random()*180 - 90)
66         else:
67             assert_is_not_none(self.geometry, "Geometry missing")
68         query = 'INSERT INTO place (%s, geometry) values(%s, %s)' % (
69                      ','.join(self.columns.keys()),
70                      ','.join(['%s' for x in range(len(self.columns))]),
71                      self.geometry)
72         cursor.execute(query, list(self.columns.values()))
73
74 class NominatimID:
75     """ Splits a unique identifier for places into its components.
76         As place_ids cannot be used for testing, we use a unique
77         identifier instead that is of the form <osmtype><osmid>[:<class>].
78     """
79
80     id_regex = re.compile(r"(?P<tp>[NRW])(?P<id>\d+)(:(?P<cls>\w+))?")
81
82     def __init__(self, oid):
83         self.typ = self.oid = self.cls = None
84
85         if oid is not None:
86             m = self.id_regex.fullmatch(oid)
87             assert_is_not_none(m, "ID '%s' not of form <osmtype><osmid>[:<class>]" % oid)
88
89             self.typ = m.group('tp')
90             self.oid = m.group('id')
91             self.cls = m.group('cls')
92
93     def table_select(self):
94         """ Return where clause and parameter list to select the object
95             from a Nominatim table.
96         """
97         where = 'osm_type = %s and osm_id = %s'
98         params = [self.typ, self. oid]
99
100         if self.cls is not None:
101             where += ' and class = %s'
102             params.append(self.cls)
103
104         return where, params
105
106     def get_place_id(self, cur):
107         where, params = self.table_select()
108         cur.execute("SELECT place_id FROM placex WHERE %s" % where, params)
109         eq_(1, cur.rowcount, "Expected exactly 1 entry in placex found %s" % cur.rowcount)
110
111         return cur.fetchone()[0]
112
113
114 def assert_db_column(row, column, value, context):
115     if column == 'object':
116         return
117
118     if column.startswith('centroid'):
119         fac = float(column[9:]) if column.startswith('centroid*') else 1.0
120         x, y = value.split(' ')
121         assert_almost_equal(float(x) * fac, row['cx'], "Bad x coordinate")
122         assert_almost_equal(float(y) * fac, row['cy'], "Bad y coordinate")
123     elif column == 'geometry':
124         geom = context.osm.parse_geometry(value, context.scene)
125         cur = context.db.cursor()
126         query = "SELECT ST_Equals(ST_SnapToGrid(%s, 0.00001, 0.00001), ST_SnapToGrid(ST_SetSRID('%s'::geometry, 4326), 0.00001, 0.00001))" % (
127                  geom, row['geomtxt'],)
128         cur.execute(query)
129         eq_(cur.fetchone()[0], True, "(Row %s failed: %s)" % (column, query))
130     elif value == '-':
131         assert_is_none(row[column], "Row %s" % column)
132     else:
133         eq_(value, str(row[column]),
134             "Row '%s': expected: %s, got: %s"
135             % (column, value, str(row[column])))
136
137
138 ################################ STEPS ##################################
139
140 @given(u'the scene (?P<scene>.+)')
141 def set_default_scene(context, scene):
142     context.scene = scene
143
144 @given("the (?P<named>named )?places")
145 def add_data_to_place_table(context, named):
146     cur = context.db.cursor()
147     cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
148     for r in context.table:
149         col = PlaceColumn(context, named is not None)
150
151         for h in r.headings:
152             col.add(h, r[h])
153
154         col.db_insert(cur)
155     cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
156     cur.close()
157     context.db.commit()
158
159 @given("the relations")
160 def add_data_to_planet_relations(context):
161     cur = context.db.cursor()
162     for r in context.table:
163         last_node = 0
164         last_way = 0
165         parts = []
166         if r['members']:
167             members = []
168             for m in r['members'].split(','):
169                 mid = NominatimID(m)
170                 if mid.typ == 'N':
171                     parts.insert(last_node, int(mid.oid))
172                     last_node += 1
173                     last_way += 1
174                 elif mid.typ == 'W':
175                     parts.insert(last_way, int(mid.oid))
176                     last_way += 1
177                 else:
178                     parts.append(int(mid.oid))
179
180                 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
181         else:
182             members = None
183
184         tags = []
185         for h in r.headings:
186             if h.startswith("tags+"):
187                 tags.extend((h[5:], r[h]))
188
189         cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
190                        VALUES (%s, %s, %s, %s, %s, %s)""",
191                     (r['id'], last_node, last_way, parts, members, tags))
192     context.db.commit()
193
194 @given("the ways")
195 def add_data_to_planet_ways(context):
196     cur = context.db.cursor()
197     for r in context.table:
198         tags = []
199         for h in r.headings:
200             if h.startswith("tags+"):
201                 tags.extend((h[5:], r[h]))
202
203         nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
204
205         cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
206                     (r['id'], nodes, tags))
207     context.db.commit()
208
209 @when("importing")
210 def import_and_index_data_from_place_table(context):
211     context.nominatim.run_setup_script('create-functions', 'create-partition-functions')
212     cur = context.db.cursor()
213     cur.execute(
214         """insert into placex (osm_type, osm_id, class, type, name, admin_level,
215            housenumber, street, addr_place, isin, postcode, country_code, extratags,
216            geometry)
217            select * from place where not (class='place' and type='houses' and osm_type='W')""")
218     cur.execute(
219         """select insert_osmline (osm_id, housenumber, street, addr_place,
220            postcode, country_code, geometry)
221            from place where class='place' and type='houses' and osm_type='W'""")
222     context.db.commit()
223     context.nominatim.run_setup_script('index', 'index-noanalyse')
224
225 @when("updating places")
226 def update_place_table(context):
227     context.nominatim.run_setup_script(
228         'create-functions', 'create-partition-functions', 'enable-diff-updates')
229     cur = context.db.cursor()
230     for r in context.table:
231         col = PlaceColumn(context, False)
232
233         for h in r.headings:
234             col.add(h, r[h])
235
236         col.db_insert(cur)
237
238     context.db.commit()
239     context.nominatim.run_update_script('index')
240
241 @when("marking for delete (?P<oids>.*)")
242 def delete_places(context, oids):
243     context.nominatim.run_setup_script(
244         'create-functions', 'create-partition-functions', 'enable-diff-updates')
245     cur = context.db.cursor()
246     for oid in oids.split(','):
247         where, params = NominatimID(oid).table_select()
248         cur.execute("DELETE FROM place WHERE " + where, params)
249     context.db.commit()
250     context.nominatim.run_update_script('index')
251
252 @then("placex contains(?P<exact> exactly)?")
253 def check_placex_contents(context, exact):
254     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
255
256     expected_content = set()
257     for row in context.table:
258         nid = NominatimID(row['object'])
259         where, params = nid.table_select()
260         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
261                        ST_X(centroid) as cx, ST_Y(centroid) as cy
262                        FROM placex where %s""" % where,
263                     params)
264         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
265
266         for res in cur:
267             if exact:
268                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
269             for h in row.headings:
270                 if h.startswith('name'):
271                     name = h[5:] if h.startswith('name+') else 'name'
272                     assert_in(name, res['name'])
273                     eq_(res['name'][name], row[h])
274                 elif h.startswith('extratags+'):
275                     eq_(res['extratags'][h[10:]], row[h])
276                 elif h in ('linked_place_id', 'parent_place_id'):
277                     if row[h] == '0':
278                         eq_(0, res[h])
279                     elif row[h] == '-':
280                         assert_is_none(res[h])
281                     else:
282                         eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
283                             res[h])
284                 else:
285                     assert_db_column(res, h, row[h], context)
286
287     if exact:
288         cur.execute('SELECT osm_type, osm_id, class from placex')
289         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
290
291     context.db.commit()
292
293 @then("place contains(?P<exact> exactly)?")
294 def check_placex_contents(context, exact):
295     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
296
297     expected_content = set()
298     for row in context.table:
299         nid = NominatimID(row['object'])
300         where, params = nid.table_select()
301         cur.execute("""SELECT *, ST_AsText(geometry) as geomtxt,
302                        ST_GeometryType(geometry) as geometrytype
303                        FROM place where %s""" % where,
304                     params)
305         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
306
307         for res in cur:
308             if exact:
309                 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
310             for h in row.headings:
311                 msg = "%s: %s" % (row['object'], h)
312                 if h in ('name', 'extratags'):
313                     if row[h] == '-':
314                         assert_is_none(res[h], msg)
315                     else:
316                         vdict = eval('{' + row[h] + '}')
317                         assert_equals(vdict, res[h], msg)
318                 elif h.startswith('name+'):
319                     assert_equals(res['name'][h[5:]], row[h], msg)
320                 elif h.startswith('extratags+'):
321                     assert_equals(res['extratags'][h[10:]], row[h], msg)
322                 elif h in ('linked_place_id', 'parent_place_id'):
323                     if row[h] == '0':
324                         assert_equals(0, res[h], msg)
325                     elif row[h] == '-':
326                         assert_is_none(res[h], msg)
327                     else:
328                         assert_equals(NominatimID(row[h]).get_place_id(context.db.cursor()),
329                                       res[h], msg)
330                 else:
331                     assert_db_column(res, h, row[h], context)
332
333     if exact:
334         cur.execute('SELECT osm_type, osm_id, class from place')
335         eq_(expected_content, set([(r[0], r[1], r[2]) for r in cur]))
336
337     context.db.commit()
338
339 @then("search_name contains")
340 def check_search_name_contents(context):
341     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
342
343     for row in context.table:
344         pid = NominatimID(row['object']).get_place_id(cur)
345         cur.execute("""SELECT *, ST_X(centroid) as cx, ST_Y(centroid) as cy
346                        FROM search_name WHERE place_id = %s""", (pid, ))
347         assert_less(0, cur.rowcount, "No rows found for " + row['object'])
348
349         for res in cur:
350             for h in row.headings:
351                 if h in ('name_vector', 'nameaddress_vector'):
352                     terms = [x.strip().replace('#', ' ') for x in row[h].split(',')]
353                     subcur = context.db.cursor()
354                     subcur.execute("""SELECT word_id, word_token
355                                       FROM word, (SELECT unnest(%s) as term) t
356                                       WHERE word_token = make_standard_name(t.term)""",
357                                    (terms,))
358                     ok_(subcur.rowcount >= len(terms))
359                     for wid in subcur:
360                         assert_in(wid[0], res[h],
361                                   "Missing term for %s/%s: %s" % (pid, h, wid[1]))
362                 else:
363                     assert_db_column(res, h, row[h], context)
364
365
366     context.db.commit()
367
368 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
369 def check_location_property_osmline(context, oid, neg):
370     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
371     nid = NominatimID(oid)
372
373     eq_('W', nid.typ, "interpolation must be a way")
374
375     cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
376                    FROM location_property_osmline WHERE osm_id = %s""",
377                 (nid.oid, ))
378
379     if neg:
380         eq_(0, cur.rowcount)
381         return
382
383     todo = list(range(len(list(context.table))))
384     for res in cur:
385         for i in todo:
386             row = context.table[i]
387             if (int(row['start']) == res['startnumber']
388                 and int(row['end']) == res['endnumber']):
389                 todo.remove(i)
390                 break
391         else:
392             assert False, "Unexpected row %s" % (str(res))
393
394         for h in row.headings:
395             if h in ('start', 'end'):
396                 continue
397             elif h == 'parent_place_id':
398                 if row[h] == '0':
399                     eq_(0, res[h])
400                 elif row[h] == '-':
401                     assert_is_none(res[h])
402                 else:
403                     eq_(NominatimID(row[h]).get_place_id(context.db.cursor()),
404                         res[h])
405             else:
406                 assert_db_column(res, h, row[h], context)
407
408     eq_(todo, [])
409
410
411 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
412 def check_placex_has_entry(context, table, oid):
413     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
414     nid = NominatimID(oid)
415     where, params = nid.table_select()
416     cur.execute("SELECT * FROM %s where %s" % (table, where), params)
417     eq_(0, cur.rowcount)
418     context.db.commit()
419
420 @then("search_name has no entry for (?P<oid>.*)")
421 def check_search_name_has_entry(context, oid):
422     cur = context.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
423     pid = NominatimID(oid).get_place_id(cur)
424     cur.execute("SELECT * FROM search_name WHERE place_id = %s", (pid, ))
425     eq_(0, cur.rowcount)
426     context.db.commit()