Esempio n. 1
0
    async def create_connection(self, with_db: bool) -> None:
        if charset_by_name(self.charset) is None:  # type: ignore
            raise DBConnectionError(f"Unknown charset {self.charset}")
        self._template = {
            "host": self.host,
            "port": self.port,
            "user": self.user,
            "db": self.database if with_db else None,
            "autocommit": True,
            "charset": self.charset,
            "minsize": self.pool_minsize,
            "maxsize": self.pool_maxsize,
            **self.extra,
        }
        try:
            self._pool = await aiomysql.create_pool(password=self.password, **self._template)

            if isinstance(self._pool, aiomysql.Pool):
                async with self.acquire_connection() as connection:
                    async with connection.cursor() as cursor:
                        if self.storage_engine:
                            await cursor.execute(
                                f"SET default_storage_engine='{self.storage_engine}';"
                            )
                            if self.storage_engine.lower() != "innodb":  # pragma: nobranch
                                self.capabilities.__dict__["supports_transactions"] = False
                        hours = timezone.now().utcoffset().seconds / 3600  # type: ignore
                        tz = "{:+d}:{:02d}".format(int(hours), int((hours % 1) * 60))
                        await cursor.execute(f"SET SESSION time_zone='{tz}';")
            self.log.debug("Created connection %s pool with params: %s", self._pool, self._template)
        except pymysql.err.OperationalError:
            raise DBConnectionError(f"Can't connect to MySQL server: {self._template}")
Esempio n. 2
0
    async def create_connection(self, with_db: bool) -> None:
        self._template = {
            "dsn": self.dsn,
            "minsize": self.pool_minsize,
            "maxsize": self.pool_maxsize,
            "executor": _g_thread_executor,
            "pool_recycle": self.pool_recycle,
            "timeout": self.timeout,
        }
        try:

            self._pool = await aioodbc.create_pool(**self._template)

            if isinstance(self._pool, aioodbc.Pool):
                async with self.acquire_connection() as connection:
                    async with connection.cursor() as cursor:
                        if self.storage_engine:
                            await cursor.execute(
                                f"SET default_storage_engine='{self.storage_engine}';"
                            )
                            if self.storage_engine.lower(
                            ) != "innodb":  # pragma: nobranch
                                self.capabilities.__dict__[
                                    "supports_transactions"] = False

            self.log.debug("Created connection %s pool with params: %s",
                           self._pool, self._template)
        except pyodbc.OperationalError as e:
            raise DBConnectionError(
                f"Can't connect to MySQL server: {self._template}")
Esempio n. 3
0
    async def retry_connection_(self, *args):
        try:
            return await func(self, *args)
        except (
                RuntimeError,
                pymysql.err.OperationalError,
                pymysql.err.InternalError,
                pymysql.err.InterfaceError,
        ):
            # Here we assume that a connection error has happened
            # Re-create connection and re-try the function call once only.
            if getattr(self, "_finalized", None) is False:
                raise TransactionManagementError(
                    "Connection gone away during transaction")
            await self._lock.acquire()
            logging.info("Attempting reconnect")
            try:
                await self._close()
                await self.create_connection(with_db=True)
                logging.info("Reconnected")
            except Exception as e:
                raise DBConnectionError("Failed to reconnect: %s", str(e))
            finally:
                self._lock.release()

            return await func(self, *args)
Esempio n. 4
0
    async def retry_connection_(self, *args):
        try:
            return await func(self, *args)
        except (
                asyncpg.PostgresConnectionError,
                asyncpg.ConnectionDoesNotExistError,
                asyncpg.ConnectionFailureError,
                asyncpg.InterfaceError,
        ):
            # Here we assume that a connection error has happened
            # Re-create connection and re-try the function call once only.
            if getattr(self, "transaction", None):
                self._finalized = True
                raise TransactionManagementError(
                    "Connection gone away during transaction")
            await self._lock.acquire()
            logging.info("Attempting reconnect")
            try:
                await self._close()
                await self.create_connection(with_db=True)
                logging.info("Reconnected")
            except Exception as e:
                raise DBConnectionError(f"Failed to reconnect: {str(e)}")
            finally:
                self._lock.release()

            return await func(self, *args)
