Guest User

Untitled

a guest
Aug 13th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. import psycopg2
  2. import pymysql
  3.  
  4.  
  5. class Database(object):
  6. def __init__(self, host_name, user_name, database_name, password, port):
  7. self.host_name = host_name
  8. self.user_name = user_name
  9. self.database_name = database_name
  10. self.password = password
  11. self.port = port
  12.  
  13. def connection_manager(self):
  14. raise NotImplementedError
  15.  
  16. def execute(self, query):
  17. raise NotImplementedError
  18.  
  19.  
  20. class RedShift(Database):
  21. def __init__(self, host_name, user_name, database_name, password, port=5439):
  22. super().__init__(host_name, user_name, database_name, password, port)
  23.  
  24. def connection_manager(self, f):
  25. """
  26. Wrap function to setup and tear down a Postgres connection while
  27. providing a cursor object to make queries with.
  28. """
  29.  
  30. def wrapper(*args, **kwargs):
  31. try:
  32. self.connection = psycopg2.connect(dbname=self.database_name,
  33. host=self.host_name,
  34. port=self.port,
  35. user=self.user_name,
  36. password=self.password)
  37.  
  38. self.cursor = self.connection.cursor()
  39. result = f(*args, **kwargs)
  40. finally:
  41. self.cursor.close()
  42. self.connection.close()
  43.  
  44. return result
  45. return wrapper
  46.  
  47. @connection_manager
  48. def execute(self, query):
  49. self.cursor.execute(query)
  50. return self.cursor.fetchall()
  51.  
  52.  
  53. class MySQL(Database):
  54. def __init__(self, host_name, user_name, database_name, password, port=3306):
  55. super().__init__(host_name, user_name, database_name, password, port)
  56.  
  57. def connection_manager(self, f):
  58. """
  59. Wrap function to setup and tear down a Postgres connection while
  60. providing a cursor object to make queries with.
  61. """
  62.  
  63. def wrapper(*args, **kwargs):
  64. try:
  65. self.connection = pymysql.connect(db=self.database_name,
  66. host=self.host_name,
  67. port=self.port,
  68. user=self.user_name,
  69. password=self.password,
  70. charset='utf8mb4',
  71. cursorclass=pymysql.cursors.DictCursor)
  72.  
  73. self.cursor = self.connection.cursor()
  74. result = f(*args, **kwargs)
  75. self.connection.commit()
  76. finally:
  77. self.connection.close()
  78.  
  79. return result
  80. return wrapper
  81.  
  82. @connection_manager
  83. def execute(self, query):
  84. self.cursor.execute(query)
  85. return self.cursor.fetchall()
Add Comment
Please, Sign In to add comment