TypedStruct. Ecto
(TypedStruct v0.6.3)
View Source
TypedStruct integration with Ecto schemas.
This module provides utilities for combining Ecto schemas with TypedStruct to get both typed structs and Ecto schema functionality in one definition.
Quick Reference: Ecto Type to Elixir Type Mapping
When defining fields, use this mapping for typedstruct field types:
| Ecto Type | Elixir Type | Example |
|---|---|---|
:id | integer() | field :id, :id (Ecto) → field :id, integer() (TypedStruct) |
:binary_id | binary() | UUID fields |
:string | String.t() | Text fields |
:binary | binary() | Binary data |
:integer | integer() | Whole numbers |
:float | float() | Decimal numbers |
:boolean | boolean() | true/false |
:map | map() | JSON/map data |
:decimal | Decimal.t() | Precise decimals |
:date | Date.t() | Calendar date |
:time | Time.t() | Time of day |
:datetime | DateTime.t() | Date and time |
:naive_datetime | NaiveDateTime.t() | Date and time without timezone |
:utc_datetime | DateTime.t() | UTC timestamp |
Usage
The recommended approach is to use use Ecto.Schema alongside use TypedStruct:
defmodule User do
use Ecto.Schema
use TypedStruct
schema "users" do
field :email, :string
field :age, :integer
timestamps()
end
typedstruct do
field :email, String.t(), enforce: true
field :age, integer()
end
@type t() :: %__MODULE__{
id: integer() | nil,
email: String.t(),
age: integer() | nil,
inserted_at: NaiveDateTime.t() | nil,
updated_at: NaiveDateTime.t() | nil
}
endHowever, if you want a more concise definition for simple schemas, you can use the
typedschema/2 macro:
defmodule Product do
use TypedStruct.Ecto
typedschema "products" do
field :name, :string, enforce: true
field :price, :decimal
field :active, :boolean, default: true
timestamps()
end
endThe typedschema macro automatically:
- Sets up
use Ecto.Schema - Calls
schemawith the table name - Infers Elixir types from Ecto field types
- Handles
enforce:,default:, and other standard options - Supports associations (
belongs_to,has_many,has_one,many_to_many) - Supports embeds (
embeds_one,embeds_many) - Supports type overrides with
::syntax for custom types
Association Support
The typedschema macro automatically generates types for associations:
defmodule User do
use TypedStruct.Ecto
typedschema "users" do
field :email, :string, enforce: true
belongs_to :company, Company
has_many :posts, Post
timestamps()
end
endThis generates:
company_id: integer()(foreign key for belongs_to)company: Company.t() | Ecto.Association.NotLoaded.t()(the association)posts: [Post.t()] | Ecto.Association.NotLoaded.t()(has_many returns a list)
All association types are automatically set to be nullable or as NotLoaded as appropriate.
Polymorphic Embeds
TypedStruct.Ecto supports polymorphic embeds through the optional
polymorphic_embed library.
When this library is installed, TypedStruct.Ecto automatically imports its
macros and generates union types for polymorphic relationships.
With polymorphic_embed Library
For the recommended approach using the polymorphic_embed library:
defmodule Notification do
use TypedStruct.Ecto
typedschema "notifications" do
field :message, :string
polymorphic_embeds_one :channel,
types: [
email: EmailConfig,
sms: SMSConfig,
push: PushConfig
],
on_replace: :update
timestamps()
end
endThis generates: channel: EmailConfig.t() | SMSConfig.t() | PushConfig.t()
For multiple items of different types:
polymorphic_embeds_many :events,
types: [
created: CreatedEvent,
updated: UpdatedEvent,
cancelled: CancelledEvent
],
on_replace: :deleteThis generates: events: [CreatedEvent.t() | UpdatedEvent.t() | CancelledEvent.t()]
Without polymorphic_embed Library
If you don't want to add the polymorphic_embed dependency, you can still
create union types manually:
defmodule Notification do
use TypedStruct.Ecto
typedschema "notifications" do
field :message, :string
field :config, EmailConfig.t() | SMSConfig.t() | PushConfig.t() :: EmailConfig.t() | SMSConfig.t() | PushConfig.t()
timestamps()
end
endNote: Without the library, you lose automatic type discriminator handling.
Type Overrides
You can override the automatically inferred type using the :: syntax. This is useful for:
- Custom Ecto types
- Narrowing generic types (e.g.,
integer()→pos_integer()) - Using domain-specific types (e.g.,
Money.t()instead ofDecimal.t())
defmodule Product do
use TypedStruct.Ecto
typedschema "products" do
field :id, :id
field :name, :string, enforce: true
# Override inferred Decimal.t() with Money.t()
field :price, :decimal :: Money.t()
# Narrow integer() to positive_integer()
field :stock, :integer :: pos_integer()
# Custom Ecto type with custom type spec
field :metadata, :map :: CustomMetadata.t()
# Union type for enum-like fields
field :status, :string :: :active | :inactive | :archived
timestamps()
end
endThe type override completely replaces the inferred type, including nullability handling:
# Without override (inferred as: String.t() | nil)
field :name, :string
# With override and enforce (type: Money.t())
field :price, :decimal, enforce: true :: Money.t()
# With override without enforce (type: Money.t() | nil)
field :price, :decimal :: Money.t()Advanced Usage
For other advanced Ecto features beyond what's supported here, consider using the dedicated typed_ecto_schema library:
defmodule User do
use TypedEctoSchema
typed_schema "users" do
field :email, :string
belongs_to :company, Company
timestamps()
end
endThis library handles all advanced Ecto features automatically.
Summary
Functions
Defines a typed Ecto schema.
Functions
Defines a typed Ecto schema.
This macro combines typedstruct and Ecto's schema macro, allowing you to define
both in one concise block. The macro handles type inference for standard Ecto types.
Example
typedschema "users" do
field :id, :id
field :email, :string, enforce: true
field :name, :string
timestamps()
endSee TypedStruct.Ecto module documentation for the Ecto type to Elixir type mapping.