]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/steps_db_ops.py
178e1a284779348a8952bb9d17f82b0fc1172323
[nominatim.git] / test / bdd / steps / steps_db_ops.py
1 import psycopg2.extras
2
3 from place_inserter import PlaceColumn
4 from table_compare import NominatimID, DBRow
5
6
7 def check_database_integrity(context):
8     """ Check some generic constraints on the tables.
9     """
10     # place_addressline should not have duplicate (place_id, address_place_id)
11     cur = context.db.cursor()
12     cur.execute("""SELECT count(*) FROM
13                     (SELECT place_id, address_place_id, count(*) as c
14                      FROM place_addressline GROUP BY place_id, address_place_id) x
15                    WHERE c > 1""")
16     assert cur.fetchone()[0] == 0, "Duplicates found in place_addressline"
17
18
19 ################################ GIVEN ##################################
20
21 @given("the (?P<named>named )?places")
22 def add_data_to_place_table(context, named):
23     with context.db.cursor() as cur:
24         cur.execute('ALTER TABLE place DISABLE TRIGGER place_before_insert')
25         for row in context.table:
26             PlaceColumn(context).add_row(row, named is not None).db_insert(cur)
27         cur.execute('ALTER TABLE place ENABLE TRIGGER place_before_insert')
28
29 @given("the relations")
30 def add_data_to_planet_relations(context):
31     with context.db.cursor() as cur:
32         for r in context.table:
33             last_node = 0
34             last_way = 0
35             parts = []
36             if r['members']:
37                 members = []
38                 for m in r['members'].split(','):
39                     mid = NominatimID(m)
40                     if mid.typ == 'N':
41                         parts.insert(last_node, int(mid.oid))
42                         last_node += 1
43                         last_way += 1
44                     elif mid.typ == 'W':
45                         parts.insert(last_way, int(mid.oid))
46                         last_way += 1
47                     else:
48                         parts.append(int(mid.oid))
49
50                     members.extend((mid.typ.lower() + mid.oid, mid.cls or ''))
51             else:
52                 members = None
53
54             tags = []
55             for h in r.headings:
56                 if h.startswith("tags+"):
57                     tags.extend((h[5:], r[h]))
58
59             cur.execute("""INSERT INTO planet_osm_rels (id, way_off, rel_off, parts, members, tags)
60                            VALUES (%s, %s, %s, %s, %s, %s)""",
61                         (r['id'], last_node, last_way, parts, members, tags))
62
63 @given("the ways")
64 def add_data_to_planet_ways(context):
65     with context.db.cursor() as cur:
66         for r in context.table:
67             tags = []
68             for h in r.headings:
69                 if h.startswith("tags+"):
70                     tags.extend((h[5:], r[h]))
71
72             nodes = [ int(x.strip()) for x in r['nodes'].split(',') ]
73
74             cur.execute("INSERT INTO planet_osm_ways (id, nodes, tags) VALUES (%s, %s, %s)",
75                         (r['id'], nodes, tags))
76
77 ################################ WHEN ##################################
78
79 @when("importing")
80 def import_and_index_data_from_place_table(context):
81     """ Import data previously set up in the place table.
82     """
83     context.nominatim.copy_from_place(context.db)
84     context.nominatim.run_setup_script('calculate-postcodes', 'index', 'index-noanalyse')
85     check_database_integrity(context)
86
87 @when("updating places")
88 def update_place_table(context):
89     context.nominatim.run_setup_script(
90         'create-functions', 'create-partition-functions', 'enable-diff-updates')
91     with context.db.cursor() as cur:
92         for row in context.table:
93             PlaceColumn(context).add_row(row, False).db_insert(cur)
94
95     context.nominatim.reindex_placex(context.db)
96     check_database_integrity(context)
97
98 @when("updating postcodes")
99 def update_postcodes(context):
100     context.nominatim.run_update_script('calculate-postcodes')
101
102 @when("marking for delete (?P<oids>.*)")
103 def delete_places(context, oids):
104     context.nominatim.run_setup_script(
105         'create-functions', 'create-partition-functions', 'enable-diff-updates')
106     with context.db.cursor() as cur:
107         for oid in oids.split(','):
108             NominatimID(oid).query_osm_id(cur, 'DELETE FROM place WHERE {}')
109
110     context.nominatim.reindex_placex(context.db)
111
112 ################################ THEN ##################################
113
114 @then("(?P<table>placex|place) contains(?P<exact> exactly)?")
115 def check_place_contents(context, table, exact):
116     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
117         expected_content = set()
118         for row in context.table:
119             nid = NominatimID(row['object'])
120             query = 'SELECT *, ST_AsText(geometry) as geomtxt, ST_GeometryType(geometry) as geometrytype'
121             if table == 'placex':
122                 query += ' ,ST_X(centroid) as cx, ST_Y(centroid) as cy'
123             query += " FROM %s WHERE {}" % (table, )
124             nid.query_osm_id(cur, query)
125             assert cur.rowcount > 0, "No rows found for " + row['object']
126
127             for res in cur:
128                 if exact:
129                     expected_content.add((res['osm_type'], res['osm_id'], res['class']))
130
131                 DBRow(nid, res, context).assert_row(row, ['object'])
132
133         if exact:
134             cur.execute('SELECT osm_type, osm_id, class from {}'.format(table))
135             assert expected_content == set([(r[0], r[1], r[2]) for r in cur])
136
137
138 @then("(?P<table>placex|place) has no entry for (?P<oid>.*)")
139 def check_place_has_entry(context, table, oid):
140     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
141         NominatimID(oid).query_osm_id(cur, "SELECT * FROM %s where {}" % table)
142         assert cur.rowcount == 0, \
143                "Found {} entries for ID {}".format(cur.rowcount, oid)
144
145
146 @then("search_name contains(?P<exclude> not)?")
147 def check_search_name_contents(context, exclude):
148     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
149         for row in context.table:
150             nid = NominatimID(row['object'])
151             nid.row_by_place_id(cur, 'search_name',
152                                 ['ST_X(centroid) as cx', 'ST_Y(centroid) as cy'])
153             assert cur.rowcount > 0, "No rows found for " + row['object']
154
155             for res in cur:
156                 db_row = DBRow(nid, res, context)
157                 for h in row.headings:
158                     if h in ('name_vector', 'nameaddress_vector'):
159                         terms = [x.strip() for x in row[h].split(',') if not x.strip().startswith('#')]
160                         words = [x.strip()[1:] for x in row[h].split(',') if x.strip().startswith('#')]
161                         with context.db.cursor() as subcur:
162                             subcur.execute(""" SELECT word_id, word_token
163                                                FROM word, (SELECT unnest(%s::TEXT[]) as term) t
164                                                WHERE word_token = make_standard_name(t.term)
165                                                      and class is null and country_code is null
166                                                      and operator is null
167                                               UNION
168                                                SELECT word_id, word_token
169                                                FROM word, (SELECT unnest(%s::TEXT[]) as term) t
170                                                WHERE word_token = ' ' || make_standard_name(t.term)
171                                                      and class is null and country_code is null
172                                                      and operator is null
173                                            """,
174                                            (terms, words))
175                             if not exclude:
176                                 assert subcur.rowcount >= len(terms) + len(words), \
177                                     "No word entry found for " + row[h] + ". Entries found: " + str(subcur.rowcount)
178                             for wid in subcur:
179                                 if exclude:
180                                     assert wid[0] not in res[h], "Found term for %s/%s: %s" % (row['object'], h, wid[1])
181                                 else:
182                                     assert wid[0] in res[h], "Missing term for %s/%s: %s" % (row['object'], h, wid[1])
183                     elif h != 'object':
184                         assert db_row.contains(h, row[h]), db_row.assert_msg(h, row[h])
185
186 @then("location_postcode contains exactly")
187 def check_location_postcode(context):
188     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
189         cur.execute("SELECT *, ST_AsText(geometry) as geomtxt FROM location_postcode")
190         assert cur.rowcount == len(list(context.table)), \
191             "Postcode table has %d rows, expected %d rows." % (cur.rowcount, len(list(context.table)))
192
193         results = {}
194         for row in cur:
195             key = (row['country_code'], row['postcode'])
196             assert key not in results, "Postcode table has duplicate entry: {}".format(row)
197             results[key] = DBRow((row['country_code'],row['postcode']), row, context)
198
199         for row in context.table:
200             db_row = results.get((row['country'],row['postcode']))
201             assert db_row is not None, \
202                 "Missing row for country '{}' postcode '{}'.".format(r['country'],['postcode'])
203
204             db_row.assert_row(row, ('country', 'postcode'))
205
206 @then("word contains(?P<exclude> not)?")
207 def check_word_table(context, exclude):
208     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
209         for row in context.table:
210             wheres = []
211             values = []
212             for h in row.headings:
213                 wheres.append("%s = %%s" % h)
214                 values.append(row[h])
215             cur.execute("SELECT * from word WHERE %s" % ' AND '.join(wheres), values)
216             if exclude:
217                 assert cur.rowcount == 0, "Row still in word table: %s" % '/'.join(values)
218             else:
219                 assert cur.rowcount > 0, "Row not in word table: %s" % '/'.join(values)
220
221 @then("place_addressline contains")
222 def check_place_addressline(context):
223     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
224         for row in context.table:
225             nid = NominatimID(row['object'])
226             pid = nid.get_place_id(cur)
227             apid = NominatimID(row['address']).get_place_id(cur)
228             cur.execute(""" SELECT * FROM place_addressline
229                             WHERE place_id = %s AND address_place_id = %s""",
230                         (pid, apid))
231             assert cur.rowcount > 0, \
232                         "No rows found for place %s and address %s" % (row['object'], row['address'])
233
234             for res in cur:
235                 DBRow(nid, res, context).assert_row(row, ('address', 'object'))
236
237 @then("place_addressline doesn't contain")
238 def check_place_addressline_exclude(context):
239     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
240         for row in context.table:
241             pid = NominatimID(row['object']).get_place_id(cur)
242             apid = NominatimID(row['address']).get_place_id(cur)
243             cur.execute(""" SELECT * FROM place_addressline
244                             WHERE place_id = %s AND address_place_id = %s""",
245                         (pid, apid))
246             assert cur.rowcount == 0, \
247                 "Row found for place %s and address %s" % (row['object'], row['address'])
248
249 @then("(?P<oid>\w+) expands to(?P<neg> no)? interpolation")
250 def check_location_property_osmline(context, oid, neg):
251     nid = NominatimID(oid)
252
253     assert 'W' == nid.typ, "interpolation must be a way"
254
255     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
256         cur.execute("""SELECT *, ST_AsText(linegeo) as geomtxt
257                        FROM location_property_osmline
258                        WHERE osm_id = %s AND startnumber IS NOT NULL""",
259                     (nid.oid, ))
260
261         if neg:
262             assert cur.rowcount == 0
263             return
264
265         todo = list(range(len(list(context.table))))
266         for res in cur:
267             for i in todo:
268                 row = context.table[i]
269                 if (int(row['start']) == res['startnumber']
270                     and int(row['end']) == res['endnumber']):
271                     todo.remove(i)
272                     break
273             else:
274                 assert False, "Unexpected row %s" % (str(res))
275
276             DBRow(nid, res, context).assert_row(row, ('start', 'end'))
277
278         assert not todo
279
280
281 @then("search_name has no entry for (?P<oid>.*)")
282 def check_search_name_has_entry(context, oid):
283     with context.db.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
284         NominatimID(oid).row_by_place_id(cur, 'search_name')
285
286         assert cur.rowcount == 0, \
287                "Found {} entries for ID {}".format(cur.rowcount, oid)