db.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import logging
  2. import sqlite3
  3. import config
  4. class connect:
  5. conn = None
  6. def __enter__(self):
  7. self.conn = sqlite3.connect(config.DB_PATH)
  8. self.cursor = self.conn.cursor()
  9. return self
  10. def __exit__(self, type, value, traceback):
  11. if traceback:
  12. logging.error(traceback)
  13. self.conn.close()
  14. def execute(self, stmt, *params):
  15. self.cursor.execute(stmt, params)
  16. self.conn.commit()
  17. def select(self, stmt, *params):
  18. res = []
  19. for row in self.cursor.execute(stmt, params):
  20. if len(row) == 1:
  21. res.append(row[0])
  22. else:
  23. res.append(row)
  24. return res
  25. def init():
  26. logging.info('Initializing database at %s...', config.DB_PATH)
  27. with connect() as conn:
  28. # conn.execute('drop table if exists localities;')
  29. conn.execute('''
  30. create table if not exists localities (
  31. id integer not null primary key,
  32. name varchar(255) not null
  33. );
  34. ''')
  35. # conn.execute('drop table if exists locality_relationships;')
  36. conn.execute('''
  37. create table if not exists locality_relationships (
  38. id varchar(255) not null primary key,
  39. parent integer not null,
  40. child integer not null
  41. )
  42. ''')
  43. conn.execute('''
  44. create table if not exists search_results (
  45. id integer not null primary key,
  46. time datetime not null,
  47. property_id integer not null,
  48. raw_json text not null
  49. )
  50. ''')
  51. conn.execute('''
  52. create table if not exists properties (
  53. id integer not null primary key,
  54. last_update datetime not null,
  55. raw_json text not null
  56. )
  57. ''')
  58. init()