【问题标题】:How to make sure the query run with read-only action on MySQL/PostgreSQL database?如何确保查询在 MySQL/PostgreSQL 数据库上以只读操作运行?
【发布时间】:2017-06-28 06:18:41
【问题描述】:

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

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

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

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

【问题讨论】:

  • 在 Postgresql BEGIN READ ONLY.
  • @iljaeverilä 谢谢!我明白了,围绕用户 SQL 做一些技巧。我为 MySQL 找到了 START TRANSACTION READ ONLY。谢谢!
  • Np。使用正则表达式等解析查询并检查它是否包含 DML 等最终会失败的原因是,您可能会在 SELECT 中调用一个实际改变某些内容的过程。几乎没有办法抓住它。注意not all operations are transactional in MySQL,所以你可能会感到惊讶...
  • ...和DDL in MySQL implicitly commits,或者换句话说,结束你的只读事务。
  • 是的,我注意到了,谢谢你的提醒!我应该首先检查它是否只包含 DML。

标签: python mysql sql database postgresql


【解决方案1】:

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

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

import re

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多