可重构的数据库查询

huangapple go评论66阅读模式
英文:

Refactorable database queries

问题

只要我有 category="foo" 和一个 NoSQL query={"category"=category}。每当我重构我的变量名称 category,如果我想采用它,我需要在查询中手动更改它。

在 Python 3.8+ 中,我可以通过变量本身获取变量名称作为字符串

现在我可以使用 query={f"{category=}".split("=")[0]=category}。现在重构也会改变查询。这适用于任何数据库查询或语句(SQL 等)。

这是否是不良实践?不仅仅是关于 Python,还涉及到任何支持这种操作的语言。

英文:

Say I have category="foo" and a NoSQL query={"category"=category}. Whenever I refactor my variable name of category, I need to manually change it inside the query if I want to adopt it.

In Python 3.8+ I'm able to get the variable name as a string via the variable itself.

Now I could use query={f"{category=}".split("=")[0]=category}. Now refactoring changes the query too. This applies to any database queries or statements (SQL etc.).

Would this be bad practice? Not just concerning Python but any language where this is possible.

答案1

得分: 1

这是否是不良实践?

是的,本地变量的名称不需要与数据存储中的字段相关联。您应该能够使用任何Python变量检索记录并过滤其字段,无论其名称如何或是否嵌套在较大的数据结构中。

伪代码中:

connection = datastore.connect(...)

# 直接传递一个字符串
connection.fetch({"category": "fruit"})

# 传递一个字符串变量
category_to_fetch = "vegetable"
connection.fetch({"category": category_to_fetch})

# 也可以像以前的记录列表一样奇特
r = [("fish",)]
connection.fetch({"category": r[0][0]})

# 或者甚至是预先制作的过滤字典
filter = {"category": "meat"}
connection.fetch(filter)
英文:

> Would this be bad practice?

Yes, the names of local variables do not need to correlate with the fields in data stores.

You should be able to retrieve a record and filter on its fields with any python variable, no matter its name or if its nested in a larger data structure.

In pseudocode:

connection = datastore.connect(...)

# passing a string directly
connection.fetch({"category": "fruit"})

# passing a string variable
category_to_fetch = "vegetable"
connection.fetch({"category": category_to_fetch})

# something more exotic like a previous list of records
r = [("fish",)]
connection.fetch({"category": r[0][0]})

# or even a premade filter dictionary
filter = {"category": "meat"}
connection.fetch(filter)

huangapple
  • 本文由 发表于 2023年2月10日 05:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定