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