feat: Add Runtime Formula for formatting numbers (#5262)

* Add new skill for creating/updating runtime formulas.

* Add abs() formula function

* Add getErrorMessage() to arg type to return a human-readable error message.

* Update skill to ensure getErrorMessage() is overridden when appropriate.

* Add null() runtime formula.

* Add number_format() runtime formula.

* Fix tests

* Add changelog entry

* Add date_interval() runtime formula.

* Fix test

* Add runtime formula: to_datetime()

* Update changelog

* Fix backend test

* Fix frontend test

* Add new ensure_date_interval() ensurer.

* Update descriptions and examples.

* Remove references to Moment.js

* Refactor validate_type_of_args() to return the index of the invalid arg.

* Refactor to_datetime() to use ensure_datetime()

* Use ensure_date_interval ensurer for IntervalStringBaserowRuntimeFormulaArgumentType

* Update skill with sections on ensurers.

* Add optional strict arg to ensure_datetime()

* Fix tests

* Simplify the ensure_string() to return total seconds for timedelta.

* ensure_date_interval() should also try to convert numbers to a timedelta.

* Fix test

* Use ensure_integer() in ensure_date_interval()

* Rename DateInterval to Duration

* Return an array of all possible errors.

* Use database duration parser for consistency

* Remove contrib references in core.

* Add additional test coverage

* Rename duration to to_duration

* Attempt to fix CI

* Reverting some changes

* Ensure empty string '' isn't accepted as a datetime format.

---------

Co-authored-by: Jeremie Pardou <571533+jrmi@users.noreply.github.com>
This commit is contained in:
Tsering PaljorandJeremie Pardou authored and GitHub committed 2026-05-26 14:47:13 +07:00
1 parent fb61bb7883
commit 87fbf1f2bb
27 files changed
+3829 -1298

No files matched your search

@@ -0,0 +1,253 @@
---
name: Runtime Formulas
description: Create or update Baserow runtime formulas in `core/formula/runtime_formula_types.py`. Use when adding or updating a runtime formula.
version: 1.0.0
---
# Create Or Update Runtime Formulas
Use this skill when a task involves creating or updating a Baserow runtime formula.
Runtime formulas are used in the Application builder, Automation builder, and the AIField in the Database builder. Any changes made to runtime formulas must be compatible with all three parts of the codebase.
The runtime formulas need to be implemented in both the backend and the frontend. In the backend, the runtime formulas are evaluated at runtime. In the frontend, the corresponding runtime formulas are used to validate correct syntax.
This repo already has the core patterns. Prefer copying an existing implementation close to the target behavior, and then modifying it to support the new requirements, instead of inventing a new structure.
## First Step
Before adding a new runtime formula type, identify whether a new argument type is needed.
Note that both the backend and frontend define `parse_args()` and `parseArgs()` respectively, which uses the argument type's `parse()` to transform arguments before they are executed.
There are some additional methods that control how the formula is rendered in the rich text formula editor, but most simple formulas shouldn't need to override them:
- `toNode()`
- `formulaComponentType()`
- `formulaComponent()`
- `fromNodeToFormula()`
## Ensurers
Ensurers are reusable normalization/coercion functions that convert an arbitrary value into a specific type, or raise an error if conversion is not possible. They live in:
- Backend: `backend/src/baserow/core/formula/validator.py`
- Frontend: `web-frontend/modules/core/utils/validator.js`
Existing ensurers include `ensure_string`, `ensure_duration`, etc.
### When to create or use an ensurer
Argument types should delegate their `test()` and `parse()` methods to an ensurer rather than implementing inline conversion logic.
- For `test()`, call the ensurer inside a try/except (backend) or try/catch (frontend) and return `True`/`False`.
- For `parse()`, return the ensurer's result directly.
Runtime formula types should use ensurers in their `execute()` method when converting input values, rather than calling low-level conversion functions (e.g. `datetime.strptime()`, `moment()`) directly.
Before creating a new ensurer, check whether an existing one already covers the target type. Only create a new ensurer when no existing one handles the conversion.
### When a new type is introduced, update existing ensurers
When introducing a new data type (e.g. `timedelta` / `Timedelta`), the existing `ensure_string()` and `ensure_integer()` ensurers may need to be updated to handle coercion of the new type into strings and integers.
For example:
- `ensure_string()` was updated to convert `timedelta` to a human-readable string like `"1 day"`
- `ensure_integer()` was updated to convert `timedelta` to total seconds.
### Ensurer implementation conventions
- Backend ensurers raise `django.core.exceptions.ValidationError` on failure.
- Frontend ensurers throw `TypeError` or `Error` on failure.
- Both backend and frontend ensurers must implement the same conversion logic and accept the same range of input types.
- Tests for ensurers go in:
- Backend: `backend/tests/baserow/core/formula/test_validator.py`
- Frontend: `web-frontend/test/unit/core/utils/validator.spec.js`
## Backend Checklist
Useful backend files:
- Runtime formula types: `backend/src/baserow/core/formula/runtime_formula_types.py`
- Runtime formula argument types: `backend/src/baserow/core/formula/argument_types.py`
- Register new runtime formula types in: `backend/src/baserow/core/apps.py`
- Tests for runtime formula types: `backend/tests/baserow/core/formula/test_runtime_formula_types.py`
### Runtime Formula Type
A new runtime formula type should subclass `RuntimeFormulaFunction` and implement the following properties and methods.
#### `type`
This is a unique lower-cased and snake-cased identifier.
#### `args`
This is a list of argument types.
If the argument type or length are dynamic or optional, `min_args`, `validate_type_of_args()`, and `validate_number_of_args()` will likely also need to be implemented.
As a general rule, prefer to use a more permissive argument type when possible. E.g. `RuntimeConcat` allows 2 or more arguments. Each argument is coerced to a string. This allows `concat()` to concatenate a mix of ints, floats, and strings to produce a result.
#### `execute()`
This method should compute and return the expected result for the runtime formula type.
### Runtime Formula Argument Type
The runtime formula argument type defines the acceptable arguments for a runtime formula types. The most permissive argument type is `AnyBaserowRuntimeFormulaArgumentType`, which will accept any argument type, such as int, string, etc.
When creating a new runtime formula type, consider whether a new argument type is necessary or whether an existing argument type is already available that satisfies the requirements.
Note that the constructor can accept kwargs, such as `cast_to_int` for `NumberBaserowRuntimeFormulaType`. E.g. `RuntimeRound` uses `optional=True, cast_to_int=True`.
All argument types must implement both `test()` and `parse()`. The `get_error_message()` method is special, which is described next.
Argument types should delegate to an ensurer in `validator.py` for their `test()` and `parse()` implementations. For example, `DurationBaserowRuntimeFormulaArgumentType` delegates to `ensure_duration()`. Avoid duplicating conversion logic inline when an ensurer exists or can be created.
##### `get_error_message()`
When an argument type can return a useful human-readable error message, this method should be overridden to return an error message.
E.g. the `TimezoneBaserowRuntimeFormulaArgumentType` argument type overrides `get_error_message()` to return a human-readable error message when the timezone value is invalid.
### Register the Runtime Formula Type
After creating a new runtime formula type, it must be imported and registered in `backend/src/baserow/core/apps.py`.
The syntax is: `formula_runtime_function_registry.register(RuntimeFoo())`
### Tests
For new runtime formula types, tests should be added in `test_runtime_formula_types.py`. Notice that existing tests ensure that:
- The `execute()` method returns the expected result.
- The `validate_type_of_args()` correctly validates various possible inputs, and either returns `None` to indicate that the argument is allowed, or returns the same argument back to indicate it is an invalid argument.
- The `validate_number_of_args()` method returns a bool where `True` indicates the number of arguments are valid, and `False` otherwise.
- If the argument type's `get_error_message()` is overridden:
- A relevant test for the argument type's method should be added to `test_argument_types.py`.
- A relevant test for the runtime formula type should be added to `test_runtime_formula_types.py`.
## Frontend Checklist
The frontend needs a parallel implementation of the backend changes in order to support validating the syntax of the runtime formula.
Useful frontend files:
- Runtime formula types: `web-frontend/modules/core/runtimeFormulaTypes.js`
- Runtime formula argument types: `web-frontend/modules/core/runtimeFormulaArgumentTypes.js`
- Register new runtime formula types in: `web-frontend/modules/core/plugin.js`
- Tests for runtime formula types: `web-frontend/test/unit/core/formula/runtimeFormulaTypes.spec.js`
- Translations for runtime formula descriptions: `web-frontend/locales/en.json`
- Re-usable utility functions should be added in: `web-frontend/modules/core/utils/`
- Enums are defined in: `web-frontend/modules/core/enums.js`
### Runtime Formula Type
A new runtime formula type should extend the RuntimeFormulaFunction class. It should implement the following methods.
#### `getType()`
This corresponds to the backend's `RuntimeFormulaFunction`'s `type` property and should be an exact match.
#### `getFormulaType()`
This defines the formula type as an enum. Possible choices are `FORMULA_TYPE.FUNCTION` if the runtime formula type is a function like `concat()`, or `FORMULA_TYPE.OPERATOR` if it is an operator such as `=`, `+`, etc.
#### `getCategoryType()`
This defines how the runtime formula type is categorized and grouped in the frontend. Pick one of the enum options in `FORMULA_CATEGORY`.
#### `execute()`
The `execute()` method should return the desired result of the runtime formula being called. The behaviour should be identical to the backend's corresponding `execute()` implementation.
#### `args` getter
This getter property corresponds to the backend's `args` property. It should return an array of argument types.
If the argument type or length are dynamic or optional, `numArgs()`, `validateArgs()`, and `validateNumberOfArgs()` will likely also need to be implemented.
As a general rule, prefer to use a more permissive argument type when possible. E.g. `RuntimeConcat` allows 2 or more arguments. Each argument is coerced to a string. This allows `concat()` to concatenate a mix of ints, floats, and strings to produce a result.
#### `validateNumberOfArgs()`
This corresponds to the backend's `validate_number_of_args()` method and should implement the same behaviour.
#### `validateArgs()`
This is a higher level method that internally calls `validateTypeOfArgs()` (corresponds to the backend's `validate_type_of_args()` method). It can be overridden for custom validation logic. It should implement the same behaviour as the backend logic.
An important point to note is that in the validation visitor, there will be additional context that can provide additional context to help with validation. This is not available to the execution visitor.
#### `getOperatorSymbol` getter
This getter property should only be implemented when the `getFormulaType()` returns an operator. It should return a operator symbol, e.g. `+`, `-`, `>=`, etc.
#### `getDescription()`
This should return a description of the runtime formula type. The description should be added to
the `runtimeFormulaTypes` dict in `web-frontend/locales/en.json`.
#### `getExamples()`
This should return an array of objects. Each object should define the `formula` and `result` keys. The `formula` value should be and example of how to use the runtime formula, and the `result` value should show an example of the expected result of calling the runtime formula.
### Runtime Formula Argument Type
Similar to the corresponding backend implementation, the runtime formula argument type defines the acceptable arguments for a runtime formula types and are defined in `web-frontend/modules/core/runtimeFormulaArgumentTypes.js`.
The most permissive argument type is `AnyBaserowRuntimeFormulaArgumentType`, which will accept any argument type, such as int, string, etc.
When creating a new runtime formula type, consider whether a new argument type is necessary or whether an existing argument type is already available that satisfies the requirements. If a new type is created for the backend, the frontend will likely also need a new type.
All argument types must implement both `test()` and `parse()`. The `getErrorMessage()` method is special, which is described next.
##### `getErrorMessage()`
When an argument type can return a useful human-readable error message, this method should be overridden with a key defined in the `runtimeFormulaTypeErrors` translation key.
E.g. the `TimezoneBaserowRuntimeFormulaArgumentType` argument type overrides `getErrorMessage()` to return a human-readable error message when the timezone value is invalid.
### Register the Runtime Formula Type
After creating a new runtime formula type, it must be imported and registered in `web-frontend/modules/core/plugin.js`.
Add the new runtime formula to the `fns` array.
### Tests
For new runtime formula types, tests should be added in `runtimeFormulaTypes.spec.js`. Notice that existing tests ensure that:
- The entire runtime formula type's tests are grouped by a `describe()` scope.
- The `execute()`, `validateTypeOfArgs()`, and `validateNumberOfArgs()` are tested with parameterized tests, similar to the corresponding backend tests.
- If the argument type's `getErrorMessage()` is overridden:
- A relevant test for the argument type's method should be added to `runtimeFormulaArgumentTypes.spec.js`.
- A relevant test for the runtime formula type should be added to `runtimeFormulaTypes.spec.js`.
## How to Implement
### Creating a new Runtime Formula Type
When creating a new runtime formula type, both the backend and frontend will need parallel implementations:
- Create the new runtime formula type.
- Backend: `backend/src/baserow/core/formula/runtime_formula_types.py`
- Frontend: `web-frontend/modules/core/runtimeFormulaTypes.js`
- Create a new argument type if an existing type doesn't provide the needed functionality.
- Backend: `backend/src/baserow/core/formula/argument_types.py`
- Frontend: `web-frontend/modules/core/runtimeFormulaArgumentTypes.js`
- Create or update an ensurer if the argument type or `execute()` method requires type coercion that isn't covered by an existing ensurer.
- Backend: `backend/src/baserow/core/formula/validator.py`
- Frontend: `web-frontend/modules/core/utils/validator.js`
- If introducing a new data type, check whether existing ensurers (e.g. `ensure_string()`, etc) need updating to handle coercion of the new type.
- Add tests for new or updated ensurers.
- Backend: `backend/tests/baserow/core/formula/test_validator.py`
- Frontend: `web-frontend/test/unit/core/utils/validator.spec.js`
- Register the runtime formula type.
- Backend: `backend/src/baserow/core/apps.py`
- Frontend: `web-frontend/modules/core/plugin.js`
- Add tests.
- Backend: `backend/tests/baserow/core/formula/test_runtime_formula_types.py`
- Frontend: `web-frontend/test/unit/core/formula/runtimeFormulaTypes.spec.js`
The frontend will additionally need translations for the description: `web-frontend/locales/en.json`.
### Updating an existing Runtime Formula Type
When updating an existing runtime formula type, ensure that both the backend and frontend have:
- Matching implementations.
- Tests are updated.
- Translations are updated.
## Guardrails
Do not add a new runtime formula type or an argument type, without first checking that an existing formula type or argument type already provides similar functionality.
If an existing type can be minimally refactored to support the new requirements, suggest a refactor.
@@ -0,0 +1,4 @@
interface:
display_name: 'Runtime Formulas'
short_description: 'Create or update Baserow Runtime Formulas'
default_prompt: 'Use $create-update-runtime-formula to create or update Baserow Runtime Formulas.'
@@ -14,192 +14,26 @@ from django.db.models import (
)
from django.db.models.functions import Cast, Extract, Mod
from baserow.core.duration import (
D_H,
D_H_M,
D_H_M_NO_COLONS,
D_H_M_S,
D_H_M_S_NO_COLONS,
H_M,
H_M_S,
H_M_S_S,
H_M_S_SS,
H_M_S_SSS,
parse_duration_value,
postgres_interval_to_seconds, # noqa: F401
)
from baserow.core.psycopg import is_psycopg3
H_M = "h:mm"
H_M_S = "h:mm:ss"
H_M_S_S = "h:mm:ss.s"
H_M_S_SS = "h:mm:ss.ss"
H_M_S_SSS = "h:mm:ss.sss"
D_H = "d h"
D_H_M = "d h:mm" # 1d 11:11
D_H_M_S = "d h:mm:ss"
D_H_M_NO_COLONS = "d h mm" # 1d 2h 3m, 1d 3m
D_H_M_S_NO_COLONS = "d h mm ss" # 1d2h3m4s, 1h 2m
MOST_ACCURATE_DURATION_FORMAT = H_M_S_SSS
if typing.TYPE_CHECKING:
from baserow.contrib.database.fields.models import DurationField
def total_secs(
days: Optional[int] = None,
hours: Optional[int] = None,
mins: Optional[int] = None,
secs: Optional[Union[int, float]] = None,
) -> float:
"""
Calculate number of seconds from higher-order units.
:param days: number of days
:param hours: number of hours
:param mins: number of minutes
:param secs: number of seconds (with milliseconds if provided as a float)
:return: number of seconds
"""
return (
int(days or 0) * 86400
+ int(hours or 0) * 3600
+ int(mins or 0) * 60
+ float(secs or 0.0)
)
POSTGRES_INTERVAL_FORMAT = re.compile(
r"""
(?P<years>-?\d+)\s+years?\s*|
(?P<months>-?\d+)\s+mons?\s*|
(?P<days>-?\d+)\s+days?\s*|
(?P<time>(-?\d{1,2}):(\d{2}):(\d{2}))?
""",
re.VERBOSE,
)
def postgres_interval_to_seconds(interval_str: str) -> Optional[float]:
matches = POSTGRES_INTERVAL_FORMAT.finditer(interval_str)
params = {
"days": 0,
"seconds": 0,
"microseconds": 0,
"milliseconds": 0,
"minutes": 0,
"hours": 0,
"weeks": 0,
}
valid = False
for match in matches:
if match.group("years"):
params["days"] += int(match.group("years")) * 365
valid = True
if match.group("months"):
params["days"] += int(match.group("months")) * 30
valid = True
if match.group("days"):
params["days"] += int(match.group("days"))
valid = True
if match.group("time"):
time_parts = match.group("time").split(":")
params["hours"] += int(time_parts[0])
params["minutes"] += int(time_parts[1])
params["seconds"] += int(time_parts[2])
valid = True
return timedelta(**params).total_seconds() if valid else None
# These regexps are supposed to tokenize the provided duration value and to return a
# proper number of seconds based on format and the tokens. NOTE: Keep these in sync with
# web-frontend/modules/database/utils/duration.js:DURATION_REGEXPS
DURATION_REGEXPS = {
# 1d 10h 20m 30s
# 1d 30m 40.50s
# 1d 30s
re.compile( # optionally capture `1d`
r"^((?P<days>\d+)(?:d\s*))?"
# optionally capture 1h
r"((?P<hours>\d+)(?:h\s*))?"
# optionally capture 1m
r"((?P<mins>\d+)(?:m\s*|\s+))?"
# optionally capture 1.2s
r"((?P<secs>\d+|\d+.\d+)?(?:s\s*))?$"
): {
"default": lambda days, hours, mins, secs: total_secs(
days=days, hours=hours, mins=mins, secs=secs
),
},
# 1d 11:12:13.14
# 1 11:12:13.14
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+):(\d+|\d+.\d+)$"): {
"default": lambda d, h, m, s: total_secs(days=d, hours=h, mins=m, secs=s),
},
# 11:12:13.14
re.compile(r"^(\d+):(\d+):(\d+|\d+.\d+)$"): {
"default": lambda h, m, s: total_secs(hours=h, mins=m, secs=s),
},
# 1d 12h
# 1 12h
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+)h$"): {
"default": lambda d, h: total_secs(days=d, hours=h),
},
# 1234h
re.compile(r"^(\d+)h$"): {
"default": lambda h: total_secs(hours=h),
},
# 123d
re.compile(r"^(\d+)d$"): {
"default": lambda d: total_secs(days=d),
},
# 1d 11:12
# 1 11:12
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+)$"): {
H_M: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H_M: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H_M_NO_COLONS: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
"default": lambda d, m, s: total_secs(days=d, mins=m, secs=s),
},
# 1d 11:12.23
# 1 11:12.23
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+.\d+)$"): {
"default": lambda d, m, s: total_secs(days=d, mins=m, secs=s),
},
# 11:12
re.compile(r"^(\d+):(\d+)$"): {
H_M: lambda h, m: total_secs(hours=h, mins=m),
D_H: lambda h, m: total_secs(hours=h, mins=m),
D_H_M: lambda h, m: total_secs(hours=h, mins=m),
"default": lambda m, s: total_secs(mins=m, secs=s),
},
# 11:12.134
re.compile(r"^(\d+):(\d+.\d+)$"): {
"default": lambda m, s: total_secs(mins=m, secs=s),
},
# 1d 123
# 1 123
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+)$"): {
H_M: lambda d, m: total_secs(days=d, mins=m),
D_H: lambda d, h: total_secs(days=d, hours=h),
D_H_M: lambda d, m: total_secs(days=d, mins=m),
D_H_M_NO_COLONS: lambda d, m: total_secs(days=d, mins=m),
"default": lambda d, s: total_secs(days=d, secs=s),
},
# 1d 12.134
# 1 12.134
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+.\d+)$"): {
"default": lambda d, s: total_secs(days=d, secs=s),
},
# 123
re.compile(r"^(\d+)$"): {
H_M: lambda m: total_secs(mins=float(m)),
D_H: lambda h: total_secs(hours=float(h)),
D_H_M: lambda m: total_secs(mins=float(m)),
D_H_M_NO_COLONS: lambda m: total_secs(mins=m),
"default": lambda s: total_secs(secs=s),
},
# 11.123
re.compile(r"^(\d+.\d+)$"): {
"default": lambda s: total_secs(secs=s),
},
}
def rround(value: float, ndigits: int = 0) -> int:
"""
Rounds a float to the specified number of decimal places. Python round will round
@@ -473,50 +307,6 @@ DURATION_FORMAT_TOKENS = {
}
def parse_duration_value(formatted_value: str, format: str) -> float:
"""
Parses a formatted duration string into a number of seconds according to the
provided format. If the format doesn't match exactly, it will still try to
parse it as best as possible.
:param formatted_value: The formatted duration string.
:param format: The format of the duration string.
:return: The total number of seconds for the given formatted duration.
:raises ValueError: If the format is invalid.
"""
if format not in DURATION_FORMATS:
raise ValueError(f"{format} is not a valid duration format.")
# support for negative values
multiplier = 1
if formatted_value.startswith("-"):
formatted_value = formatted_value[1:]
multiplier = -1
for regex, format_funcs in DURATION_REGEXPS.items():
match = regex.match(formatted_value)
if match:
format_func = format_funcs.get(format, format_funcs["default"])
# handle named groups in regexps
captured = match.groupdict()
if any(v for v in captured.values()):
return format_func(**captured) * multiplier
# if no named groups, use standard args
try:
return format_func(*match.groups()) * multiplier
# invalid number of args
except TypeError:
pass
# If it's not one of the known formats, try to parse it as a postgres interval
# Lookups formula save duration in the postgres interval format in the database.
total_seconds = postgres_interval_to_seconds(formatted_value)
if total_seconds is not None:
return total_seconds
raise ValueError(f"{formatted_value} is not a valid duration string.")
def duration_value_to_timedelta(
value: Union[int, float, timedelta, str, None], format: str
) -> Optional[timedelta]:
@@ -650,7 +440,7 @@ def is_duration_format_conversion_lossy(new_format, old_format):
return ordered_tokens.index(old_lst) > ordered_tokens.index(new_lst)
def get_duration_search_expression(field) -> Func:
def get_duration_search_expression(field: "DurationField") -> Func:
"""
Returns a search expression that can be used to search the field as a formatted
string.
+10
View File
@@ -36,6 +36,7 @@ class CoreConfig(AppConfig):
from baserow.core.formula.registries import formula_runtime_function_registry
from baserow.core.formula.runtime_formula_types import (
RuntimeAbs,
RuntimeAdd,
RuntimeAnd,
RuntimeAt,
@@ -68,6 +69,8 @@ class CoreConfig(AppConfig):
RuntimeMultiply,
RuntimeNotEqual,
RuntimeNow,
RuntimeNull,
RuntimeNumberFormat,
RuntimeOr,
RuntimeRandomBool,
RuntimeRandomFloat,
@@ -80,7 +83,9 @@ class CoreConfig(AppConfig):
RuntimeStrip,
RuntimeSum,
RuntimeToArray,
RuntimeToDatetime,
RuntimeToday,
RuntimeToDuration,
RuntimeUpper,
RuntimeYear,
)
@@ -101,6 +106,7 @@ class CoreConfig(AppConfig):
formula_runtime_function_registry.register(RuntimeLower())
formula_runtime_function_registry.register(RuntimeCapitalize())
formula_runtime_function_registry.register(RuntimeRound())
formula_runtime_function_registry.register(RuntimeAbs())
formula_runtime_function_registry.register(RuntimeIsEven())
formula_runtime_function_registry.register(RuntimeIsOdd())
formula_runtime_function_registry.register(RuntimeDateTimeFormat())
@@ -132,6 +138,10 @@ class CoreConfig(AppConfig):
formula_runtime_function_registry.register(RuntimeAvg())
formula_runtime_function_registry.register(RuntimeAt())
formula_runtime_function_registry.register(RuntimeToArray())
formula_runtime_function_registry.register(RuntimeNull())
formula_runtime_function_registry.register(RuntimeNumberFormat())
formula_runtime_function_registry.register(RuntimeToDuration())
formula_runtime_function_registry.register(RuntimeToDatetime())
from baserow.core.permission_manager import (
AllowIfTemplatePermissionManagerType,
+257
View File
@@ -0,0 +1,257 @@
import re
from datetime import timedelta
from typing import Optional, Union
H_M = "h:mm"
H_M_S = "h:mm:ss"
H_M_S_S = "h:mm:ss.s"
H_M_S_SS = "h:mm:ss.ss"
H_M_S_SSS = "h:mm:ss.sss"
D_H = "d h"
D_H_M = "d h:mm" # 1d 11:11
D_H_M_S = "d h:mm:ss"
D_H_M_NO_COLONS = "d h mm" # 1d 2h 3m, 1d 3m
D_H_M_S_NO_COLONS = "d h mm ss" # 1d2h3m4s, 1h 2m
MOST_ACCURATE_DURATION_FORMAT = H_M_S_SSS
DURATION_PATTERNS = [
(re.compile(r"^(\d+)\s+years?$", re.IGNORECASE), "days", 365),
(re.compile(r"^(\d+)\s+months?$", re.IGNORECASE), "days", 30),
(re.compile(r"^(\d+)\s+weeks?$", re.IGNORECASE), "weeks", 1),
(re.compile(r"^(\d+)\s+days?$", re.IGNORECASE), "days", 1),
(re.compile(r"^(\d+)\s+hours?$", re.IGNORECASE), "hours", 1),
(re.compile(r"^(\d+)\s+minutes?$", re.IGNORECASE), "minutes", 1),
(re.compile(r"^(\d+)\s+seconds?$", re.IGNORECASE), "seconds", 1),
]
def total_secs(
days: Optional[int] = None,
hours: Optional[int] = None,
mins: Optional[int] = None,
secs: Optional[Union[int, float]] = None,
) -> float:
"""
Calculate number of seconds from higher-order units.
:param days: number of days
:param hours: number of hours
:param mins: number of minutes
:param secs: number of seconds (with milliseconds if provided as a float)
:return: number of seconds
"""
return (
int(days or 0) * 86400
+ int(hours or 0) * 3600
+ int(mins or 0) * 60
+ float(secs or 0.0)
)
POSTGRES_INTERVAL_FORMAT = re.compile(
r"""
(?P<years>-?\d+)\s+years?\s*|
(?P<months>-?\d+)\s+mons?\s*|
(?P<days>-?\d+)\s+days?\s*|
(?P<time>(-?\d{1,2}):(\d{2}):(\d{2}))?
""",
re.VERBOSE,
)
def postgres_interval_to_seconds(interval_str: str) -> Optional[float]:
matches = POSTGRES_INTERVAL_FORMAT.finditer(interval_str)
params = {
"days": 0,
"seconds": 0,
"microseconds": 0,
"milliseconds": 0,
"minutes": 0,
"hours": 0,
"weeks": 0,
}
valid = False
for match in matches:
if match.group("years"):
params["days"] += int(match.group("years")) * 365
valid = True
if match.group("months"):
params["days"] += int(match.group("months")) * 30
valid = True
if match.group("days"):
params["days"] += int(match.group("days"))
valid = True
if match.group("time"):
time_parts = match.group("time").split(":")
params["hours"] += int(time_parts[0])
params["minutes"] += int(time_parts[1])
params["seconds"] += int(time_parts[2])
valid = True
return timedelta(**params).total_seconds() if valid else None
# These regexps are supposed to tokenize the provided duration value and to return a
# proper number of seconds based on format and the tokens. NOTE: Keep these in sync with
# web-frontend/modules/core/utils/duration.js:DURATION_REGEXPS
DURATION_REGEXPS = {
# 1d 10h 20m 30s
# 1d 30m 40.50s
# 1d 30s
re.compile( # optionally capture `1d`
r"^((?P<days>\d+)(?:d\s*))?"
# optionally capture 1h
r"((?P<hours>\d+)(?:h\s*))?"
# optionally capture 1m
r"((?P<mins>\d+)(?:m\s*|\s+))?"
# optionally capture 1.2s
r"((?P<secs>\d+|\d+.\d+)?(?:s\s*))?$"
): {
"default": lambda days, hours, mins, secs: total_secs(
days=days, hours=hours, mins=mins, secs=secs
),
},
# 1d 11:12:13.14
# 1 11:12:13.14
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+):(\d+|\d+.\d+)$"): {
"default": lambda d, h, m, s: total_secs(days=d, hours=h, mins=m, secs=s),
},
# 11:12:13.14
re.compile(r"^(\d+):(\d+):(\d+|\d+.\d+)$"): {
"default": lambda h, m, s: total_secs(hours=h, mins=m, secs=s),
},
# 1d 12h
# 1 12h
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+)h$"): {
"default": lambda d, h: total_secs(days=d, hours=h),
},
# 1234h
re.compile(r"^(\d+)h$"): {
"default": lambda h: total_secs(hours=h),
},
# 123d
re.compile(r"^(\d+)d$"): {
"default": lambda d: total_secs(days=d),
},
# 1d 11:12
# 1 11:12
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+)$"): {
H_M: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H_M: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
D_H_M_NO_COLONS: lambda d, h, m: total_secs(days=d, hours=h, mins=m),
"default": lambda d, m, s: total_secs(days=d, mins=m, secs=s),
},
# 1d 11:12.23
# 1 11:12.23
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+):(\d+.\d+)$"): {
"default": lambda d, m, s: total_secs(days=d, mins=m, secs=s),
},
# 11:12
re.compile(r"^(\d+):(\d+)$"): {
H_M: lambda h, m: total_secs(hours=h, mins=m),
D_H: lambda h, m: total_secs(hours=h, mins=m),
D_H_M: lambda h, m: total_secs(hours=h, mins=m),
"default": lambda m, s: total_secs(mins=m, secs=s),
},
# 11:12.134
re.compile(r"^(\d+):(\d+.\d+)$"): {
"default": lambda m, s: total_secs(mins=m, secs=s),
},
# 1d 123
# 1 123
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+)$"): {
H_M: lambda d, m: total_secs(days=d, mins=m),
D_H: lambda d, h: total_secs(days=d, hours=h),
D_H_M: lambda d, m: total_secs(days=d, mins=m),
D_H_M_NO_COLONS: lambda d, m: total_secs(days=d, mins=m),
"default": lambda d, s: total_secs(days=d, secs=s),
},
# 1d 12.134
# 1 12.134
re.compile(r"^(\d+)(?:d\s*|\s+)(\d+.\d+)$"): {
"default": lambda d, s: total_secs(days=d, secs=s),
},
# 123
re.compile(r"^(\d+)$"): {
H_M: lambda m: total_secs(mins=float(m)),
D_H: lambda h: total_secs(hours=float(h)),
D_H_M: lambda m: total_secs(mins=float(m)),
D_H_M_NO_COLONS: lambda m: total_secs(mins=m),
"default": lambda s: total_secs(secs=s),
},
# 11.123
re.compile(r"^(\d+.\d+)$"): {
"default": lambda s: total_secs(secs=s),
},
}
def parse_duration_value(formatted_value: str, format: str) -> float:
"""
Parses a formatted duration string into a number of seconds according to the
provided format. If the format doesn't match exactly, it will still try to
parse it as best as possible.
:param formatted_value: The formatted duration string.
:param format: The format of the duration string.
:return: The total number of seconds for the given formatted duration.
:raises ValueError: If the format is invalid.
"""
# support for negative values
multiplier = 1
if formatted_value.startswith("-"):
formatted_value = formatted_value[1:]
multiplier = -1
for regex, format_funcs in DURATION_REGEXPS.items():
match = regex.match(formatted_value)
if match:
format_func = format_funcs.get(format, format_funcs["default"])
# handle named groups in regexps
captured = match.groupdict()
if any(v for v in captured.values()):
return format_func(**captured) * multiplier
# if no named groups, use standard args
try:
return format_func(*match.groups()) * multiplier
# invalid number of args
except TypeError:
pass
# If it's not one of the known formats, try to parse it as a postgres interval
# Lookups formula save duration in the postgres interval format in the database.
total_seconds = postgres_interval_to_seconds(formatted_value)
if total_seconds is not None:
return total_seconds
raise ValueError(f"{formatted_value} is not a valid duration string.")
def parse_duration_string(value: str) -> Optional[timedelta]:
"""Parse a duration string into a timedelta, or None if invalid."""
if not isinstance(value, str):
return None
if value.strip() == "":
return None
try:
total_seconds = parse_duration_value(value, MOST_ACCURATE_DURATION_FORMAT)
return timedelta(seconds=round(total_seconds, 3))
except (ValueError, OverflowError):
pass
for pattern, unit, factor in DURATION_PATTERNS:
match = pattern.match(value.strip())
if match:
amount = int(match.group(1)) * factor
return timedelta(**{unit: amount})
return None
@@ -1,18 +1,26 @@
from datetime import timedelta
from typing import Optional
from django.core.exceptions import ValidationError
import pytz
from baserow.core.formula.utils.date import (
is_valid_datetime_format,
)
from baserow.core.formula.validator import (
ensure_array,
ensure_boolean,
ensure_datetime,
ensure_duration,
ensure_numeric,
ensure_object,
ensure_string,
)
VALID_THOUSAND_SEPARATORS = {",", ".", " ", ""}
VALID_DECIMAL_SEPARATORS = {",", "."}
class BaserowRuntimeFormulaArgumentType:
def __init__(self, optional: Optional[bool] = False):
@@ -24,6 +32,16 @@ class BaserowRuntimeFormulaArgumentType:
def parse(self, value):
return value
def get_error_message(self, value) -> Optional[str]:
"""
This function should return a specific human-friendly error message
if the value for the type is invalid.
Defaults to returning None.
"""
return None
class NumberBaserowRuntimeFormulaArgumentType(BaserowRuntimeFormulaArgumentType):
def __init__(self, *args, **kwargs):
@@ -106,6 +124,13 @@ class TimezoneBaserowRuntimeFormulaArgumentType(BaserowRuntimeFormulaArgumentTyp
def parse(self, value):
return ensure_string(value)
def get_error_message(self, value) -> Optional[str]:
return (
f"'{value}' is not a valid timezone. "
f"Please use a valid IANA timezone name "
f"(e.g. 'Europe/Amsterdam')."
)
class AnyBaserowRuntimeFormulaArgumentType(BaserowRuntimeFormulaArgumentType):
def test(self, value):
@@ -135,3 +160,81 @@ class ArrayOfNumbersBaserowRuntimeFormulaArgumentType(
def parse(self, value):
value = ensure_array(value)
return [ensure_numeric(item) for item in value]
class ThousandSeparatorBaserowRuntimeFormulaArgumentType(
BaserowRuntimeFormulaArgumentType
):
def test(self, value):
if not isinstance(value, str):
return False
return value in VALID_THOUSAND_SEPARATORS
def parse(self, value):
return ensure_string(value)
def get_error_message(self, value) -> Optional[str]:
return (
f"'{value}' is not a valid thousand separator. "
f"Valid options are: ',', '.', ' ', or '' (empty string)."
)
class DecimalSeparatorBaserowRuntimeFormulaArgumentType(
BaserowRuntimeFormulaArgumentType
):
def test(self, value):
if not isinstance(value, str):
return False
return value in VALID_DECIMAL_SEPARATORS
def parse(self, value):
return ensure_string(value)
def get_error_message(self, value) -> Optional[str]:
return (
f"'{value}' is not a valid decimal separator. "
f"Valid options are: ',' or '.'."
)
class TimedeltaBaserowRuntimeFormulaArgumentType(BaserowRuntimeFormulaArgumentType):
def test(self, value):
return isinstance(value, timedelta)
def parse(self, value):
return value
class DurationBaserowRuntimeFormulaArgumentType(BaserowRuntimeFormulaArgumentType):
def test(self, value):
try:
ensure_duration(value)
return True
except ValidationError:
return False
def parse(self, value):
return ensure_duration(value)
def get_error_message(self, value) -> Optional[str]:
return (
f"'{value}' is not a valid duration. "
f"Expected format: '<number> <unit>', e.g. '1 day', '2 hours'."
)
class DatetimeFormatBaserowRuntimeFormulaArgumentType(
BaserowRuntimeFormulaArgumentType
):
def test(self, value):
return is_valid_datetime_format(value)
def parse(self, value):
return ensure_string(value)
def get_error_message(self, value) -> Optional[str]:
return (
f"'{value}' is not a valid datetime format. "
f"Examples: 'YYYY-MM-DD' or 'DD/MM/YYYY HH:mm:ss'."
)
+15 -14
View File
@@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional, TypeVar
from baserow.core.formula.argument_types import BaserowRuntimeFormulaArgumentType
from baserow.core.formula.parser.exceptions import (
BaserowFormulaSyntaxError,
FormulaFunctionTypeDoesNotExist,
InvalidFormulaArgumentType,
)
@@ -79,8 +80,11 @@ class RuntimeFormulaFunction(ABC, Instance):
:raises InvalidFormulaArgumentType: If any of the arguments have a wrong type
"""
invalid_arg = self.validate_type_of_args(args)
if invalid_arg:
if result := self.validate_type_of_args(args):
index, invalid_arg = result[0]
if self.args:
if message := self.args[index].get_error_message(invalid_arg):
raise BaserowFormulaSyntaxError(message)
raise InvalidFormulaArgumentType(self, invalid_arg)
def validate_number_of_args(self, args: FormulaArgs) -> bool:
@@ -99,26 +103,23 @@ class RuntimeFormulaFunction(ABC, Instance):
return required_args <= len(args) <= total_args
def validate_type_of_args(self, args: FormulaArgs) -> Optional[FormulaArg]:
def validate_type_of_args(self, args: FormulaArgs) -> list[tuple[int, FormulaArg]]:
"""
This function validates that the type of all args is correct.
If a type is incorrect it will return that arg.
:param args: The args that are being checked
:return: The arg that has the wrong type, if any
:param args: The args that are being checked.
:return: A list of tuples of the index and the arg that has the wrong type.
"""
if self.args is None:
return None
return []
return next(
(
arg
for arg, index in zip(args, range(len(args)))
if not self.args[index].test(arg)
),
None,
)
return [
(index, arg)
for index, arg in enumerate(args)
if not self.args[index].test(arg)
]
def parse_args(self, args: FormulaArgs) -> FormulaArgs:
"""
@@ -1,8 +1,10 @@
import random
import uuid
from datetime import datetime, timedelta
from typing import Any, Dict, Optional
from zoneinfo import ZoneInfo
from django.core.exceptions import ValidationError
from django.utils import timezone
from baserow.core.exceptions import InstanceTypeDoesNotExist
@@ -12,15 +14,20 @@ from baserow.core.formula.argument_types import (
ArrayOfNumbersBaserowRuntimeFormulaArgumentType,
BooleanBaserowRuntimeFormulaArgumentType,
DateTimeBaserowRuntimeFormulaArgumentType,
DatetimeFormatBaserowRuntimeFormulaArgumentType,
DecimalSeparatorBaserowRuntimeFormulaArgumentType,
DictBaserowRuntimeFormulaArgumentType,
DurationBaserowRuntimeFormulaArgumentType,
NumberBaserowRuntimeFormulaArgumentType,
TextBaserowRuntimeFormulaArgumentType,
ThousandSeparatorBaserowRuntimeFormulaArgumentType,
TimedeltaBaserowRuntimeFormulaArgumentType,
TimezoneBaserowRuntimeFormulaArgumentType,
)
from baserow.core.formula.registries import RuntimeFormulaFunction
from baserow.core.formula.types import FormulaArg, FormulaArgs, FormulaContext
from baserow.core.formula.utils.date import convert_date_format_moment_to_python
from baserow.core.formula.validator import ensure_array, ensure_string
from baserow.core.formula.validator import ensure_array, ensure_datetime, ensure_string
from baserow.core.utils import to_path
@@ -28,12 +35,11 @@ class RuntimeConcat(RuntimeFormulaFunction):
type = "concat"
min_args = 2
def validate_type_of_args(self, args) -> Optional[FormulaArg]:
def validate_type_of_args(self, args) -> list[tuple[int, FormulaArg]]:
arg_type = TextBaserowRuntimeFormulaArgumentType()
return next(
(arg for arg in args if not arg_type.test(arg)),
None,
)
return [
(index, arg) for index, arg in enumerate(args) if not arg_type.test(arg)
]
def validate_number_of_args(self, args):
return len(args) >= self.min_args
@@ -86,6 +92,28 @@ class RuntimeAdd(RuntimeFormulaFunction):
NumberBaserowRuntimeFormulaArgumentType(),
]
def validate_type_of_args(self, args) -> list[tuple[int, FormulaArg]]:
if len(args) == 2:
a, b = args
num = NumberBaserowRuntimeFormulaArgumentType()
dt = DateTimeBaserowRuntimeFormulaArgumentType()
td = TimedeltaBaserowRuntimeFormulaArgumentType()
if num.test(a) and num.test(b):
return []
if (dt.test(a) and td.test(b)) or (td.test(a) and dt.test(b)):
return []
if not (num.test(a) or dt.test(a) or td.test(a)):
return [(0, a)]
if not (num.test(b) or dt.test(b) or td.test(b)):
return [(1, b)]
return [(0, a)]
return super().validate_type_of_args(args)
def parse_args(self, args: FormulaArgs) -> FormulaArgs:
if any(isinstance(a, (datetime, timedelta)) for a in args):
return list(args)
return super().parse_args(args)
def execute(self, context: FormulaContext, args: FormulaArgs):
return args[0] + args[1]
@@ -98,6 +126,26 @@ class RuntimeMinus(RuntimeFormulaFunction):
NumberBaserowRuntimeFormulaArgumentType(),
]
def validate_type_of_args(self, args) -> list[tuple[int, FormulaArg]]:
if len(args) == 2:
a, b = args
num = NumberBaserowRuntimeFormulaArgumentType()
dt = DateTimeBaserowRuntimeFormulaArgumentType()
td = TimedeltaBaserowRuntimeFormulaArgumentType()
if num.test(a) and num.test(b):
return []
if dt.test(a) and td.test(b):
return []
if not (num.test(a) or dt.test(a)):
return [(0, a)]
return [(1, b)]
return super().validate_type_of_args(args)
def parse_args(self, args: FormulaArgs) -> FormulaArgs:
if any(isinstance(a, (datetime, timedelta)) for a in args):
return list(args)
return super().parse_args(args)
def execute(self, context: FormulaContext, args: FormulaArgs):
return args[0] - args[1]
@@ -238,6 +286,15 @@ class RuntimeRound(RuntimeFormulaFunction):
return round(args[0], decimal_places)
class RuntimeAbs(RuntimeFormulaFunction):
type = "abs"
args = [NumberBaserowRuntimeFormulaArgumentType()]
def execute(self, context: FormulaContext, args: FormulaArgs):
return abs(args[0])
class RuntimeIsEven(RuntimeFormulaFunction):
type = "is_even"
@@ -261,7 +318,7 @@ class RuntimeDateTimeFormat(RuntimeFormulaFunction):
args = [
DateTimeBaserowRuntimeFormulaArgumentType(),
TextBaserowRuntimeFormulaArgumentType(),
DatetimeFormatBaserowRuntimeFormulaArgumentType(),
TimezoneBaserowRuntimeFormulaArgumentType(optional=True),
]
@@ -610,3 +667,101 @@ class RuntimeToArray(RuntimeFormulaFunction):
def execute(self, context: FormulaContext, args: FormulaArgs):
return ensure_array(args[0])
class RuntimeNull(RuntimeFormulaFunction):
type = "null"
args = []
def execute(self, context: FormulaContext, args: FormulaArgs):
return None
class RuntimeNumberFormat(RuntimeFormulaFunction):
type = "number_format"
args = [
NumberBaserowRuntimeFormulaArgumentType(),
NumberBaserowRuntimeFormulaArgumentType(optional=True, cast_to_int=True),
ThousandSeparatorBaserowRuntimeFormulaArgumentType(optional=True),
DecimalSeparatorBaserowRuntimeFormulaArgumentType(optional=True),
]
def validate_args(self, args, validation_context=None):
super().validate_args(args, validation_context)
if len(args) >= 4 and args[2] == args[3]:
raise BaserowFormulaSyntaxError(
"The thousand separator and decimal separator cannot be the same."
)
def execute(self, context: FormulaContext, args: FormulaArgs):
value = args[0]
decimal_places = max(int(args[1]), 0) if len(args) > 1 else 0
thousand_sep = args[2] if len(args) > 2 else ","
decimal_sep = args[3] if len(args) > 3 else "."
is_negative = value < 0
abs_value = abs(value)
formatted = f"{abs_value:,.{decimal_places}f}"
if decimal_places > 0:
int_part, dec_part = formatted.split(".")
else:
int_part = formatted
dec_part = None
int_part = int_part.replace(",", thousand_sep)
result = int_part if dec_part is None else int_part + decimal_sep + dec_part
if is_negative:
result = "-" + result
return result
class RuntimeToDuration(RuntimeFormulaFunction):
type = "to_duration"
args = [DurationBaserowRuntimeFormulaArgumentType()]
def execute(self, context: FormulaContext, args: FormulaArgs):
return args[0]
class RuntimeToDatetime(RuntimeFormulaFunction):
type = "to_datetime"
args = [
TextBaserowRuntimeFormulaArgumentType(),
DatetimeFormatBaserowRuntimeFormulaArgumentType(optional=True),
]
def validate_args(self, args, validation_context=None):
super().validate_args(args, validation_context)
value = args[0]
if len(args) == 2:
moment_format = args[1]
python_format = convert_date_format_moment_to_python(moment_format)
try:
ensure_datetime(value, date_format=python_format, strict=True)
except ValidationError:
raise BaserowFormulaSyntaxError(
f"'{value}' could not be parsed using format '{moment_format}'."
)
else:
try:
ensure_datetime(value)
except ValidationError:
raise BaserowFormulaSyntaxError(
f"'{value}' is not a valid ISO datetime string. "
f"Expected a format like '2024-01-15' or '2024-01-15T12:00:00'."
)
def execute(self, context: FormulaContext, args: FormulaArgs):
value = args[0]
if len(args) == 2:
python_format = convert_date_format_moment_to_python(args[1])
return ensure_datetime(value, date_format=python_format, strict=True)
else:
return ensure_datetime(value)
+51 -36
View File
@@ -1,5 +1,54 @@
import re
from baserow.core.duration import parse_duration_string as parse_duration_string
MOMENT_FORMAT_MAP = {
"YYYY": "%Y",
"YY": "%y",
"MMMM": "%B",
"MMM": "%b",
"MM": "%m",
"M": "%-m",
"DD": "%d",
"D": "%-d",
"dddd": "%A",
"ddd": "%a",
"HH": "%H",
"H": "%-H",
"hh": "%I",
"h": "%-I",
"mm": "%M",
"m": "%-M",
"ss": "%S",
"s": "%-S",
"A": "%p",
"a": "%p",
"SSS": "%f",
}
RE_SUPPORTED_MOMENT_TOKEN = re.compile(
"|".join(sorted(MOMENT_FORMAT_MAP.keys(), key=len, reverse=True))
)
# Extends the conversion regex with T, the ISO 8601 date-time separator, which
# is a valid literal in Moment.js format strings but has no mapped Python token.
RE_VALID_FORMAT = re.compile(
"|".join(sorted(MOMENT_FORMAT_MAP.keys(), key=len, reverse=True)) + "|T"
)
def is_valid_datetime_format(value: str) -> bool:
"""Return True if the string contains only supported Moment.js format tokens."""
if not isinstance(value, str):
return False
# An empty string is not a valid datetime format
if not value:
return False
stripped = RE_VALID_FORMAT.sub("", value)
return not re.search(r"[a-zA-Z]", stripped)
def convert_date_format_moment_to_python(moment_format: str) -> str:
"""
@@ -9,41 +58,7 @@ def convert_date_format_moment_to_python(moment_format: str) -> str:
:return: The Python datetime equivalent, e.g. '%Y-%m-%d'
"""
format_map = {
"YYYY": "%Y",
"YY": "%y",
"MMMM": "%B",
"MMM": "%b",
"MM": "%m",
"M": "%-m",
"DD": "%d",
"D": "%-d",
"dddd": "%A",
"ddd": "%a",
"HH": "%H",
"H": "%-H",
"hh": "%I",
"h": "%-I",
"mm": "%M",
"m": "%-M",
"ss": "%S",
"s": "%-S",
"A": "%p",
"a": "%p",
# Moment's SSS is milliseconds, whereas Python's %f is microseconds
"SSS": "%f",
}
# Sort longest tokens first so 'MMMM' matches before 'MM', etc.
tokens = sorted(format_map.keys(), key=len, reverse=True)
# Build a regex, e.g. re.compile("YYYY|YY")
pattern = re.compile("|".join(token for token in tokens))
def replace_token(match: re.Match) -> str:
"""Replace a matched Moment token with its Python equivalent."""
return MOMENT_FORMAT_MAP[match.group(0)]
token = match.group(0)
return format_map[token]
return pattern.sub(replace_token, moment_format)
return RE_SUPPORTED_MOMENT_TOKEN.sub(replace_token, moment_format)
+54 -3
View File
@@ -1,6 +1,6 @@
import json
import re
from datetime import date, datetime
from datetime import date, datetime, timedelta
from decimal import Decimal
from json.decoder import JSONDecodeError
from typing import Any, List, Optional, Union
@@ -13,6 +13,7 @@ from baserow.contrib.database.fields.constants import (
BASEROW_BOOLEAN_FIELD_TRUE_VALUES,
)
from baserow.core.datetime import FormattedDate, FormattedDateTime
from baserow.core.duration import parse_duration_string
def ensure_boolean(value: Any, strict=True) -> bool:
@@ -99,6 +100,9 @@ def ensure_integer(value: Any, allow_empty: bool = False) -> Optional[int]:
raise ValidationError("The value is required")
return None
if isinstance(value, timedelta):
return int(value.total_seconds())
try:
return int(value)
except (ValueError, TypeError) as exc:
@@ -125,6 +129,10 @@ def ensure_string(value: Any, allow_empty: bool = True) -> str:
if isinstance(value, bool):
# To match the frontend
return "true" if value else "false"
if isinstance(value, timedelta):
return str(int(value.total_seconds()))
if isinstance(value, list):
results = [ensure_string(item) for item in value if item]
return ",".join(results)
@@ -206,21 +214,64 @@ def ensure_date(value: Any) -> Optional[date]:
raise ValidationError("Value cannot be converted to a date.") from exc
def ensure_datetime(value: Any) -> Optional[datetime]:
def ensure_datetime(
value: Any, date_format: str = "%Y-%m-%d %H:%M", strict: bool = False
) -> Optional[datetime]:
"""
Ensures that the value is a datetime or can be converted to a datetime.
:param value: The value to ensure as a datetime.
:param date_format: The format to use to parse the datetime.
:param strict: If True, always validates the date format.
:return: The value as a datetime.
:raises ValidationError: If the value is not a valid datetime or convertible to a
datetime.
"""
if value is None:
return None
try:
return FormattedDateTime(value).datetime if value is not None else None
if strict and isinstance(value, str):
parsed = datetime.strptime(value, date_format)
return FormattedDateTime(parsed, date_format=date_format).datetime
return FormattedDateTime(value, date_format=date_format).datetime
except (ValueError, TypeError) as exc:
raise ValidationError("Value cannot be converted to a datetime.") from exc
def ensure_duration(value: Any) -> timedelta:
"""
Ensures that the value is a timedelta or is convertible to a timedelta.
:param value: The value to ensure as a timedelta.
:return: The value as a timedelta.
:raises ValidationError: If the value is not a valid timedelta or
convertible to a timedelta.
"""
if isinstance(value, timedelta):
return value
if isinstance(value, str):
result = parse_duration_string(value)
if result is not None:
return result
try:
return timedelta(seconds=ensure_integer(value))
except ValidationError:
pass
raise ValidationError(
f"'{value}' is not a valid duration. "
f"Expected format: e.g. '1 day', '2 hours'."
)
if isinstance(value, (int, float)):
return timedelta(seconds=value)
raise ValidationError("Value cannot be converted to a duration.")
def ensure_object(value: Any) -> Optional[dict]:
"""
Ensures that the value is a dict or can be converted to a dict.
@@ -1097,12 +1097,17 @@ def baserow_db_setup(django_db_setup, django_db_blocker):
with connection.cursor() as cursor:
cursor.execute(f"CREATE SEQUENCE IF NOT EXISTS {sequence_name};")
all_formula_functions = "\n".join(iter_formula_pgsql_functions())
with django_db_blocker.unblock():
with connection.cursor() as cursor:
cursor.execute(all_formula_functions)
with transaction.atomic():
with connection.cursor() as cursor:
# In CI, multiple pytest-xdist workers can run this session fixture
# against the same database. PostgreSQL function creation is not
# concurrency-safe when two workers create the same missing
# signature, even with CREATE OR REPLACE.
cursor.execute("SELECT pg_advisory_xact_lock(20240503, 1103);")
cursor.execute("\n".join(iter_formula_pgsql_functions()))
init_link_row_sequence()
init_link_row_sequence()
@pytest.fixture()
@@ -1,12 +1,17 @@
from datetime import date, datetime
from datetime import date, datetime, timedelta
import pytest
from baserow.core.formula.argument_types import (
DateTimeBaserowRuntimeFormulaArgumentType,
DatetimeFormatBaserowRuntimeFormulaArgumentType,
DecimalSeparatorBaserowRuntimeFormulaArgumentType,
DictBaserowRuntimeFormulaArgumentType,
DurationBaserowRuntimeFormulaArgumentType,
NumberBaserowRuntimeFormulaArgumentType,
TextBaserowRuntimeFormulaArgumentType,
ThousandSeparatorBaserowRuntimeFormulaArgumentType,
TimezoneBaserowRuntimeFormulaArgumentType,
)
@@ -175,3 +180,156 @@ def test_dict_test_method(value, expected):
)
def test_dict_parse_method(value, expected):
assert DictBaserowRuntimeFormulaArgumentType().parse(value) == expected
def test_base_argument_type_get_error_message_returns_none():
from baserow.core.formula.argument_types import BaserowRuntimeFormulaArgumentType
assert BaserowRuntimeFormulaArgumentType().get_error_message("foo") is None
def test_timezone_get_error_message_returns_human_readable_string():
arg_type = TimezoneBaserowRuntimeFormulaArgumentType()
message = arg_type.get_error_message("Europe/Foo")
assert "'Europe/Foo' is not a valid timezone" in message
@pytest.mark.parametrize(
"value,expected",
[
(",", True),
(".", True),
(" ", True),
("", True),
(";", False),
("|", False),
("_", False),
(1, False),
(None, False),
],
)
def test_thousand_separator_test_method(value, expected):
assert ThousandSeparatorBaserowRuntimeFormulaArgumentType().test(value) == expected
def test_thousand_separator_get_error_message_returns_human_readable_string():
arg_type = ThousandSeparatorBaserowRuntimeFormulaArgumentType()
message = arg_type.get_error_message(";")
assert "';' is not a valid thousand separator" in message
@pytest.mark.parametrize(
"value,expected",
[
(",", True),
(".", True),
(" ", False),
("", False),
(";", False),
(1, False),
(None, False),
],
)
def test_decimal_separator_test_method(value, expected):
assert DecimalSeparatorBaserowRuntimeFormulaArgumentType().test(value) == expected
def test_decimal_separator_get_error_message_returns_human_readable_string():
arg_type = DecimalSeparatorBaserowRuntimeFormulaArgumentType()
message = arg_type.get_error_message(";")
assert "';' is not a valid decimal separator" in message
@pytest.mark.parametrize(
"value,expected",
[
("1 day", True),
("2 days", True),
("3 weeks", True),
("4 hours", True),
("30 minutes", True),
("45 seconds", True),
("1 year", True),
("1 month", True),
(timedelta(days=1), True),
("1", True),
(1, True),
("1:30", True),
("1:30:00", True),
("11:12:13.14", True),
("1d", True),
("5h", True),
("1d 12h", True),
("1d 2h 3m", True),
("12.5", True),
("0 days", True),
("-1:30", True),
("foo", False),
("", False),
(None, False),
],
)
def test_duration_string_test_method(value, expected):
assert DurationBaserowRuntimeFormulaArgumentType().test(value) == expected
@pytest.mark.parametrize(
"value,expected",
[
("1 day", timedelta(days=1)),
("2 days", timedelta(days=2)),
("3 weeks", timedelta(weeks=3)),
("4 hours", timedelta(hours=4)),
("30 minutes", timedelta(minutes=30)),
("45 seconds", timedelta(seconds=45)),
("1 year", timedelta(days=365)),
("1 month", timedelta(days=30)),
("1:30", timedelta(seconds=90)),
("1:30:00", timedelta(hours=1, minutes=30)),
("11:12:13.14", timedelta(hours=11, minutes=12, seconds=13.14)),
("1d", timedelta(days=1)),
("5h", timedelta(hours=5)),
("1d 12h", timedelta(days=1, hours=12)),
("1d 2h 3m", timedelta(days=1, hours=2, minutes=3)),
("12.5", timedelta(seconds=12.5)),
("0 days", timedelta(0)),
("-1:30", timedelta(seconds=-90)),
],
)
def test_duration_parse_method(value, expected):
assert DurationBaserowRuntimeFormulaArgumentType().parse(value) == expected
def test_duration_string_get_error_message_returns_human_readable_string():
arg_type = DurationBaserowRuntimeFormulaArgumentType()
message = arg_type.get_error_message("not valid")
assert "is not a valid duration" in message
@pytest.mark.parametrize(
"value,expected",
[
("YYYY-MM-DD", True),
("DD/MM/YYYY", True),
("YYYY-MM-DD HH:mm:ss", True),
("DD/MM/YYYY HH:mm:ss", True),
("YYYY-MM-DDTHH:mm:ss", True),
("HH:mm:ss", True),
("SSS", True),
("SS", False),
("S", False),
("Z", False),
("YYYY-MM-DD HH:mm:SS", False),
("", False),
(123, False),
(None, False),
],
)
def test_datetime_format_test_method(value, expected):
assert DatetimeFormatBaserowRuntimeFormulaArgumentType().test(value) == expected
def test_datetime_format_get_error_message_returns_human_readable_string():
arg_type = DatetimeFormatBaserowRuntimeFormulaArgumentType()
message = arg_type.get_error_message("SS")
assert "is not a valid datetime format" in message
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,16 @@
from datetime import date, datetime
from datetime import date, datetime, timedelta
from django.core.exceptions import ValidationError
import pytest
from baserow.core.formula.validator import ensure_date, ensure_datetime
from baserow.core.formula.validator import (
ensure_date,
ensure_datetime,
ensure_duration,
ensure_integer,
ensure_string,
)
def test_ensure_date():
@@ -24,8 +30,136 @@ def test_ensure_datetime():
assert ensure_datetime("2024-12-17 12:00") == datetime(2024, 12, 17, 12, 0, 0)
def test_ensure_datetime_with_date_format():
assert ensure_datetime(
"05/05/2026 14:30", date_format="%d/%m/%Y %H:%M"
) == datetime(2026, 5, 5, 14, 30)
assert ensure_datetime("2026-05-05", date_format="%Y-%m-%d") == datetime(2026, 5, 5)
def test_ensure_datetime_with_date_format_iso_takes_priority():
assert ensure_datetime("2026-05-05T12:00:00", date_format="%d/%m/%Y") == datetime(
2026, 5, 5, 12, 0, 0
)
def test_ensure_datetime_strict_rejects_iso_when_format_differs():
with pytest.raises(ValidationError):
ensure_datetime("2026-05-06", date_format="%d/%m/%Y", strict=True)
def test_ensure_datetime_strict_accepts_matching_format():
assert ensure_datetime(
"06/05/2026", date_format="%d/%m/%Y", strict=True
) == datetime(2026, 5, 6)
def test_ensure_datetime_strict_none_value():
assert ensure_datetime(None, date_format="%d/%m/%Y", strict=True) is None
def test_ensure_datetime_with_date_format_invalid_value():
with pytest.raises(ValidationError) as exc:
ensure_datetime("foo", date_format="%d/%m/%Y %H:%M")
assert exc.value.args[0] == "Value cannot be converted to a datetime."
def test_ensure_datetime_with_date_format_none_value():
assert ensure_datetime(None, date_format="%d/%m/%Y") is None
@pytest.mark.parametrize("value", [1, 0.1, [], {}, False, "invalid"])
def test_ensure_datetime_throws_exception_for_invalid_value(value):
with pytest.raises(ValidationError) as exc:
ensure_datetime(value)
assert exc.value.args[0] == "Value cannot be converted to a datetime."
@pytest.mark.parametrize(
"value,expected",
[
(timedelta(days=2), timedelta(days=2)),
(timedelta(hours=3, minutes=30), timedelta(hours=3, minutes=30)),
(timedelta(0), timedelta(0)),
("1 day", timedelta(days=1)),
("2 days", timedelta(days=2)),
("3 hours", timedelta(hours=3)),
("30 minutes", timedelta(minutes=30)),
("45 seconds", timedelta(seconds=45)),
("1 week", timedelta(weeks=1)),
("1 year", timedelta(days=365)),
("1 month", timedelta(days=30)),
("86400", timedelta(days=1)),
("3600", timedelta(hours=1)),
("60", timedelta(seconds=60)),
("0", timedelta(0)),
("1:30", timedelta(seconds=90)),
("0:01:30", timedelta(minutes=1, seconds=30)),
("1:30:00", timedelta(hours=1, minutes=30)),
("11:12:13.14", timedelta(hours=11, minutes=12, seconds=13.14)),
("1d", timedelta(days=1)),
("5h", timedelta(hours=5)),
("1d 12h", timedelta(days=1, hours=12)),
("1d 2h 3m", timedelta(days=1, hours=2, minutes=3)),
("1d 11:12:13", timedelta(days=1, hours=11, minutes=12, seconds=13)),
("12.5", timedelta(seconds=12.5)),
("0 days", timedelta(0)),
("0 hours", timedelta(0)),
("-1:30", timedelta(seconds=-90)),
("-1d 12h", timedelta(days=-1, hours=-12)),
(60, timedelta(seconds=60)),
(3600, timedelta(hours=1)),
(86400, timedelta(days=1)),
(0, timedelta(0)),
(1.5, timedelta(seconds=1.5)),
],
)
def test_ensure_duration_passthrough(value, expected):
assert ensure_duration(value) == expected
@pytest.mark.parametrize("value", ["foo", ""])
def test_ensure_duration_invalid_string(value):
with pytest.raises(ValidationError) as e:
ensure_duration(value)
assert f"'{value}' is not a valid duration." in str(e)
@pytest.mark.parametrize("value", [None, [], {}])
def test_ensure_duration_invalid_type(value):
with pytest.raises(ValidationError) as e:
ensure_duration(value)
assert e.value.args[0] == "Value cannot be converted to a duration."
@pytest.mark.parametrize(
"value,expected",
[
(timedelta(0), "0"),
(timedelta(days=1), "86400"),
(timedelta(days=2), "172800"),
(timedelta(hours=1), "3600"),
(timedelta(days=1, hours=2, minutes=3, seconds=4), "93784"),
(timedelta(seconds=90), "90"),
(timedelta(seconds=-86400), "-86400"),
],
)
def test_ensure_string_with_timedelta(value, expected):
assert ensure_string(value) == expected
@pytest.mark.parametrize(
"value,expected",
[
(timedelta(0), 0),
(timedelta(days=1), 86400),
(timedelta(hours=1), 3600),
(timedelta(minutes=30), 1800),
(timedelta(seconds=45), 45),
(timedelta(days=2, hours=3), 183600),
],
)
def test_ensure_integer_with_timedelta(value, expected):
assert ensure_integer(value) == expected
@@ -0,0 +1,9 @@
{
"type": "feature",
"message": "Added new runtime formulas: number_format(), abs(), null(), to_duration(), and to_datetime().",
"issue_origin": "github",
"issue_number": 4974,
"domain": "core",
"bullet_points": [],
"created_at": "2026-04-28"
}
+13
View File
@@ -666,6 +666,7 @@
"lowerDescription": "Converts the argument to lower case.",
"capitalizeDescription": "Capitalizes the argument's first letter.",
"roundDescription": "Rounds the first argument to the number of decimal places specified by the second argument.",
"absDescription": "Returns the absolute value of the argument.",
"evenDescription": "Return true if the argument is even, false otherwise.",
"oddDescription": "Return true if the argument is odd, false otherwise.",
"dateTimeDescription": "Formats the date time argument using the format and timezone arguments. If the timezone is left blank, it will default to the browser's timezone.",
@@ -696,6 +697,10 @@
"avgDescription": "Averages the numbers inside the argument.",
"atDescription": "Returns the item in the first argument at the index specified by the second argument.",
"toArrayDescription": "Converts a comma-delimited string into an array.",
"nullDescription": "Returns null, which can be used as a value or for comparison",
"numberFormatDescription": "Formats a number as a string with configurable decimal places, thousand separator, and decimal separator.",
"toDatetimeDescription": "Parses a string into a datetime object. An optional second argument specifies the format (e.g. 'DD/MM/YYYY'). If omitted, ISO 8601 format is assumed.",
"toDurationDescription": "Returns the duration corresponding to the provided argument.",
"formulaTypeFormula": "Function | Functions",
"formulaTypeOperator": "Operator | Operators",
"formulaTypeData": "Data",
@@ -706,6 +711,14 @@
"categoryDate": "Date",
"categoryCondition": "Condition"
},
"runtimeFormulaTypeErrors": {
"invalidTimezone": "'{value}' is not a valid timezone. Use a valid IANA timezone (e.g. 'Europe/Amsterdam').",
"invalidThousandSeparator": "'{value}' is not a valid thousand separator. Valid options are: ',', '.', ' ', or '' (empty string).",
"invalidDecimalSeparator": "'{value}' is not a valid decimal separator. Valid options are: ',' or '.'.",
"sameSeparators": "The thousand separator and decimal separator cannot be the same.",
"invalidDuration": "'{value}' is not a valid duration. Valid options are: '1 day', '2 hours', etc.",
"invalidDatetimeFormat": "'{value}' is not a valid datetime format. Valid options are: 'YYYY-MM-DD', 'DD/MM/YYYY HH:mm:ss', etc."
},
"runtimeGetErrors": {
"invalidPath": "The 'get' argument '{path}' must be a dot-delimited path (e.g., 'provider.property').",
"missingProvider": "The 'get' argument '{path}' is missing its formula provider prefix.",
@@ -525,6 +525,9 @@ export default {
title: this.$t('formulaInputField.invalidFormulaTitle'),
message: validationResult.errors[0],
}
this.$nextTick(() => {
this.editor.commands.repositionContext()
})
} else {
this.$emit('input', formula)
}
+13
View File
@@ -84,6 +84,7 @@ import {
RuntimeLower,
RuntimeCapitalize,
RuntimeRound,
RuntimeAbs,
RuntimeIsEven,
RuntimeIsOdd,
RuntimeDateTimeFormat,
@@ -94,6 +95,9 @@ import {
RuntimeMinute,
RuntimeSecond,
RuntimeNow,
RuntimeNull,
RuntimeNumberFormat,
RuntimeToDuration,
RuntimeToday,
RuntimeGetProperty,
RuntimeRandomInt,
@@ -115,6 +119,7 @@ import {
RuntimeAvg,
RuntimeAt,
RuntimeToArray,
RuntimeToDatetime,
} from '@baserow/modules/core/runtimeFormulaTypes'
import {
@@ -257,6 +262,7 @@ export default defineNuxtPlugin({
registry.register('runtimeFormulaFunction', new RuntimeLower(context))
registry.register('runtimeFormulaFunction', new RuntimeCapitalize(context))
registry.register('runtimeFormulaFunction', new RuntimeRound(context))
registry.register('runtimeFormulaFunction', new RuntimeAbs(context))
registry.register('runtimeFormulaFunction', new RuntimeIsEven(context))
registry.register('runtimeFormulaFunction', new RuntimeIsOdd(context))
registry.register(
@@ -294,6 +300,13 @@ export default defineNuxtPlugin({
registry.register('runtimeFormulaFunction', new RuntimeAvg(context))
registry.register('runtimeFormulaFunction', new RuntimeAt(context))
registry.register('runtimeFormulaFunction', new RuntimeToArray(context))
registry.register('runtimeFormulaFunction', new RuntimeNull(context))
registry.register(
'runtimeFormulaFunction',
new RuntimeNumberFormat(context)
)
registry.register('runtimeFormulaFunction', new RuntimeToDuration(context))
registry.register('runtimeFormulaFunction', new RuntimeToDatetime(context))
registry.register('errorPage', new DefaultErrorPageType(context))
const fns = [
@@ -5,8 +5,18 @@ import {
ensureObject,
ensureBoolean,
ensureArray,
ensureDuration,
} from '@baserow/modules/core/utils/validator'
import moment from '@baserow/modules/core/moment'
import {
Timedelta,
isValidDatetimeFormat,
parseDurationString,
} from '@baserow/modules/core/utils/date'
export { Timedelta, parseDurationString }
const VALID_THOUSAND_SEPARATORS = new Set([',', '.', ' ', ''])
const VALID_DECIMAL_SEPARATORS = new Set([',', '.'])
export class BaserowRuntimeFormulaArgumentType {
constructor({ optional = false } = {}) {
@@ -34,6 +44,17 @@ export class BaserowRuntimeFormulaArgumentType {
parse(value) {
return value
}
/**
* This function returns a specific human-friendly error message if the
* value for the type is invalid. Defaults to returning null.
* @param value - The value that is incorrect.
* @param i18n - The i18n instance.
* @returns {string|null} - The human-friendly error message.
*/
getErrorMessage(value, i18n) {
return null
}
}
export class NumberBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
@@ -177,6 +198,10 @@ export class TimezoneBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFor
parse(value) {
return ensureString(value)
}
getErrorMessage(value, i18n) {
return i18n.t('runtimeFormulaTypeErrors.invalidTimezone', { value })
}
}
export class AnyBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
@@ -188,3 +213,78 @@ export class AnyBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaA
return value
}
}
export class ThousandSeparatorBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
test(value) {
if (typeof value !== 'string') return false
return VALID_THOUSAND_SEPARATORS.has(value)
}
parse(value) {
return ensureString(value)
}
getErrorMessage(value, i18n) {
return i18n.t('runtimeFormulaTypeErrors.invalidThousandSeparator', {
value,
})
}
}
export class DecimalSeparatorBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
test(value) {
if (typeof value !== 'string') return false
return VALID_DECIMAL_SEPARATORS.has(value)
}
parse(value) {
return ensureString(value)
}
getErrorMessage(value, i18n) {
return i18n.t('runtimeFormulaTypeErrors.invalidDecimalSeparator', { value })
}
}
export class TimedeltaBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
test(value) {
return value instanceof Timedelta
}
parse(value) {
return value
}
}
export class DurationBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
test(value) {
try {
ensureDuration(value)
return true
} catch (e) {
return false
}
}
parse(value) {
return ensureDuration(value)
}
getErrorMessage(value, i18n) {
return i18n.t('runtimeFormulaTypeErrors.invalidDuration', { value })
}
}
export class DatetimeFormatBaserowRuntimeFormulaArgumentType extends BaserowRuntimeFormulaArgumentType {
test(value) {
return isValidDatetimeFormat(value)
}
parse(value) {
return ensureString(value)
}
getErrorMessage(value, i18n) {
return i18n.t('runtimeFormulaTypeErrors.invalidDatetimeFormat', { value })
}
}
@@ -9,6 +9,12 @@ import {
AnyBaserowRuntimeFormulaArgumentType,
ArrayBaserowRuntimeFormulaArgumentType,
ArrayOfNumbersBaserowRuntimeFormulaArgumentType,
ThousandSeparatorBaserowRuntimeFormulaArgumentType,
DecimalSeparatorBaserowRuntimeFormulaArgumentType,
TimedeltaBaserowRuntimeFormulaArgumentType,
DatetimeFormatBaserowRuntimeFormulaArgumentType,
DurationBaserowRuntimeFormulaArgumentType,
Timedelta,
} from '@baserow/modules/core/runtimeFormulaArgumentTypes'
import {
InvalidFormulaArgument,
@@ -20,6 +26,7 @@ import { avg, sum } from '@baserow/modules/core/utils/number'
import {
ensureString,
ensureArray,
ensureDateTime,
} from '@baserow/modules/core/utils/validator'
import { Node, VueNodeViewRenderer } from '@tiptap/vue-3'
import GetFormulaComponent from '@baserow/modules/core/components/formula/GetFormulaComponent'
@@ -86,8 +93,18 @@ export class RuntimeFormulaFunction extends Registerable {
* @throws InvalidFormulaArgumentType - If any of the arguments have a wrong type
*/
validateArgs(args, { ctx = null, validationContext = {} } = {}) {
const invalidArg = this.validateTypeOfArgs(args)
if (invalidArg) {
const results = this.validateTypeOfArgs(args)
if (results.length > 0) {
const [index, invalidArg] = results[0]
if (this.args) {
const message = this.args[index].getErrorMessage(
invalidArg,
this.app.$i18n
)
if (message) {
throw new InvalidFormulaArgument(this.getType(), message)
}
}
throw new InvalidFormulaArgumentType(this, invalidArg)
}
}
@@ -116,14 +133,19 @@ export class RuntimeFormulaFunction extends Registerable {
* If a type is incorrect it will return that arg.
*
* @param args - The args that are being checked
* @returns {any} - The arg that has the wrong type, if any
* @returns {any} - An array of [index, arg] that has the wrong type.
*/
validateTypeOfArgs(args) {
if (this.args === null) {
return null
return []
}
return args.find((arg, index) => !this.args[index].test(arg))
return args.reduce((errors, arg, index) => {
if (!this.args[index].test(arg)) {
errors.push([index, arg])
}
return errors
}, [])
}
/**
@@ -451,8 +473,36 @@ export class RuntimeAdd extends RuntimeFormulaFunction {
]
}
validateTypeOfArgs(args) {
if (args.length === 2) {
const [a, b] = args
const num = new NumberBaserowRuntimeFormulaArgumentType()
const dt = new DateTimeBaserowRuntimeFormulaArgumentType()
const td = new TimedeltaBaserowRuntimeFormulaArgumentType()
if (num.test(a) && num.test(b)) return []
if ((dt.test(a) && td.test(b)) || (td.test(a) && dt.test(b))) return []
if (!(num.test(a) || dt.test(a) || td.test(a))) return [[0, a]]
return [[1, b]]
}
return super.validateTypeOfArgs(args)
}
parseArgs(args) {
if (args.some((a) => a instanceof Timedelta || a instanceof Date)) {
return args
}
return super.parseArgs(args)
}
execute(context, args) {
return args[0] + args[1]
const [a, b] = args
if (a instanceof Date && b instanceof Timedelta) {
return new Date(a.getTime() + b.ms)
}
if (a instanceof Timedelta && b instanceof Date) {
return new Date(b.getTime() + a.ms)
}
return a + b
}
getDescription() {
@@ -498,8 +548,33 @@ export class RuntimeMinus extends RuntimeFormulaFunction {
]
}
validateTypeOfArgs(args) {
if (args.length === 2) {
const [a, b] = args
const num = new NumberBaserowRuntimeFormulaArgumentType()
const dt = new DateTimeBaserowRuntimeFormulaArgumentType()
const td = new TimedeltaBaserowRuntimeFormulaArgumentType()
if (num.test(a) && num.test(b)) return []
if (dt.test(a) && td.test(b)) return []
if (!(num.test(a) || dt.test(a))) return [[0, a]]
return [[1, b]]
}
return super.validateTypeOfArgs(args)
}
parseArgs(args) {
if (args.some((a) => a instanceof Timedelta || a instanceof Date)) {
return args
}
return super.parseArgs(args)
}
execute(context, args) {
return args[0] - args[1]
const [a, b] = args
if (a instanceof Date && b instanceof Timedelta) {
return new Date(a.getTime() - b.ms)
}
return a - b
}
getDescription() {
@@ -1153,6 +1228,46 @@ export class RuntimeRound extends RuntimeFormulaFunction {
}
}
export class RuntimeAbs extends RuntimeFormulaFunction {
static getType() {
return 'abs'
}
static getFormulaType() {
return FORMULA_TYPE.FUNCTION
}
static getCategoryType() {
return FORMULA_CATEGORY.NUMBER
}
get args() {
return [new NumberBaserowRuntimeFormulaArgumentType()]
}
execute(context, [n]) {
return Math.abs(n)
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.absDescription')
}
getExamples() {
return [
{
formula: 'abs(-5)',
result: '5',
},
{
formula: 'abs(3.14)',
result: '3.14',
},
]
}
}
export class RuntimeIsEven extends RuntimeFormulaFunction {
static getType() {
return 'is_even'
@@ -1249,7 +1364,7 @@ export class RuntimeDateTimeFormat extends RuntimeFormulaFunction {
get args() {
return [
new DateTimeBaserowRuntimeFormulaArgumentType(),
new TextBaserowRuntimeFormulaArgumentType(),
new DatetimeFormatBaserowRuntimeFormulaArgumentType(),
new TimezoneBaserowRuntimeFormulaArgumentType({ optional: true }),
]
}
@@ -2490,3 +2605,248 @@ export class RuntimeToArray extends RuntimeFormulaFunction {
]
}
}
export class RuntimeNull extends RuntimeFormulaFunction {
static getType() {
return 'null'
}
static getFormulaType() {
return FORMULA_TYPE.FUNCTION
}
static getCategoryType() {
return FORMULA_CATEGORY.TEXT
}
get args() {
return []
}
execute(context, args) {
return null
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.nullDescription')
}
getExamples() {
return [
{
formula: 'null()',
result: 'null',
},
]
}
}
export class RuntimeNumberFormat extends RuntimeFormulaFunction {
static getType() {
return 'number_format'
}
static getFormulaType() {
return FORMULA_TYPE.FUNCTION
}
static getCategoryType() {
return FORMULA_CATEGORY.NUMBER
}
get args() {
return [
new NumberBaserowRuntimeFormulaArgumentType(),
new NumberBaserowRuntimeFormulaArgumentType({
optional: true,
castToInt: true,
}),
new ThousandSeparatorBaserowRuntimeFormulaArgumentType({
optional: true,
}),
new DecimalSeparatorBaserowRuntimeFormulaArgumentType({ optional: true }),
]
}
validateArgs(args, { ctx = null, validationContext = {} } = {}) {
super.validateArgs(args, { ctx, validationContext })
if (args.length >= 4 && args[2] === args[3]) {
const { $i18n } = this.app
throw new InvalidFormulaArgument(
this.getType(),
$i18n.t('runtimeFormulaTypeErrors.sameSeparators')
)
}
}
execute(context, args) {
const value = args[0]
const decimalPlaces = args.length > 1 ? Math.max(Math.trunc(args[1]), 0) : 0
const thousandSep = args.length > 2 ? args[2] : ','
const decimalSep = args.length > 3 ? args[3] : '.'
const isNegative = value < 0
const absValue = Math.abs(value)
const formatted = absValue.toFixed(decimalPlaces)
let intPart, decPart
if (decimalPlaces > 0) {
;[intPart, decPart] = formatted.split('.')
} else {
intPart = formatted
decPart = undefined
}
intPart = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep)
let result =
decPart !== undefined ? intPart + decimalSep + decPart : intPart
if (isNegative) result = '-' + result
return result
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.numberFormatDescription')
}
getExamples() {
return [
{
formula: "number_format(1000000, 2, ',', '.')",
result: "'1,000,000.00'",
},
{
formula: 'number_format(1000000)',
result: "'1,000,000'",
},
{
formula: 'number_format(1000000, 2)',
result: "'1,000,000.00'",
},
]
}
}
export class RuntimeToDatetime extends RuntimeFormulaFunction {
static getType() {
return 'to_datetime'
}
static getFormulaType() {
return FORMULA_TYPE.FUNCTION
}
static getCategoryType() {
return FORMULA_CATEGORY.DATE
}
get args() {
return [
new TextBaserowRuntimeFormulaArgumentType(),
new DatetimeFormatBaserowRuntimeFormulaArgumentType({ optional: true }),
]
}
validateArgs(args, { ctx = null, validationContext = {} } = {}) {
super.validateArgs(args, { ctx, validationContext })
const value = args[0]
if (args.length === 2) {
const fmt = args[1]
try {
ensureDateTime(value, { allowEmpty: false, format: fmt })
} catch {
throw new InvalidFormulaArgument(
this.getType(),
`'${value}' could not be parsed using format '${fmt}'.`
)
}
} else {
// "2026" is a valid string argument to moment, but the backend
// expects the full datetime string. This ensures that we don't
// allow "2026" or "2026-05" to be accepted as valid.
const hasMinDatePart = /^\d{4}-\d{2}-\d{2}/.test(value)
if (!hasMinDatePart) {
throw new InvalidFormulaArgument(
this.getType(),
`'${value}' is not a valid datetime string.`
)
}
try {
ensureDateTime(value, { allowEmpty: false })
} catch {
throw new InvalidFormulaArgument(
this.getType(),
`'${value}' is not a valid datetime string.`
)
}
}
}
execute(context, args) {
if (args.length === 2) {
return ensureDateTime(args[0], { allowEmpty: false, format: args[1] })
}
return ensureDateTime(args[0], { allowEmpty: false })
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.toDatetimeDescription')
}
getExamples() {
return [
{
formula: "to_datetime('2024-01-15')",
result: '2024-01-15T00:00:00',
},
{
formula: "to_datetime('15/01/2024', 'DD/MM/YYYY')",
result: '2024-01-15T00:00:00',
},
]
}
}
export class RuntimeToDuration extends RuntimeFormulaFunction {
static getType() {
return 'to_duration'
}
static getFormulaType() {
return FORMULA_TYPE.FUNCTION
}
static getCategoryType() {
return FORMULA_CATEGORY.DATE
}
get args() {
return [new DurationBaserowRuntimeFormulaArgumentType()]
}
execute(context, args) {
return args[0]
}
getDescription() {
const { $i18n: i18n } = this.app
return i18n.t('runtimeFormulaTypes.toDurationDescription')
}
getExamples() {
return [
{
formula: "to_duration('1 day')",
result: '86400 seconds',
},
{
formula: "now() + to_duration('1 day')",
result: "'2025-10-17 11:05:38'",
},
]
}
}
+14
View File
@@ -1,4 +1,18 @@
import moment from '@baserow/modules/core/moment'
export {
Timedelta,
parseDurationString,
} from '@baserow/modules/core/utils/duration'
const SUPPORTED_MOMENT_TOKEN_RE =
/YYYY|MMMM|dddd|MMM|ddd|SSS|YY|MM|DD|HH|hh|mm|ss|[MDHhmsAaT]/g
export function isValidDatetimeFormat(value) {
if (typeof value !== 'string') return false
// An empty string is not a valid datetime format
if (value === '') return false
return !/[a-zA-Z]/.test(value.replace(SUPPORTED_MOMENT_TOKEN_RE, ''))
}
export const getHumanPeriodAgoCount = (dateTime) => {
const now = moment()
+405
View File
@@ -0,0 +1,405 @@
import _ from 'lodash'
const MOST_ACCURATE_DURATION_FORMAT = 'h:mm:ss.sss'
// taken from backend timedelta.max.total_seconds() == 1_000_000_000 days
export const MAX_BACKEND_DURATION_VALUE_NUMBER_OF_SECS = 86400000000000
export const MIN_BACKEND_DURATION_VALUE_NUMBER_OF_SECS =
MAX_BACKEND_DURATION_VALUE_NUMBER_OF_SECS * -1
export const DEFAULT_DURATION_FORMAT = 'h:mm'
const D_H = 'd h'
const D_H_M = 'd h:mm'
const D_H_M_S = 'd h:mm:ss'
const H_M = 'h:mm'
const H_M_S = 'h:mm:ss'
const H_M_S_S = 'h:mm:ss.s'
const H_M_S_SS = 'h:mm:ss.ss'
const H_M_S_SSS = 'h:mm:ss.sss'
const D_H_M_NO_COLONS = 'd h mm' // 1d2h3m
const D_H_M_S_NO_COLONS = 'd h mm ss' // 1d2h3m4s
const SECS_IN_DAY = 86400
const SECS_IN_HOUR = 3600
const SECS_IN_MIN = 60
export class Timedelta {
constructor(ms) {
this.ms = ms
}
}
const DURATION_PATTERNS = [
{ regex: /^(\d+)\s+years?$/i, unit: 'days', factor: 365 },
{ regex: /^(\d+)\s+months?$/i, unit: 'days', factor: 30 },
{ regex: /^(\d+)\s+weeks?$/i, unit: 'days', factor: 7 },
{ regex: /^(\d+)\s+days?$/i, unit: 'days', factor: 1 },
{ regex: /^(\d+)\s+hours?$/i, unit: 'hours', factor: 1 },
{ regex: /^(\d+)\s+minutes?$/i, unit: 'minutes', factor: 1 },
{ regex: /^(\d+)\s+seconds?$/i, unit: 'seconds', factor: 1 },
]
const UNIT_TO_MS = {
days: SECS_IN_DAY * 1000,
hours: SECS_IN_HOUR * 1000,
minutes: SECS_IN_MIN * 1000,
seconds: 1000,
}
function totalSecs({ secs = null, mins = null, hours = null, days = null }) {
return (
parseInt(days || 0) * SECS_IN_DAY +
parseInt(hours || 0) * SECS_IN_HOUR +
parseInt(mins || 0) * SECS_IN_MIN +
parseFloat(secs || 0.0)
)
}
/** DURATION_REGEXPS
*
* A map of regexps to parse input values. Input values are normalized into seconds.
*
* Input value semantics may change depending on duration format selection. In
* some cases the same values may mean hours or minutes, depending on a format context.
* This mapping helps managing this aspect.
*
* @type {Map<RegExp, {string: (function({int, int, int, int}): int)}>}
*/
const DURATION_REGEXPS = new Map([
[
// 1d 10h 20m 30s
/^((?<days>\d+)(?:d\s*))?((?<hours>\d+)(?:h\s*))?((?<mins>\d+)(?:m\s*))?((?<secs>\d+|\d+\.\d+)(?:s\s*))?$/,
{
default: ({ days, hours, mins, secs }) =>
totalSecs({ days, hours, mins, secs }),
},
],
[
// 1d 12:13:14.123
/^(\d+)(?:d\s*|\s+)(\d+):(\d+):(\d+|\d+\.\d+)$/,
{
default: (days, hours, mins, secs) =>
totalSecs({ days, hours, mins, secs }),
},
],
[
// 1:11:12.134
/^(\d+):(\d+):(\d+|\d+\.\d+)$/,
{
default: (hours, mins, secs) => totalSecs({ hours, mins, secs }),
},
],
[
// 1d 12:13
/^(\d+)(?:d\s*|\s+)(\d+):(\d+)$/,
{
[D_H]: (days, hours, mins) => totalSecs({ days, hours, mins }),
[D_H_M]: (days, hours, mins) => totalSecs({ days, hours, mins }),
[D_H_M_NO_COLONS]: (days, hours, mins) =>
totalSecs({ days, hours, mins }),
default: (days, mins, secs) => totalSecs({ days, mins, secs }),
},
],
[
// 1d 11:12 -> 1 00:11:12
/^(\d+)(?:d\s*|\s+)(\d+):(\d+\.\d+)$/,
{ default: (days, mins, secs) => totalSecs({ days, mins, secs }) },
],
[
// 123h -> 5d 3h
/^(\d+)h$/,
{ default: (hours) => totalSecs({ hours }) },
],
[
// 1d 12h
/^(\d+)(?:d\s*|\s+)(\d+)h$/,
{
default: (days, hours) => totalSecs({ days, hours }),
},
],
[
// 123d
/^(\d+)d$/,
{ default: (days) => totalSecs({ days }) },
],
[
// 1d 12
/^(\d+)(?:d\s*|\s+)(\d+)$/,
{
[D_H]: (days, hours) => totalSecs({ days, hours }),
[D_H_M]: (days, mins) => totalSecs({ days, mins }),
[H_M]: (days, mins) => totalSecs({ days, mins }),
[D_H_M_NO_COLONS]: (days, mins) => totalSecs({ days, mins }),
default: (days, secs) => totalSecs({ days, secs }),
},
],
[
// 1d 123.234
/^(\d+)(?:d\s*|\s+)(\d+\.\d+)$/,
{ default: (days, secs) => totalSecs({ days, secs }) },
],
[
// 11:12
/^(\d+):(\d+)$/,
{
[D_H]: (hours, mins) => totalSecs({ hours, mins }),
[D_H_M]: (hours, mins) => totalSecs({ hours, mins }),
[H_M]: (hours, mins) => totalSecs({ hours, mins }),
[D_H_M_NO_COLONS]: (hours, mins) => totalSecs({ hours, mins }),
default: (mins, secs) => totalSecs({ mins, secs }),
},
],
[
// 123:12.123 -> 2h3m12s
/^(\d+):(\d+\.\d+)$/,
{ default: (mins, secs) => totalSecs({ mins, secs }) },
],
[
// 123.2134
/^(\d+\.\d+)$/,
{ default: (secs) => totalSecs({ secs }) },
],
[
// 123
/^(\d+)$/,
{
[D_H]: (hours) => totalSecs({ hours }),
[D_H_M]: (mins) => totalSecs({ mins }),
[H_M]: (mins) => totalSecs({ mins }),
[D_H_M_NO_COLONS]: (mins) => totalSecs({ mins }),
default: (secs) => totalSecs({ secs }),
},
],
])
// Map guarantees the order of the entries
export const DURATION_FORMATS = new Map([
[
H_M,
{
description: 'h:mm (1:23)',
example: '1:23',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}`
},
round: (value) => Math.round(value / 60) * 60,
},
],
[
H_M_S,
{
description: 'h:mm:ss (1:23:40)',
example: '1:23:40',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(0)
.padStart(2, '0')}`
},
round: (value) => Math.round(value),
},
],
[
H_M_S_S,
{
description: 'h:mm:ss.s (1:23:40.0)',
example: '1:23:40.0',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(1)
.padStart(4, '0')}`
},
round: (value) => Math.round(value * 10) / 10,
},
],
[
H_M_S_SS,
{
description: 'h:mm:ss.ss (1:23:40.00)',
example: '1:23:40.00',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(2)
.padStart(5, '0')}`
},
round: (value) => Math.round(value * 100) / 100,
},
],
[
H_M_S_SSS,
{
description: 'h:mm:ss.sss (1:23:40.000)',
example: '1:23:40.000',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(3)
.padStart(6, '0')}`
},
round: (value) => Math.round(value * 1000) / 1000,
},
],
[
D_H,
{
description: 'd h (1d 2h)',
example: '1d 2h',
toString(d, h, m, s) {
return `${d}d ${h}h`
},
round: (value) => Math.round(value / 3600) * 3600,
},
],
[
D_H_M,
{
description: 'd h:mm (1d 2:34)',
example: '1d 2:34',
toString(d, h, m, s) {
return `${d}d ${h}:${m.toString().padStart(2, '0')}`
},
round: (value) => Math.round(value / 60) * 60,
},
],
[
D_H_M_S,
{
description: 'd h:mm:ss (1d 2:34:56)',
example: '1d 2:34:56',
toString(d, h, m, s) {
return `${d}d ${h}:${m.toString().padStart(2, '0')}:${s
.toFixed(0)
.padStart(2, '0')}`
},
round: (value) => Math.round(value),
},
],
[
D_H_M_NO_COLONS,
{
description: 'd h m (1d 2h 3m)',
example: '1d 2h 3m',
toString(d, h, m, s) {
return `${d}d ${h}h ${m.toString().padStart(2, '0')}m`
},
// round to a minute
round: (value) => Math.round(value / 60) * 60,
},
],
[
D_H_M_S_NO_COLONS,
{
description: 'd h m s (1d 2h 3m 4s)',
example: '1d 2h 3m 4s',
toString(d, h, m, s) {
return `${d}d ${h}h ${m.toString().padStart(2, '0')}m ${s
.toFixed(0)
.padStart(2, '0')}s`
},
round: (value) => Math.round(value),
},
],
])
export const roundDurationValueToFormat = (value, format) => {
if (value === null) {
return null
}
const durationFormatOptions = DURATION_FORMATS.get(format)
if (!durationFormatOptions) {
throw new Error(`Unknown duration format ${format}`)
}
return durationFormatOptions.round(value)
}
/**
* It tries to parse the input value using the given format.
* If the input value does not match the format, it tries to parse it using
* the most accurate format if strict is false, otherwise it throws an error.
*/
export const parseDurationValue = (
inputValue,
format = MOST_ACCURATE_DURATION_FORMAT
) => {
if (inputValue === null || inputValue === undefined || inputValue === '') {
return null
}
// If the value is a number, we assume it's already in seconds (i.e. from the backend).
if (Number.isFinite(inputValue)) {
return inputValue
}
let multiplier = 1
if (inputValue.startsWith('-')) {
multiplier = -1
inputValue = inputValue.substring(1)
}
for (const [fmtRegExp, formatFuncs] of DURATION_REGEXPS) {
let matchedGroups = {}
// exec may be null, which will throw an exception
try {
matchedGroups = fmtRegExp.exec(inputValue).groups
} catch (err) {
/* empty */
}
const match = inputValue.match(fmtRegExp)
const formatFunc = formatFuncs[format] || formatFuncs.default
// the regex is using named groups, so the handler function should too
if (!_.isEmpty(matchedGroups)) {
return formatFunc(matchedGroups) * multiplier
}
// no named groups, so we use positional args
if (match) {
return formatFunc(...match.slice(1)) * multiplier
}
}
return null
}
export const parseDurationString = (value) => {
if (
value === null ||
value === undefined ||
value === '' ||
(typeof value !== 'string' && !Number.isFinite(value))
) {
return null
}
const seconds = parseDurationValue(value, MOST_ACCURATE_DURATION_FORMAT)
if (seconds !== null) {
return new Timedelta(seconds * 1000)
}
if (typeof value !== 'string') return null
for (const { regex, unit, factor } of DURATION_PATTERNS) {
const match = value.trim().match(regex)
if (match) {
const amount = parseInt(match[1], 10) * factor
return new Timedelta(amount * UNIT_TO_MS[unit])
}
}
return null
}
/**
* It formats the given duration value using the given format.
*/
export const formatDurationValue = (value, format) => {
if (value === null || value === undefined || value === '') {
return ''
}
let sign = ''
if (value < 0) {
sign = '-'
value = -1 * value
}
const days = Math.floor(value / 86400)
const hours = Math.floor((value % 86400) / 3600)
const mins = Math.floor((value % 3600) / 60)
const secs = value % 60
const formatFunc = DURATION_FORMATS.get(format).toString
return `${sign}${formatFunc(days, hours, mins, secs)}`
}
+38 -1
View File
@@ -2,7 +2,8 @@ import _ from 'lodash'
import { trueValues, falseValues } from '@baserow/modules/core/utils/constants'
import moment from '@baserow/modules/core/moment'
import { DateOnly } from '@baserow/modules/core/utils/date'
import { DateOnly, Timedelta } from '@baserow/modules/core/utils/date'
import { parseDurationString } from '@baserow/modules/core/utils/duration'
const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/
const isoDateFormat = 'YYYY-MM-DD HH:mm:ss'
@@ -47,6 +48,9 @@ export const ensureInteger = (value) => {
return Number(value)
}
}
if (value instanceof Timedelta) {
return Math.floor(value.ms / 1000)
}
throw new Error(
`Value '${value}' is not a valid integer or convertible to an integer.`
)
@@ -102,6 +106,8 @@ export const ensureString = (value, { allowEmpty = true } = {}) => {
if (!isNaN(value)) {
return moment(value).format(isoDateFormat)
}
} else if (value instanceof Timedelta) {
return `${Math.floor(value.ms / 1000)}`
} else if (typeof value === 'object') {
// If it's a file we just extract the name
if (value.__file__) {
@@ -285,3 +291,34 @@ export const ensureObject = (value) => {
'Value is not a valid object or convertible to an object.'
)
}
/**
* Ensures that the value is a valid duration or converts it to one.
* @param {*} value - The value to ensure as a duration.
* @returns {Timedelta} - The converted value as a Timedelta.
* @throws {TypeError} if `value` is not convertable to a Timedelta.
*/
export const ensureDuration = (value) => {
if (value instanceof Timedelta) {
return value
}
if (typeof value === 'string') {
const result = parseDurationString(value)
if (result !== null) return result
try {
return new Timedelta(ensureInteger(value) * 1000)
} catch {
throw new TypeError(
`'${value}' is not a valid duration. Expected format: e.g. '1 day', '2 hours'.`
)
}
}
if (typeof value === 'number') {
return new Timedelta(value * 1000)
}
throw new TypeError('Value cannot be converted to a duration.')
}
+2 -356
View File
@@ -1,356 +1,2 @@
import _ from 'lodash'
const MOST_ACCURATE_DURATION_FORMAT = 'h:mm:ss.sss'
// taken from backend timedelta.max.total_seconds() == 1_000_000_000 days
export const MAX_BACKEND_DURATION_VALUE_NUMBER_OF_SECS = 86400000000000
export const MIN_BACKEND_DURATION_VALUE_NUMBER_OF_SECS =
MAX_BACKEND_DURATION_VALUE_NUMBER_OF_SECS * -1
export const DEFAULT_DURATION_FORMAT = 'h:mm'
const D_H = 'd h'
const D_H_M = 'd h:mm'
const D_H_M_S = 'd h:mm:ss'
const H_M = 'h:mm'
const H_M_S = 'h:mm:ss'
const H_M_S_S = 'h:mm:ss.s'
const H_M_S_SS = 'h:mm:ss.ss'
const H_M_S_SSS = 'h:mm:ss.sss'
const D_H_M_NO_COLONS = 'd h mm' // 1d2h3m
const D_H_M_S_NO_COLONS = 'd h mm ss' // 1d2h3m4s
const SECS_IN_DAY = 86400
const SECS_IN_HOUR = 3600
const SECS_IN_MIN = 60
function totalSecs({ secs = null, mins = null, hours = null, days = null }) {
return (
parseInt(days || 0) * SECS_IN_DAY +
parseInt(hours || 0) * SECS_IN_HOUR +
parseInt(mins || 0) * SECS_IN_MIN +
parseFloat(secs || 0.0)
)
}
/** DURATION_REGEXPS
*
* A map of regexps to parse input values. Input values are normalized into seconds.
*
* Input value semantics may change depending on duration format selection. In
* some cases the same values may mean hours or minutes, depending on a format context.
* This mapping helps managing this aspect.
*
* @type {Map<RegExp, {string: (function({int, int, int, int}): int)}>}
*/
const DURATION_REGEXPS = new Map([
[
// 1d 10h 20m 30s
/^((?<days>\d+)(?:d\s*))?((?<hours>\d+)(?:h\s*))?((?<mins>\d+)(?:m\s*))?((?<secs>\d+|\d+\.\d+)(?:s\s*))?$/,
{
default: ({ days, hours, mins, secs }) =>
totalSecs({ days, hours, mins, secs }),
},
],
[
// 1d 12:13:14.123
/^(\d+)(?:d\s*|\s+)(\d+):(\d+):(\d+|\d+\.\d+)$/,
{
default: (days, hours, mins, secs) =>
totalSecs({ days, hours, mins, secs }),
},
],
[
// 1:11:12.134
/^(\d+):(\d+):(\d+|\d+\.\d+)$/,
{
default: (hours, mins, secs) => totalSecs({ hours, mins, secs }),
},
],
[
// 1d 12:13
/^(\d+)(?:d\s*|\s+)(\d+):(\d+)$/,
{
[D_H]: (days, hours, mins) => totalSecs({ days, hours, mins }),
[D_H_M]: (days, hours, mins) => totalSecs({ days, hours, mins }),
[D_H_M_NO_COLONS]: (days, hours, mins) =>
totalSecs({ days, hours, mins }),
default: (days, mins, secs) => totalSecs({ days, mins, secs }),
},
],
[
// 1d 11:12 -> 1 00:11:12
/^(\d+)(?:d\s*|\s+)(\d+):(\d+\.\d+)$/,
{ default: (days, mins, secs) => totalSecs({ days, mins, secs }) },
],
[
// 123h -> 5d 3h
/^(\d+)h$/,
{ default: (hours) => totalSecs({ hours }) },
],
[
// 1d 12h
/^(\d+)(?:d\s*|\s+)(\d+)h$/,
{
default: (days, hours) => totalSecs({ days, hours }),
},
],
[
// 123d
/^(\d+)d$/,
{ default: (days) => totalSecs({ days }) },
],
[
// 1d 12
/^(\d+)(?:d\s*|\s+)(\d+)$/,
{
[D_H]: (days, hours) => totalSecs({ days, hours }),
[D_H_M]: (days, mins) => totalSecs({ days, mins }),
[H_M]: (days, mins) => totalSecs({ days, mins }),
[D_H_M_NO_COLONS]: (days, mins) => totalSecs({ days, mins }),
default: (days, secs) => totalSecs({ days, secs }),
},
],
[
// 1d 123.234
/^(\d+)(?:d\s*|\s+)(\d+\.\d+)$/,
{ default: (days, secs) => totalSecs({ days, secs }) },
],
[
// 11:12
/^(\d+):(\d+)$/,
{
[D_H]: (hours, mins) => totalSecs({ hours, mins }),
[D_H_M]: (hours, mins) => totalSecs({ hours, mins }),
[H_M]: (hours, mins) => totalSecs({ hours, mins }),
[D_H_M_NO_COLONS]: (hours, mins) => totalSecs({ hours, mins }),
default: (mins, secs) => totalSecs({ mins, secs }),
},
],
[
// 123:12.123 -> 2h3m12s
/^(\d+):(\d+\.\d+)$/,
{ default: (mins, secs) => totalSecs({ mins, secs }) },
],
[
// 123.2134
/^(\d+\.\d+)$/,
{ default: (secs) => totalSecs({ secs }) },
],
[
// 123
/^(\d+)$/,
{
[D_H]: (hours) => totalSecs({ hours }),
[D_H_M]: (mins) => totalSecs({ mins }),
[H_M]: (mins) => totalSecs({ mins }),
[D_H_M_NO_COLONS]: (mins) => totalSecs({ mins }),
default: (secs) => totalSecs({ secs }),
},
],
])
// Map guarantees the order of the entries
export const DURATION_FORMATS = new Map([
[
H_M,
{
description: 'h:mm (1:23)',
example: '1:23',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}`
},
round: (value) => Math.round(value / 60) * 60,
},
],
[
H_M_S,
{
description: 'h:mm:ss (1:23:40)',
example: '1:23:40',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(0)
.padStart(2, '0')}`
},
round: (value) => Math.round(value),
},
],
[
H_M_S_S,
{
description: 'h:mm:ss.s (1:23:40.0)',
example: '1:23:40.0',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(1)
.padStart(4, '0')}`
},
round: (value) => Math.round(value * 10) / 10,
},
],
[
H_M_S_SS,
{
description: 'h:mm:ss.ss (1:23:40.00)',
example: '1:23:40.00',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(2)
.padStart(5, '0')}`
},
round: (value) => Math.round(value * 100) / 100,
},
],
[
H_M_S_SSS,
{
description: 'h:mm:ss.sss (1:23:40.000)',
example: '1:23:40.000',
toString(d, h, m, s) {
return `${d * 24 + h}:${m.toString().padStart(2, '0')}:${s
.toFixed(3)
.padStart(6, '0')}`
},
round: (value) => Math.round(value * 1000) / 1000,
},
],
[
D_H,
{
description: 'd h (1d 2h)',
example: '1d 2h',
toString(d, h, m, s) {
return `${d}d ${h}h`
},
round: (value) => Math.round(value / 3600) * 3600,
},
],
[
D_H_M,
{
description: 'd h:mm (1d 2:34)',
example: '1d 2:34',
toString(d, h, m, s) {
return `${d}d ${h}:${m.toString().padStart(2, '0')}`
},
round: (value) => Math.round(value / 60) * 60,
},
],
[
D_H_M_S,
{
description: 'd h:mm:ss (1d 2:34:56)',
example: '1d 2:34:56',
toString(d, h, m, s) {
return `${d}d ${h}:${m.toString().padStart(2, '0')}:${s
.toFixed(0)
.padStart(2, '0')}`
},
round: (value) => Math.round(value),
},
],
[
D_H_M_NO_COLONS,
{
description: 'd h m (1d 2h 3m)',
example: '1d 2h 3m',
toString(d, h, m, s) {
return `${d}d ${h}h ${m.toString().padStart(2, '0')}m`
},
// round to a minute
round: (value) => Math.round(value / 60) * 60,
},
],
[
D_H_M_S_NO_COLONS,
{
description: 'd h m s (1d 2h 3m 4s)',
example: '1d 2h 3m 4s',
toString(d, h, m, s) {
return `${d}d ${h}h ${m.toString().padStart(2, '0')}m ${s
.toFixed(0)
.padStart(2, '0')}s`
},
round: (value) => Math.round(value),
},
],
])
export const roundDurationValueToFormat = (value, format) => {
if (value === null) {
return null
}
const durationFormatOptions = DURATION_FORMATS.get(format)
if (!durationFormatOptions) {
throw new Error(`Unknown duration format ${format}`)
}
return durationFormatOptions.round(value)
}
/**
* It tries to parse the input value using the given format.
* If the input value does not match the format, it tries to parse it using
* the most accurate format if strict is false, otherwise it throws an error.
*/
export const parseDurationValue = (
inputValue,
format = MOST_ACCURATE_DURATION_FORMAT
) => {
if (inputValue === null || inputValue === undefined || inputValue === '') {
return null
}
// If the value is a number, we assume it's already in seconds (i.e. from the backend).
if (Number.isFinite(inputValue)) {
return inputValue
}
let multiplier = 1
if (inputValue.startsWith('-')) {
multiplier = -1
inputValue = inputValue.substring(1)
}
for (const [fmtRegExp, formatFuncs] of DURATION_REGEXPS) {
let matchedGroups = {}
// exec may be null, which will throw an exception
try {
matchedGroups = fmtRegExp.exec(inputValue).groups
} catch (err) {
/* empty */
}
const match = inputValue.match(fmtRegExp)
const formatFunc = formatFuncs[format] || formatFuncs.default
// the regex is using named groups, so the handler function should too
if (!_.isEmpty(matchedGroups)) {
return formatFunc(matchedGroups) * multiplier
}
// no named groups, so we use positional args
if (match) {
return formatFunc(...match.slice(1)) * multiplier
}
}
return null
}
/**
* It formats the given duration value using the given format.
*/
export const formatDurationValue = (value, format) => {
if (value === null || value === undefined || value === '') {
return ''
}
let sign = ''
if (value < 0) {
sign = '-'
value = -1 * value
}
const days = Math.floor(value / 86400)
const hours = Math.floor((value % 86400) / 3600)
const mins = Math.floor((value % 3600) / 60)
const secs = value % 60
const formatFunc = DURATION_FORMATS.get(format).toString
return `${sign}${formatFunc(days, hours, mins, secs)}`
}
// Keep this module for compatibility with existing imports.
export * from '@baserow/modules/core/utils/duration'
@@ -0,0 +1,157 @@
import { expect } from 'vitest'
import {
BaserowRuntimeFormulaArgumentType,
DatetimeFormatBaserowRuntimeFormulaArgumentType,
TimezoneBaserowRuntimeFormulaArgumentType,
ThousandSeparatorBaserowRuntimeFormulaArgumentType,
DecimalSeparatorBaserowRuntimeFormulaArgumentType,
DurationBaserowRuntimeFormulaArgumentType,
Timedelta,
} from '@baserow/modules/core/runtimeFormulaArgumentTypes'
describe('BaserowRuntimeFormulaArgumentType', () => {
test('getErrorMessage returns null by default', () => {
const argType = new BaserowRuntimeFormulaArgumentType()
expect(argType.getErrorMessage('foo', {})).toBeNull()
})
})
describe('TimezoneBaserowRuntimeFormulaArgumentType', () => {
test('getErrorMessage returns a human-readable message for invalid timezone', () => {
const argType = new TimezoneBaserowRuntimeFormulaArgumentType()
const mocki18n = {
t: (key, params) => `'${params.value}' is not a valid timezone.`,
}
const message = argType.getErrorMessage('Europe/Foo', mocki18n)
expect(message).toContain("'Europe/Foo' is not a valid timezone.")
})
})
describe('ThousandSeparatorBaserowRuntimeFormulaArgumentType', () => {
test.each([
{ value: ',', expected: true },
{ value: '.', expected: true },
{ value: ' ', expected: true },
{ value: '', expected: true },
{ value: ';', expected: false },
{ value: '|', expected: false },
{ value: 1, expected: false },
{ value: null, expected: false },
])('returns $expected for $value', ({ value, expected }) => {
expect(
new ThousandSeparatorBaserowRuntimeFormulaArgumentType().test(value)
).toBe(expected)
})
test('getErrorMessage returns a human-readable message', () => {
const argType = new ThousandSeparatorBaserowRuntimeFormulaArgumentType()
const mocki18n = {
t: (key, params) =>
`'${params.value}' is not a valid thousand separator.`,
}
const message = argType.getErrorMessage(';', mocki18n)
expect(message).toContain("';' is not a valid thousand separator.")
})
})
describe('DecimalSeparatorBaserowRuntimeFormulaArgumentType', () => {
test.each([
{ value: ',', expected: true },
{ value: '.', expected: true },
{ value: ' ', expected: false },
{ value: '', expected: false },
{ value: ';', expected: false },
{ value: 1, expected: false },
{ value: null, expected: false },
])('returns $expected for $value', ({ value, expected }) => {
expect(
new DecimalSeparatorBaserowRuntimeFormulaArgumentType().test(value)
).toBe(expected)
})
test('getErrorMessage returns a human-readable message', () => {
const argType = new DecimalSeparatorBaserowRuntimeFormulaArgumentType()
const mocki18n = {
t: (key, params) => `'${params.value}' is not a valid decimal separator.`,
}
const message = argType.getErrorMessage(';', mocki18n)
expect(message).toContain("';' is not a valid decimal separator.")
})
})
describe('DurationBaserowRuntimeFormulaArgumentType', () => {
test.each([
{ value: '1 day', expected: true },
{ value: '2 days', expected: true },
{ value: '3 weeks', expected: true },
{ value: '4 hours', expected: true },
{ value: '30 minutes', expected: true },
{ value: '45 seconds', expected: true },
{ value: '1 year', expected: true },
{ value: '1 month', expected: true },
{ value: new Timedelta(86400000), expected: true },
{ value: '-1 day', expected: false },
{ value: 'foo', expected: false },
{ value: '', expected: false },
{ value: '1', expected: true },
{ value: 1, expected: true },
{ value: null, expected: false },
])('returns $expected for "$value"', ({ value, expected }) => {
expect(new DurationBaserowRuntimeFormulaArgumentType().test(value)).toBe(
expected
)
})
test.each([
{ value: '1 day', expected: new Timedelta(86400000) },
{ value: '2 days', expected: new Timedelta(2 * 86400000) },
{ value: '3 weeks', expected: new Timedelta(3 * 7 * 86400000) },
{ value: '4 hours', expected: new Timedelta(4 * 3600000) },
{ value: '30 minutes', expected: new Timedelta(30 * 60000) },
{ value: '45 seconds', expected: new Timedelta(45 * 1000) },
])('parse converts "$value" to Timedelta', ({ value, expected }) => {
expect(
new DurationBaserowRuntimeFormulaArgumentType().parse(value)
).toStrictEqual(expected)
})
test('getErrorMessage returns a human-readable message', () => {
const argType = new DurationBaserowRuntimeFormulaArgumentType()
const mocki18n = {
t: (key, params) => `'${params.value}' is not a valid duration string.`,
}
const message = argType.getErrorMessage('not valid', mocki18n)
expect(message).toContain("'not valid' is not a valid duration string.")
})
})
describe('DatetimeFormatBaserowRuntimeFormulaArgumentType', () => {
test.each([
{ value: 'YYYY-MM-DD', expected: true },
{ value: 'DD/MM/YYYY', expected: true },
{ value: 'YYYY-MM-DD HH:mm:ss', expected: true },
{ value: 'DD/MM/YYYY HH:mm:ss', expected: true },
{ value: 'HH:mm:ss', expected: true },
{ value: 'SSS', expected: true },
{ value: '', expected: false },
{ value: 'SS', expected: false },
{ value: 'S', expected: false },
{ value: 'Z', expected: false },
{ value: 'YYYY-MM-DD HH:mm:SS', expected: false },
{ value: 123, expected: false },
{ value: null, expected: false },
])('test() returns $expected for "$value"', ({ value, expected }) => {
expect(
new DatetimeFormatBaserowRuntimeFormulaArgumentType().test(value)
).toBe(expected)
})
test('getErrorMessage returns a human-readable message', () => {
const argType = new DatetimeFormatBaserowRuntimeFormulaArgumentType()
const mocki18n = {
t: (key, params) => `'${params.value}' is not a valid datetime format.`,
}
const message = argType.getErrorMessage('SS', mocki18n)
expect(message).toContain("'SS' is not a valid datetime format.")
})
})
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
import {
ensureArray,
ensureDateTime,
ensureDuration,
ensureInteger,
ensureString,
ensureNumeric,
@@ -10,7 +11,7 @@ import {
} from '@baserow/modules/core/utils/validator'
import { expect } from 'vitest'
import { QUERY_PARAM_TYPE_HANDLER_FUNCTIONS } from '@baserow/modules/builder/enums'
import { DateOnly } from '@baserow/modules/core/utils/date'
import { DateOnly, Timedelta } from '@baserow/modules/core/utils/date'
describe('ensureInteger', () => {
it('should return the value as an integer if it is already an integer', () => {
@@ -30,6 +31,13 @@ describe('ensureInteger', () => {
expect(() => ensureInteger(null)).toThrow(Error)
expect(() => ensureInteger([])).toThrow(Error)
})
it('should convert a Timedelta to total seconds', () => {
expect(ensureInteger(new Timedelta(86400000))).toBe(86400)
expect(ensureInteger(new Timedelta(3600000))).toBe(3600)
expect(ensureInteger(new Timedelta(0))).toBe(0)
expect(ensureInteger(new Timedelta(1500))).toBe(1)
})
})
describe('ensurePositiveInteger', () => {
@@ -228,6 +236,16 @@ describe('ensureString', () => {
expect(ensureString(new DateOnly(NaN))).toBe('Invalid Date')
expect(ensureString(new Date(NaN))).toBe('Invalid Date')
})
it('should convert Timedelta to total seconds string', () => {
expect(ensureString(new Timedelta(0))).toBe('0')
expect(ensureString(new Timedelta(86400000))).toBe('86400')
expect(ensureString(new Timedelta(2 * 86400000))).toBe('172800')
expect(ensureString(new Timedelta(3600000))).toBe('3600')
expect(ensureString(new Timedelta(93784000))).toBe('93784')
expect(ensureString(new Timedelta(90000))).toBe('90')
expect(ensureString(new Timedelta(-86400000))).toBe('-86400')
})
})
describe('ensureStringOrInteger', () => {
@@ -535,3 +553,53 @@ describe('ensureDateTime', () => {
})
})
})
describe('ensureDuration', () => {
test('returns Timedelta for valid duration strings', () => {
expect(ensureDuration('1 day')).toStrictEqual(new Timedelta(86400000))
expect(ensureDuration('2 hours')).toStrictEqual(new Timedelta(2 * 3600000))
expect(ensureDuration('30 minutes')).toStrictEqual(
new Timedelta(30 * 60000)
)
expect(ensureDuration('1 week')).toStrictEqual(new Timedelta(7 * 86400000))
expect(ensureDuration('1 year')).toStrictEqual(
new Timedelta(365 * 86400000)
)
expect(ensureDuration('1 month')).toStrictEqual(
new Timedelta(30 * 86400000)
)
})
test('returns Timedelta passthrough', () => {
const td = new Timedelta(5000)
expect(ensureDuration(td)).toBe(td)
})
test('converts number to Timedelta in seconds', () => {
expect(ensureDuration(60)).toStrictEqual(new Timedelta(60000))
expect(ensureDuration(3600)).toStrictEqual(new Timedelta(3600000))
expect(ensureDuration(0)).toStrictEqual(new Timedelta(0))
})
test('converts numeric string to Timedelta in seconds', () => {
expect(ensureDuration('86400')).toStrictEqual(new Timedelta(86400000))
expect(ensureDuration('3600')).toStrictEqual(new Timedelta(3600000))
expect(ensureDuration('60')).toStrictEqual(new Timedelta(60000))
expect(ensureDuration('0')).toStrictEqual(new Timedelta(0))
})
test('throws for invalid strings', () => {
expect(() => ensureDuration('foo')).toThrow()
expect(() => ensureDuration('')).toThrow()
})
test('throws for null/undefined', () => {
expect(() => ensureDuration(null)).toThrow()
expect(() => ensureDuration(undefined)).toThrow()
})
test('throws for invalid types', () => {
expect(() => ensureDuration([])).toThrow()
expect(() => ensureDuration({})).toThrow()
})
})