Advertisement
Guest User

Untitled

a guest
Jan 16th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.72 KB | None | 0 0
  1. #! coding: utf-8
  2.  
  3. import logging
  4. import psycopg2
  5. import ORM.settings as settings
  6. from errors import TableAlreadyExistsException, NoRequestToExecuteException
  7. from tables import Table
  8.  
  9.  
  10. class Database(object):
  11. """ Этот класс отражает базу данных """
  12.  
  13. def __init__(self):
  14. self.connection = None
  15. self.cursor = None
  16.  
  17. # здесь хранятся все новоиспеченные (объекты) sql-запросы, кроме запросов на взаимодействие с таблицами
  18. self.new_requests = []
  19. # тут хранятся объекты таблиц, которые уже существуют в системе
  20. self.exist_tables = []
  21. # тут хранятся таблицы, которые еще не были созданы
  22. self.new_tables = []
  23.  
  24. # соединяется с базой данных
  25. def connect(self):
  26. try:
  27. self.connection = psycopg2.connect(database=settings.PSQL_DBNAME, user=settings.PSQL_USER,
  28. password=settings.PSQL_PASSWORD)
  29. self.cursor = self.connection.cursor()
  30.  
  31. except psycopg2.Error as e:
  32. logging.error(str(e.pgerror))
  33.  
  34. # сохраняет изменения в базе данных
  35. def save(self):
  36. try:
  37. self.connection.commit()
  38.  
  39. except psycopg2.Error as e:
  40. logging.error(str(e.pgerror))
  41.  
  42. # создает таблицу на объектном уровне
  43. def create_table(self, table_name):
  44. # если такой таблицы еще не существует
  45. if len([table for table in self.new_tables if table.name == table_name]) == 0:
  46. # добавь
  47. self.new_tables.append(Table(table_name))
  48.  
  49. # и верни
  50. return self.new_tables[len(self.new_tables) - 1]
  51. else:
  52. raise TableAlreadyExistsException
  53.  
  54. # собирает все подготовленные sql-запросы в одну кучу
  55. def __collect_sql_requests(self):
  56. requests = ""
  57.  
  58. # запросы на добавление новых таблиц
  59. for table in self.new_tables:
  60. requests += table.get_sql_create_request()
  61.  
  62. # запросы insert-delete-update
  63. for request in self.new_requests:
  64. requests += request.get_sql_request()
  65.  
  66. return requests
  67.  
  68. # применяет накопившиеся запросы
  69. def apply(self):
  70.  
  71. request = self.__collect_sql_requests()
  72. if not request:
  73. raise NoRequestToExecuteException
  74.  
  75. try:
  76. self.cursor.execute(request)
  77. except psycopg2.Error as e:
  78. logging.error(str(e.pgerror))
  79.  
  80. # обновляем информацию
  81. self.exist_tables += self.new_tables
  82. self.new_tables = []
  83.  
  84. self.new_requests = []
  85.  
  86. # закрывает соединение с базой данных
  87. def __del__(self):
  88. try:
  89. self.cursor.close()
  90. self.connection.close()
  91.  
  92. except psycopg2.Error as e:
  93. logging.error(str(e.pgerror))
  94.  
  95.  
  96. # TODO: requests + delete functions + VALIDATION
  97.  
  98. """
  99. Контракт создания таблицы следующий:
  100. 1. Создаем объект базы данных, соединяемся с ней
  101. 2. Создаем объект таблицы, добавляем нужное количество колонок
  102. 3. Применяем изменения методом apply - создается и запускается sql-запрос
  103. 4. Сохраняем изменения функцией save
  104. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement