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