postgres.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import json
  2. import psycopg2
  3. import traceback
  4. from colorama import Fore
  5. from toolset.utils.output_helper import log
  6. from toolset.databases.abstract_database import AbstractDatabase
  7. class Database(AbstractDatabase):
  8. @classmethod
  9. def get_connection(cls, config):
  10. db = psycopg2.connect(
  11. host=config.database_host,
  12. port="5432",
  13. user="benchmarkdbuser",
  14. password="benchmarkdbpass",
  15. database="hello_world")
  16. cursor = db.cursor()
  17. cursor.execute("CREATE EXTENSION IF NOT EXISTS pg_stat_statements")
  18. return db
  19. @classmethod
  20. def get_current_world_table(cls, config):
  21. results_json = []
  22. try:
  23. db = cls.get_connection(config)
  24. cursor = db.cursor()
  25. cursor.execute("SELECT * FROM \"World\"")
  26. results = cursor.fetchall()
  27. results_json.append(json.loads(json.dumps(dict(results))))
  28. cursor = db.cursor()
  29. cursor.execute("SELECT * FROM \"world\"")
  30. results = cursor.fetchall()
  31. results_json.append(json.loads(json.dumps(dict(results))))
  32. db.close()
  33. except Exception:
  34. tb = traceback.format_exc()
  35. log("ERROR: Unable to load current Postgres World table.",
  36. color=Fore.RED)
  37. log(tb)
  38. return results_json
  39. @classmethod
  40. def test_connection(cls, config):
  41. try:
  42. db = cls.get_connection(config)
  43. cursor = db.cursor()
  44. cursor.execute("SELECT 1")
  45. cursor.fetchall()
  46. db.close()
  47. return True
  48. except:
  49. return False
  50. @classmethod
  51. def get_queries(cls, config):
  52. return cls.__exec_and_fetchone(config, "SELECT SUM(calls) FROM pg_stat_statements WHERE query ~* '[[:<:]]%s[[:>:]]'" % cls.tbl_name)
  53. @classmethod
  54. def get_rows(cls, config):
  55. return cls.__exec_and_fetchone(config, "SELECT SUM(rows) FROM pg_stat_statements WHERE query ~* '[[:<:]]%s[[:>:]]' AND query ~* 'select'" % cls.tbl_name)
  56. @classmethod
  57. def get_rows_updated(cls, config):
  58. return cls.__exec_and_fetchone(config, "SELECT SUM(rows) FROM pg_stat_statements WHERE query ~* '[[:<:]]%s[[:>:]]' AND query ~* 'update'" % cls.tbl_name)
  59. @classmethod
  60. def reset_cache(cls, config):
  61. # To fix: DISCARD ALL cannot run inside a transaction block
  62. # cursor = self.db.cursor()
  63. # cursor.execute("END;DISCARD ALL;")
  64. # self.db.commit()
  65. return
  66. @classmethod
  67. def __exec_and_fetchone(cls, config, query):
  68. db = cls.get_connection(config)
  69. cursor = db.cursor()
  70. cursor.execute(query)
  71. record = cursor.fetchone()
  72. return record[0]