Esempio n. 5
0
    async def create_connection(self, with_db: bool) -> None:
        self._template = {
            "host": self.host,
            "port": self.port,
            "user": self.user,
            "db": self.database if with_db else None,
            "autocommit": True,
            "charset": self.charset,
            **self.extra,
        }
        try:
            self._connection = await aiomysql.connect(password=self.password,
                                                      **self._template)

            if isinstance(self._connection, aiomysql.Connection):
                async with self._connection.cursor() as cursor:
                    if self.storage_engine:
                        await cursor.execute(
                            f"SET default_storage_engine='{self.storage_engine}';"
                        )
                        if self.storage_engine.lower() != "innodb":
                            self.capabilities.__dict__[
                                "supports_transactions"] = False

            self.log.debug("Created connection %s with params: %s",
                           self._connection, self._template)
        except pymysql.err.OperationalError:
            raise DBConnectionError(
                f"Can't connect to MySQL server: {self._template}")
Esempio n. 6
0
 async def create_connection(self) -> None:
     try:
         if not self.single_connection:
             self._db_pool = await asyncpg.create_pool(self.dsn)
         else:
             self._connection = await asyncpg.connect(self.dsn)
         self.log.debug(
             'Created connection with params: user=%s database=%s host=%s port=%s',
             self.user, self.database, self.host, self.port)
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError(
             "Can't establish connection to database {}".format(
                 self.database))
Esempio n. 7
0
 async def create_connection(self):
     try:
         if not self.single_connection:
             self._db_pool = await asyncpg.create_pool(self.dsn)
         else:
             self._connection = await asyncpg.connect(self.dsn)
         self.log.debug(
             'Created connection with params: '
             'user={user} database={database} host={host} port={port}'.format(
                 user=self.user, database=self.database, host=self.host, port=self.port
             )
         )
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError("Can't establish connection to database {}".format(
             self.database
         ))
Esempio n. 8
0
 async def create_connection(self, with_db: bool) -> None:
     dsn = self.DSN_TEMPLATE.format(
         user=self.user,
         password=self.password,
         host=self.host,
         port=self.port,
         database=self.database if with_db else '')
     try:
         self._connection = await asyncpg.connect(dsn)
         self.log.debug(
             'Created connection %s with params: user=%s database=%s host=%s port=%s',
             self._connection, self.user, self.database, self.host,
             self.port)
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError(
             "Can't establish connection to database {}".format(
                 self.database))
Esempio n. 9
0
 async def create_connection(self, with_db: bool) -> None:
     self._template = {
         "host": self.host,
         "port": self.port,
         "user": self.user,
         "database": self.database if with_db else None,
         "min_size": self.pool_minsize,
         "max_size": self.pool_maxsize,
         **self.extra,
     }
     if self.schema:
         self._template["server_settings"] = {"search_path": self.schema}
     try:
         self._pool = await asyncpg.create_pool(None, password=self.password, **self._template)
         self.log.debug("Created connection pool %s with params: %s", self._pool, self._template)
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError(f"Can't establish connection to database {self.database}")
Esempio n. 10
0
 async def create_connection(self, with_db: bool) -> None:
     self._template = {
         "host": self.host,
         "port": self.port,
         "user": self.user,
         "db": self.database if with_db else None,
         "autocommit": True,
         **self.extra,
     }
     try:
         self._connection = await aiomysql.connect(password=self.password,
                                                   **self._template)
         self.log.debug("Created connection %s with params: %s",
                        self._connection, self._template)
     except pymysql.err.OperationalError:
         raise DBConnectionError(
             "Can't connect to MySQL server: {template}".format(
                 template=self._template))
