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