Coverage for /var/devmt/py/dbilib_0.5.0/dbilib/_dbi_sqlite.py: 100%

1#!/usr/bin/env python3

2# -*- coding: utf-8 -*-

3"""

4:Purpose: This module contains the library's *SQLite* database methods

5 and attribute accessors; which are a specialised version of

6 the :class:`_dbi_base._DBIBase` class methods.

7

8:Platform: Linux/Windows | Python 3.10+

9:Developer: J Berendt

10:Email: support@s3dev.uk

11

12:Comments: n/a

13

14:Example:

15

16 For class-specific usage examples, please refer to the docstring

17 for the following classes:

18

19 - :class:`_DBISQLite`

20

21"""

22# Silence the spurious IDE-based error.

23# pylint: disable=import-error

24

25 from utils4 import utils

26 from utils4.user_interface import ui

27# locals

28 try:

29 from ._dbi_base import _DBIBase

30 except ImportError:

31 from _dbi_base import _DBIBase

32

33

34 class _DBISQLite(_DBIBase):

35 """This *private* class holds the methods and properties which are

36 used for accessing SQLite databases.

37

38 Note:

39 This class is *not* designed to be interacted with directly.

40

41 Rather, please use the :class:`database.DBInterface` class

42 instead, as the proper interface class has an automatic switch

43 for database interfaces, based on the ``sqlalchemy.Engine``

44 object which is created from the connection string.

45

46 Args:

47 connstr (str): The database-specific SQLAlchemy connection

48 string.

49

50 :Example Use:

51

52 This low-level generalised class is designed to be inherited by

53 the calling/wrapping class as::

54

55 >>> from dbilib.database import DBInterface

56

57 class MyDB(DBInterface):

58

59 def __init__(self, connstr: str):

60 super().__init__(connstr=('sqlite:////path/to/database.db'))

61

62 """

63

64 def __init__(self, connstr: str):

65 """SQLite database interface initialiser."""

66 super().__init__(connstr=connstr)

67 self._verify_db_exists()

68

69 def table_exists(self, table_name: str, verbose: bool=False) -> bool:

70 """Using the ``engine`` object, test if the given table exists.

71

72 Args:

73 table_name (str): Name of the table to test.

74 verbose (bool, optional): Print a message if the table does

75 not exist. Defaults to False.

76

77 Returns:

78 bool: True if the given table exists, otherwise False.

79

80 """

81 params = {'table_name': table_name}

82 stmt = ('select count(*) from sqlite_master '

83 'where type = \'table\' '

84 'and name = :table_name')

85 exists = bool(self.execute_query(stmt, params=params, raw=True)[0][0])

86 if (not exists) & verbose:

87 msg = f'Table does not exist: {self._engine.url.database}.{table_name}'

88 ui.print_warning(text=msg)

89 return exists

90

91 def _verify_db_exists(self):

92 """Verify the database file exists.

93

94 Raises:

95 FileNotFoundError: Raised if the database file passed via the

96 connection string does not exist.

97

98 """

99 utils.fileexists(filepath=self.engine.url.database, error='raise')