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