Esempio n. 11
0
 async def create_connection(self, with_db: bool) -> None:
     self._template = {
         "host": self.host,
         "port": self.port,
         "user": self.user,
         "database": self.database if with_db else None,
         **self.extra,
     }
     try:
         self._connection = await asyncpg.connect(None,
                                                  password=self.password,
                                                  **self._template)
         self.log.debug("Created connection %s with params: %s",
                        self._connection, self._template)
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError(
             "Can't establish connection to database {}".format(
                 self.database))
Esempio n. 12
0
 async def create_connection(self) -> None:
     try:
         if not self.single_connection:
             self._db_pool = await aiomysql.create_pool(db=self.database,
                                                        **self.template)
         else:
             self._connection = await aiomysql.connect(db=self.database,
                                                       **self.template)
         self.log.debug(
             'Created connection with params: user=%s database=%s host=%s port=%s',
             self.user, self.database, self.host, self.port)
     except pymysql.err.OperationalError:
         raise DBConnectionError(
             "Can't connect to MySQL server: "
             'user={user} database={database} host={host} port={port}'.
             format(user=self.user,
                    database=self.database,
                    host=self.host,
                    port=self.port))
Esempio n. 13
0
    async def create_connection(self, with_db: bool) -> None:
        if self._connection:
            raise DBConnectionError("Called create_connection on active connection. Call close() first.")

        self._lock = asyncio.Lock()

        self._connection = await aiosqlite.connect(self.filename, isolation_level=None)
        self._connection._conn.row_factory = sqlite3.Row

        for pragma, val in self.pragmas.items():
            cursor = await self._connection.execute(f"PRAGMA {pragma}={val}")
            await cursor.close()

        self.log.debug(
            "Created connection %s with params: filename=%s %s",
            self._connection,
            self.filename,
            " ".join([f"{k}={v}" for k, v in self.pragmas.items()]),
        )
Esempio n. 14
0
 async def create_connection(self, with_db: bool) -> None:
     self._template = {
         "minsize": self.minsize,
         "maxsize": self.maxsize,
         "echo": self.echo,
         "pool_recycle": self.pool_recycle,
         "dsn": self.dsn,
         "autocommit": True,
         **self._kwargs,
     }
     if with_db:
         self._template["database"] = self.database
     try:
         self._pool = await asyncodbc.create_pool(**self._template, )
         self.log.debug("Created connection %s pool with params: %s",
                        self._pool, self._template)
     except pyodbc.InterfaceError:
         raise DBConnectionError(
             f"Can't establish connection to database {self.database}")
Esempio n. 15
0
 async def create_connection(self, with_db: bool) -> None:
     self._template = {
         "host": self.host,
         "port": self.port,
         "user": self.user,
         "database": self.database if with_db else None,
         **self.extra,
     }
     try:
         self._connection = await asyncpg.connect(None,
                                                  password=self.password,
                                                  **self._template)
         self.log.debug("Created connection %s with params: %s",
                        self._connection, self._template)
     except asyncpg.InvalidCatalogNameError:
         raise DBConnectionError(
             f"Can't establish connection to database {self.database}")
     # Set post-connection variables
     if self.schema:
         await self.execute_script(f"SET search_path TO {self.schema}")
Esempio n. 16
0
    async def create_connection(self, with_db: bool) -> None:
        template = {
            'host': self.host,
            'port': self.port,
            'user': self.user,
            'password': self.password,
            'db': self.database if with_db else None,
            'autocommit': True,
        }

        try:
            self._connection = await aiomysql.connect(**template)
            self.log.debug(
                'Created connection %s with params: user=%s database=%s host=%s port=%s',
                self._connection, self.user, self.database, self.host, self.port
            )
        except pymysql.err.OperationalError:
            raise DBConnectionError(
                "Can't connect to MySQL server: "
                'user={user} database={database} host={host} port={port}'.format(
                    user=self.user, database=self.database, host=self.host, port=self.port
                )
            )