Skip to content

A Python library for creating queries and compiling them to different targets.

License

Notifications You must be signed in to change notification settings

nielslerches/common-query

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

common-query

A Python library for creating queries and compiling them to different targets.

Creating queries

query = The('users')[0]['name'].startswith('John')

Behind the scenes the library generates a tree-structure that represents the query. The nodes more or less maps to the Python magic methods. The above query is actually the following:

Call(
  arguments=(('John',), {}),
  parent=GetAttr(
    arguments='startswith',
    parent=GetItem(
      arguments='name',
      parent=GetItem(
        arguments=0,
        parent=The(
          arguments='users',
          parent=None
        )
      )
    )
  )
)

Compiling queries

compiler = LambdaCompiler()
program = compiler.compile(The('x') > 10)
print(program({'x': 11})) # True

A compiler in this case is just an object that transforms a tree. The LambdaCompiler that comes with this library simply transforms the tree into a lambda function. This function takes in a context object, which the compiled query is executed on.

Special things

This library has the concept of function creation and execution:

compiler = LambdaCompiler()
function = Function('x', The('x') * 2)
program = compiler.compile(function)
compiled_function = program({})
print(compiled_function(10)) # 20

An obvious idea would be to implement a compiler/transpiler that transform a tree into a tree of SQLAlchemy filters, or Django Q objects.

About

A Python library for creating queries and compiling them to different targets.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages