Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions docs/4_extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,48 @@ Similarly analytic functions can be defined by extending ``pypika.terms.Analytic

SELECT ROW_NUMBER() OVER(PARTITION BY "foo" ORDER BY "date") FROM "abc"

Operators not included in PyPika
""""""""""""""""""""""""""""""""""""

PyPika may not include certain operators used in SQL, such as the ``<->``, ``<#>`` or ``<=>`` operators often used in extensions. To incorporate these operators, you can utilize a custom ``ArithmeticExpression`` from ``pypika.terms``.

Custom Operator: ``<->`` for Distance Calculation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For instance, consider a scenario where you want to use the ``<->`` operator in an ``ORDER BY`` clause for geographic distance calculation. You can define this operator using a custom ``ArithmeticExpression``.

.. code-block:: python

from pypika import Field, Query
from pypika.terms import ArithmeticExpression

# Wrapper class for the custom operator
class CustomOperator:
value: str = "<->" # Define your operator here

# Preparing the operands
left_operand = Field("left_operand_field")
right_operand = Field("right_operand_field")

# Creating the custom ArithmeticExpression
orderby_expression = ArithmeticExpression(CustomOperator, left_operand, right_operand)

Using the Custom Operator in a Query
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

With the custom operator defined, you can now incorporate it into your PyPika queries. For example:

.. code-block:: python

# Constructing the query with the custom ORDER BY clause
query = Query.from_("your_table").select("your_columns").orderby(orderby_expression)

# The resulting SQL query will be similar to:
# SELECT "your_columns" FROM "your_table" ORDER BY "left_operand_field" <-> "right_operand_field"

Adapting to Other Operators
^^^^^^^^^^^^^^^^^^^^^^^^^^^

This method is not limited to the ``<->`` operator. You can adapt it for any other operator by changing the ``value`` in the ``CustomOperator`` class. This allows for a flexible approach to integrate various operators that are not natively supported in PyPika.