View Source mix ecto.gen.schema (Introspex v0.3.0)

Generates Ecto schemas from an existing PostgreSQL database.

This task introspects your PostgreSQL database and generates Ecto schema files with proper field types, associations, and changesets.

Examples

$ mix ecto.gen.schema --repo MyApp.Repo
$ mix ecto.gen.schema --repo MyApp.Repo --schema public --table users
$ mix ecto.gen.schema --repo MyApp.Repo --exclude-views
$ mix ecto.gen.schema --repo MyApp.Repo --binary-id --dry-run
$ mix ecto.gen.schema --repo MyApp.Repo --context Accounts --context-tables users,profiles
$ mix ecto.gen.schema --repo MyApp.Repo --context Blog --context-tables posts,comments,tags

Options

  • --repo - the repository module (required)
  • --schema - PostgreSQL schema name (default: "public")
  • --table - generate schema for a specific table only
  • --exclude-views - skip generating schemas for views and materialized views
  • --binary-id - use binary_id (UUID) for primary keys
  • --no-timestamps - do not generate timestamps() in schemas
  • --no-changesets - skip generating changeset functions
  • --no-associations - skip detecting and generating associations
  • --module-prefix - prefix for generated module names (default: app name)
  • --output-dir - output directory for schema files (default: lib/app_name)
  • --dry-run - preview what would be generated without writing files
  • --context - Phoenix context name for organizing related schemas
  • --context-tables - comma-separated list of tables to include in the context (only these tables will be generated)
  • --path - custom path segment(s) to insert in the output directory (e.g., "queries" results in lib/app_name/queries/...)
  • --association-naming - association naming strategy: fk_stem, table_plus_stem, constraint (default: table_plus_stem)
  • --association-naming-apply - when to apply naming strategy: duplicates_only, always (default: duplicates_only)

Association Naming

Introspex can disambiguate association field names when multiple relationships would otherwise produce duplicates.

Strategies:

  • fk_stem - uses role stems from foreign key names (e.g. creator_id -> :creator)
  • table_plus_stem - combines target table and role stem (default)
  • constraint - uses foreign key constraint names when available

Apply modes:

  • duplicates_only - only rename when collisions occur (default)
  • always - always apply the selected strategy

Collision detection is global across belongs_to, has_many, has_one, and many_to_many.