2025-06-01 15:34:12 +08:00
|
|
|
import configparser
|
|
|
|
import os
|
|
|
|
from sqlalchemy_utils import database_exists, create_database
|
2025-09-13 08:23:54 +08:00
|
|
|
from flask import current_app
|
|
|
|
|
|
|
|
def ConnectionString(database) -> str:
|
2025-06-01 15:34:12 +08:00
|
|
|
parser = configparser.ConfigParser(strict=False)
|
|
|
|
parser.read_file(open('wg-dashboard.ini', "r+"))
|
|
|
|
sqlitePath = os.path.join("db")
|
|
|
|
if not os.path.isdir(sqlitePath):
|
|
|
|
os.mkdir(sqlitePath)
|
|
|
|
if parser.get("Database", "type") == "postgresql":
|
2025-07-08 16:31:03 +08:00
|
|
|
cn = f'postgresql+psycopg://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
2025-06-02 12:04:01 +08:00
|
|
|
elif parser.get("Database", "type") == "mysql":
|
2025-09-13 08:23:54 +08:00
|
|
|
cn = f'mysql+pymysql://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
2025-06-01 15:34:12 +08:00
|
|
|
else:
|
|
|
|
cn = f'sqlite:///{os.path.join(sqlitePath, f"{database}.db")}'
|
2025-06-19 00:41:08 +08:00
|
|
|
try:
|
|
|
|
if not database_exists(cn):
|
|
|
|
create_database(cn)
|
|
|
|
except Exception as e:
|
2025-09-13 08:23:54 +08:00
|
|
|
current_app.logger.error("Database error. Terminating...", e)
|
2025-06-19 00:41:08 +08:00
|
|
|
exit(1)
|
|
|
|
|
2025-06-01 15:34:12 +08:00
|
|
|
return cn
|