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