2 Main work horse for indexing (computing addresses) the database.
 
   4 # pylint: disable=C0111
 
  10 from .progress import ProgressLogger
 
  11 from ..db.async_connection import DBConnection
 
  13 LOG = logging.getLogger()
 
  16     """ Returns SQL commands for indexing one rank within the placex table.
 
  19     def __init__(self, rank):
 
  23         return "rank {}".format(self.rank)
 
  25     def sql_count_objects(self):
 
  26         return """SELECT count(*) FROM placex
 
  27                   WHERE rank_address = {} and indexed_status > 0
 
  30     def sql_get_objects(self):
 
  31         return """SELECT place_id FROM placex
 
  32                   WHERE indexed_status > 0 and rank_address = {}
 
  33                   ORDER BY geometry_sector""".format(self.rank)
 
  36     def sql_index_place(ids):
 
  37         return "UPDATE placex SET indexed_status = 0 WHERE place_id IN ({})"\
 
  38                .format(','.join((str(i) for i in ids)))
 
  41 class InterpolationRunner:
 
  42     """ Returns SQL commands for indexing the address interpolation table
 
  43         location_property_osmline.
 
  48         return "interpolation lines (location_property_osmline)"
 
  51     def sql_count_objects():
 
  52         return """SELECT count(*) FROM location_property_osmline
 
  53                   WHERE indexed_status > 0"""
 
  56     def sql_get_objects():
 
  57         return """SELECT place_id FROM location_property_osmline
 
  58                   WHERE indexed_status > 0
 
  59                   ORDER BY geometry_sector"""
 
  62     def sql_index_place(ids):
 
  63         return """UPDATE location_property_osmline
 
  64                   SET indexed_status = 0 WHERE place_id IN ({})"""\
 
  65                .format(','.join((str(i) for i in ids)))
 
  68     """ Returns SQL commands for indexing the administrative boundaries
 
  72     def __init__(self, rank):
 
  76         return "boundaries rank {}".format(self.rank)
 
  78     def sql_count_objects(self):
 
  79         return """SELECT count(*) FROM placex
 
  80                   WHERE indexed_status > 0
 
  82                     AND class = 'boundary' and type = 'administrative'""".format(self.rank)
 
  84     def sql_get_objects(self):
 
  85         return """SELECT place_id FROM placex
 
  86                   WHERE indexed_status > 0 and rank_search = {}
 
  87                         and class = 'boundary' and type = 'administrative'
 
  88                   ORDER BY partition, admin_level""".format(self.rank)
 
  91     def sql_index_place(ids):
 
  92         return "UPDATE placex SET indexed_status = 0 WHERE place_id IN ({})"\
 
  93                .format(','.join((str(i) for i in ids)))
 
  96     """ Main indexing routine.
 
  99     def __init__(self, dsn, num_threads):
 
 100         self.conn = psycopg2.connect(dsn)
 
 101         self.threads = [DBConnection(dsn) for _ in range(num_threads)]
 
 103     def index_boundaries(self, minrank, maxrank):
 
 104         LOG.warning("Starting indexing boundaries using %s threads",
 
 107         for rank in range(max(minrank, 4), min(maxrank, 26)):
 
 108             self.index(BoundaryRunner(rank))
 
 110     def index_by_rank(self, minrank, maxrank):
 
 111         """ Run classic indexing by rank.
 
 113         maxrank = min(maxrank, 30)
 
 114         LOG.warning("Starting indexing rank (%i to %i) using %i threads",
 
 115                     minrank, maxrank, len(self.threads))
 
 117         for rank in range(max(1, minrank), maxrank):
 
 118             self.index(RankRunner(rank))
 
 121             self.index(RankRunner(0))
 
 122             self.index(InterpolationRunner(), 20)
 
 123             self.index(RankRunner(30), 20)
 
 125             self.index(RankRunner(maxrank))
 
 127     def update_status_table(self):
 
 128         """ Update the status in the status table to 'indexed'.
 
 130         with self.conn.cursor() as cur:
 
 131             cur.execute('UPDATE import_status SET indexed = true')
 
 134     def index(self, obj, batch=1):
 
 135         """ Index a single rank or table. `obj` describes the SQL to use
 
 136             for indexing. `batch` describes the number of objects that
 
 137             should be processed with a single SQL statement
 
 139         LOG.warning("Starting %s (using batch size %s)", obj.name(), batch)
 
 141         cur = self.conn.cursor()
 
 142         cur.execute(obj.sql_count_objects())
 
 144         total_tuples = cur.fetchone()[0]
 
 145         LOG.debug("Total number of rows: %i", total_tuples)
 
 149         progress = ProgressLogger(obj.name(), total_tuples)
 
 152             cur = self.conn.cursor(name='places')
 
 153             cur.execute(obj.sql_get_objects())
 
 155             next_thread = self.find_free_thread()
 
 157                 places = [p[0] for p in cur.fetchmany(batch)]
 
 161                 LOG.debug("Processing places: %s", str(places))
 
 162                 thread = next(next_thread)
 
 164                 thread.perform(obj.sql_index_place(places))
 
 165                 progress.add(len(places))
 
 169             for thread in self.threads:
 
 174     def find_free_thread(self):
 
 175         """ Generator that returns the next connection that is free for
 
 187             # refresh the connections occasionaly to avoid potential
 
 188             # memory leaks in Postgresql.
 
 189             if command_stat > 100000:
 
 190                 for thread in self.threads:
 
 191                     while not thread.is_done():
 
 197                 ready, _, _ = select.select(self.threads, [], [])
 
 199         assert False, "Unreachable code"