### Example schema with overrides and options Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Example schema using `typed_schema/3` with overrides and options. Shows field-level type overrides with `::`, per-field null opt-out, default values disabling enforcement, and timestamps configuration. ```elixir defmodule Person do use TypedEctoSchema typed_schema "people", null: false, enforce: true do field(:name, :string) field(:age, :integer) :: non_neg_integer() | nil # :: override wins over inference field(:nickname, :string, null: true) # opt back out per field field(:bio, :string, default: "") # default => not enforced belongs_to(:company, Company) timestamps(type: :naive_datetime_usec, null: false) end end ``` -------------------------------- ### Define __using__/1 macro for TypedEctoSchema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Defines the __using__/1 macro that imports only the typed schema macros and calls use Ecto.Schema. This is the implementation of the macro, not the usage example. ```elixir @doc false defmacro __using__(_) do quote do import TypedEctoSchema, only: [ typed_embedded_schema: 1, typed_embedded_schema: 2, typed_schema: 2, typed_schema: 3 ] use Ecto.Schema end end ``` -------------------------------- ### Use TypedEctoSchema in a module Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Shows basic usage of use TypedEctoSchema in a module, which imports the typed schema macros and calls use Ecto.Schema. The example defines a Person schema with typed_schema. ```elixir defmodule Person do use TypedEctoSchema # equivalent to: import + use Ecto.Schema typed_schema "people" do field(:name, :string) field(:age, :integer) end end ``` -------------------------------- ### Use typed_embedded_schema in a module Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Shows usage of typed_embedded_schema in a module, defining an embedded schema with fields and options. The example includes comments showing the generated type and enforce_keys. ```elixir defmodule Address do use TypedEctoSchema typed_embedded_schema do field(:street, :string, null: false) field(:city, :string, enforce: true) field(:zip, :string) end # Generates @type t() :: %Address{street: String.t(), city: String.t(), zip: String.t() | nil} # and @enforce_keys [:city] end ``` -------------------------------- ### Inference outputs example for typed_schema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_ecto_type_mapper.md Shows the inferred types for various field declarations in a typed_schema. Fields without null: false default to nil, while embeds_many and has_many are never nullable. The example includes a fallback to any() when values are empty or unresolvable, and demonstrates how the :: override salvages the spec. ```elixir defmodule Post do use TypedEctoSchema typed_schema "posts" do field(:title, :string) # String.t() | nil field(:views, :integer, null: false) # integer() field(:tags, {:array, :string}) # list(String.t()) | nil field(:meta, {:map, :string}) # %{optional(any()) => String.t()} | nil field(:status, Ecto.Enum, values: [:draft, :published]) # (:draft | :published) | nil field(:payload, :binary_id) # binary() | nil field(:custom, MyCustomType) # MyCustomType.t() | nil has_one(:profile, Profile) # Ecto.Schema.has_one(Profile.t()) | nil has_many(:comments, Comment) # Ecto.Schema.has_many(Comment.t()) embeds_many(:entries, Entry) # list(Entry.t()) end end ``` -------------------------------- ### Use inline embeds with embeds_many in Invoice module Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md Example of using the macro: defines an Invoice module with typed_embedded_schema, uses embeds_many with primary_key: false, and creates Invoice.Line with @primary_key false. The lines field is typed as list(Invoice.Line.t()). ```elixir defmodule Invoice do use TypedEctoSchema @primary_key false typed_embedded_schema do embeds_many(:lines, Line, primary_key: false) do field(:description, :string, null: false) field(:qty, :integer) :: pos_integer() end end # creates Invoice.Line with @primary_key false; # lines: list(Invoice.Line.t()) end ``` -------------------------------- ### Use polymorphic_embeds_one with types option Source: https://github.com/bamorim/typed_ecto_schema/blob/master/guides/experimental.md Example of using `polymorphic_embeds_one/2` inside a `typed_schema` block. The `:types` option lists the possible embedded modules, and `on_replace: :update` is passed through. This generates a typespec of `(SMS.t() | Email.t()) | nil`. ```elixir typed_schema "reminders" do polymorphic_embeds_one(:channel, types: [sms: SMS, email: Email], on_replace: :update ) end ``` -------------------------------- ### Non-atom field name example with typed_embedded_schema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/errors.md Shows a compile-time failure when using a non-atom field name (42) inside a `typed_embedded_schema` block. The error is raised by the library's `add_field/5`. ```elixir defmodule Broken do use TypedEctoSchema typed_embedded_schema do field(42, :integer) end end # => ** (ArgumentError) a field name must be an atom, got 42 ``` -------------------------------- ### Default generated type for typed_schema/typed_embedded_schema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/types.md Every module using `use TypedEctoSchema` receives this `@type t()` definition, with field types inferred or overridden. The `...` represents the list of fields in declaration order, always starting with `__meta__: Ecto.Schema.Metadata.t()` for `typed_schema` (never for embedded schemas). ```elixir @type t() :: %__MODULE__{ field_name: , ... } ``` -------------------------------- ### init/1 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that initializes schema options by merging defaults, global additional types, and user-provided options. It registers module attributes for types, enforced keys, additional types, and docs. ```APIDOC ## `init/1` — macro ### Description Macro that initializes schema options by merging defaults, global additional types, and user-provided options. It registers module attributes for types, enforced keys, additional types, and docs. ### Parameters - `schema_opts` (keyword) - Required - Schema options passed to `typed_schema/3` / `typed_embedded_schema/2`. ### Returns AST quote. ### Example ```elixir defmacro init(schema_opts) do schema_opts = @default_schema_opts |> Keyword.merge(additional_types: global_additional_types(__CALLER__)) |> Keyword.merge(schema_opts) quote do Module.register_attribute(__MODULE__, :__typed_ecto_schema_types__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_enforced_keys__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_additional_types__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_docs__, accumulate: true) Module.put_attribute(__MODULE__, :__typed_ecto_schema_module_opts__, unquote(schema_opts)) end end ``` ``` -------------------------------- ### __using__/1 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Macro that injects TypedEctoSchema imports and Ecto.Schema usage into a module. ```APIDOC ## __using__/1 ### Description Injects `use TypedEctoSchema` into a module, importing only the typed schema macros and calling `use Ecto.Schema`. ### Signature ```elixir defmacro __using__(_) ``` ### Parameters - `_` (any) - Required - Any value; ignored. ### Returns AST quote (`Macro.t()`). ### Example ```elixir defmodule Person do use TypedEctoSchema # equivalent to: import + use Ecto.Schema typed_schema "people" do field(:name, :string) field(:age, :integer) end end ``` ``` -------------------------------- ### init/1 macro - merge schema options and register attributes Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that merges schema options with defaults and global additional types, then registers module attributes for typed schema metadata. The merge order is: defaults, then global additional types, then user options (user wins). Returns an AST quote. ```elixir defmacro init(schema_opts) do schema_opts = @default_schema_opts |> Keyword.merge(additional_types: global_additional_types(__CALLER__)) |> Keyword.merge(schema_opts) quote do Module.register_attribute(__MODULE__, :__typed_ecto_schema_types__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_enforced_keys__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_additional_types__, accumulate: true) Module.register_attribute(__MODULE__, :__typed_ecto_schema_docs__, accumulate: true) Module.put_attribute(__MODULE__, :__typed_ecto_schema_module_opts__, unquote(schema_opts)) end end ``` -------------------------------- ### define_type/1 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that sets up the typedoc, defines the schema type, additional types, and moduledoc marker. ```APIDOC ## define_type/1 ### Description Macro that sets up the typedoc, defines the schema type, additional types, and moduledoc marker. ### Method macro ### Parameters - `schema_opts` (keyword) - Required - Schema options; only `:opaque` is read here. ### Returns AST quote emitting, in order: the `@typedoc` setup, `@type t()`/`@opaque t()`, the additional named types, and the `@moduledoc` marker replacement. ### Example ```elixir defmacro define_type(schema_opts) do quote do unquote(__MODULE__).__set_typedoc__(__MODULE__, __ENV__.line) unquote(__MODULE__).__define_type__(@__typed_ecto_schema_types__, unquote(schema_opts)) unquote(__MODULE__).__define_additional_types__(@__typed_ecto_schema_additional_types__) unquote(__MODULE__).__set_moduledoc__(__MODULE__) end end ``` ``` -------------------------------- ### Enable additional_types globally via config Source: https://github.com/bamorim/typed_ecto_schema/blob/master/guides/experimental.md Set this in `config/config.exs` to enable the feature for all schemas. The schema-level option takes precedence. Must be in compile-time config, not runtime. ```elixir # config/config.exs config :typed_ecto_schema, additional_types: true ``` -------------------------------- ### Configure TypedEctoSchema in config.exs Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/configuration.md Enables polymorphic_embed globally and shows commented option for additional_types. Set these in config/config.exs before using the schema. ```elixir # config/config.exs import Config config :typed_ecto_schema, polymorphic_embed: true # enable integration everywhere # config :typed_ecto_schema, additional_types: true # global default for named types ``` -------------------------------- ### typed_schema/3 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Macro that replaces Ecto.Schema.schema/2, registering __meta__ as the first type and applying schema options. ```APIDOC ## `typed_schema/3` ### Description Replaces `Ecto.Schema.schema/2` with a macro that registers `__meta__` as the first type and applies schema options. ### Signature ```elixir defmacro typed_schema(table_name, opts \\ [], do: block) ``` ### Parameters - `table_name` (`String.t()`) - Required - The database table name, passed verbatim to `Ecto.Schema.schema/2`. - `opts` (keyword) - Optional - Schema options. Defaults to `[]`. See Schema options. - `block` (`Macro.t()`) - Required - The schema body. ### Returns AST quote. ### Example ```elixir defmodule Person do use TypedEctoSchema typed_schema "people", null: false, enforce: true do field(:name, :string) field(:age, :integer) :: non_neg_integer() | nil # :: override wins over inference field(:nickname, :string, null: true) # opt back out per field field(:bio, :string, default: "") # default => not enforced belongs_to(:company, Company) timestamps(type: :naive_datetime_usec, null: false) end end ``` ``` -------------------------------- ### Define __embeds_module__/4 macro for inline embeds Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md Macro implementation that pops the :primary_key option, wraps the block in a new module using TypedEctoSchema and typed_embedded_schema, and creates the module with Module.create. Returns {module, opts} for the outer embeds_one/embeds_many call. ```elixir @doc false def __embeds_module__(env, {:__aliases__, _, name}, opts, block) do {pk, opts} = Keyword.pop(opts, :primary_key, {:id, :binary_id, autogenerate: true}) block = quote do use TypedEctoSchema @primary_key unquote(Macro.escape(pk)) typed_embedded_schema do unquote(block) end end module = Module.concat(env.module, Module.concat(name)) Module.create(module, block, env) {module, opts} end ``` -------------------------------- ### add_field/5 main implementation Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Defines the main add_field/5 implementation. It reads schema options, resolves the type (using the :__typed_ecto_type__ override or delegating to TypedEctoSchema.EctoTypeMapper.type_for/4), stores the type, enforces keys, stores docs, adds additional types when enabled, and recursively adds a foreign key field for belongs_to when define_field is not false. Returns :ok. ```elixir @spec add_field( module(), function_name(), atom(), Ecto.Type.t() | Macro.t(), field_options() ) :: :ok def add_field(mod, function_name, name, ecto_type, field_opts) when is_atom(name) do schema_opts = Module.get_attribute(mod, :__typed_ecto_schema_module_opts__) type = case Keyword.fetch(field_opts, :__typed_ecto_type__) do {:ok, overriden_type} -> overriden_type :error -> TypedEctoSchema.EctoTypeMapper.type_for( ecto_type, function_name, Keyword.get(schema_opts, :null), Keyword.take(field_opts, [:null, :values]) ) end Module.put_attribute(mod, :__typed_ecto_schema_types__, {name, type}) if field_is_enforced?(schema_opts, field_opts), do: Module.put_attribute(mod, :__typed_ecto_schema_enforced_keys__, name) doc = Keyword.get(field_opts, :doc) if doc, do: Module.put_attribute(mod, :__typed_ecto_schema_docs__, {name, doc}) if Keyword.get(schema_opts, :additional_types, false), do: add_additional_type(mod, function_name, name, ecto_type, field_opts) if function_name == :belongs_to and Keyword.get(field_opts, :define_field, true) do add_field( mod, :field, Keyword.get(field_opts, :foreign_key, :"#{name}_id"), Keyword.get(field_opts, :type, Module.get_attribute(mod, :foreign_key_type, :integer)), Keyword.delete(field_opts, :doc) ) end :ok end ``` -------------------------------- ### Standard Ecto schema with manual typespec Source: https://github.com/bamorim/typed_ecto_schema/blob/master/README.md Shows the traditional way to define an Ecto schema with a hand-written `@type t()` and `@enforce_keys`. Requires manually keeping fields, enforced keys, and typespec in sync. ```elixir defmodule Person do use Ecto.Schema @enforce_keys [:name] schema "people" do field(:name, :string) field(:age, :integer) field(:happy, :boolean, default: true) field(:phone, :string) belongs_to(:company, Company) timestamps(type: :naive_datetime_usec) end @type t() :: %__MODULE__{ __meta__: Ecto.Schema.Metadata.t(), id: integer() | nil, name: String.t(), age: non_neg_integer() | nil, happy: boolean(), phone: String.t() | nil, company_id: integer() | nil, company: Company.t() | Ecto.Association.NotLoaded.t() | nil, inserted_at: NaiveDateTime.t() | nil, updated_at: NaiveDateTime.t() | nil } end ``` -------------------------------- ### Default schema options Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Defines the default schema options used by the type builder. These defaults are applied when no explicit options are provided. ```elixir @default_schema_opts null: true, enforce: false, opaque: false, additional_types: false ``` -------------------------------- ### Type builder option names (syntax_sugar.ex:28-38) Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md The exact list of options forwarded to the type builder. Only these options are read by `TypeBuilder.add_field/5`; other options are not passed through to avoid injecting the full options list into the module body, which would create compile-time dependencies for module aliases in pass-through options. ```elixir [:__typed_ecto_type__, :enforce, :null, :default, :values, :define_field, :foreign_key, :type, :doc] ``` -------------------------------- ### Strip primary key options Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md When `@primary_key` is `{name, type, field_opts}`, stores the original tuple in `@__typed_ecto_schema_primary_key__` and rewrites `@primary_key` with `:null`, `:enforce`, and `:doc` removed. Runs in the prelude before `Ecto.Schema` reads the attribute. Returns `:ok`. ```elixir @spec strip_primary_key_opts(module()) :: :ok def strip_primary_key_opts(module) ``` -------------------------------- ### apply_to_block/2 implementation (syntax_sugar.ex:40) Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md Rewrites each call in the schema do-block using `transform_expression/2`. Handles both a block of multiple expressions and a single expression, returning a new `:__block__` AST with the rewritten calls. ```elixir @spec apply_to_block(Macro.t(), Macro.Env.t()) :: Macro.t() def apply_to_block(block, env) do calls = case block do {:__block__, _, calls} -> calls call -> [call] end new_calls = Enum.map(calls, &transform_expression(&1, env)) {:__block__, [], new_calls} end ``` -------------------------------- ### Options splitting for 3-arg form (syntax_sugar.ex:62-93) Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md Splits the options keyword list at compile time when it's a literal keyword list, or generates runtime splitting code when it's an AST variable reference. The split separates Ecto options from type builder options, preserving the original AST for taken values so that expressions like `values: @attr` still resolve correctly. ```elixir {ecto_opts, builder_opts} = if Keyword.keyword?(opts) do # compile-time keyword list: split keys at compile time, # taken values keep their original AST (so `values: @attr` still resolves) {Keyword.drop(opts, [:__typed_ecto_type__, :enforce, :null, :doc]), Keyword.take(opts, @type_builder_option_names)} else # AST variable reference: generate runtime keyword splitting {quote(do: Keyword.drop(unquote(opts), [:__typed_ecto_type__, :enforce, :null, :doc])), quote(do: Keyword.take(unquote(opts), unquote(@type_builder_option_names)))} end ``` -------------------------------- ### Set moduledoc with field list Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Replaces the `` marker in the module's `@moduledoc` with the field list. The marker is the only trigger; without it or without a `@moduledoc`, nothing happens. Returns `:ok`. ```elixir @spec __set_moduledoc__(module()) :: :ok def __set_moduledoc__(module) ``` -------------------------------- ### Add primary key field Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Adds the primary key as a field via `add_field(module, :field, name, type, field_opts)`. Uses `@__typed_ecto_schema_primary_key__` if present (i.e., `strip_primary_key_opts/1` ran), otherwise the plain `@primary_key` attribute. `@primary_key false` results in no field. Returns `:ok`. ```elixir @spec add_primary_key(module()) :: :ok def add_primary_key(module) ``` -------------------------------- ### enforce_keys/0 macro - emit @enforce_keys attribute Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that emits the module attribute @enforce_keys from the accumulated enforced keys. Returns an AST quote. ```elixir defmacro enforce_keys do quote do @enforce_keys @__typed_ecto_schema_enforced_keys__ end end ``` -------------------------------- ### Define schema_option and schema_options types for typed_schema options Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/types.md Defines the private `schema_option` type and the public `schema_options` type. `schema_option` is a tuple type with keys `:null`, `:enforce`, `:opaque`, and `:additional_types`, each with a boolean value. `schema_options` is a list of these options. These types are used by `TypedEctoSchema.TypeBuilder.init/1`, `define_type/1`, and `field_is_enforced?/2`. ```elixir @typep schema_option :: {:null, boolean()} | {:enforce, boolean()} | {:opaque, boolean()} | {:additional_types, boolean()} @type schema_options :: list(schema_option) ``` -------------------------------- ### TypedEctoSchema equivalent with typed_schema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/README.md Shows the same schema using `TypedEctoSchema`, which automatically generates the typespec and enforced keys. Uses `typed_schema` instead of `schema` and supports `::` overrides and `:enforce`/`:null` options. ```elixir defmodule Person do use TypedEctoSchema typed_schema "people" do field(:name, :string, enforce: true, null: false) field(:age, :integer) :: non_neg_integer() | nil field(:happy, :boolean, default: true, null: false) field(:phone, :string) belongs_to(:company, Company) timestamps(type: :naive_datetime_usec) end end ``` -------------------------------- ### Define typed_embedded_schema/2 macro Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Shows the implementation of the typed_embedded_schema/2 macro, which wraps Ecto.Schema.embedded_schema/1 with the TypeBuilder pipeline. The /1 arity is the same macro with defaulted options. ```elixir @doc """ Replaces `Ecto.Schema.embedded_schema/1` """ defmacro typed_embedded_schema(opts \\ [], do: block) do quote do unquote(prelude(opts)) Ecto.Schema.embedded_schema do unquote(inner(block, __CALLER__)) end unquote(postlude(opts)) end end ``` -------------------------------- ### enforce_keys/0 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that emits the module attribute `@enforce_keys` from the accumulated enforced keys. ```APIDOC ## `enforce_keys/0` — macro ### Description Macro that emits the module attribute `@enforce_keys` from the accumulated enforced keys. ### Returns AST quote that emits the module attribute `@enforce_keys` from the accumulated enforced keys. ### Example ```elixir defmacro enforce_keys do quote do @enforce_keys @__typed_ecto_schema_enforced_keys__ end end ``` ``` -------------------------------- ### define_type/1 macro Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that emits AST for setting up typedoc, defining the type t(), additional named types, and moduledoc marker. Reads only the :opaque option from schema_opts. ```elixir defmacro define_type(schema_opts) do quote do unquote(__MODULE__).__set_typedoc__(__MODULE__, __ENV__.line) unquote(__MODULE__).__define_type__(@__typed_ecto_schema_types__, unquote(schema_opts)) unquote(__MODULE__).__define_additional_types__(@__typed_ecto_schema_additional_types__) unquote(__MODULE__).__set_moduledoc__(__MODULE__) end end ``` -------------------------------- ### Documentation fields marker Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Marker string used in the module documentation. Replacing this marker is the only way the :doc options affect the @moduledoc. ```elixir @fields_marker "" ``` -------------------------------- ### Add typed_ecto_schema to deps Source: https://github.com/bamorim/typed_ecto_schema/blob/master/README.md Adds the `typed_ecto_schema` package as a dependency with `runtime: false`. After adding, replace `use Ecto.Schema` with `use TypedEctoSchema` and `schema` with `typed_schema`. ```elixir {:typed_ecto_schema, "~> 0.5.0", runtime: false} ``` -------------------------------- ### Define typed_schema macro Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Defines the `typed_schema/3` macro that replaces `Ecto.Schema.schema/2`. It injects a prelude, adds metadata via `TypeBuilder.add_meta/1`, expands the schema body, and appends a postlude. The macro accepts a table name, optional schema options, and a do-block. ```elixir @doc """ Replaces `Ecto.Schema.schema/2` """ defmacro typed_schema(table_name, opts \\ [], do: block) do quote do unquote(prelude(opts)) unquote(TypeBuilder).add_meta(__MODULE__) Ecto.Schema.schema unquote(table_name) do unquote(inner(block, __CALLER__)) end unquote(postlude(opts)) end end ``` -------------------------------- ### add_meta/1 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Registers the `__meta__` field type as the first entry of the schema's types list for `typed_schema/3`. This is required for schemas that use the typed schema macro and cannot be overridden. ```APIDOC ### add_meta/1 #### Description Registers `{:__meta__, Ecto.Schema.Metadata.t()}` as the first entry of `@__typed_ecto_schema_types__` (for `typed_schema/3` only — embedded schemas skip this). The `__meta__` typespec cannot be overridden. #### Function Signature ```elixir @spec add_meta(module()) :: :ok def add_meta(module) ``` #### Parameters - `module` (module()) - Required - The schema module. #### Returns `:ok` ``` -------------------------------- ### add_meta/1 function spec and definition Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Registers `{:__meta__, Ecto.Schema.Metadata.t()}` as the first entry of `@__typed_ecto_schema_types__` for `typed_schema/3` only; embedded schemas skip this. The `__meta__` typespec cannot be overridden. Returns `:ok`. ```elixir @spec add_meta(module()) :: :ok def add_meta(module) ``` -------------------------------- ### add_field/5 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Documentation for the `add_field/5` function in the TypedEctoSchema.TypeBuilder module. ```APIDOC ## `add_field/5` ### Description Adds a field to a typed Ecto schema, computing its type, enforcement, doc, and additional types. It also handles the implicit foreign key field for `belongs_to` associations. ### Method Function ### Signature ```elixir @spec add_field( module(), function_name(), atom(), Ecto.Type.t() | Macro.t(), field_options() ) :: :ok def add_field(mod, function_name, name, ecto_type, field_opts) ``` ### Parameters - `mod` (module()) - Required - Schema module. - `function_name` (TypedEctoSchema.TypeBuilder.function_name()) - Required - Which Ecto macro produced the field: `:field`, `:embeds_one`, `:embeds_many`, `:has_one`, `:has_many`, `:belongs_to`, `:many_to_many`, `:polymorphic_embeds_one`, `:polymorphic_embeds_many`. - `name` (atom()) - Required - Field name; must be an atom or the fallback clause raises. - `ecto_type` (Ecto.Type.t() or Macro.t()) - Required - Ecto type (e.g. `:string`, `Ecto.Enum`, `{:array, :string}`, a module, or a `{source, type}` tuple). - `field_opts` (field_options()) - Required - The options the type builder reads (see `@type_builder_option_names` in the SyntaxSugar page). ### Behavior 1. **Typespec** — the `:__typed_ecto_type__` override wins verbatim; otherwise the type is delegated to `TypedEctoSchema.EctoTypeMapper.type_for/4` with the schema-level `:null` default and the field's `:null`/`:values` options. 2. **Enforce** — `field_is_enforced?/2` decides: `enforce: true` always; else `schema_opts[:enforce] && is_nil(field_opts[:default])` (schema-level enforce is skipped when the field has a `default:`). 3. **Doc** — a truthy `:doc` is stored. 4. **Additional types** — when `:additional_types` is on for the schema: polymorphic embeds produce the union of their `:types` modules (unless the field is named `t` or the type fell back to `any()`); other fields produce a named type when the Ecto type is a (possibly array-nested) `Ecto.Enum` with statically known values. 5. **belongs_to foreign key** — when `:define_field` is not `false`, recursively adds a `:field` named `:foreign_key` (default `:"#{name}_id"`) with type `:type` (default `@foreign_key_type`, default `:integer`), forwarding all field options except `:doc`. ### Returns `:ok`. ### Errors Raises `ArgumentError` when `name` is not an atom — with message `"a field name must be an atom, got #{inspect(name)}"`. ``` -------------------------------- ### Define Reminder schema with TypedEctoSchema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/configuration.md Defines a schema with null: false, additional_types: true, and various field options. Includes polymorphic_embeds_one for channel with on_replace: :update. ```elixir defmodule Reminder do use TypedEctoSchema import PolymorphicEmbed # your own dependency # schema-level: no null by default, no global enforce # (explicit additional_types: true overrides the global config to *off* here) typed_schema "reminders", null: false, additional_types: true do field(:title, :string, enforce: true) field(:note, :string, default: "") # not enforced (has default) field(:priority, :integer, null: true) # back to nullable field(:status, Ecto.Enum, values: [:pending, :done]) # @type status() :: :pending | :done polymorphic_embeds_one(:channel, types: [sms: SMS, email: Email], on_replace: :update) end end ``` -------------------------------- ### Read configuration at compile time Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/configuration.md Reads the :polymorphic_embed config value with a default of false. Use in application code for diagnostics. ```elixir Application.compile_env(:typed_ecto_schema, :polymorphic_embed, false) ``` -------------------------------- ### Enable polymorphic_embed integration via config flag Source: https://github.com/bamorim/typed_ecto_schema/blob/master/guides/experimental.md Set the compile-time flag `:polymorphic_embed` to `true` in `config/config.exs`. This must be in compile-time config (not `runtime.exs`) and requires Elixir 1.14+. ```elixir # config/config.exs config :typed_ecto_schema, polymorphic_embed: true ``` -------------------------------- ### __define_type__/2 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that defines the `t/0` type as `@type` or `@opaque` based on the `:opaque` option. ```APIDOC ## __define_type__/2 ### Description Macro that defines the `t/0` type as `@type` or `@opaque` based on the `:opaque` option. ### Method macro ### Parameters - `types` (list({atom(), Macro.t()})) - Required - Field-name/type-AST pairs from `@__typed_ecto_schema_types__`. - `schema_opts` (keyword) - Required - `:opaque` boolean. ### Returns AST quote defining `t/0` as `@type` or `@opaque`. ### Example ```elixir defmacro __define_type__(types, schema_opts) do if Keyword.get(schema_opts, :opaque, false) do quote bind_quoted: [types: types] do @opaque t() :: %__MODULE__{unquote_splicing(types)} end else quote bind_quoted: [types: types] do @type t() :: %__MODULE__{unquote_splicing(types)} end end end ``` ``` -------------------------------- ### Define a full typed Ecto schema with TypedEctoSchema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Use this snippet to define a complete Ecto schema with TypedEctoSchema, including typed fields, associations, embedded schemas, and timestamps. The `typed_schema` macro generates a `t()` type with non-nullable fields where `null: false` is specified, and enforces keys for fields with `enforce: true`. The primary key type is derived from `@primary_key`, and the foreign key type follows `@foreign_key_type`. ```elixir defmodule Blog.Post do use TypedEctoSchema @primary_key {:id, :binary_id, autogenerate: true, null: false} typed_schema "posts" do field(:title, :string, enforce: true, null: false, doc: "Post title") field(:body, :string) field(:status, Ecto.Enum, values: [:draft, :published]) belongs_to(:author, Blog.Author, null: false) has_many(:comments, Blog.Comment) embeds_one(:meta, Blog.PostMeta) # or an inline block, see SyntaxSugar timestamps(null: false) end end ``` -------------------------------- ### TypeBuilder field_option and field_options type definitions Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/types.md Defines the field_option and field_options types used by TypeBuilder.add_field/5. The field_option is any keyword pair, and field_options is a list of such pairs. The TypeBuilder reads specific keys like :__typed_ecto_type__, :enforce, :null, :default, :values, :define_field, :foreign_key, :type, and :doc. ```elixir @type field_option :: {atom(), any()} @type field_options :: list(field_option) ``` -------------------------------- ### __define_type__/2 macro Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Macro that defines t/0 as @type or @opaque based on the :opaque option. types is a list of field-name/type-AST pairs. ```elixir defmacro __define_type__(types, schema_opts) do if Keyword.get(schema_opts, :opaque, false) do quote bind_quoted: [types: types] do @opaque t() :: %__MODULE__{unquote_splicing(types)} end else quote bind_quoted: [types: types] do @type t() :: %__MODULE__{unquote_splicing(types)} end end end ``` -------------------------------- ### Set typed_ecto_schema config in config.exs Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/configuration.md Use this in config/config.exs (compile-time, not runtime.exs) to enable additional types and polymorphic embed support. The compiler recompiles affected schemas when these values change. ```elixir # config/config.exs — compile-time config, NOT runtime.exs import Config config :typed_ecto_schema, additional_types: true config :typed_ecto_schema, polymorphic_embed: true ``` -------------------------------- ### typed_embedded_schema/2 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema.md Macro that replaces Ecto.Schema.embedded_schema/1, generating types and enforce keys. ```APIDOC ## typed_embedded_schema/2 ### Description Defines an embedded schema with type generation and enforce keys, wrapping `Ecto.Schema.embedded_schema/1`. ### Signature ```elixir defmacro typed_embedded_schema(opts \\ [], do: block) ``` ### Parameters - `opts` (keyword) - Optional - Schema options (see Schema options). - `block` (Macro.t()) - Required - The schema body: field/3, associations, embeds, timestamps/1, :: overrides, any Elixir code. ### Returns AST quote. ### Example ```elixir defmodule Address do use TypedEctoSchema typed_embedded_schema do field(:street, :string, null: false) field(:city, :string, enforce: true) field(:zip, :string) end # Generates @type t() :: %Address{street: String.t(), city: String.t(), zip: String.t() | nil} # and @enforce_keys [:city] end ``` ``` -------------------------------- ### Override typespec with :: and use null/enforce options Source: https://github.com/bamorim/typed_ecto_schema/blob/master/guides/experimental.md Shows the `::` type override syntax and the `:null` and `:enforce` options. With `null: false` and `enforce: true`, the generated typespec is `SMS.t() | Email.t()` (no `| nil`) and `:channel` is added to `@enforce_keys`. ```elixir polymorphic_embeds_one(:channel, types: [sms: SMS, email: Email], on_replace: :update ) :: SMS.t() | Email.t() ``` ```elixir polymorphic_embeds_one(:channel, types: [sms: SMS, email: Email], on_replace: :update, null: false, enforce: true ) ``` -------------------------------- ### add_timestamps/2 Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Reads timestamp options (`:type`, `:inserted_at`, `:updated_at`) and forwards only `:null`/`:enforce` to each `add_field/5` call, adding the corresponding timestamp fields to the schema's types list. ```APIDOC ### add_timestamps/2 #### Description Reads `:type` (default `:naive_datetime`), `:inserted_at` and `:updated_at` (a `false` value skips that field), and forwards only `:null`/`:enforce` to each `add_field/5` call. #### Function Signature ```elixir @spec add_timestamps(module(), list({atom(), any()})) :: :ok def add_timestamps(module, opts) ``` #### Parameters - `module` (module()) - Required - The schema module. - `opts` (list({atom(), any()})) - Required - Merged `@timestamps_opts` + call options, e.g. `[type: :utc_datetime, inserted_at: :my_inserted_at, updated_at: :my_updated_at]`. #### Returns `:ok` ``` -------------------------------- ### add_timestamps/2 function spec and definition Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Adds timestamp fields to a schema module. Reads `:type` (default `:naive_datetime`), `:inserted_at` and `:updated_at` (a `false` value skips that field), and forwards only `:null`/`:enforce` to each `add_field/5` call. Returns `:ok`. ```elixir @spec add_timestamps(module(), list({atom(), any()})) :: :ok def add_timestamps(module, opts) do type = Keyword.get(opts, :type, :naive_datetime) field_opts = Keyword.take(opts, [:null, :enforce]) with field when not is_boolean(field) <- Keyword.get(opts, :inserted_at, :inserted_at) do add_field(module, :field, field, type, field_opts) end with field when not is_boolean(field) <- Keyword.get(opts, :updated_at, :updated_at) do add_field(module, :field, field, type, field_opts) end end ``` -------------------------------- ### EctoTypeMapper field_option and field_options type definitions Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/types.md Defines the field_option and field_options types for EctoTypeMapper, which are narrower than TypeBuilder's. Only :null and :values are read by the mapper, used for nullability and Ecto.Enum values respectively. ```elixir @type field_option :: {:null, boolean()} | {:values, list(atom())} @type field_options :: list(field_option) ``` -------------------------------- ### Check if PolymorphicEmbed integration is enabled Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_syntax_sugar.md This function reads the `:polymorphic_embed` compile-time configuration flag, defaulting to `false`. It is used to gate the integration so that same-named macros from other libraries are left untouched when disabled. ```elixir defp polymorphic_embed_enabled?(env) do Application.compile_env(env, :typed_ecto_schema, :polymorphic_embed, false) end ``` -------------------------------- ### Enforcement interplay with typed_schema Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Shows how `enforce: true` on `typed_schema` interacts with field options: fields without a default are enforced, fields with a default or `enforce: false` are not, and `belongs_to` enforces both the association and its foreign key. The output of `Order.enforce_keys()` is `[:customer, :customer_id, :total]`. ```elixir defmodule Order do use TypedEctoSchema typed_schema "orders", enforce: true do field(:total, :decimal) # enforced (schema default) field(:note, :string, default: "") # NOT enforced (has default) field(:state, :string, enforce: false) # NOT enforced (explicit opt-out) belongs_to(:customer, Customer) # enforces :customer (and its :customer_id foreign key) end def enforce_keys, do: @enforce_keys end IO.inspect(Order.enforce_keys()) # [:customer, :customer_id, :total] ``` -------------------------------- ### Define additional types macro Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_type_builder.md Defines a macro that generates public zero-arity type definitions for each accumulated named type. It reverses the list to preserve order and uses bind_quoted to avoid hygiene issues. ```elixir defmacro __define_additional_types__(additional_types) do quote bind_quoted: [additional_types: additional_types] do for {name, type} <- Enum.reverse(additional_types) do @type unquote(name)() :: unquote(type) end end end ``` -------------------------------- ### Fallback to any() with :: override Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/api-reference/typed_ecto_schema_ecto_type_mapper.md Demonstrates how empty or unresolvable Ecto.Enum values fall back to any() in the typespec. The :: override on the role field prevents the fallback by explicitly specifying term(). The mystery field with an unknown type also falls back to any() | nil. ```elixir defmodule Weird do use TypedEctoSchema typed_embedded_schema do # empty :values -> no union can be built, falls back to any() field(:role, Ecto.Enum, values: []) :: term() # :: override salvages the spec # unknown type -> any() field(:mystery, :not_a_real_type) # mystery: any() | nil end end ``` -------------------------------- ### Assert compile-time failure with assert_raise in ExUnit Source: https://github.com/bamorim/typed_ecto_schema/blob/master/_autodocs/errors.md Use this snippet in an ExUnit test to assert that a broken schema definition raises an ArgumentError at compile time. The error message must match exactly: "a field name must be an atom, got 3". The broken module is defined inside the assert_raise block, and the test expects the failure when the schema uses a non-atom field name. ```elixir assert_raise ArgumentError, "a field name must be an atom, got 3", fn -> defmodule InvalidStruct do use TypedEctoSchema typed_embedded_schema do field(3, :integer) end end end ```