Skip to content

add support for math database functions #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions .github/workflows/test-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ jobs:
bulk_create
dates
datetimes
db_functions.math
empty
defer
defer_regress
Expand Down
32 changes: 32 additions & 0 deletions django_mongodb/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,20 @@ class DatabaseFeatures(BaseDatabaseFeatures):
"lookup.tests.LookupTests.test_pattern_lookups_with_substr",
# Querying ObjectID with string doesn't work.
"lookup.tests.LookupTests.test_lookup_int_as_str",
# MongoDB gives the wrong result of log(number, base) when base is a
# fractional Decimal: https://jira.mongodb.org/browse/SERVER-91223
"db_functions.math.test_log.LogTests.test_decimal",
# MongoDB gives ROUND(365, -1)=360 instead of 370 like other databases.
"db_functions.math.test_round.RoundTests.test_integer_with_negative_precision",
}

django_test_skips = {
"Insert expressions aren't supported.": {
"bulk_create.tests.BulkCreateTests.test_bulk_insert_now",
"bulk_create.tests.BulkCreateTests.test_bulk_insert_expressions",
# PI()
"db_functions.math.test_round.RoundTests.test_decimal_with_precision",
"db_functions.math.test_round.RoundTests.test_float_with_precision",
},
"Pattern lookups on UUIDField are not supported.": {
"model_fields.test_uuid.TestQuerying.test_contains",
Expand Down Expand Up @@ -292,4 +300,28 @@ class DatabaseFeatures(BaseDatabaseFeatures):
"timezones.tests.NewDatabaseTests.test_aware_datetime_in_local_timezone_with_microsecond",
"timezones.tests.NewDatabaseTests.test_naive_datetime_with_microsecond",
},
"Transform not supported.": {
"db_functions.math.test_abs.AbsTests.test_transform",
"db_functions.math.test_acos.ACosTests.test_transform",
"db_functions.math.test_asin.ASinTests.test_transform",
"db_functions.math.test_atan.ATanTests.test_transform",
"db_functions.math.test_ceil.CeilTests.test_transform",
"db_functions.math.test_cos.CosTests.test_transform",
"db_functions.math.test_cot.CotTests.test_transform",
"db_functions.math.test_degrees.DegreesTests.test_transform",
"db_functions.math.test_exp.ExpTests.test_transform",
"db_functions.math.test_floor.FloorTests.test_transform",
"db_functions.math.test_ln.LnTests.test_transform",
"db_functions.math.test_radians.RadiansTests.test_transform",
"db_functions.math.test_round.RoundTests.test_transform",
"db_functions.math.test_sin.SinTests.test_transform",
"db_functions.math.test_sqrt.SqrtTests.test_transform",
"db_functions.math.test_tan.TanTests.test_transform",
},
"MongoDB does not support Sign.": {
"db_functions.math.test_sign.SignTests",
},
"MongoDB can't annotate ($project) a function like PI().": {
"db_functions.math.test_pi.PiTests.test",
},
}
40 changes: 40 additions & 0 deletions django_mongodb/functions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
from django.db import NotSupportedError
from django.db.models.expressions import Func
from django.db.models.functions.datetime import Extract
from django.db.models.functions.math import Ceil, Cot, Degrees, Log, Power, Radians, Random, Round
from django.db.models.functions.text import Upper

from .query_utils import process_lhs

MONGO_OPERATORS = {
Ceil: "ceil",
Degrees: "radiansToDegrees",
Power: "pow",
Radians: "degreesToRadians",
Random: "rand",
Upper: "toUpper",
}


def cot(self, compiler, connection):
lhs_mql = process_lhs(self, compiler, connection)
return {"$divide": [1, {"$tan": lhs_mql}]}


def extract(self, compiler, connection):
lhs_mql = process_lhs(self, compiler, connection)
Expand All @@ -17,5 +34,28 @@ def extract(self, compiler, connection):
return {operator: lhs_mql}


def func(self, compiler, connection):
lhs_mql = process_lhs(self, compiler, connection)
operator = MONGO_OPERATORS.get(self.__class__, self.function.lower())
return {f"${operator}": lhs_mql}


def log(self, compiler, connection):
# This function is usually log(base, num) but on MongoDB it's log(num, base).
clone = self.copy()
clone.set_source_expressions(self.get_source_expressions()[::-1])
return func(clone, compiler, connection)


def round_(self, compiler, connection):
# Round needs its own function because it's a special case that inherits
# from Transform but has two arguments.
return {"$round": [expr.as_mql(compiler, connection) for expr in self.get_source_expressions()]}


def register_functions():
Cot.as_mql_agg = cot
Extract.as_mql = extract
Func.as_mql_agg = func
Log.as_mql_agg = log
Round.as_mql_agg = round_
2 changes: 2 additions & 0 deletions django_mongodb/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ def adapt_datetimefield_value(self, value):

def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
"""Store DecimalField as Decimal128."""
if value is None:
return None
return Decimal128(value)

def adapt_timefield_value(self, value):
Expand Down
4 changes: 4 additions & 0 deletions django_mongodb/query_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ def is_direct_value(node):


def process_lhs(node, compiler, connection, bare_column_ref=False):
if not hasattr(node, "lhs"):
# node is a Func or Expression, possibly with multiple source expressions.
return [expr.as_mql(compiler, connection) for expr in node.get_source_expressions()]
# node is a Transform with just one source expression, aliased as "lhs".
if is_direct_value(node.lhs):
return node
mql = node.lhs.as_mql(compiler, connection)
Expand Down