### Install pygeofilter
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Install the pygeofilter package using pip.
```bash
pip3 install pygeofilter
```
--------------------------------
### Install and Enable Pre-commit Hooks
Source: https://github.com/geopython/pygeofilter/blob/main/CONTRIBUTING.md
Install the pre-commit tool and enable it in your local pygeofilter environment to ensure code quality and formatting consistency before committing.
```bash
pip3 install pre-commit
```
```bash
cd /pygeofilter
pre-commit install
```
```bash
pre-commit run --all-files
```
--------------------------------
### Install pygeofilter with backend dependencies
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Install pygeofilter with specific backend dependencies for Django, SQLAlchemy, or native Python object filtering.
```bash
# for the Django backend
pip3 install pygeofilter[backend-django]
# for the sqlalchemy backend
pip3 install pygeofilter[backend-sqlalchemy]
# for the native backend
pip3 install pygeofilter[backend-native]
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Installs development and testing dependencies for pygeofilter using pip. Ensure you have `pip3` and the `requirements-dev.txt` and `requirements-test.txt` files available.
```bash
pip3 install -r requirements-dev.txt
pip3 install -r requirements-test.txt
```
--------------------------------
### Display pygeofilter Version
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Use the `--version` flag to display the installed version of the pygeofilter utility. This is a simple command for checking the installed package version.
```bash
pygeofilter --version
```
--------------------------------
### Basic Evaluator Usage
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Demonstrates the basic setup for using the Evaluator class to process an AST, with filters potentially created externally.
```python
from pygeofilter import ast
from pygeofilter.backends.evaluator import Evaluator, handle
from myapi import filters # <- this is where the filters are created.
# of course, this can also be done in the
# evaluator itself
```
--------------------------------
### Compare CQL2 text and JSON parsing results
Source: https://github.com/geopython/pygeofilter/blob/main/examples/cql2.ipynb
This script iterates through examples, parsing both text and JSON representations of CQL2 expressions. It then compares the resulting parsed trees and the reconstructed JSON output to ensure consistency between the two formats.
```python
from pygeofilter.parsers.cql2_text import parse as text_parse
from pygeofilter.parsers.cql2_json import parse as json_parse
from pygeofilter.backends.cql2_json import to_cql2
import orjson
import json
import pprint
def pp(j):
print(orjson.dumps(j))
with open('tests/parsers/cql2_json/fixtures.json') as f:
examples = json.load(f)
for k, v in examples.items():
parsed_text = None
parsed_json = None
print (k)
t=v['text'].replace('filter=','')
j=v['json']
# print('\t' + t)
# pp(orjson.loads(j))
# print('*****')
try:
parsed_text=text_parse(t)
parsed_json=json_parse(j)
if parsed_text == parsed_json:
print('*******parsed trees match***************')
else:
print(parsed_text)
print('-----')
print(parsed_json)
if parsed_json is None or parsed_text is None:
raise Exception
if to_cql2(parsed_text) == to_cql2(parsed_json):
print('*******reconstructed json matches*******')
else:
pp(to_cql2(parsed_text))
print('-----')
pp(to_cql2(parsed_json))
except Exception as e:
print(parsed_text)
print(parsed_json)
print(j)
traceback.print_exc(f"Error: {e}")
pass
print('____________________________________________________________')
```
--------------------------------
### Run pygeofilter Tests
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Executes the pygeofilter test suite using pytest. This command assumes pytest is installed and the necessary dependencies are met.
```bash
python -m pytest
```
--------------------------------
### Inspect AST with get_repr
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Use pygeofilter.get_repr or pygeofilter.ast.get_repr to get a string representation of the parsed Abstract Syntax Tree (AST).
```python
>>> filters = pygeofilter.parsers.ecql.parse('id = 10')
>>> print(pygeofilter.get_repr(ast))
ATTRIBUTE id = LITERAL 10.0
>>>
>>>
>>> filter_expr = '(number BETWEEN 5 AND 10 AND string NOT LIKE
'%B
') OR INTERSECTS(geometry, LINESTRING(0 0, 1 1))'
>>> print(pygeofilter.ast.get_repr(pygeofilter.parse(filter_expr)))
(
(
ATTRIBUTE number BETWEEN 5 AND 10
) AND (
ATTRIBUTE string NOT LIKE '%B'
)
) OR (
INTERSECTS(ATTRIBUTE geometry, Geometry(geometry={'type': 'LineString', 'coordinates': ((0.0, 0.0), (1.0, 1.0))}))
)
```
--------------------------------
### Using Evaluator for Backend Filtering
Source: https://github.com/geopython/pygeofilter/blob/main/README.md
Demonstrates the basic setup for using the `Evaluator` class to process an AST and build filters for a specific API. The `handle` decorator is used to register evaluation logic.
```python
from pygeofilter import ast
from pygeofilter.backends.evaluator import Evaluator, handle
from myapi import filters # <- this is where the filters are created.
# of course, this can also be done in the
# evaluator itself
```
--------------------------------
### pygeofilter.values.Interval
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a time interval with optional start and end points.
```APIDOC
## pygeofilter.values.Interval
### Description
Represents a time interval with optional start and end points.
### Class Signature
`Interval(start: date | datetime | timedelta | NoneType = None, end: date | datetime | timedelta | NoneType = None)`
### Attributes
* `start` (date | datetime | timedelta | None)
* `end` (date | datetime | timedelta | None)
### Methods
* `get_sub_nodes() -> List[Any]`: Returns a list of sub-nodes within the interval.
```
--------------------------------
### Optimize Static Computation in AST
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Demonstrates how to optimize a static computation within an AST to a static value. This is useful for reducing the cost of filtering operations by pre-calculating known values. Ensure necessary modules like `ast`, `parse`, and `optimize` are imported.
```python
>>> import math
>>> from pygeofilter import ast
>>> from pygeofilter.parsers.ecql import parse
>>> from pygeofilter.backends.optimize import optimize
>>>
>>> root = parse('attr < sin(3.7) - 5')
>>> optimized_root = optimize(root, {'sin': math.sin})
>>> print(ast.get_repr(root))
ATTRIBUTE attr < (
(
sin (3.7)
) - 5
)
>>> print(ast.get_repr(optimized_root))
ATTRIBUTE attr < -5.529836140908493
```
--------------------------------
### pygeofilter.ast.get_repr
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Get a debug representation of the given AST node. This function is useful for inspecting the structure of parsed filter expressions.
```APIDOC
## pygeofilter.ast.get_repr
### Description
Get a debug representation of the given AST node. This function is useful for inspecting the structure of parsed filter expressions.
### Signature
`get_repr(node: Node, indent_amount: int = 0, indent_incr: int = 4) -> str`
### Parameters
* `node` (Node) - The AST node to represent.
* `indent_amount` (int, optional) - The current indentation level. Defaults to 0.
* `indent_incr` (int, optional) - The increment for indentation in recursive calls. Defaults to 4.
```
--------------------------------
### SQL Backend Modules
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
Overview of the SQL backend modules for pygeofilter.
```APIDOC
## SQL Backend Modules
The generic SQL backend provides modules for evaluating filter expressions and generating SQL queries.
### Modules
- `pygeofilter.backends.sql.evaluate`
```
--------------------------------
### pygeofilter.cql2 Module
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/modules.md
Documentation for the CQL2 parsing module, including the get_op function.
```APIDOC
## CQL2 Parsing (pygeofilter.cql2)
### Description
Provides functionality for parsing CQL2 expressions.
### Functions
* **get_op()**: Parses and returns the operator for a given CQL2 expression.
```
--------------------------------
### Running SQLAlchemy Integration Tests
Source: https://github.com/geopython/pygeofilter/blob/main/pygeofilter/backends/sqlalchemy/README.md
Command to discover and run tests for the SQLAlchemy integration using Python's unittest module.
```shell
python -m unittest discover tests/sqlalchemy_test/ tests.py
```
--------------------------------
### Parse CQL2 Text Query
Source: https://github.com/geopython/pygeofilter/blob/main/README.md
Demonstrates parsing a CQL2 text string into an abstract syntax tree using the pygeofilter command-line utility.
```bash
pygeofilter parse cql2_text "title = "birds'"
```
--------------------------------
### pygeofilter.util Module
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/modules.md
Documentation for utility functions in pygeofilter, including pattern matching and date/time parsing.
```APIDOC
## Utility Functions (pygeofilter.util)
### Description
Contains various utility functions for pattern matching and parsing.
### Functions
* **like_pattern_to_re()**: Converts a LIKE pattern to a regular expression.
* **like_pattern_to_re_pattern()**: Converts a LIKE pattern to a compiled regular expression object.
* **parse_datetime()**: Parses a string into a datetime object.
* **parse_duration()**: Parses a string into a duration object.
```
--------------------------------
### Execute Tests with Docker Compose
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Runs the pygeofilter tests using Docker Compose. This method is useful for setting up a consistent testing environment.
```bash
./execute-tests.sh
```
--------------------------------
### Parse CQL2 Text to AST
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Demonstrates parsing a CQL2 text query string into an abstract syntax tree (AST) using the `pygeofilter parse` command. This is useful for validating and understanding the structure of CQL2 queries.
```bash
# parse a CQL2 text string into AST
pygeofilter parse cql2_text "title = "birds'"
Parsing cql2_text query into AST
Equal(lhs=ATTRIBUTE title, rhs='birds')
```
--------------------------------
### pygeofilter.ast.Like
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a wildcard string matching predicate.
```APIDOC
## pygeofilter.ast.Like
### Description
Node class to represent a wildcard string matching predicate. Supports case sensitivity, wildcards, and escape characters.
### Class Definition
`class Like(lhs: Node, pattern: Node | int | float | str, nocase: bool, wildcard: str, singlechar: str, escapechar: str, not_: bool)`
### Attributes
* **lhs** (Node) - The left-hand side operand.
* **pattern** (Node | int | float | str) - The pattern to match against.
* **nocase** (bool) - If True, the match is case-insensitive.
* **wildcard** (str) - The character used for wildcard matching.
* **singlechar** (str) - The character used for single character matching.
* **escapechar** (str) - The character used to escape special characters.
* **not_** (bool) - Indicates if the predicate is negated.
```
--------------------------------
### Solr Backend Modules
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
Overview of the Solr backend modules for pygeofilter.
```APIDOC
## Solr Backend Modules
The Solr backend includes modules for evaluation and utility functions to translate pygeofilter expressions into Solr queries.
### Modules
- `pygeofilter.backends.solr.evaluate`
- `pygeofilter.backends.solr.util`
```
--------------------------------
### SQLAlchemy Backend Modules
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
Overview of the SQLAlchemy backend modules for pygeofilter.
```APIDOC
## SQLAlchemy Backend Modules
The SQLAlchemy backend offers modules for evaluating filters and constructing SQLAlchemy expressions.
### Modules
- `pygeofilter.backends.sqlalchemy.evaluate`
- `pygeofilter.backends.sqlalchemy.filters`
```
--------------------------------
### pygeofilter.ast.And
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a logical AND combination of two expressions.
```APIDOC
## pygeofilter.ast.And
### Description
Represents a logical AND combination of two expressions.
### Class Signature
`pygeofilter.ast.And(lhs: pygeofilter.ast.Node, rhs: pygeofilter.ast.Node)`
### Attributes
* `op`: ClassVar[CombinationOp] = 'AND'
```
--------------------------------
### pygeofilter.ast.Include
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents an 'Include' predicate, which can be negated.
```APIDOC
## pygeofilter.ast.Include
### Description
Node class to represent an include predicate. This can be negated using the `not_` parameter.
### Class Definition
`class Include(not_: bool)`
### Attributes
* **not_** (bool) - Indicates if the predicate is negated.
```
--------------------------------
### Import necessary modules for CQL2 JSON parsing
Source: https://github.com/geopython/pygeofilter/blob/main/examples/cql2.ipynb
Imports modules required for parsing CQL2 expressions into JSON format and for converting them back to CQL2.
```python
from pygeofilter.parsers.cql2_json import parse
from pygeofilter.backends.cql2_json import to_cql2
import json
import traceback
from lark import lark, logger, v_args
from pygeofilter.cql2 import BINARY_OP_PREDICATES_MAP
```
--------------------------------
### to_sql_where_with_bind_variables Function
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.oraclesql.md
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string, also returning a dictionary of bind variables. This is useful for preventing SQL injection and improving performance by separating the SQL query from its parameters.
```APIDOC
### pygeofilter.backends.oraclesql.evaluate.to_sql_where_with_bind_variables(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str], function_map: Dict[str, str] | None = None) → Tuple[str, Dict[str, Any]]
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string, returning the SQL and a dictionary of bind variables.
```
--------------------------------
### pygeofilter.ast Time Operations
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/modules.md
Documentation for time-related operations within the pygeofilter AST module, including TimeMeets, TimeMetBy, TimeOverlappedBy, and TimeOverlaps.
```APIDOC
## Time Operations (pygeofilter.ast)
### Description
Provides classes for representing temporal relationships in filters.
### Classes
* **TimeMeets**: Represents the 'meets' temporal relation.
* `op`: The operator for this relation.
* **TimeMetBy**: Represents the 'metBy' temporal relation.
* `op`: The operator for this relation.
* **TimeOverlappedBy**: Represents the 'overlappedBy' temporal relation.
* `op`: The operator for this relation.
* **TimeOverlaps**: Represents the 'overlaps' temporal relation.
* `op`: The operator for this relation.
### Utility Functions
* **get_repr()**: Returns a string representation of an AST node.
* **indent()**: Indents a string for pretty printing.
```
--------------------------------
### pygeofilter.ast.Node
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
The base class for all Abstract Syntax Tree (AST) nodes in pygeofilter.
```APIDOC
## pygeofilter.ast.Node
### Description
The base class for all other nodes used to display the AST of CQL (Common Query Language).
### Methods
* **get_sub_nodes()** → List[Node]
Get a list of sub-node of this node.
* **Returns:** A list of all sub-nodes.
* **get_template()** → str
Get a template string (using the `.format` method) to represent the current node and sub-nodes. The template string must provide a template replacement for each sub-node reported by `get_sub_nodes()`.
* **Returns:** The template to render.
### Attributes
* **inline** (bool) - Controls whether the node should be rendered inline. Defaults to False.
```
--------------------------------
### Module Level to_sql_where_with_bind_variables Function
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.oraclesql.md
Provides a top-level function to convert a pygeofilter AST root node into an Oracle SQL WHERE clause string, also returning a dictionary of bind variables. This function is an alias for `pygeofilter.backends.oraclesql.evaluate.to_sql_where_with_bind_variables`.
```APIDOC
### pygeofilter.backends.oraclesql.to_sql_where_with_bind_variables(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str], function_map: Dict[str, str] | None = None) → Tuple[str, Dict[str, Any]]
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string, returning the SQL and a dictionary of bind variables.
```
--------------------------------
### OracleSQLEvaluator Class
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.oraclesql.md
The `OracleSQLEvaluator` class is responsible for translating pygeofilter Abstract Syntax Tree (AST) nodes into Oracle SQL expressions. It handles various node types, including arithmetic operations, comparisons, spatial operations, and literal values, mapping them to their corresponding Oracle SQL syntax.
```APIDOC
## class pygeofilter.backends.oraclesql.evaluate.OracleSQLEvaluator(attribute_map: Dict[str, str], function_map: Dict[str, str])
Bases: [`Evaluator`](pygeofilter.backends.md#pygeofilter.backends.evaluator.Evaluator)
### Methods
- **arithmetic(node: [Arithmetic](pygeofilter.md#pygeofilter.ast.Arithmetic), lhs, rhs)**
- **attribute(node: [Attribute](pygeofilter.md#pygeofilter.ast.Attribute))**
- **bbox(node, lhs)**
- **between(node, lhs, low, high)**
- **combination(node, lhs, rhs)**
- **comparison(node, lhs, rhs)**
- **envelope(node: [Envelope](pygeofilter.md#pygeofilter.values.Envelope))**
- **function(node, *arguments)**
- **geometry(node: [Geometry](pygeofilter.md#pygeofilter.values.Geometry))**
- **in_(node, lhs, *options)**
- **like(node, lhs)**
- **literal(node)**
- **not_(node, sub)**
- **null(node, lhs)**
- **spatial_operation(node, lhs, rhs)**
### Class Attributes
- **bind_variables**: Dict[str, Any]
- **handler_map**: Dict[Type, Callable]
```
--------------------------------
### Applying CQL Filters with SQLAlchemy
Source: https://github.com/geopython/pygeofilter/blob/main/pygeofilter/backends/sqlalchemy/README.md
Translates a CQL expression into SQLAlchemy filters and applies them to a query. Requires the 'parse' and 'to_filter' functions from pygeofilter.integrations.sqlalchemy.
```python
from pygeofilter.integrations.sqlalchemy import to_filter, parse
cql_expr = 'strMetaAttribute LIKE "%parent%" AND datetimeAttribute BEFORE 2000-01-01T00:00:01Z'
# NOTE: we are using the sqlalchemy integration `parse` wrapper here
ast = parse(cql_expr)
print(ast)
filters = to_filter(ast, FIELD_MAPPING)
q = session.query(Record).join(RecordMeta).filter(filters)
```
--------------------------------
### pygeofilter.cql2.get_op
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Retrieves the CQL2 operator string corresponding to a given AST node.
```APIDOC
## pygeofilter.cql2.get_op
### Description
Retrieves the CQL2 operator string corresponding to a given AST node.
### Signature
`get_op(node: Node) -> str | None`
### Parameters
* `node` (Node) - The AST node to get the operator for.
### Returns
The CQL2 operator string, or None if the node does not correspond to a known operator.
```
--------------------------------
### pygeofilter.backends.cql2_json.evaluate.to_cql2
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.cql2_json.md
Converts an AST node into a CQL2 JSON string.
```APIDOC
## pygeofilter.backends.cql2_json.evaluate.to_cql2(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str] | None = None, function_map: Dict[str, str] | None = None) → str
### Description
Converts an Abstract Syntax Tree (AST) node into a CQL2 compliant JSON string.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Parse ECQL and CQL JSON filters
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Import and use the parse function from pygeofilter.parsers.ecql or pygeofilter.parsers.cql_json to parse filter expressions.
```python
>>> from pygeofilter.parsers.ecql import parse as parse_ecql
>>> filters = parse_ecql(filter_expression)
>>> from pygeofilter.parsers.cql_json import parse as parse_json
>>> filters = parse_json(filter_expression)
```
--------------------------------
### pygeofilter.ast.Node
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Base class for all nodes in the Abstract Syntax Tree. Provides methods for retrieving sub-nodes and generating template strings.
```APIDOC
## pygeofilter.ast.Node
### Description
Base class for all nodes in the Abstract Syntax Tree. Provides methods for retrieving sub-nodes and generating template strings.
### Methods
#### get_sub_nodes()
Get a list of sub-node of this node.
* **Returns:** a list of all sub-nodes
* **Return type:** list[[Node](#pygeofilter.ast.Node)]
#### get_template()
Get a template string (using the `.format` method) to represent the current node and sub-nodes. The template string must provide a template replacement for each sub-node reported by [`get_sub_nodes()`](#pygeofilter.ast.Node.get_sub_nodes).
* **Returns:** the template to render
### Attributes
#### high *: [Node](#pygeofilter.ast.Node) | int | float | str*
#### lhs *: [Node](#pygeofilter.ast.Node)*
#### low *: [Node](#pygeofilter.ast.Node) | int | float | str*
#### not_ *: bool*
```
--------------------------------
### pygeofilter.ast.Add
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents an addition operation between two expressions.
```APIDOC
## pygeofilter.ast.Add
### Description
Represents an addition operation between two expressions.
### Class Signature
`pygeofilter.ast.Add(lhs: ForwardRef('Node') | int | float | str, rhs: ForwardRef('Node') | int | float | str)`
### Attributes
* `op`: ClassVar[ArithmeticOp] = '+'
```
--------------------------------
### pygeofilter.parsers.cql2_text.CQLTransformer
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.md
A PLY parsing transformer for converting CQL text queries into an abstract syntax tree (AST). It defines methods for handling various CQL grammar elements.
```APIDOC
## Class: pygeofilter.parsers.cql2_text.CQLTransformer
### Description
A PLY parsing transformer for converting CQL text queries into an abstract syntax tree (AST).
### Methods
* **BOOLEAN(self, p)**: Handles boolean literals.
* **DOUBLE_QUOTED(self, p)**: Handles double-quoted string literals.
* **FLOAT(self, p)**: Handles float literals.
* **INT(self, p)**: Handles integer literals.
* **SINGLE_QUOTED(self, p)**: Handles single-quoted string literals.
* **add(self, p)**: Handles addition operations.
* **after(self, p)**: Handles the 'after' temporal predicate.
* **and_(self, p)**: Handles the 'AND' logical operator.
* **attribute(self, p)**: Handles attribute references.
* **bbox_spatial_predicate(self, p)**: Handles the BBOX spatial predicate.
* **before(self, p)**: Handles the 'before' temporal predicate.
* **before_or_during(self, p)**: Handles the 'before or during' temporal predicate.
* **between(self, p)**: Handles the 'BETWEEN' operator.
* **binary_spatial_predicate(self, p)**: Handles general binary spatial predicates.
* **binary_temporal_predicate(self, p)**: Handles general binary temporal predicates.
* **distance_spatial_predicate(self, p)**: Handles distance-based spatial predicates.
* **distance_units(self, p)**: Handles distance unit specifications.
* **div(self, p)**: Handles division operations.
* **does_not_exist(self, p)**: Handles the 'does not exist' operator.
* **during(self, p)**: Handles the 'during' temporal predicate.
* **during_or_after(self, p)**: Handles the 'during or after' temporal predicate.
* **envelope(self, p)**: Handles the ENVELOPE spatial predicate.
* **eq(self, p)**: Handles the equality operator.
* **exclude(self, p)**: Handles the 'EXCLUDE' spatial predicate.
* **exists(self, p)**: Handles the 'EXISTS' operator.
* **function(self, p)**: Handles function calls.
* **geometry(self, p)**: Handles geometry literals.
```
--------------------------------
### pygeofilter.values Module
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/modules.md
Documentation for value types used in pygeofilter, including Envelope, Geometry, and Interval.
```APIDOC
## Value Types (pygeofilter.values)
### Description
Defines various data types used for representing spatial and temporal values.
### Classes
* **Envelope**: Represents a rectangular bounding box.
* `geometry`: The geometry representation of the envelope.
* `x1`: The minimum x-coordinate.
* `x2`: The maximum x-coordinate.
* `y1`: The minimum y-coordinate.
* `y2`: The maximum y-coordinate.
* **Geometry**: Represents a generic geometry object.
* `geometry`: The geometry data.
* **Interval**: Represents a time or numerical interval.
* `end`: The end point of the interval.
* `get_sub_nodes()`: Retrieves the sub-nodes of the interval.
* `start`: The start point of the interval.
```
--------------------------------
### pygeofilter.parsers.cql2_json.walk_cql_json
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.md
Recursively walks through a CQL2 JSON AST, allowing for custom processing of each node. Useful for traversing and manipulating parsed queries.
```APIDOC
## Function: pygeofilter.parsers.cql2_json.walk_cql_json
### Description
Recursively walks through a CQL2 JSON AST, allowing for custom processing of each node.
### Parameters
* **node** (dict): The current node in the CQL2 JSON AST.
* **visitor** (callable): A function to call for each node visited.
### Returns
* None. The visitor function is called for each node.
```
--------------------------------
### OracleSQLEvaluator Methods
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
This section lists the methods available on the OracleSQLEvaluator class, which are used to build SQL expressions for Oracle databases.
```APIDOC
## OracleSQLEvaluator Methods
This class provides methods to construct SQL expressions for Oracle.
### Methods
- `arithmetic()`: Handles arithmetic operations.
- `attribute()`: Represents a database attribute.
- `bbox()`: Creates a bounding box filter.
- `between()`: Implements a BETWEEN clause.
- `combination()`: Combines multiple conditions.
- `comparison()`: Performs comparison operations.
- `envelope()`: Creates an envelope filter.
- `function()`: Calls a SQL function.
- `geometry()`: Represents a geometry literal.
- `in_()`: Implements an IN clause.
- `like()`: Performs a LIKE comparison.
- `literal()`: Represents a SQL literal.
- `not_()`: Negates a condition.
- `null()`: Checks for NULL values.
- `spatial_operation()`: Executes a spatial operation.
```
--------------------------------
### pygeofilter.backends.cql2_json.to_cql2
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.cql2_json.md
Converts an AST node into a CQL2 JSON string (module level function).
```APIDOC
## pygeofilter.backends.cql2_json.to_cql2(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str] | None = None, function_map: Dict[str, str] | None = None) → str
### Description
Converts an Abstract Syntax Tree (AST) node into a CQL2 compliant JSON string. This is the top-level function for serialization.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### pygeofilter.ast.LessThan
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a less than comparison operation.
```APIDOC
## pygeofilter.ast.LessThan
### Description
Node class to represent a less than comparison.
### Class Definition
`class LessThan(lhs: Node | int | float | str, rhs: Node | int | float | str)`
### Attributes
* **op** (ClassVar[ComparisonOp]) - The comparison operator, fixed to '<'.
```
--------------------------------
### pygeofilter.parsers.cql2_text.parser.parse
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.md
Parses a CQL text string into an abstract syntax tree (AST). This is the main entry point for parsing CQL text expressions.
```APIDOC
## Function: pygeofilter.parsers.cql2_text.parser.parse
### Description
Parses a CQL text string into an abstract syntax tree (AST).
### Parameters
* **cql_string** (str) - The CQL text string to parse.
### Returns
An AST representation of the CQL string.
```
--------------------------------
### pygeofilter.backends.cql2_json.to_cql2
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
Alias for the to_cql2 function in the evaluate module for the cql2_json backend.
```APIDOC
## Function: to_cql2 (in pygeofilter.backends.cql2_json)
### Description
This is an alias for the `to_cql2` function found in `pygeofilter.backends.cql2_json.evaluate`. It provides a direct way to access the CQL2 JSON conversion utility.
### Usage
```python
from pygeofilter.backends.cql2_json import to_cql2
from pygeofilter.expressions import Literal
expression = Literal('example')
cql2_json_string = to_cql2(expression)
```
```
--------------------------------
### to_sql_where Function
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.oraclesql.md
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string. It utilizes the `OracleSQLEvaluator` to perform the translation, taking an attribute mapping and an optional function mapping as input.
```APIDOC
### pygeofilter.backends.oraclesql.evaluate.to_sql_where(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str], function_map: Dict[str, str] | None = None) → str
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string.
```
--------------------------------
### pygeofilter.parsers.cql2_json.parse
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.md
Parses a CQL2 JSON string into an abstract syntax tree (AST). This function is the main entry point for parsing CQL2 JSON queries.
```APIDOC
## Function: pygeofilter.parsers.cql2_json.parse
### Description
Parses a CQL2 JSON string into an abstract syntax tree (AST).
### Parameters
* **cql_json** (str): The CQL2 JSON string to parse.
### Returns
* An AST representation of the CQL2 JSON query.
```
--------------------------------
### Parse FES XML to AST
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Shows how to parse an OGC Filter Encoding (FES) XML string into an abstract syntax tree (AST) using the `pygeofilter parse` command. This is useful for converting FES queries into a structured format.
```bash
# parse a FES text string into AST
pygeofilter parse fes "titlebirds"
Parsing fes query into AST
Equal(lhs=ATTRIBUTE title, rhs='birds')
```
--------------------------------
### Module Level to_sql_where Function
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.oraclesql.md
Provides a top-level function to convert a pygeofilter AST root node into an Oracle SQL WHERE clause string. This function is an alias for `pygeofilter.backends.oraclesql.evaluate.to_sql_where`.
```APIDOC
### pygeofilter.backends.oraclesql.to_sql_where(root: [Node](pygeofilter.md#pygeofilter.ast.Node), field_mapping: Dict[str, str], function_map: Dict[str, str] | None = None) → str
Converts a pygeofilter AST root node into an Oracle SQL WHERE clause string.
```
--------------------------------
### pygeofilter.ast.Or
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a logical OR combination of two nodes. It inherits from the Combination base class and defines the 'OR' operator.
```APIDOC
## pygeofilter.ast.Or
### Description
Represents a logical OR combination of two nodes. It inherits from the Combination base class and defines the 'OR' operator.
### Class Signature
`class Or(lhs: pygeofilter.ast.Node, rhs: pygeofilter.ast.Node)`
### Attributes
- **op**: `ClassVar[CombinationOp]` = 'OR'
```
--------------------------------
### Parse FES XML Filter
Source: https://github.com/geopython/pygeofilter/blob/main/README.md
Shows how to parse a Filter Encoding Service (FES) XML string into an abstract syntax tree using the pygeofilter command-line utility.
```bash
pygeofilter parse fes "titlebirds"
```
--------------------------------
### SQL WHERE Clause Generation
Source: https://github.com/geopython/pygeofilter/blob/main/docs/index.md
Generates an SQL WHERE clause from a pygeofilter AST, useful for OGR ExecuteSQL function.
```python
from osgeo import ogr
from pygeofilter.backends.sql import to_sql_where
from pygeofilter.parsers.ecql import parse
FIELD_MAPPING = {
'str_attr': 'str_attr',
'maybe_str_attr': 'maybe_str_attr',
'int_attr': 'int_attr',
'float_attr': 'float_attr',
'date_attr': 'date_attr',
'datetime_attr': 'datetime_attr',
'point_attr': 'GEOMETRY',
}
FUNCTION_MAP = {
'sin': 'sin'
}
# parse the expression
ast = parse('int_attr > 6')
# open an OGR DataSource
data = ogr.Open(...)
# create the WHERE clause, field and function mappings must be provided
where = to_sql_where(ast, FIELD_MAPPING, FUNCTION_MAP)
# filter the DataSource to get a result Layer
layer = data.ExecuteSQL(f"""
SELECT id, str_attr, maybe_str_attr, int_attr, float_attr, date_attr, datetime_attr, GEOMETRY
FROM layer
WHERE {where}
""", None, "SQLite")
```
--------------------------------
### pygeofilter.parsers.cql_json.parser.walk_cql_json
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.cql_json.md
Recursively walks through a dictionary representation of a CQL JSON expression to build an AST node or extract values.
```APIDOC
## pygeofilter.parsers.cql_json.parser.walk_cql_json
### Description
Recursively walks through a dictionary representation of a CQL JSON expression to build an AST node or extract values.
### Signature
`walk_cql_json(node: dict, is_temporal: bool = False) -> Node | Geometry | Envelope | date | datetime | timedelta | Interval | bool | float | int | str | list`
### Parameters
* **node** (dict) - The dictionary representing the current node in the CQL JSON structure.
* **is_temporal** (bool, optional) - Flag indicating if the current context is temporal. Defaults to False.
### Returns
Returns an AST Node, Geometry, Envelope, date, datetime, timedelta, Interval, bool, float, int, str, or list, depending on the parsed expression.
```
--------------------------------
### Inspect AST with get_repr
Source: https://github.com/geopython/pygeofilter/blob/main/README.md
Use the `get_repr` function to obtain a string representation of the parsed abstract syntax tree (AST). This helps in understanding the structure of the parsed filter.
```python
>>> filters = pygeofilter.parsers.ecql.parse('id = 10')
>>> print(pygeofilter.get_repr(ast))
ATTRIBUTE id = LITERAL 10.0
```
```python
>>> filter_expr = '(number BETWEEN 5 AND 10 AND string NOT LIKE
'%B
') OR INTERSECTS(geometry, LINESTRING(0 0, 1 1))'
>>> print(pygeofilter.ast.get_repr(pygeofilter.parse(filter_expr)))
(
(
ATTRIBUTE number BETWEEN 5 AND 10
) AND (
ATTRIBUTE string NOT LIKE '%B'
)
) OR (
INTERSECTS(ATTRIBUTE geometry, Geometry(geometry={'type': 'LineString', 'coordinates': ((0.0, 0.0), (1.0, 1.0))}))
)
```
--------------------------------
### SQLAlchemy Model Definition
Source: https://github.com/geopython/pygeofilter/blob/main/pygeofilter/backends/sqlalchemy/README.md
Defines SQLAlchemy models for 'Record' and 'RecordMeta' with various column types, including a GeoAlchemy2 Geometry column.
```python
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey
from geoalchemy2 import Geometry
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Record(Base):
__tablename__ = "record"
identifier = Column(String, primary_key=True)
geometry = Column(
Geometry(
geometry_type="MULTIPOLYGON",
srid=4326,
spatial_index=False,
management=True,
)
)
float_attribute = Column(Float)
int_attribute = Column(Integer)
str_attribute = Column(String)
datetime_attribute = Column(DateTime)
choice_attribute = Column(Integer)
class RecordMeta(Base):
__tablename__ = "record_meta"
identifier = Column(Integer, primary_key=True)
record = Column(String, ForeignKey("record.identifier"))
float_meta_attribute = Column(Float)
int_meta_attribute = Column(Integer)
str_meta_attribute = Column(String)
datetime_meta_attribute = Column(DateTime)
choice_meta_attribute = Column(Integer)
```
--------------------------------
### pygeofilter.ast.Div
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a division operation in the AST. Inherits from Arithmetic.
```APIDOC
### *class* pygeofilter.ast.Div(lhs: ForwardRef('Node') | int | float | str, rhs: ForwardRef('Node') | int | float | str)
Bases: [`Arithmetic`](#pygeofilter.ast.Arithmetic)
```
--------------------------------
### pygeofilter.ast.Mul
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a multiplication arithmetic operation.
```APIDOC
## pygeofilter.ast.Mul
### Description
Node class to represent a multiplication arithmetic operation.
### Class Definition
`class Mul(lhs: Node | int | float | str, rhs: Node | int | float | str)`
### Attributes
* **op** (ClassVar[ArithmeticOp]) - The arithmetic operator, fixed to '*'.
```
--------------------------------
### pygeofilter.parsers.cql2_text.parser.CQLTransformer
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.cql2_text.md
A transformer class for parsing CQL2 text expressions. It inherits from WKTTransformer and ISO8601Transformer, providing methods to handle various CQL2 syntax elements including spatial and temporal predicates, boolean logic, and attribute access.
```APIDOC
## class pygeofilter.parsers.cql2_text.parser.CQLTransformer(visit_tokens: bool = True)
Bases: [`WKTTransformer`](pygeofilter.parsers.md#pygeofilter.parsers.wkt.WKTTransformer), [`ISO8601Transformer`](pygeofilter.parsers.md#pygeofilter.parsers.iso8601.ISO8601Transformer)
### Methods
- **BOOLEAN(value)**
- **DOUBLE_QUOTED(token)**
- **FLOAT(value)**
- **INT(value)**
- **SINGLE_QUOTED(token)**
- **add(lhs, rhs)**
- **after(node, dt)**
- **and_(*args)**
- **attribute(name)**
- **bbox_spatial_predicate(lhs, minx, miny, maxx, maxy, crs=None)**
- **before(node, dt)**
- **before_or_during(node, period)**
- **between(lhs, low, high)**
- **binary_spatial_predicate(op, lhs, rhs)**
- **binary_temporal_predicate(lhs, op, rhs)**
- **distance_spatial_predicate(op, lhs, rhs, distance, units)**
- **distance_units(value)**
- **div(lhs, rhs)**
- **does_not_exist(attribute)**
- **during(node, period)**
- **during_or_after(node, period)**
- **envelope(x1, x2, y1, y2)**
- **eq(lhs, rhs)**
- **exclude()**
- **exists(attribute)**
- **function(func_name, *expressions)**
- **geometry(value)**
- **gt(lhs, rhs)**
- **gte(lhs, rhs)**
- **ilike(node, pattern)**
- **in_(*options)**
- **include()**
- **interval(start, end)**
- **like(node, pattern)**
- **lt(lhs, rhs)**
- **lte(lhs, rhs)**
- **mul(lhs, rhs)**
- **ne(lhs, rhs)**
- **neg(value)**
- **not_(node)**
- **not_between(lhs, low, high)**
- **not_ilike(node, pattern)**
- **not_in(node, *options)**
- **not_like(node, pattern)**
- **not_null(node)**
- **null(node)**
- **or_(*args)**
- **period(start, end)**
- **relate_spatial_predicate(lhs, rhs, pattern)**
- **sub(lhs, rhs)**
```
--------------------------------
### pygeofilter.parsers.cql_json.parser.walk_cql_json
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.md
Recursively walks through a CQL JSON structure, applying a visitor function to each node. Useful for custom processing or traversal of CQL JSON.
```APIDOC
## Function: pygeofilter.parsers.cql_json.parser.walk_cql_json
### Description
Recursively walks through a CQL JSON structure, applying a visitor function to each node.
### Parameters
* **cql_json** (dict) - The CQL JSON object to walk.
* **visitor** (callable) - The function to apply to each node.
### Returns
None. The visitor function is called for its side effects.
```
--------------------------------
### parse Function
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.ecql.md
The parse function takes a string of ECQL text and returns a structured representation of the query.
```APIDOC
## Function: parse
### Description
Parses a string containing ECQL (Enhanced Common Query Language) text into a structured query object.
### Parameters
- **cql_text** (string) - Required - The ECQL query string to parse.
```
--------------------------------
### pygeofilter.backends.cql2_json.evaluate.to_cql2
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.md
Converts a pygeofilter expression to its CQL2 JSON representation.
```APIDOC
## Function: to_cql2
### Description
Converts a pygeofilter expression object into its corresponding CQL2 JSON string representation.
### Usage
```python
from pygeofilter.backends.cql2_json import to_cql2
from pygeofilter.expressions import Literal
expression = Literal('world')
cql2_json_string = to_cql2(expression)
# cql2_json_string will be the JSON string for the expression
```
```
--------------------------------
### pygeofilter.ast.Combination
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a condition to combine two other conditions using either AND or OR. Inherits from Condition.
```APIDOC
### *class* pygeofilter.ast.Combination(lhs: [Node](#pygeofilter.ast.Node), rhs: [Node](#pygeofilter.ast.Node))
Bases: [`Condition`](#pygeofilter.ast.Condition)
Node class to represent a condition to combine two other conditions using either AND or OR.
#### *classmethod* from_items(first, *rest)
#### get_sub_nodes() → List[[Node](#pygeofilter.ast.Node) | [Geometry](#pygeofilter.values.Geometry) | [Envelope](#pygeofilter.values.Envelope) | date | datetime | timedelta | [Interval](#pygeofilter.values.Interval) | bool | float | int | str | list]
Get a list of sub-node of this node.
* **Returns:**
a list of all sub-nodes
* **Return type:**
list[[Node](#pygeofilter.ast.Node)]
#### get_template() → str
Get a template string (using the `.format` method)
to represent the current node and sub-nodes. The template string
must provide a template replacement for each sub-node reported by
[`get_sub_nodes()`](#pygeofilter.ast.Node.get_sub_nodes).
* **Returns:**
the template to render
#### lhs *: [Node](#pygeofilter.ast.Node)*
#### op *: ClassVar[[CombinationOp](#pygeofilter.ast.CombinationOp)]*
#### rhs *: [Node](#pygeofilter.ast.Node)*
```
--------------------------------
### pygeofilter.parsers.cql2_json.parser.walk_cql_json
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.parsers.cql2_json.md
Recursively walks through a CQL2 JSON node, which can be a dictionary, list, string, number, or boolean.
```APIDOC
## pygeofilter.parsers.cql2_json.parser.walk_cql_json
### Description
Recursively walks through a CQL2 JSON node, which can be a dictionary, list, string, number, or boolean.
### Signature
`walk_cql_json(node: dict | list | str | float | int | bool | None)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **node** (dict | list | str | float | int | bool | None) - The CQL2 JSON node to walk.
```
--------------------------------
### pygeofilter.backends.cql2_json.evaluate.json_serializer
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.backends.cql2_json.md
Serializes Python objects into a JSON-compatible format for CQL2.
```APIDOC
## pygeofilter.backends.cql2_json.evaluate.json_serializer(obj)
### Description
Serializes a Python object into a JSON-compatible representation suitable for CQL2.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### TimeBegunBy
Source: https://github.com/geopython/pygeofilter/blob/main/docs/api/pygeofilter.md
Represents a temporal predicate where the left-hand side is begun by the right-hand side.
```APIDOC
## TimeBegunBy
### Description
Represents a temporal predicate where the left-hand side is begun by the right-hand side. This is a subclass of `TemporalPredicate`.
### Class Signature
`pygeofilter.ast.TimeBegunBy(lhs: Node | datetime.date | datetime.datetime | datetime.timedelta | Interval, rhs: Node | datetime.date | datetime.datetime | datetime.timedelta | Interval)`
### Operator
`BEGUNBY`
```