Skip to content

Commit

Permalink
新增数据库查询数据表接口
Browse files Browse the repository at this point in the history
  • Loading branch information
wuranxu committed Aug 21, 2021
1 parent e28ccf2 commit 1bd3044
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 4 deletions.
55 changes: 54 additions & 1 deletion app/dao/config/DbConfigDao.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from datetime import datetime
from typing import List

from sqlalchemy import select
from sqlalchemy import select, MetaData

from app.dao.config.EnvironmentDao import EnvironmentDao
from app.models import async_session, DatabaseHelper, db_helper
from app.models.database import PityDatabase
from app.models.schema.database import DatabaseForm
Expand Down Expand Up @@ -93,6 +95,57 @@ async def query_database(id: int):
DbConfigDao.log.error(f"获取数据库配置失败, error: {e}")
raise Exception("获取数据库配置失败")

@staticmethod
async def query_database_and_tables():
"""
方法会查询所有数据库表配置的信息
:return:
"""
try:
# 返回树图, 最外层是环境
result = []
env_index = dict()
env_data = EnvironmentDao.list_env(1, 1, exactly=True)
env_map = {env.id: env.name for env in env_data}
# 获取数据库相关的信息
meta = MetaData()
async with async_session() as session:
query = await session.execute(select(PityDatabase).where(PityDatabase.deleted_at == None))
data = query.scalars().all()
for d in data:
name = env_map[d.env]
idx = env_index.get(name)
if not idx:
result.append(dict(title=name, key=f"env_{name}", children=list()))
idx = len(result) - 1
env_index[name] = idx
DbConfigDao.get_tables(d, meta, result[idx]['children'])
return result
except Exception as err:
DbConfigDao.log.error(f"获取数据库配置详情失败, error: {err}")
raise Exception(f"获取数据库配置详情失败: {err}")

@staticmethod
def get_tables(data: PityDatabase, meta, children: List):
conn = db_helper.get_connection(data.sql_type, data.host, data.port, data.username, data.password,
data.database)
database_child = list()
dbs = dict(title=f"{data.database}{data.host}:{data.port})", key=f"database_{data.id}",
children=database_child, sql_type=data.sql_type)
eng = conn.get('engine')
meta.reflect(bind=eng)
for t in meta.sorted_tables:
temp = []
database_child.append(dict(title=str(t), key=f"table_{data.id}_{t}", children=temp))
for k, v in t.c.items():
temp.append(dict(
title=k,
primary_key=v.primary_key,
type={str(v.type)},
key=f"column_{t}_{data.id}_{k}",
))
children.append(dbs)

@staticmethod
async def online_sql(id: int, sql: str):
try:
Expand Down
4 changes: 3 additions & 1 deletion app/dao/config/EnvironmentDao.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ def update_env(data: EnvironmentForm, user):
return None

@staticmethod
def list_env(page, size, name=None):
def list_env(page, size, name=None, exactly=False):
try:
search = [Environment.deleted_at == None]
with Session() as session:
if name:
search.append(Environment.name.ilike("%{}%".format(name)))
if exactly:
return session.query(Environment).filter(*search).all()
data = session.query(Environment).filter(*search)
total = data.count()
return data.order_by(desc(Environment.created_at)).offset((page - 1) * size).limit(
Expand Down
4 changes: 2 additions & 2 deletions app/routers/config/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@


@router.get("/environment/list")
async def list_environment(page: int = 1, size: int = 8, name: str = "", user_info=Depends(Permission())):
data, total, err = EnvironmentDao.list_env(page, size, name)
async def list_environment(page: int = 1, size: int = 8, name: str = "", exactly=False, user_info=Depends(Permission())):
data, total, err = EnvironmentDao.list_env(page, size, name, exactly)
if err:
return dict(code=110, msg=err)
return dict(code=0, data=PityResponse.model_to_list(data), total=total, msg="操作成功")
Expand Down
9 changes: 9 additions & 0 deletions app/routers/online/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ async def execute_sql(data: OnlineSQLForm, user_info=Depends(Permission())):
return PityResponse.success(data=result)
except Exception as err:
return PityResponse.failed(err)


@router.get("/tables")
async def list_tables(user_info=Depends(Permission())):
try:
result = await DbConfigDao.query_database_and_tables()
return PityResponse.success(result)
except Exception as err:
return PityResponse.failed(err)

0 comments on commit 1bd3044

Please sign in to comment.