项目作者: thanethomson

项目描述 :
Python library to convert YAML/JSON into SQLAlchemy SELECT queries
高级语言: Python
项目地址: git://github.com/thanethomson/MLAlchemy.git
创建时间: 2017-01-26T08:31:43Z
项目社区:https://github.com/thanethomson/MLAlchemy

开源协议:MIT License

下载


MLAlchemy

Build Status
PyPI
PyPI

Overview

MLAlchemy is a Python-based utility library aimed at allowing relatively safe
conversion from YAML/JSON to SQLAlchemy read-only queries. One use case here is
to allow RESTful web applications (written in Python) to receive YAML- or
JSON-based queries for data, e.g. from a front-end JavaScript-based application.

The name “MLAlchemy” is an abbreviation for “Markup Language for
SQLAlchemy”.

Installation

Installation via PyPI:

  1. > pip install mlalchemy

Query Examples

To get a feel for what MLAlchemy queries look like, take a look at the
following. Note: All field names are converted from camelCase or kebab-case
to snake_case prior to query execution.

Example YAML Queries

Fetching all the entries from a table called Users:

  1. from: Users

Limiting the users to only those with the last name “Michaels”:

  1. from: Users
  2. where:
  3. last-name: Michaels

A more complex YAML query:

  1. from: Users
  2. where:
  3. $or:
  4. last-name: Michaels
  5. first-name: Michael
  6. $gt:
  7. date-of-birth: 1984-01-01

The raw SQL query for the above would look like:

  1. SELECT * FROM users WHERE
  2. (last_name = "Michaels" OR first_name = "Michael") AND
  3. (date_of_birth > "1984-01-01")

Example JSON Queries

The same queries as above, but in JSON format. To fetch all entries
in the Users table:

  1. {
  2. "from": "Users"
  3. }

Limiting the users to only those with the last name “Michaels”:

  1. {
  2. "from": "Users",
  3. "where": {
  4. "lastName": "Michaels"
  5. }
  6. }

And finally, the more complex query:

  1. {
  2. "from": "Users",
  3. "where": {
  4. "$or": {
  5. "lastName": "Michaels",
  6. "firstName": "Michael"
  7. },
  8. "$gt": {
  9. "dateOfBirth": "1984-01-01"
  10. }
  11. }
  12. }

Usage

A simple example of how to use MLAlchemy:

  1. from sqlalchemy import create_engine, Column, Integer, String, Date
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy.orm import sessionmaker
  4. from mlalchemy import parse_yaml_query, parse_json_query
  5. Base = declarative_base()
  6. class User(Base):
  7. __tablename__ = "users"
  8. id = Column(Integer, primary_key=True)
  9. first_name = Column(String)
  10. last_name = Column(String)
  11. date_of_birth = Column(Date)
  12. # use an in-memory SQLite database for this example
  13. engine = create_engine("sqlite:///:memory:")
  14. Base.metadata.create_all(engine)
  15. Session = sessionmaker(bind=engine)
  16. session = Session()
  17. # add a couple of dummy users
  18. user1 = User(first_name="Michael", last_name="Anderson", date_of_birth=date(1980, 1, 1))
  19. user2 = User(first_name="James", last_name="Michaels", date_of_birth=date(1976, 10, 23))
  20. user3 = User(first_name="Andrew", last_name="Michaels", date_of_birth=date(1988, 8, 12))
  21. session.add_all([user1, user2, user3])
  22. session.commit()
  23. # we need a lookup table for MLAlchemy
  24. tables = {
  25. "User": User
  26. }
  27. # try a simple YAML-based query first
  28. all_users = parse_yaml_query("from: User").to_sqlalchemy(session, tables).all()
  29. print(all_users)
  30. # same query, but this time in JSON
  31. all_users = parse_json_query("""{"from": "User"}""").to_sqlalchemy(session, tables).all()
  32. print(all_users)
  33. # a slightly more complex query
  34. young_users = parse_yaml_query("""from: User
  35. where:
  36. $gt:
  37. date-of-birth: 1988-01-01
  38. """).to_sqlalchemy(session, tables).all()
  39. print(young_users)

Query Language Syntax

As mentioned before, queries can either be supplied in YAML format or
in JSON format to one of the respective parsers.

