| 576 | |
| 577 | |
| 578 | class DbConnection(metaclass=ABCMeta): |
| 579 | |
| 580 | LOCK = Lock() |
| 581 | |
| 582 | PORT = None |
| 583 | USER_NAME = None |
| 584 | PASSWORD = None |
| 585 | |
| 586 | _CURSOR_CLASS = DbCursor |
| 587 | |
| 588 | def __init__(self, host_name="localhost", port=None, user_name=None, password=None, |
| 589 | db_name=None, log_sql=False): |
| 590 | self._host_name = host_name |
| 591 | self._port = port or self.PORT |
| 592 | self._user_name = user_name or self.USER_NAME |
| 593 | self._password = password or self.PASSWORD |
| 594 | self.db_name = db_name |
| 595 | self._conn = None |
| 596 | self._connect() |
| 597 | |
| 598 | if log_sql: |
| 599 | with DbConnection.LOCK: |
| 600 | sql_log_path = gettempdir() + '/sql_log_%s_%s.sql' \ |
| 601 | % (self.db_type.lower(), time()) |
| 602 | self.sql_log = open(sql_log_path, 'w') |
| 603 | link = gettempdir() + '/sql_log_%s.sql' % self.db_type.lower() |
| 604 | try: |
| 605 | unlink(link) |
| 606 | except OSError as e: |
| 607 | if 'No such file' not in str(e): |
| 608 | raise e |
| 609 | try: |
| 610 | symlink(sql_log_path, link) |
| 611 | except OSError as e: |
| 612 | raise e |
| 613 | else: |
| 614 | self.sql_log = None |
| 615 | |
| 616 | def _clone(self, db_name, **kwargs): |
| 617 | return type(self)(host_name=self._host_name, port=self._port, |
| 618 | user_name=self._user_name, password=self._password, db_name=db_name, **kwargs) |
| 619 | |
| 620 | def clone(self, db_name): |
| 621 | return self._clone(db_name) |
| 622 | |
| 623 | def __getattr__(self, attr): |
| 624 | if attr == "_conn": |
| 625 | raise AttributeError() |
| 626 | return getattr(self._conn, attr) |
| 627 | |
| 628 | def __setattr__(self, attr, value): |
| 629 | _conn = getattr(self, "_conn", None) |
| 630 | if not _conn or not hasattr(_conn, attr): |
| 631 | object.__setattr__(self, attr, value) |
| 632 | else: |
| 633 | setattr(self._conn, attr, value) |
| 634 | |
| 635 | def __enter__(self): |