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