sql.py 2.31 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8
#!/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
崔为之's avatar
崔为之 committed
9
# @File        : sql.py
Weizhi Cui's avatar
Weizhi Cui committed
10 11 12 13
# @Description :
"""


崔为之's avatar
崔为之 committed
14
class DatabaseUri:
Weizhi Cui's avatar
Weizhi Cui committed
15
    """
崔为之's avatar
崔为之 committed
16 17
    The DatabaseURI class is a utility for generating SQLAlchemy database
    connection strings for various types of databases.
Weizhi Cui's avatar
Weizhi Cui committed
18

崔为之's avatar
崔为之 committed
19 20 21 22 23 24 25
    :param db_type: The type of the database. It could be "mysql", "postgresql", "oracle", "sqlite".
    :param username: The username of the database. Not required for "sqlite".
    :param password: The password of the database. Not required for "sqlite".
    :param host: The host of the database. Not required for "sqlite".
    :param port: The port of the database. Not required for "sqlite".
    :param db: The database name. For "sqlite", it is the path to the database file.
    :param driver: The python library to connect to the database. Not required but could be provided.
Weizhi Cui's avatar
Weizhi Cui committed
26
    """
崔为之's avatar
崔为之 committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

    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.

        :return: A SQLAlchemy engine string.
        """
        # SQLite database only require 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):
崔为之's avatar
崔为之 committed
63
        return f'<DatabaseUri({self.db_type})>'
崔为之's avatar
崔为之 committed
64 65 66

    def __str__(self):
        return self.create()