from

At present, MLAlchemy can only support selecting data from a single
table (multi-table support is planned in future). Here, the from
parameter allows you to specify the name of the table from which
to select data.

where

The where parameter defines, in hierarchical fashion, the structure
of the logical query to perform. There are 3 kinds of key types in
the JSON/YAML structures, as described in the following table.

Kind Description Options
Operators Logical (boolean) operators for combining sub-clauses $and, $or, $not
Comparators Comparative operators for comparing fields to values $eq, $gt, $gte, $lt, $lte, $like, $neq, $in, $nin, $is
Field Names The name of a field in the from table (Depends on table)

order-by (YAML) or orderBy (JSON)

Provides the ordering for the resulting query. Must either be a single
field name or a list of field names, with the direction specifier in
front of the field name. For example:

  1. # Order by "field2" in ascending order
  2. order-by: field2

Another example:

  1. # Order by "field2" in *descending* order
  2. order-by: "-field2"

A more complex example:

  1. # Order first by "field1" in ascending order, then by "field2" in
  2. # descending order
  3. order-by:
  4. - field1
  5. - "-field2"

offset

Specifies the number of results to skip before providing results. If
not specified, no results are skipped.

limit

Specifies the maximum number of results to return. If not specified,
there will be no limit to the number of returned results.

Query Examples

Example 1: Simple Query

The following is an example of a relatively simple query in YAML format:

  1. from: SomeTable
  2. where:
  3. - $gt:
  4. field1: 5
  5. - $lt:
  6. field2: 3
  7. order-by:
  8. - field1
  9. offset: 2
  10. limit: 10

This would translate into the following SQLAlchemy query:

  1. from sqlalchemy.sql.expression import and_
  2. session.query(SomeTable).filter(
  3. and_(SomeTable.field1 > 5, SomeTable.field2 < 3)
  4. ) \
  5. .order_by(SomeTable.field1) \
  6. .offset(2) \
  7. .limit(10)

Example 2: Slightly More Complex Query

The following is an example of a more complex query in YAML format:

  1. from: SomeTable
  2. where:
  3. - $or:
  4. field1: 5
  5. field2: something
  6. - $not:
  7. $like:
  8. field3: "else%"

This would translate into the following SQLAlchemy query:

  1. from sqlalchemy.sql.expression import and_, or_, not_
  2. session.query(SomeTable) \
  3. .filter(
  4. and_(
  5. or_(
  6. SomeTable.field1 == 5,
  7. SomeTable.field2 == "something"
  8. ),
  9. not_(
  10. SomeTable.field3.like("else%")
  11. )
  12. )
  13. )

Example 3: Complex JSON Query

The following is an example of a relatively complex query in
JSON format:

  1. {
  2. "from": "SomeTable",
  3. "where": [
  4. {
  5. "$or": [
  6. {"field1": 10},
  7. {
  8. "$gt": {
  9. "field2": 5
  10. }
  11. }
  12. ],
  13. "$and": [
  14. {"field3": "somevalue"},
  15. {"field4": "othervalue"},
  16. {
  17. "$or": {
  18. "field5": 5,
  19. "field6": 6
  20. }
  21. }
  22. ]
  23. }
  24. ],
  25. "orderBy": [
  26. "field1",
  27. "-field2"
  28. ],
  29. "offset": 2,
  30. "limit": 10
  31. }

This query would be translated into the following SQLAlchemy code:

  1. from sqlalchemy.sql.expression import and_, or_, not_
  2. session.query(SomeTable) \
  3. .filter(
  4. and_(
  5. or_(
  6. SomeTable.field1 == 10,
  7. SomeTable.field2 > 5
  8. ),
  9. and_(
  10. SomeTable.field3 == "somevalue",
  11. SomeTable.field4 == "othervalue",
  12. or_(
  13. SomeTable.field5 == 5,
  14. SomeTable.field6 == 6
  15. )
  16. )
  17. )
  18. ) \
  19. .order_by(SomeTable.field1, SomeTable.field2.desc()) \
  20. .offset(2) \
  21. .limit(10)

License

The MIT License (MIT)

Copyright (c) 2017 Thane Thomson

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.