#
View Source Vtc.Ecto.Postgres.PgRational (vtc v0.13.15)

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 it's 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

db_record()

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

## Functions

embed_as(_)

Callback implementation for `Ecto.Type.embed_as/1`.

equal?(term1, term2)

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

type()

The database type for `PgRational`.

# Link to this section Types

Link to this type

# db_record()

View Source

    @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 Functions

Link to this function

# embed_as(_)

View Source

Callback implementation for `Ecto.Type.embed_as/1`.

Link to this function

# equal?(term1, term2)

View Source

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

Link to this function

# type()

View Source

    @spec type() :: atom()

The database type for `PgRational`.

Can be used in migrations as the fields type.