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