PgCase (PgCase v0.1.0) View Source

Helper macros to work with PostgreSQL case expression.

Example

import Ecto.Query, only: [from: 2]
import PgCase, only: [pg_case: 1]

def query do
  from e in Entity,
    select: %{
      value: pg_case do
        e.x < 0 -> "negative"
        e.x > 0 -> "positive"
      else
        "zero"
      end
    }
end

Link to this section Summary

Functions

Adapts PostgreSQL case expression to elixir syntax.

Syntax sugar in case your use-case for case expression is simple if-else construction.

Link to this section Functions

Adapts PostgreSQL case expression to elixir syntax.

The following construction

pg_case do
  some_cond -> some_expr
  some_other_cond -> some_other_expr
else
  otherwise_expr
end

is equivalent to

CASE WHEN some_cond THEN some_expr
     WHEN some_other_cond THEN some_other_expr
ELSE otherwise_expr
END

PostgreSQL expression.

Note that else-clause may be omitted. Then it works exactly like case from PostgreSQL which returns null when none of when-clauses matched.

Link to this macro

pg_if(condition, body)

View Source (macro)

Syntax sugar in case your use-case for case expression is simple if-else construction.

pg_if some_cond do
  some_expr
else
  otherwise_expr
end

The code above is equivalent to following PosgreSQL expression:

CASE WHEN some_cond THEN some_expr
ELSE otherwise_expr
END

Note that else-clause may be omitted.