Coverage for /var/devmt/py/dbilib_0.4.0rc1/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 from _dbi_base import _DBIBase

29

30

31 class _DBISQLite(_DBIBase):

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

33 used for accessing SQLite databases.

34

35 Note:

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

37

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

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

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

41 object which is created from the connection string.

42

43 Args:

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

45 string.

46

47 :Example Use:

48

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

50 the calling/wrapping class as::

51

52 >>> from dblib.database import DBInterface

53

54 class MyDB(DBInterface):

55

56 def __init__(self, connstr: str):

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

58

59 """

60

61 def __init__(self, connstr: str):

62 """SQLite database interface initialiser."""

63 super().__init__(connstr=connstr)

64 self._verify_db_exists()

65

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

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

68

69 Args:

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

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

72 not exist. Defaults to False.

73

74 Returns:

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

76

77 """

78 params = {'table_name': table_name}

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

80 'where type = \'table\' '

81 'and name = :table_name')

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

83 if (not exists) & verbose:

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

85 ui.print_warning(text=msg)

86 return exists

87

88 def _verify_db_exists(self):

89 """Verify the database file exists.

90

91 Raises:

92 FileNotFoundError: Raised if the database file passed via the

93 connection string does not exist.

94

95 """

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