| 9 | from utils.utils import CastDB, Util |
| 10 | |
| 11 | class PostgreSQL(DataBase): |
| 12 | |
| 13 | def __init__(self, dbname:str, connectionsettings:Connection): |
| 14 | super().__init__(dbname=dbname, connectionsettings=connectionsettings) |
| 15 | self._tables_schema = "information_schema.tables" |
| 16 | self._queries = { |
| 17 | "databases":"SELECT datname FROM pg_catalog.pg_database" |
| 18 | } |
| 19 | |
| 20 | @property |
| 21 | def principal_database(self)->str: |
| 22 | return "postgres" |
| 23 | |
| 24 | def _get_cursor(self): |
| 25 | try: |
| 26 | self._conn = psycopg2.connect(dbname=self._database if self._database is not None else self.principal_database, |
| 27 | user=self.username, |
| 28 | password=self.password, |
| 29 | host=self.host, connect_timeout=30) |
| 30 | self._conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT); |
| 31 | cursor = self._conn.cursor() |
| 32 | return cursor |
| 33 | except Exception as e: |
| 34 | raise e |
| 35 | |
| 36 | def _destroy(self, cursor): |
| 37 | cursor.close() |
| 38 | self._conn.close() |
| 39 | |
| 40 | def close(self): |
| 41 | if self._conn: |
| 42 | self._conn.close() |
| 43 | |
| 44 | |
| 45 | def _execute(self, sentence, values=None): |
| 46 | try: |
| 47 | cur = self._get_cursor() |
| 48 | generated = cur.execute(sentence, values) |
| 49 | self._conn.commit() |
| 50 | cur.close() |
| 51 | self._destroy(cur) |
| 52 | |
| 53 | return generated |
| 54 | except Exception as e: |
| 55 | raise e |
| 56 | |
| 57 | def _executemany(self, sentence, values=None): |
| 58 | try: |
| 59 | cur = self._get_cursor() |
| 60 | generated = cur.executemany(sentence, values) |
| 61 | self._conn.commit() |
| 62 | self._destroy(cur) |
| 63 | cur.close() |
| 64 | return generated |
| 65 | except Exception as e: |
| 66 | raise e |
| 67 | |
| 68 | |