38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""将 :name 命名参数 SQL 编译为带字面量的方言 SQL,供外部库驱动执行"""
|
|
from typing import Any, Dict
|
|
|
|
from sqlalchemy import bindparam, text
|
|
from sqlalchemy.dialects import mysql, mssql, oracle, postgresql
|
|
|
|
_DIALECTS = {
|
|
"postgresql": postgresql.dialect(),
|
|
"postgres": postgresql.dialect(),
|
|
"mysql": mysql.dialect(),
|
|
"sqlserver": mssql.dialect(),
|
|
"mssql": mssql.dialect(),
|
|
"oracle": oracle.dialect(),
|
|
}
|
|
|
|
|
|
def compile_sql_with_named_params(
|
|
sql: str,
|
|
params: Dict[str, Any],
|
|
db_type: str,
|
|
) -> str:
|
|
"""
|
|
将 :param 绑定为字面量后返回可执行 SQL 字符串。
|
|
|
|
注意:仅用于已校验过的参数(表单/数据源内部使用),勿用于未过滤的用户原始 SQL。
|
|
"""
|
|
dialect = _DIALECTS.get((db_type or "postgresql").lower(), postgresql.dialect())
|
|
stmt = text(sql)
|
|
if params:
|
|
stmt = stmt.bindparams(
|
|
*[bindparam(key, value=value) for key, value in params.items()]
|
|
)
|
|
return str(
|
|
stmt.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
|
|
)
|