4 from check_functions import Almost
5 from place_inserter import PlaceColumn
6 from table_compare import NominatimID
8 class PlaceObjName(object):
10 def __init__(self, placeid, conn):
21 cur = self.conn.cursor()
22 cur.execute("""SELECT osm_type, osm_id, class
23 FROM placex WHERE place_id = %s""",
25 assert cur.rowcount == 1, "No entry found for place id %s" % self.pid
27 return "%s%s:%s" % cur.fetchone()
29 def compare_place_id(expected, result, column, context):
32 "Bad place id in column {}. Expected: 0, got: {!s}.".format(
33 column, PlaceObjName(result, context.db))
35 assert result is None, \
36 "Bad place id in column {}: {!s}.".format(
37 column, PlaceObjName(result, context.db))
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))
43 def check_database_integrity(context):
44 """ Check some generic constraints on the tables.
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
52 assert cur.fetchone()[0] == 0, "Duplicates found in place_addressline"
55 def assert_db_column(row, column, value, context):
56 if column == 'object':
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()
66 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
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'],)
78 assert cur.fetchone()[0], "(Row %s failed: %s)" % (column, query)
80 assert row[column] is None, "Row %s" % column
82 assert value == str(row[column]), \
83 "Row '%s': expected: %s, got: %s" % (column, value, str(row[column]))
86 ################################ GIVEN ##################################
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')
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:
105 for m in r['members'].split(','):
108 parts.insert(last_node, int(mid.oid))
112 parts.insert(last_way, int(mid.oid))
115 parts.append(int(mid.oid))
117 members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
123 if h.startswith("tags+"):
124 tags.extend((h[5:], r[h]))
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))
131 def add_data_to_planet_ways(context):
132 with context.db.cursor() as cur:
133 for r in context.table:
136 if h.startswith("tags+"):
137 tags.extend((h[5:], r[h]))
139 nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
141 cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
142 (r['id'], nodes, tags))
144 ################################ WHEN ##################################
147 def import_and_index_data_from_place_table(context):
148 """ Import data previously set up in the place table.
150 context.nominatim.copy_from_place(context.db)
151 context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
152 check_database_integrity(context)
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)
162 context.nominatim.reindex_placex(context.db)
163 check_database_integrity(context)
165 @when("updating postcodes")
166 def update_postcodes(context):
167 context.nominatim.run_update_script('calculate-postcodes')
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 {}')
177 context.nominatim.reindex_placex(context.db)
179 ################################ THEN ##################################
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']
194 expected_content.add((res['osm_type'], res['osm_id'], res['class']))
195 for h in row.headings:
196 if h in ('extratags', 'address'):
198 assert res[h] is None
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+'):
210 if res['address'] is not None:
211 assert h[5:] not in res['address']
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)
218 assert_db_column(res, h, row[h], context)
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])
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']
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'):
242 assert res[h] is None, msg
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+'):
252 if res['address'] is not None:
253 assert h[5:] not in res['address']
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)
259 assert_db_column(res, h, row[h], context)
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])
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']
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
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
294 assert subcur.rowcount >= len(terms) + len(words), \
295 "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
298 assert wid[0] not in res[h], "Found term for %s/%s: %s" % (row['object'], h, wid[1])
300 assert wid[0] in res[h], "Missing term for %s/%s: %s" % (row['object'], h, wid[1])
302 assert_db_column(res, h, row[h], context)
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)))
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']:
317 for h in row.headings:
318 if h not in ('country', 'postcode'):
319 assert_db_column(table[i], h, row[h], context)
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:
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)
332 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
334 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
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""",
345 assert cur.rowcount > 0, \
346 "No rows found for place %s and address %s" % (row['object'], row['address'])
349 for h in row.headings:
350 if h not in ('address', 'object'):
351 assert_db_column(res, h, row[h], context)
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""",
362 assert cur.rowcount == 0, \
363 "Row found for place %s and address %s" % (row['object'], row['address'])
365 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
366 def check_location_property_osmline(context, oid, neg):
367 nid = NominatimID(oid)
369 assert 'W' == nid.typ, "interpolation must be a way"
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""",
378 assert cur.rowcount == 0
381 todo = list(range(len(list(context.table))))
384 row = context.table[i]
385 if (int(row['start']) == res['startnumber']
386 and int(row['end']) == res['endnumber']):
390 assert False, "Unexpected row %s" % (str(res))
392 for h in row.headings:
393 if h in ('start', 'end'):
395 elif h == 'parent_place_id':
396 compare_place_id(row[h], res[h], h, context)
398 assert_db_column(res, h, row[h], context)
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)
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)