Coverage for /var/devmt/py/dbilib_0.5.0/dbilib/_dbi_sqlite.py: 100%
20 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-09-20 12:37 +0100
« prev ^ index » next coverage.py v7.8.0, created at 2025-09-20 12:37 +0100
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.
8:Platform: Linux/Windows | Python 3.10+
9:Developer: J Berendt
10:Email: support@s3dev.uk
12:Comments: n/a
14:Example:
16 For class-specific usage examples, please refer to the docstring
17 for the following classes:
19 - :class:`_DBISQLite`
21"""
22# Silence the spurious IDE-based error.
23# pylint: disable=import-error
25from utils4 import utils
26from utils4.user_interface import ui
27# locals
28try:
29 from ._dbi_base import _DBIBase
30except ImportError:
31 from _dbi_base import _DBIBase
34class _DBISQLite(_DBIBase):
35 """This *private* class holds the methods and properties which are
36 used for accessing SQLite databases.
38 Note:
39 This class is *not* designed to be interacted with directly.
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.
46 Args:
47 connstr (str): The database-specific SQLAlchemy connection
48 string.
50 :Example Use:
52 This low-level generalised class is designed to be inherited by
53 the calling/wrapping class as::
55 >>> from dbilib.database import DBInterface
57 class MyDB(DBInterface):
59 def __init__(self, connstr: str):
60 super().__init__(connstr=('sqlite:////path/to/database.db'))
62 """
64 def __init__(self, connstr: str):
65 """SQLite database interface initialiser."""
66 super().__init__(connstr=connstr)
67 self._verify_db_exists()
69 def table_exists(self, table_name: str, verbose: bool=False) -> bool:
70 """Using the ``engine`` object, test if the given table exists.
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.
77 Returns:
78 bool: True if the given table exists, otherwise False.
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
91 def _verify_db_exists(self):
92 """Verify the database file exists.
94 Raises:
95 FileNotFoundError: Raised if the database file passed via the
96 connection string does not exist.
98 """
99 utils.fileexists(filepath=self.engine.url.database, error='raise')