|
| 1 | +__all__ = ('SqliteOperator',) |
| 2 | + |
| 3 | +import sqlite3 |
| 4 | + |
| 5 | +from sqlalchemy import create_engine |
| 6 | +from sqlalchemy.sql import text |
| 7 | + |
| 8 | +from .base import PasswordVault |
| 9 | +from ..logger import LOG |
| 10 | + |
| 11 | + |
| 12 | +class SqliteOperator: |
| 13 | + def __init__(self, db_config, **kwargs): |
| 14 | + self._connection_pattern = "sqlite://{dbname}" |
| 15 | + dbname = db_config.get('dbname', '') |
| 16 | + if len(dbname) > 0: |
| 17 | + dbname = '/%s' % dbname |
| 18 | + self._config = {'dbname': dbname} |
| 19 | + |
| 20 | + if 'password' in db_config: |
| 21 | + try: |
| 22 | + import sqlcipher3 |
| 23 | + except ImportError: |
| 24 | + raise RuntimeError('Python package required for encrypted sqlite3: sqlcipher3-binary') |
| 25 | + LOG.debug('Version of sqlcipher3 = %s' % sqlcipher3.sqlite_version) |
| 26 | + password_vault = PasswordVault.get_vault(db_config.get('vault_type'), db_config.get('vault_config')) |
| 27 | + password = password_vault.get_password(db_config.get('password', None)) |
| 28 | + self._config['password'] = password |
| 29 | + self._connection_pattern = "sqlite+pysqlcipher://:{password}@/{dbname}" |
| 30 | + else: |
| 31 | + LOG.debug('Version of sqlite = %s' % sqlite3.sqlite_version) |
| 32 | + |
| 33 | + try: |
| 34 | + self.db = create_engine( |
| 35 | + self._connection_pattern.format(**self._config), **kwargs |
| 36 | + ) |
| 37 | + LOG.debug("Sqlite connected: %s" % self.connection_str) |
| 38 | + except Exception as e: |
| 39 | + LOG.exception(e) |
| 40 | + raise RuntimeError('Failed to connect to sqlite') |
| 41 | + |
| 42 | + @property |
| 43 | + def connection(self): |
| 44 | + return self.db |
| 45 | + |
| 46 | + def execute_query(self, sql, *args, **kwargs): |
| 47 | + with self.db.connect() as conn: |
| 48 | + cur = conn.execute(text(sql), *args, **kwargs) |
| 49 | + return cur |
| 50 | + |
| 51 | + @property |
| 52 | + def connection_str(self) -> str: |
| 53 | + return self._connection_pattern.format(**self._config) |
0 commit comments