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