|
| 1 | +import os, psycopg |
| 2 | +from flask import g |
| 3 | +from psycopg.rows import dict_row |
| 4 | + |
| 5 | +class DatabaseConnection: |
| 6 | + DEV_DATABASE_NAME = "giga" |
| 7 | + TEST_DATABASE_NAME = "giga_test" |
| 8 | + |
| 9 | + def __init__(self, test_mode=False): |
| 10 | + self.test_mode = test_mode |
| 11 | + |
| 12 | + def connect(self): |
| 13 | + try: |
| 14 | + self.connection = psycopg.connect( |
| 15 | + f"postgresql://localhost/{self._database_name()}", |
| 16 | + row_factory=dict_row) |
| 17 | + except psycopg.OperationalError: |
| 18 | + raise Exception(f"Couldn't connect to the database {self._database_name()}! " \ |
| 19 | + f"Did you create it using `createdb {self._database_name()}`?") |
| 20 | + |
| 21 | + def seed(self, sql_filename): |
| 22 | + self._check_connection() |
| 23 | + if not os.path.exists(sql_filename): |
| 24 | + raise Exception(f"File {sql_filename} does not exist") |
| 25 | + with self.connection.cursor() as cursor: |
| 26 | + cursor.execute(open(sql_filename, "r").read()) |
| 27 | + self.connection.commit() |
| 28 | + |
| 29 | + def execute(self, query, params=[]): |
| 30 | + self._check_connection() |
| 31 | + with self.connection.cursor() as cursor: |
| 32 | + cursor.execute(query, params) |
| 33 | + if cursor.description is not None: |
| 34 | + result = cursor.fetchall() |
| 35 | + else: |
| 36 | + result = None |
| 37 | + self.connection.commit() |
| 38 | + return result |
| 39 | + |
| 40 | + CONNECTION_MESSAGE = '' \ |
| 41 | + 'DatabaseConnection.exec_params: Cannot run a SQL query as ' \ |
| 42 | + 'the connection to the database was never opened. Did you ' \ |
| 43 | + 'make sure to call first the method DatabaseConnection.connect` ' \ |
| 44 | + 'in your app.py file (or in your tests)?' |
| 45 | + |
| 46 | + def _check_connection(self): |
| 47 | + if self.connection is None: |
| 48 | + raise Exception(self.CONNECTION_MESSAGE) |
| 49 | + |
| 50 | + def _database_name(self): |
| 51 | + if self.test_mode: |
| 52 | + return self.TEST_DATABASE_NAME |
| 53 | + else: |
| 54 | + return self.DEV_DATABASE_NAME |
| 55 | + |
| 56 | +def get_flask_database_connection(app): |
| 57 | + if not hasattr(g, 'flask_database_connection'): |
| 58 | + g.flask_database_connection = DatabaseConnection( |
| 59 | + test_mode=((os.getenv('APP_ENV') == 'test') or (app.config['TESTING'] == True)) |
| 60 | + ) |
| 61 | + g.flask_database_connection.connect() |
| 62 | + return g.flask_database_connection |
0 commit comments