使用JSON作为SQL查询生成器。

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

Use JSON as SQL Query Builder

问题

我需要运行带有多个条件的SQL查询,所以我在考虑是否能够将每个查询的条件存储在一个JSON文件中,然后运行JSON文件并逐个输出结果对象。有人知道是否有适用于Python的库,可以从JSON文件中构建SQL查询吗?我不想将JSON数据移入数据库,而是想使用JSON对象作为构建要在数据库上运行的搜索条件的工具。

例如,假设我的数据库表包含联系信息,如名字、姓氏、街道地址、城市、州、邮政编码、电话号码、电子邮件地址、婚姻状况等。如果我想要一个查询,显示我表中居住在NV、CA和UT州但婚姻状况不为单身的人的结果,我的JSON对象可能包含类似以下的内容:

{
  "include": {
    "State": ["NV", "CA", "UT"]
  },
  "exclude": {
    "Marital Status": "Single"
  }
}

我也愿意听取关于如何实现这一目标的其他建议,但我的目标是让用户能够填写某种形式的搜索条件表单,将其保存为JSON对象(或等效对象),然后转到我的数据库并运行这些查询。似乎这样的东西可能已经存在。如果不存在,而其他人认为它有价值,那就太棒了!

英文:

I need to run SQL Queries with multiple conditions so I'm thinking if I'm able to store the conditions for each query in a JSON file I can run the JSON file and spit out the results object by object. Does anyone know of any libraries for Python that will take a JSON file and from that file build an SQL Query? I'm not looking to move JSON data into a database, but rather use the JSON objects as a means to build search criteria I want to run on a database.

For example assume my database table contains contact information such as First Name, Last Name, Street Address, City, State, Zip Code, Phone Number, Email Address, Marital Status, etc. If I wanted to have a query that would show results of people in my table that live in the states of NV, CA, and UT but do not have a marital status of single my JSON Object could contain something like the following:

{
  "include": {
    "State": {
        "NV",
        "CA",
        "UT" }
  "exclude": {
    "Marital Status":"Single"
  }
 }

I'm open to other suggestions on how to accomplish this, but my goal is for users to be able to fill out some type of form of their search criteria and save that as a JSON object (or equivalent) and then go to my database and run those queries. It seems like something like this probably already exists. If it doesn't and others think it valuable cool!

答案1

得分: 2

你可能正在寻找类似GraphQL的解决方案,但也可以使用标准的SQLAlchemy语法来实现类似的功能。考虑以下请求:

{
    "table": "people",
    "where": {"State": "NV"}
}

您可以解码此请求以搜索表格"people"中所有具有"State" = "NV"的行:

table = request_data.get('table')
selected_table = db.Table(table, metadata, autoload=True)

然后,实际的查询将通过以下方式构建:

query = selected_table.select()
where_fields = request_data.get('where', {})
for k, v in where_fields.items():
    query = query.where(getattr(selected_table.c, k) == v)

并且可以通过以下方式执行:

my_session = Session(engine)
result = my_session.execute(query)
my_session.close()

这只是一个非常基本的示例,但您可以看到,使用这种技术,用户可以使用他们JSON请求中的"where"属性来定义查询应该如何看起来,它将适用于任何表格上的任何列。

可能的缺点:特殊情况,例如"exclude"不那么直接,以及提供允许的项目列表(NV、CA、UT)(OR而不是AND等等...),但从技术上讲是可行的(也许使用"where_not"或"where_or"字段?)

只要您的用户对数据库结构有深入了解,这是一个(在我看来)优雅的解决方案,可以让您的用户在不断更新路由、模型和模式以满足其需求的情况下获得更多访问权限。

GraphQL将让您进行大量的模式和模型创建工作,但与自己像这样操作相比,有更多关于它的信息。

英文:

EDIT: I assumed you were attempting to do this using API calls rather than a "json file", but its still relevant.

You are possibly looking for something like GraphQL, but similar solutions can be achieved with standard sqlalchemy syntax.

Consider the following request:

{
	"table": "people",
	"where": {"State": "NV"}
}

you can decode this request to search the table "people" for all rows that have "State" = "NV"

    table = request_data.get('table')
    selected_table = db.Table(table, metadata, autoload=True)

the actual query would then be constructed via

    query = selected_table.select()
    where_fields = request_data.get('where', {})
    for k, v in where_fields.items():
        query = query.where(getattr(selected_table.c, k) == v)

and executed with

    my_session = Session(engine)
    result = my_session.execute(query)
    my_session.close()

This is a very basic example, but you can see that with this technique, the user is able to define what the query should look like using the "where" attribute in their JSON request and it will work for any column on any table.

Possible downsides: Special cases such as "exclude" is not so straight-forward, as well as providing a list of items (NV, CA, UT) which are allowed (OR instead of AND, etc...), but technically realistic. (maybe with a "where_not" or "where_or" field ?)

Provided that your users have in-dept knowledge about your db structure, this is an (imo) elegant solution to give your users way more access without constantly having to update your routes, models and schemas according to their needs.

GraphQL will put you through a LOT of schema & model creation, but there is more information about it than doing it on your own like this.

huangapple
  • 本文由 发表于 2020年1月3日 15:01:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574446.html
匿名

发表评论

匿名网友

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

确定