Localize.Translate.QueryBuilder (Localize Translate v0.5.0)

Copy Markdown View Source

Provides helpers for filtering translations in Ecto.Queries.

This module requires Ecto.SQL to be available during the compilation.

Summary

Functions

Generates a SQL fragment for accessing a translated field in an Ecto.Query.

Generates a SQL fragment for use in an Ecto.Query select clause, aliased to the original field name.

Functions

translated(module, translatable, locale, options \\ [])

(macro)

Generates a SQL fragment for accessing a translated field in an Ecto.Query.

The generated SQL fragment can be coupled with the rest of the functions and operators provided by Ecto.Query and Ecto.Query.API.

Arguments

  • module is the Ecto.Schema module that uses Localize.Translate. Validated at compile time: its store must be queryable for it, as Localize.Translate.Store.queryable?/1 reports, or the query raises an ArgumentError when it is compiled. Localize.Translate.Store.Embedded is; Localize.Translate.Store.SiblingResource, whose container is filled after loading, is not.

  • translatable is either a query binding (such as a) for whole-record access, or a field access expression (such as a.title) for a specific translatable field.

  • locale is a locale (an atom, a string or a Localize.LanguageTag) or a list of locales acting as a fallback chain. May be a literal, a variable, or a runtime expression; either way it is expanded through the CLDR parent chain (:"es-419" → :es) and filtered to the schema's :locales when the query is built. A locale that is not valid, including nil, is left out of the chain, so a locale taken from a request never raises.

  • options is a literal keyword list of options.

Options

  • :default_locale is the locale of the base columns for this query, overriding the schema's :default_locale. May be a variable or a runtime expression, such as the language of the site being queried. Without it the schema's default is used, and a function default is called with nil, since a query has no record. A value that is not a valid locale, or nil, means no default: every locale is looked up in the translation container.

Returns

A fragment/1 AST suitable for use in Ecto.Query clauses. For a field, the fragment is the first non-null value in the chain, where a locale's value is its translation, or the base column for the default locale, and the base column when no locale has one. A NULL translation counts as missing, as it does in Localize.Translate.translate/3. For a whole record, it is the first locale's translations, or NULL when no locale in the chain has any.

The chain is passed as one array parameter and its first four locales are read with plain expressions, which is as fast as a hand-written jsonb expression; a longer chain walks the rest with a subquery. Columns are read through Ecto, so no database function is needed and any binding name, join or subquery works.

Safety

This macro emits errors when used with untranslatable schema modules or fields. Errors are emitted during compilation so invalid queries fail before they can run.

Examples

Assuming the Article schema defined in Structured translations:

# Return all articles that have a Spanish translation
from a in Article, where: not is_nil(translated(Article, a, :es))
#=> SELECT a0."id", a0."title", a0."body", a0."translations"
#=> FROM "articles" AS a0
#=> WHERE (NOT (COALESCE(
#=>   NULLIF(a0."translations"->($1::varchar[])[1], 'null'),
#=>   ... the same for positions 2 to 4,
#=>   CASE WHEN cardinality($5::varchar[]) > 4 THEN (... the rest ...) END) IS NULL))
#=> -- $1 = ['es']

# Query items with a certain translated value
from a in Article, where: translated(Article, a.title, :fr) == "Elixir"
#=> SELECT a0."id", a0."title", a0."body", a0."translations"
#=> FROM "articles" AS a0
#=> WHERE (COALESCE(
#=>   CASE WHEN ($1::varchar[])[1] = $2::varchar THEN a0."title"
#=>     ELSE a0."translations"->($3::varchar[])[1]->>$4 END,
#=>   ... the same for positions 2 to 4,
#=>   CASE WHEN cardinality($17::varchar[]) > 4 THEN (... the rest ...) END,
#=>   a0."title") = 'Elixir')
#=> -- the chain ['fr'] as $1, $3, ...; $2 = 'en' (the default locale); $4 = 'title'

# Query items using a case insensitive comparison
from a in Article, where: ilike(translated(Article, a.body, :es), "%elixir%")

# The base columns of each site are in that site's language
from a in Article,
  where: translated(Article, a.title, :fr, default_locale: site.locale) == "Elixir"

Structured translations vs free-form translations

Localize.Translate.QueryBuilder works with both structured translations and free-form translations.

When using structured translations, the translations are saved as an embedded schema. This means that the locale keys will be always present even if there is no translation for that locale. In the database we have a NULL value (nil in Elixir).

# If MyApp.Article uses structured translations, a locale with no
# translation is stored as null and is not counted
from a in Article, where: not is_nil(translated(Article, a, :es))

More complex queries

The translated/4 macro can also be used with relations and joined schemas. For more complex examples take a look at the QueryBuilder tests (the file is located in test/localize/translate/query_builder_test.exs).

translated_as(module, translatable, locale, options \\ [])

(macro)

Generates a SQL fragment for use in an Ecto.Query select clause, aliased to the original field name.

Wraps translated/4 so the returned column carries the base column's name. Ecto can therefore load the translated value directly into the schema struct without further processing or conversion.

Arguments

  • module is the Ecto.Schema module that uses Localize.Translate.

  • translatable is a field access expression such as a.title. The base field name is used as the column alias.

  • locale is either a single locale or a list of locales acting as a fallback chain.

  • options is a literal keyword list of options.

Options

  • :default_locale is the locale of the base columns for this query. See translated/4.

Returns

A fragment/1 AST that selects the translated value aliased to the original field name. See translated/4 for the underlying SQL produced.

Examples

# Load each article with its title in French, falling back to the base column
from a in Article,
  select: %{a | title: translated_as(Article, a.title, :fr)}

# The same, with the default locale of the site being queried
from a in Article,
  select: %{a | title: translated_as(Article, a.title, locale, default_locale: site.locale)}