Test Failed
Push — master ( 8a6195...3318f0 )
by P.R.
10:24
created

MySqlDefaultConnector.is_alive()   A

Complexity

Conditions 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 15.664

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 17
ccs 1
cts 10
cp 0.1
rs 9.9
c 0
b 0
f 0
cc 4
nop 1
crap 15.664
1 1
from typing import Dict, Optional, Union
2
3 1
from mysql.connector import MySQLConnection
4
5 1
from pystratum_mysql.MySqlConnector import MySqlConnector
6
7
8 1
class MySqlDefaultConnector(MySqlConnector):
9
    """
10
    Connects to a MySQL instance using username and password.
11
    """
12
13
    # ------------------------------------------------------------------------------------------------------------------
14 1
    def __init__(self, params: Dict[str, Union[str, int]]):
15
        """
16
        Object constructor.
17
        
18
        :param params: The connection parameters.
19
        """
20
21 1
        self._params: Dict[str, Union[str, int]] = params
22
        """
23
        The connection parameters.
24
        """
25
26 1
        self._connection: Optional[MySQLConnection] = None
27 1
        """
28
        The connection between Python and the MySQL instance.
29
        """
30
31
    # ------------------------------------------------------------------------------------------------------------------
32 1
    def connect(self) -> MySQLConnection:
33
        """
34
        Connects to the MySQL instance.
35
        """
36 1
        self._connection = MySQLConnection(**self._params)
37
38
        return self._connection
39
40
    # ------------------------------------------------------------------------------------------------------------------
41 1
    def disconnect(self) -> None:
42
        """
43
        Disconnects from the MySQL instance.
44
        """
45
        if self._connection:
46
            self._connection.close()
47
            self._connection = None
48
49
    # ------------------------------------------------------------------------------------------------------------------
50 1
    def is_alive(self) -> bool:
51
        """
52
        Returns whether Python is (still) connected to a MySQL or MariaDB instance.
53
54
        :rtype: bool
55
        """
56
        is_alive = False
57
58
        if self._connection:
59
            try:
60
                result = self._connection.cmd_ping()
61
                if isinstance(result, dict):
62
                    is_alive = True
63
            except:
64
                pass
65
66
        return is_alive
67
68
# ----------------------------------------------------------------------------------------------------------------------
69