83 lines
2.7 KiB
Python
83 lines
2.7 KiB
Python
from sqlalchemy import text
|
|
|
|
from config.pgDb import pg_pool
|
|
from config.ssDb import mssql_pool
|
|
|
|
|
|
def executeSQL(sql: str):
|
|
"""
|
|
执行 SQL 并返回结果列表,每行是 dict
|
|
"""
|
|
with mssql_pool.getConn() as conn:
|
|
result = conn.execute(text(sql))
|
|
# SQLAlchemy 2.x 返回 Row 对象,转成 dict
|
|
return [dict(row._mapping) for row in result]
|
|
|
|
|
|
def execute_parameterized_sql(sql: str, params: dict | None = None):
|
|
"""执行参数化只读 SQL,返回列名和字典行。"""
|
|
with mssql_pool.getConn() as conn:
|
|
result = conn.execute(text(sql), params or {})
|
|
columns = list(result.keys())
|
|
rows = [dict(row._mapping) for row in result]
|
|
return columns, rows
|
|
|
|
|
|
def execute_parameterized_scalar(sql: str, params: dict | None = None):
|
|
with mssql_pool.getConn() as conn:
|
|
result = conn.execute(text(sql), params or {})
|
|
return result.scalar()
|
|
|
|
|
|
def get_company_list(user_id: str):
|
|
# 1️⃣ 从 PostgreSQL 获取 tenant_id
|
|
with pg_pool.getConn() as pg_conn:
|
|
with pg_conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT bbit_tenant_id FROM sys_users WHERE id = %s", (user_id,)
|
|
)
|
|
row = cur.fetchone()
|
|
tenant_id = row[0] if row else None
|
|
|
|
# 2️⃣ 从 SQL Server 查询租户信息
|
|
if tenant_id:
|
|
query = text("SELECT Id, Name FROM dbo.POC_TENANTS WHERE Id = :tenant_id")
|
|
params = {"tenant_id": tenant_id}
|
|
else:
|
|
query = text("SELECT Id, Name FROM dbo.POC_TENANTS")
|
|
params = {}
|
|
|
|
with mssql_pool.getConn() as mssql_conn:
|
|
result = mssql_conn.execute(query, params)
|
|
return [{"id": str(row[0]), "name": row[1]} for row in result.fetchall()]
|
|
|
|
|
|
def get_user_company_scope(user_id: str):
|
|
"""返回数据助手使用的租户范围;用户不存在时绝不能按全局用户处理。"""
|
|
with pg_pool.getConn() as pg_conn:
|
|
with pg_conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT bbit_tenant_id FROM sys_users WHERE id = %s", (user_id,)
|
|
)
|
|
row = cur.fetchone()
|
|
|
|
if not row:
|
|
return {"canGlobal": False, "companies": []}
|
|
|
|
tenant_id = row[0]
|
|
if tenant_id:
|
|
query = text("SELECT Id, Name FROM dbo.POC_TENANTS WHERE Id = :tenant_id")
|
|
params = {"tenant_id": tenant_id}
|
|
can_global = False
|
|
else:
|
|
query = text("SELECT Id, Name FROM dbo.POC_TENANTS ORDER BY Name")
|
|
params = {}
|
|
can_global = True
|
|
|
|
with mssql_pool.getConn() as mssql_conn:
|
|
result = mssql_conn.execute(query, params)
|
|
companies = [
|
|
{"id": str(item[0]), "name": item[1]} for item in result.fetchall()
|
|
]
|
|
return {"canGlobal": can_global, "companies": companies}
|