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