create_data_tbl.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. @Date :2021/5/21/00219:10:57
  3. @Desc :此类可以根据站表和点表的内容自动创建table开头的存储历史数据的数据表
  4. 运行只对status为1的站点所对应的数据表有修改。
  5. """
  6. import os
  7. import sys
  8. from event_storage import EventStorage
  9. import threading
  10. class CreateDataTable(threading.Thread):
  11. def __init__(self):
  12. super().__init__()
  13. self.storage = EventStorage()
  14. def get_stations_info(self):
  15. """
  16. 获取激活的站点信息
  17. """
  18. sql = "SELECT * FROM station_info_tbl WHERE status = 1;"
  19. res = self.storage.execute_sql(sql)
  20. return res
  21. def get_device_by_station_name(self, station_name):
  22. sql = "select DISTINCT (device_name) from data_point_tbl where station_name = '%s'" % station_name
  23. results = self.storage.execute_sql(sql)
  24. return results
  25. def get_point_by_device_name(self, device_name):
  26. sql = "SELECT * FROM data_point_tbl WHERE device_name = '%s'" % device_name
  27. results = self.storage.execute_sql(sql)
  28. return results
  29. def run(self):
  30. stations_list = self.get_stations_info()
  31. for each_station in stations_list:
  32. devices_list = self.get_device_by_station_name(each_station['station_name'])
  33. for each_device in devices_list:
  34. points_list = self.get_point_by_device_name(each_device['device_name'])
  35. table_name = 'table_' + each_device['device_name']
  36. sql_c = "CREATE TABLE IF NOT EXISTS %s (id bigint primary key auto_increment, times datetime NOT NULL,INDEX (times)) ENGINE=InnoDB DEFAULT CHARSET=utf8;" % table_name
  37. self.storage.execute_sql(sql_c)
  38. for i in points_list:
  39. dataType = i['storage_type']
  40. columnName = "c" + str(i['serial_number'])
  41. sql = "SELECT * FROM information_schema.COLUMNS WHERE column_name='%s' and table_name='%s' and table_schema='shucai'" % (columnName, table_name)
  42. res = self.storage.execute_sql(sql)
  43. if not res:
  44. sql_add = "ALTER TABLE %s ADD COLUMN %s %s comment '%s' " % (table_name, columnName, dataType, i['io_point_name'])
  45. self.storage.execute_sql(sql_add)
  46. sql = "SELECT * FROM information_schema.COLUMNS WHERE column_name='is_send' and table_name='%s' and table_schema='shucai'" % (table_name)
  47. res = self.storage.execute_sql(sql)
  48. if not res:
  49. sql_add_is_send = "ALTER TABLE %s ADD COLUMN is_send tinyint" % (table_name)
  50. self.storage.execute_sql(sql_add_is_send)
  51. print(table_name, "done !")
  52. if __name__ == '__main__':
  53. CreateDataTable().run()