View Source Vtc.Ecto.Postgres.PgRational (vtc v0.17.5)

Defines a composite type for storing rational values as dual int64s. These values are cast to %Ratio{} structs for use in application code, provided by the Ratio library.

The composite type is defined as follows:

CREATE TYPE rational as (
  numerator bigint,
  denominator bigint
)

Rational values can be cast in SQL expressions like so:

SELECT (1, 2)::rational

See Vtc.Ecto.Postgres.PgRational.Migrations for more information on how to create rational and its supporting functions in your database.

field-migrations

Field migrations

You can create a field as a rational during a migration like so:

create table("rationals") do
  add(:a, PgRational.type())
  add(:b, PgRational.type())
end

schema-fields

Schema fields

Then in your schema module:

defmodule MyApp.Rationals do
@moduledoc false
use Ecto.Schema

alias Vtc.Ecto.Postgres.PgRational

@type t() :: %__MODULE__{
        a: Ratio.t(),
        b: Ratio.t()
      }

schema "rationals_01" do
  field(:a, PgRational)
  field(:b, PgRational)
end

... notice that the schema field type is PgRational, but the type-spec field uses Ratio.t(), the type that our DB fields will be deserialized into.

changesets

Changesets

With the above setup, changesets should just work:

def changeset(schema, attrs) do
  schema
  |> Changeset.cast(attrs, [:a, :b])
  |> Changeset.validate_required([:a, :b])
end

Rational values can be cast from the following values in changesets:

  • %Ratio{} structs.

  • [numerator, denominator] integer arrays. Useful for non-text JSON values that can be set in a single field.

  • Strings formatted as 'numerator/denominator'. Useful for casting from a JSON string.

Link to this section Summary

Types

Type of the raw composite value that will be sent to / received from the database.

Ecto Migrations

The database type for PgRational.

Functions

Callback implementation for Ecto.Type.embed_as/1.

Callback implementation for Ecto.Type.equal?/2.

Link to this section Types

@type db_record() :: {non_neg_integer(), pos_integer()}

Type of the raw composite value that will be sent to / received from the database.

Link to this section Ecto Migrations

@spec type() :: atom()

The database type for PgRational.

Can be used in migrations as the fields type.

Link to this section Functions

Callback implementation for Ecto.Type.embed_as/1.

Callback implementation for Ecto.Type.equal?/2.