#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # @Version : Python 3.11.4 # @Software : Sublime Text 4 # @Author : StudentCWZ # @Email : StudentCWZ@outlook.com # @Date : 2023/10/29 00:36 # @File : sql.py # @Description : Defines the DatabaseUri class for generating SQLAlchemy database connection strings. """ class DatabaseUri: """ A utility class to generate SQLAlchemy database connection strings for various types of databases. Args: db_type (str): The type of the database. It could be "mysql", "postgresql", "oracle", "sqlite". username (str, optional): The username of the database. Not required for "sqlite". password (str, optional): The password of the database. Not required for "sqlite". host (str, optional): The host of the database. Not required for "sqlite". port (str, optional): The port of the database. Not required for "sqlite". db (str, optional): The database name. For "sqlite", it is the path to the database file. driver (str, optional): The python library to connect to the database. Not required but could be provided. """ def __init__(self, db_type: str, username: str = None, password: str = None, host: str = None, port: str = None, db: str = None, driver: str = None) -> None: self.db_type = db_type self.username = username self.password = password self.host = host self.port = port self.db = db self.driver = driver def create(self) -> str: """ Creates a SQLAlchemy engine string for the specified database. Returns: str: A SQLAlchemy engine string. """ # SQLite database only requires a path to the database file if self.db_type == 'sqlite': return f'{self.db_type}:///{self.db}' else: # Other databases require a full connection string with optional driver if self.driver: return (f'{self.db_type}+{self.driver}://' f'{self.username}:{self.password}@{self.host}:{self.port}/{self.db}') else: return f'{self.db_type}://{self.username}:{self.password}@{self.host}:{self.port}/{self.db}' def __repr__(self): """ Returns a formal string representation of the DatabaseUri object. Returns: str: The formal string representation of the DatabaseUri object. """ return f'' def __str__(self): """ Returns a string representation of the DatabaseUri object, which is the SQLAlchemy engine string. Returns: str: The string representation of the DatabaseUri object. """ return self.create()