semolina.fields¶
Field descriptors for Semolina semantic models.
Descriptor classes for defining typed fields in semantic view models. Fields use the descriptor protocol for class-level access and validation.
Attributes¶
A time grain that |
|
Every |
|
The grains a |
Classes¶
How to position NULL values in ORDER BY clause. |
|
Base descriptor for semantic view fields. |
|
Descriptor for metric fields (aggregatable measures). |
|
Descriptor for dimension fields (groupable attributes). |
|
A date or timestamp dimension truncated to a coarser grain, from |
|
Descriptor for fact fields (raw numeric values). |
|
Wrapper specifying sort direction and NULL handling for a field in order_by(). |
Functions¶
|
Return the type a field was declared with, as in |
Module Contents¶
- type semolina.fields.Grain = Literal['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'][source]¶
A time grain that
Dimension.grain()accepts, from the units all three backends share.
- semolina.fields.DATE_GRAINS[source]¶
The grains a
DATEcan be truncated to, and those whose result is aDATE.
- class semolina.fields.NullsOrdering[source]¶
Bases:
enum.EnumHow to position NULL values in ORDER BY clause.
- class semolina.fields.Field(source: str | None = None, *, label: str | None = None, description: str | None = None, synonyms: collections.abc.Iterable[str] = (), semantic_format: s_layer_semantic_formats.SemanticFormat | collections.abc.Mapping[str, Any] | None = None)[source]¶
Bases:
Generic[T]Base descriptor for semantic view fields.
Fields are descriptors that: - Validate field names at class creation time (__set_name__) - Return themselves for class-level access (Sales.revenue) - Prevent instance-level access, modification, and deletion - Support Python comparison operators to create Predicate filters
- Operators:
Field descriptors support Python comparison operators that return typed Predicate nodes:
Users.country == 'US' # -> Exact(field_name='country', value='US') Users.country != 'CA' # -> NotEqual(field_name='country', value='CA') Users.revenue > 1000 # -> Gt(field_name='revenue', value=1000) Users.revenue >= 1000 # -> Gte(...) Users.revenue < 100 # -> Lt(...) Users.revenue <= 100 # -> Lte(...)
Combine with & (AND) and | (OR):
(Users.country == 'US') | (Users.country == 'CA') # -> Or(...) (Users.revenue > 1000) & (Users.country == 'US') # -> And(...)
- Named filter methods:
Additional filter methods for common SQL operations:
Users.country.in_(['US', 'CA']) # -> In(...) Users.revenue.between(100, 1000) # -> Between(...) Users.name.like('%Smith%') # -> Like(...) Users.name.ilike('%smith%') # -> ILike(...) Users.name.startswith('A') # -> StartsWith(...) Users.name.endswith('son') # -> EndsWith(...) Users.country.iexact('united states') # -> IExact(...) Users.country.isnull() # -> IsNull(...)
- between(lo: Any, hi: Any) semolina.filters.Between[source]¶
Create range predicate:
field BETWEEN lo AND hi.- Parameters:
lo – Lower bound (inclusive).
hi – Upper bound (inclusive).
- Returns:
Between predicate with value as (lo, hi) tuple.
- Raises:
TypeError – If either bound is
None. For an open-ended range, use>=or<=.
Example
>>> Sales.revenue.between(100, 1000) Between(field_name='revenue', value=(100, 1000))
- in_(values: collections.abc.Iterable[Any]) semolina.filters.In[source]¶
Create membership predicate:
field IN (values).- Parameters:
values – The values to match: a list, tuple, set, or any other iterable, including a generator. They are copied into a tuple now, so changing the list afterwards does not change the predicate. An empty collection matches no rows.
- Returns:
In predicate holding a tuple of the given values.
- Raises:
TypeError – If
valuesis a singlestrorbytes, which would otherwise be read as its characters, or is not iterable. Also if any value isNone: to include missing values, OR thein_()with.isnull().
Example
>>> Sales.country.in_(['US', 'CA', 'UK']) In(field_name='country', value=('US', 'CA', 'UK'))
- like(pattern: str) semolina.filters.Like[source]¶
Create case-sensitive pattern match:
field LIKE pattern.- Parameters:
pattern – SQL LIKE pattern (use % and _ wildcards).
- Returns:
Like predicate with the given pattern.
Example
>>> Users.name.like('%Smith%') Like(field_name='name', value='%Smith%')
- ilike(pattern: str) semolina.filters.ILike[source]¶
Create case-insensitive pattern match:
field ILIKE pattern.- Parameters:
pattern – SQL ILIKE pattern (use % and _ wildcards).
- Returns:
ILike predicate with the given pattern.
Example
>>> Users.name.ilike('%smith%') ILike(field_name='name', value='%smith%')
- startswith(prefix: str) semolina.filters.StartsWith[source]¶
Create case-sensitive prefix match:
field LIKE 'prefix%'.The prefix is matched literally: a
%or_in it is escaped (withESCAPE '!'), not treated as a wildcard.- Parameters:
prefix – The prefix string to match.
- Returns:
StartsWith predicate with the given prefix.
- Raises:
TypeError – If the prefix is
None.
Example
>>> Users.name.startswith('A') StartsWith(field_name='name', value='A')
- istartswith(prefix: str) semolina.filters.IStartsWith[source]¶
Create case-insensitive prefix match:
field ILIKE 'prefix%'.The prefix is matched literally: a
%or_in it is escaped (withESCAPE '!'), not treated as a wildcard.- Parameters:
prefix – The prefix string to match (case-insensitive).
- Returns:
IStartsWith predicate with the given prefix.
- Raises:
TypeError – If the prefix is
None.
Example
>>> Users.name.istartswith('a') IStartsWith(field_name='name', value='a')
- endswith(suffix: str) semolina.filters.EndsWith[source]¶
Create case-sensitive suffix match:
field LIKE '%suffix'.The suffix is matched literally: a
%or_in it is escaped (withESCAPE '!'), not treated as a wildcard.- Parameters:
suffix – The suffix string to match.
- Returns:
EndsWith predicate with the given suffix.
- Raises:
TypeError – If the suffix is
None.
Example
>>> Users.name.endswith('son') EndsWith(field_name='name', value='son')
- iendswith(suffix: str) semolina.filters.IEndsWith[source]¶
Create case-insensitive suffix match:
field ILIKE '%suffix'.The suffix is matched literally: a
%or_in it is escaped (withESCAPE '!'), not treated as a wildcard.- Parameters:
suffix – The suffix string to match (case-insensitive).
- Returns:
IEndsWith predicate with the given suffix.
- Raises:
TypeError – If the suffix is
None.
Example
>>> Users.name.iendswith('SON') IEndsWith(field_name='name', value='SON')
- iexact(value: str) semolina.filters.IExact[source]¶
Create case-insensitive equality:
field ILIKE value(no wildcards).The value is matched literally: a
%or_in it is escaped (withESCAPE '!'), not treated as a wildcard.- Parameters:
value – The value to compare (case-insensitive).
- Returns:
IExact predicate with the given value.
- Raises:
TypeError – If the value is
None.
Example
>>> Users.country.iexact('united states') IExact(field_name='country', value='united states')
- isnull() semolina.filters.IsNull[source]¶
Create null check predicate:
field IS NULL.- Returns:
IsNull predicate with value=True.
Example
>>> Users.country.isnull() IsNull(field_name='country', value=True)
- lookup(lookup_cls: type[semolina.filters.Lookup[Any]], value: Any) semolina.filters.Lookup[Any][source]¶
Build a predicate from a built-in Lookup class.
The operators and named methods cover every built-in lookup, so you rarely need this. It is not an extension point: only the
Lookupsubclasses insemolina.filterscompile, and a subclass of your own raisesNotImplementedErroratto_sql()orexecute().- Parameters:
lookup_cls – A built-in Lookup subclass to instantiate.
value – The value for the lookup.
- Returns:
Instance of lookup_cls with this field’s name and the given value.
Example
>>> from semolina.filters import Exact >>> Users.country.lookup(Exact, 'US') Exact(field_name='country', value='US')
- asc(nulls: NullsOrdering | None = None) OrderTerm[source]¶
Return ascending OrderTerm for use in order_by().
- Parameters:
nulls – How to position NULL values (NullsOrdering.FIRST, NullsOrdering.LAST, or None for default)
- Returns:
OrderTerm with descending=False
Example
>>> term = Sales.revenue.asc() >>> term.descending False
- desc(nulls: NullsOrdering | None = None) OrderTerm[source]¶
Return descending OrderTerm for use in order_by().
- Parameters:
nulls – How to position NULL values (NullsOrdering.FIRST, NullsOrdering.LAST, or None for default)
- Returns:
OrderTerm with descending=True
Example
>>> term = Sales.revenue.desc() >>> term.descending True
- class semolina.fields.Metric(source: str | None = None, *, label: str | None = None, description: str | None = None, synonyms: collections.abc.Iterable[str] = (), semantic_format: s_layer_semantic_formats.SemanticFormat | collections.abc.Mapping[str, Any] | None = None)[source]¶
Bases:
Field[T]Descriptor for metric fields (aggregatable measures).
Metrics represent quantitative measurements that can be aggregated, such as SUM(revenue), AVG(price), COUNT(*).
- class semolina.fields.Dimension(source: str | None = None, *, label: str | None = None, description: str | None = None, synonyms: collections.abc.Iterable[str] = (), semantic_format: s_layer_semantic_formats.SemanticFormat | collections.abc.Mapping[str, Any] | None = None)[source]¶
Bases:
Field[T]Descriptor for dimension fields (groupable attributes).
Dimensions represent categorical or descriptive attributes used for grouping and filtering, such as country, product_category, date.
- grain(unit: Grain) GrainedDimension[source]¶
Select this date or timestamp dimension truncated to a coarser time grain.
Use the result in
.dimensions()and.order_by()like any dimension. Its result column is named<field>__<unit>(ordered_at__week), and the query truncates in the warehouse, so a metric is aggregated per week rather than per day.The value is the start of the period. Weeks start on Monday on every backend (Snowflake’s
WEEK_STARTsession parameter does not change it). A grain of a day or coarser comes back as aDATE, and an hour, minute or second as aTIMESTAMP, whichever backend runs the query.- Parameters:
unit – One of
GRAINS:"year","quarter","month","week","day","hour","minute"or"second".- Returns:
The truncated dimension. Calling
grain()again with the same unit returns the same object.- Raises:
ValueError – If
unitis not a grain, is finer than the dimension holds (an hour of aDimension[datetime.date]), or its column name is already a field of the model.TypeError – If the dimension is declared with a type that is not a date or timestamp, or is itself a truncated dimension.
Example
Orders.query( metrics=[Orders.revenue], dimensions=[Orders.ordered_at.grain("week")], ) # rows keyed {"revenue": ..., "ordered_at__week": datetime.date(...)}
- semolina.fields.declared_type(field: Field[Any]) object[source]¶
Return the type a field was declared with, as in
Dimension[datetime.date]().An optional type, as in
Dimension[datetime.date | None](), gives the type it wraps: the column is nullable, and its values are still dates.- Parameters:
field – A field.
- Returns:
The type argument, or
Nonefor a field declared without one.
- class semolina.fields.GrainedDimension(base: Dimension[Any], unit: Grain)[source]¶
Bases:
Dimension[Any]A date or timestamp dimension truncated to a coarser grain, from
Dimension.grain().It selects and orders like a dimension, under the name
<field>__<unit>. It cannot be filtered: filter the dimension it came from, which narrows rows before they are grouped (Orders.ordered_at >= datetime.date(2024, 1, 1)).- property result_is_date: bool[source]¶
Whether the truncated value is a
DATE(a day or coarser) or aTIMESTAMP.
- grain(unit: Grain) GrainedDimension[source]¶
Refuse to truncate twice; truncate the base dimension instead.
- Parameters:
unit – The grain asked for.
- Raises:
TypeError – Always.
- class semolina.fields.Fact(source: str | None = None, *, label: str | None = None, description: str | None = None, synonyms: collections.abc.Iterable[str] = (), semantic_format: s_layer_semantic_formats.SemanticFormat | collections.abc.Mapping[str, Any] | None = None)[source]¶
Bases:
Field[T]Descriptor for fact fields (raw numeric values).
Facts represent raw numeric values in fact tables that may be used in calculations but aren’t pre-aggregated, such as unit_price, quantity.
- class semolina.fields.OrderTerm[source]¶
Wrapper specifying sort direction and NULL handling for a field in order_by().
Created via Field.asc() or Field.desc() methods.
- nulls[source]¶
How to position NULL values (NullsOrdering.FIRST, NullsOrdering.LAST, or NullsOrdering.DEFAULT)
Example
>>> term = Sales.revenue.desc() >>> term.descending True >>> term_nulls = Sales.revenue.desc(NullsOrdering.FIRST) >>> term_nulls.nulls NULLS FIRST