繁体   English   中英

如何确保查询在 MySQL/PostgreSQL 数据库上以只读操作运行?

[英]How to make sure the query run with read-only action on MySQL/PostgreSQL database?

前提条件:数据库在我无法控制的地方运行,但我有连接数据库的授权帐户。

我需要确保通过我的应用程序连接到数据库运行的所有查询都应该是只读的。 比如 DML 中的 SELECT。

使用正则表达式判断SQL查询? SQLAlchemy 或其他 Python 包中是否有任何可重用的函数/类?

任何建议都会有所帮助! 谢谢!

假设您只需要SELECT查询,您可以创建一个控制流来停止执行/在查询具有任何其他类型时引发错误。 有几种方法可以做到这一点:

1 - 使用正则表达式提取查询的第一个单词。 例子:

import re

def is_read_only_query(sql_query: str) -> bool:
    # Assumes a single query is defined in sql_query
    return (
        True
        if re.search(r"^\W*([\w-]+)", sql_query).group(0).strip().lower()
        == "select"
        else False
    )

if not is_read_only_query(sql_query):
   # Do something, e.g. raise Exception

2 - 使用 Python 包sqlparse中的get_type()方法。 例子:

import re
import sqlparse

def is_read_only_query(sql_query: str) -> bool:
    # Assumes a single query is defined in sql_query
    query_type = sqlparse.parse(sql_query)[0].get_type().lower()
    return True if query_type == "select" else False

if not is_read_only_query(sql_query):
   # Do something, e.g. raise Exception

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM