### Example: Starting Unnamed Repositories Source: https://ecto.hexdocs.pm/Ecto.Repo.md Shows how to start Ecto repositories without assigning a specific name by setting the name to nil. ```elixir MyApp.Repo.start_link(name: nil, hostname: "temp.example.com") ``` -------------------------------- ### Example: Starting Multiple Named Repositories Source: https://ecto.hexdocs.pm/Ecto.Repo.md Demonstrates how to start multiple Ecto repositories with distinct names, allowing for interaction with different database instances. ```elixir MyApp.Repo.start_link(name: :tenant_foo, hostname: "foo.example.com") MyApp.Repo.start_link(name: :tenant_bar, hostname: "bar.example.com") ``` -------------------------------- ### Run Ecto Migrations and Start IEx Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md After setting up your schema prefix, run Ecto migrations and start an interactive Elixir shell to test your setup. ```bash mix ecto.migrate iex -S mix Interactive Elixir - press Ctrl+C to exit iex(1)> MyApp.Repo.all MyApp.Sample [] ``` -------------------------------- ### Start and Manage Dynamic Repository with PID Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Start a dynamic repository without a name, retrieve its PID, and use it for queries. This example also demonstrates proper cleanup by stopping the repository and reverting the dynamic repo setting. ```elixir default_dynamic_repo = MyApp.Repo.get_dynamic_repo() {:ok, repo} = MyApp.Repo.start_link( name: nil, hostname: "client.example.com", username: "...", password: "...", pool_size: 1 ) try do MyApp.Repo.put_dynamic_repo(repo) MyApp.Repo.all(Post) after MyApp.Repo.put_dynamic_repo(default_dynamic_repo) Supervisor.stop(repo) end ``` -------------------------------- ### Install Dependencies Source: https://ecto.hexdocs.pm/getting-started.md Fetches and installs the application's dependencies, including Ecto and Postgrex. ```bash mix deps.get ``` -------------------------------- ### Start Repositories in Supervision Tree Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Lists all Ecto repositories (primary and replicas) to be started as part of the application's supervision tree. ```elixir children = [ MyApp.Repo, MyApp.Repo.Replica1, MyApp.Repo.Replica2, MyApp.Repo.Replica3, MyApp.Repo.Replica4 ] ``` -------------------------------- ### Start Ecto Repo in Supervision Tree Source: https://ecto.hexdocs.pm/getting-started.md Adds the Friends.Repo to the application's children in lib/friends/application.ex to ensure it starts. ```elixir def start(_type, _args) do children = [ Friends.Repo, ] ... ``` -------------------------------- ### Start Repo Supervision Tree Source: https://ecto.hexdocs.pm/Ecto.Repo.md Starts the Repo supervision tree. Returns {:error, {:already_started, pid}} if the repo is already started or {:error, term} in case anything else goes wrong. ```elixir @callback start_link(opts :: Keyword.t()) :: {:ok, pid()} | {:error, {:already_started, pid()}} | {:error, term()} ``` -------------------------------- ### Run Initial Database Commands Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md Commands to create the database, apply migrations, and start an IEx session for testing. ```bash $ mix ecto.create $ mix ecto.migrate $ iex -S mix Interactive Elixir - press Ctrl+C to exit iex(1)> MyApp.Repo.all MyApp.Sample [] ``` -------------------------------- ### Example Parameters with Dropped Entry and Re-indexing Source: https://ecto.hexdocs.pm/Ecto.Changeset.md Illustrates a scenario where an entry is dropped from 'addresses', and the remaining elements are re-indexed sequentially starting from 0. ```elixir %{ "addresses" => %{ 0 => %{"street" => "First St"}, 1 => %{"street" => "Second St"}, 2 => %{"street" => "Third St"} }, "addresses_drop" => [1] } ``` -------------------------------- ### init/1 Source: https://ecto.hexdocs.pm/Ecto.Adapter.md Initializes the adapter supervision tree by returning the children and adapter metadata. This is the first step in starting an adapter. ```APIDOC ## init/1 ### Description Initializes the adapter supervision tree by returning the children and adapter metadata. ### Method Signature `init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta()}` ``` -------------------------------- ### Ensure All Applications Started Callback Source: https://ecto.hexdocs.pm/Ecto.Adapter.md This callback ensures all applications necessary to run the adapter are started. It takes configuration and a type (:permanent, :transient, or :temporary) and returns an {:ok, [atom()]} or {:error, atom()} tuple. ```elixir @callback ensure_all_started( config :: Keyword.t(), type :: :permanent | :transient | :temporary ) :: {:ok, [atom()]} | {:error, atom()} ``` -------------------------------- ### start_link Source: https://ecto.hexdocs.pm/Ecto.Repo.md Starts the Repo supervision tree. It returns `{:error, {:already_started, pid}}` if the repo is already started or `{:error, term}` in case anything else goes wrong. ```APIDOC ## `start_link` ### Description Starts the Repo supervision tree. It returns `{:error, {:already_started, pid}}` if the repo is already started or `{:error, term}` in case anything else goes wrong. ### Callback Signature ```elixir @callback start_link(opts :: Keyword.t()) :: {:ok, pid()} | {:error, {:already_started, pid()}} | {:error, term()} ``` ### Options See the configuration in the moduledoc for options shared between adapters, for adapter-specific configuration see the adapter's documentation. ``` -------------------------------- ### Ecto Query Window Function Example Source: https://ecto.hexdocs.pm/Ecto.Query.WindowAPI.md Demonstrates the basic syntax for applying a window function with partitioning. ```Elixir from e in Employee, select: over(avg(e.salary), partition_by: e.depname) ``` -------------------------------- ### Join with Subquery to Get Book and Visitor Names Source: https://ecto.hexdocs.pm/aggregates-and-subqueries.md This example joins the `Lending` table with the `last_lendings` subquery and then with `book` and `visitor` associations to select their names. ```elixir from l in Lending, \ join: last in subquery(last_lendings), \ on: last.last_lending_id == l.id, \ join: b in assoc(l, :book), \ join: v in assoc(l, :visitor), \ select: {b.name, v.name} ``` -------------------------------- ### Ecto.ParameterizedType init Callback Example Source: https://ecto.hexdocs.pm/Ecto.ParameterizedType.md Example of how the init callback is called with schema and field information injected into the options. ```elixir MyParameterizedType.init([schema: "my_table", field: :my_field, opt1: :foo, opt2: nil]) ``` -------------------------------- ### ensure_all_started/2 Source: https://ecto.hexdocs.pm/Ecto.Adapter.md Ensures all applications necessary to run the adapter are started. This is part of the adapter's lifecycle management. ```APIDOC ## ensure_all_started/2 ### Description Ensure all applications necessary to run the adapter are started. ### Method Signature `ensure_all_started(config :: Keyword.t(), type :: :permanent | :transient | :temporary) :: {:ok, [atom()]} | {:error, atom()}` ``` -------------------------------- ### Basic Deletion Example Source: https://ecto.hexdocs.pm/Ecto.Repo.md This example demonstrates how to delete a Post struct using MyRepo.delete. It shows how to handle the successful deletion and error cases using a case statement. ```elixir post = MyRepo.get!(Post, 42) case MyRepo.delete(post) do {:ok, struct} -> # Deleted with success {:error, changeset} -> # Something went wrong end ``` -------------------------------- ### Start a Dynamic Ecto Repository Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Dynamically start an Ecto repository with a given name and connection credentials. This is useful for managing multiple database connections. ```elixir MyApp.Repo.start_link( name: :some_client, hostname: "client.example.com", username: "...", password: "...", pool_size: 1 ) ``` -------------------------------- ### Example: Ecto.Multi.exists? with Post Source: https://ecto.hexdocs.pm/Ecto.Multi.md Demonstrates using Ecto.Multi.exists?/4 with a Post query and then transacting the Multi. ```elixir Ecto.Multi.new() |> Ecto.Multi.exists?(:post, Post) |> MyApp.Repo.transact() ``` -------------------------------- ### Ecto.Multi.new Example Source: https://ecto.hexdocs.pm/Ecto.Multi.md Returns an empty Ecto.Multi struct. This is the starting point for defining a sequence of operations. ```elixir Ecto.Multi.new() |> Ecto.Multi.to_list() [] ``` -------------------------------- ### Example: Prepending SQL Commit Comments Source: https://ecto.hexdocs.pm/Ecto.Repo.md An example implementation of the `prepare_transaction` callback that prepends a SQL comment to commit statements using the `commit_comment` option. ```elixir @impl true def prepare_transaction(multi_or_fun, opts) do opts = Keyword.put_new_lazy(opts, :commit_comment, fn -> extract_comment(opts) end) {multi_or_fun, opts} end ``` -------------------------------- ### Example: Setting Dynamic Repo at Runtime Source: https://ecto.hexdocs.pm/Ecto.Repo.md Illustrates how to change the default dynamic repository for the current process to a specific named repository. ```elixir MyApp.Repo.put_dynamic_repo(:tenant_foo) ``` -------------------------------- ### Example Usage of insert_or_update Source: https://ecto.hexdocs.pm/Ecto.Repo.md This example demonstrates how to use `insert_or_update`. It first attempts to retrieve a post by ID. If found, it uses the existing post; otherwise, it builds a new one. The post is then passed through `Post.changeset` and finally to `MyRepo.insert_or_update`. ```elixir result = case MyRepo.get(Post, id) do nil -> %Post{id: id} # Post not found, we build one post -> post # Post exists, let's use it ] |> Post.changeset(changes) |> MyRepo.insert_or_update() case result do {:ok, struct} -> # Inserted or updated with success {:error, changeset} -> # Something went wrong end ``` -------------------------------- ### Ecto.Multi.update_all Example 1 Source: https://ecto.hexdocs.pm/Ecto.Multi.md Example demonstrating a simple bulk update operation using `Ecto.Multi.update_all/5` to set a new title for all posts. ```elixir Ecto.Multi.new() |> Ecto.Multi.update_all(:update_all, Post, set: [title: "New title"]) |> MyApp.Repo.transact() ``` -------------------------------- ### Example Usage of Repo.checkout Source: https://ecto.hexdocs.pm/Ecto.Adapter.md Demonstrates how to use `Repo.checkout/1` to ensure multiple related database operations run on the same connection, potentially improving performance. ```elixir Repo.checkout(fn -> for _ <- 1..100 do Repo.insert!(%Post{}) end end) ``` -------------------------------- ### init Source: https://ecto.hexdocs.pm/Ecto.Repo.md An optional callback executed when the repo starts or when configuration is read. It can be used for backwards compatibility and runtime configuration adjustments. ```APIDOC ## init ### Description An optional callback executed when the repo starts or when configuration is read. It can be used for backwards compatibility and runtime configuration adjustments. ### Callback Signature ```elixir @callback init(context :: :supervisor | :runtime, config :: Keyword.t()) :: {:ok, Keyword.t()} | :ignore ``` ### Parameters * `context` (:supervisor | :runtime) - The context in which the callback is invoked. `:supervisor` if the Repo supervisor is starting, `:runtime` if reading configuration without starting a process. * `config` (Keyword.t()) - The repository configuration as stored in the application environment. ### Returns * `{:ok, Keyword.t()}` - The updated list of configuration. * `:ignore` - Only valid when `context` is `:supervisor`. ``` -------------------------------- ### Get Repository Configuration Source: https://ecto.hexdocs.pm/Ecto.Repo.md Returns the adapter configuration stored in the :otp_app environment. If c:init/2 is implemented, it will be invoked with :runtime. ```elixir @callback config() :: Keyword.t() ``` -------------------------------- ### Define Multiple Repository Processes Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Demonstrates how to start multiple Ecto repository processes from the same module with distinct process names. ```elixir children = [ MyApp.Repo, {MyApp.Repo, name: :another_instance_of_repo} ] ``` -------------------------------- ### Understanding Changeset Action Source: https://ecto.hexdocs.pm/Ecto.Changeset.md Example demonstrating how the action field of a changeset is set, typically by Ecto.Repo operations like insert. ```elixir changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"}) {:error, changeset} = Repo.insert(changeset) changeset.action #=> :insert ``` -------------------------------- ### Ecto.Multi.update_all Example 2 Source: https://ecto.hexdocs.pm/Ecto.Multi.md Example showing a more complex `update_all` operation within a transaction, involving a `run` operation and a dynamic query based on previous changes. ```elixir Ecto.Multi.new() |> Ecto.Multi.run(:post, fn repo, _changes -> case repo.get(Post, 1) do nil -> {:error, :not_found} post -> {:ok, post} end end) |> Ecto.Multi.update_all(:update_all, fn %{post: post} -> # Others validations from(c in Comment, where: c.post_id == ^post.id, update: [set: [title: "New title"]]) end, []) |> MyApp.Repo.transact() ``` -------------------------------- ### Configuring a Repository with Ecto.Adapters.Postgres Source: https://ecto.hexdocs.pm/Ecto.Repo.md Example configuration for a PostgreSQL repository within the `:my_app` OTP application. This configuration includes database connection details. ```elixir config :my_app, Repo, database: "ecto_simple", username: "postgres", password: "postgres", hostname: "localhost" ``` -------------------------------- ### Example: Ecto.Multi.insert with a Post struct Source: https://ecto.hexdocs.pm/Ecto.Multi.md Demonstrates adding an insert operation for a Post struct to a Multi and then transacting it. ```elixir Ecto.Multi.new() |> Ecto.Multi.insert(:insert, %Post{title: "first"}) |> MyApp.Repo.transact() ``` -------------------------------- ### Start Repository in Supervisor Tree Source: https://ecto.hexdocs.pm/Ecto.html Integrate your Ecto repository into your application's supervision tree by adding it to the `children` list in your `application.ex` file. ```elixir def start(_type, _args) do children = [ MyApp.Repo, ] opts = [strategy: :one_for_one, name: MyApp.Supervisor] Supervisor.start_link(children, opts) end ``` -------------------------------- ### Example: Ecto.Multi.exists? with a function Source: https://ecto.hexdocs.pm/Ecto.Multi.md Shows how to use Ecto.Multi.exists?/4 with a function that returns a Post query, followed by transacting the Multi. ```elixir Ecto.Multi.new() |> Ecto.Multi.exists?(:post, fn _changes -> Post end) |> MyApp.Repo.transact() ``` -------------------------------- ### Intersect All Keyword Example (Unordered) Source: https://ecto.hexdocs.pm/Ecto.Query.md Shows an unordered intersect query using keyword arguments for select and intersect_all. ```elixir supplier_query = from s in Supplier, select: s.city from c in Customer, select: c.city, intersect_all: ^supplier_query ``` -------------------------------- ### Ecto.Multi.one Example Source: https://ecto.hexdocs.pm/Ecto.Multi.md Runs a query expecting one result and stores it in the Multi. The name must be unique. Options are the same as Ecto.Repo.one/2. ```elixir Ecto.Multi.new() |> Ecto.Multi.one(:post, Post) |> Ecto.Multi.one(:author, fn %{post: post} -> from(a in Author, where: a.id == ^post.author_id) end) |> MyApp.Repo.transact() ``` -------------------------------- ### Basic Window Function Usage Source: https://ecto.hexdocs.pm/Ecto.Query.WindowAPI.md Demonstrates how to use window functions with `over/2` by defining a window name. This is useful for reusing partitioning logic. ```elixir from e in Employee, select: {e.depname, e.empno, e.salary, over(avg(e.salary), :department)}, windows: [department: [partition_by: e.depname]] ``` -------------------------------- ### Ecto.Multi.update Example 1 Source: https://ecto.hexdocs.pm/Ecto.Multi.md Example demonstrating how to use `Ecto.Multi.update/4` to update a specific post by its ID. ```elixir post = MyApp.Repo.get!(Post, 1) changeset = Ecto.Changeset.change(post, title: "New title") Ecto.Multi.new() |> Ecto.Multi.update(:update, changeset) |> MyApp.Repo.transact() ``` -------------------------------- ### Intersect All Keyword Example (Ordered) Source: https://ecto.hexdocs.pm/Ecto.Query.md Illustrates an ordered intersect query using keyword arguments, including wrapping the result in a subquery for ordering. ```elixir supplier_query = from s in Supplier, select: s.city intersect_all_query = from c in Customer, select: c.city, intersect_all: ^supplier_query from s in subquery(intersect_all_query), order_by: s.city ``` -------------------------------- ### Ecto Changeset Errors Example Source: https://ecto.hexdocs.pm/getting-started.md An example of the keyword list format for errors within an Ecto changeset. ```elixir [first_name: {"can't be blank", [validation: :required]}, last_name: {"can't be blank", [validation: :required]}] ``` -------------------------------- ### Configuring a Repository with URL and Query Parameters Source: https://ecto.hexdocs.pm/Ecto.Repo.md Demonstrates configuring a repository using a URL that includes query parameters to override specific options like SSL and pool size. ```elixir config :my_app, Repo, url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10" ``` -------------------------------- ### config Source: https://ecto.hexdocs.pm/Ecto.Repo.md Returns the adapter configuration stored in the `:otp_app` environment. If the `c:init/2` callback is implemented in the repository, it will be invoked with the first argument set to `:runtime`. It does not consider the options given on `c:start_link/1`. ```APIDOC ## `config` ### Description Returns the adapter configuration stored in the `:otp_app` environment. If the `c:init/2` callback is implemented in the repository, it will be invoked with the first argument set to `:runtime`. It does not consider the options given on `c:start_link/1`. ### Callback Signature ```elixir @callback config() :: Keyword.t() ``` ``` -------------------------------- ### Example Data Structure with List of Addresses Source: https://ecto.hexdocs.pm/Ecto.Changeset.md An example of how data for a -many association might be represented as a list of maps. ```elixir %{"name" => "john doe", "addresses" => [ %{"street" => "somewhere", "country" => "brazil", "id" => 1}, %{"street" => "elsewhere", "country" => "poland"}, ]} ``` -------------------------------- ### Example Data Structure with Map of Addresses Source: https://ecto.hexdocs.pm/Ecto.Changeset.md An example of how data for a -many association might be represented as a map, where keys are integer indexes. ```elixir %{"name" => "john doe", "addresses" => %{ 0 => %{"street" => "somewhere", "country" => "brazil", "id" => 1}, 1 => %{"street" => "elsewhere", "country" => "poland"} }} ``` -------------------------------- ### Basic Repo Operations on Default Prefix Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md Demonstrates basic Ecto repository operations like `all` and `insert` which run on the default configured prefix. ```iex alias MyApp.Sample MyApp.Repo.all(Sample) Myspp.Repo.insert(%Sample{name: "mary"}) Myspp.Repo.all(Sample) ``` -------------------------------- ### Ecto.Multi.update Example 2 Source: https://ecto.hexdocs.pm/Ecto.Multi.md Example showing how to use `Ecto.Multi.update/4` with a function to dynamically generate a changeset for an update operation within a transaction. ```elixir Ecto.Multi.new() |> Ecto.Multi.insert(:post, %Post{title: "first"}) |> Ecto.Multi.update(:fun, fn %{post: post} -> Ecto.Changeset.change(post, title: "New title") end) |> MyApp.Repo.transact() ``` -------------------------------- ### List Ecto Tasks and Information Source: https://ecto.hexdocs.pm/Mix.Tasks.Ecto.md Run this command in your project's root directory to display all available Ecto tasks and their descriptions. ```bash mix ecto ``` -------------------------------- ### Example: Run query with Ecto.Multi.all Source: https://ecto.hexdocs.pm/Ecto.Multi.md Demonstrates using Ecto.Multi.all to run a query and then transact the changes. Supports passing a queryable directly or as a function of changes. ```elixir Ecto.Multi.new() |> Ecto.Multi.all(:all, Post) |> MyApp.Repo.transact() ``` ```elixir Ecto.Multi.new() |> Ecto.Multi.all(:all, fn _changes -> Post end) |> MyApp.Repo.transact() ``` -------------------------------- ### Perform Query on Dynamic Repository Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md After starting a dynamic repository, set it as the current repository using `put_dynamic_repo/1` before performing queries. This ensures queries target the correct, dynamically started repository. ```elixir MyApp.Repo.put_dynamic_repo(:some_client) MyApp.Repo.all(Post) ``` -------------------------------- ### Create Query with Hints Source: https://ecto.hexdocs.pm/Ecto.Query.md Use `from` with the `hints` option to specify query hints like `USE INDEX` or `TABLESAMPLE`. Hints must be compile-time strings or unsafe fragments. ```Elixir from p in Post, hints: ["USE INDEX FOO"], where: p.title == "title" ``` ```Elixir from p in Post, hints: "TABLESAMPLE SYSTEM(1)" ``` ```Elixir sample = "SYSTEM_ROWS(1)" from p in Post, hints: ["TABLESAMPLE", unsafe_fragment(^sample)] ``` -------------------------------- ### Get Association Entries with get_assoc Source: https://ecto.hexdocs.pm/Ecto.Changeset.md Retrieves association entries from changes or data. By default, returns normalized changesets. Use the :struct flag to get data as structs with changes applied. ```elixir iex> %Author{posts: [%Post{id: 1, title: "hello"}]} ...> |> change() ...> |> get_assoc(:posts) [%Ecto.Changeset{data: %Post{id: 1, title: "hello"}, changes: %{}}] ``` ```elixir iex> %Author{posts: [%Post{id: 1, title: "hello"}]} ...> |> cast(%{posts: [%{id: 1, title: "world"}]}, []) ...> |> cast_assoc(:posts) ...> |> get_assoc(:posts, :changeset) [%Ecto.Changeset{data: %Post{id: 1, title: "hello"}, changes: %{title: "world"}}] ``` ```elixir iex> %Author{posts: [%Post{id: 1, title: "hello"}]} ...> |> cast(%{posts: [%{id: 1, title: "world"}]}, []) ...> |> cast_assoc(:posts) ...> |> get_assoc(:posts, :struct) [%Post{id: 1, title: "world"}] ``` -------------------------------- ### Basic Insert with Ecto.Repo Source: https://ecto.hexdocs.pm/Ecto.Repo.md Demonstrates a typical insert operation using MyRepo.insert/1 and handling the result with a case statement. ```Elixir case MyRepo.insert(%Post{title: "Ecto is great"}) do {:ok, struct} -> # Inserted with success {:error, changeset} -> # Something went wrong end ``` -------------------------------- ### Dynamically Set Primary Repo for Replicas in Tests Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Configures replica repositories to use the primary `MyApp.Repo` connection pool during test execution. This setup is performed within a test's setup callback. ```elixir @replicas [ MyApp.Repo.Replica1, MyApp.Repo.Replica2, MyApp.Repo.Replica3, MyApp.Repo.Replica4 ] setup do for replica <- @replicas do replica.put_dynamic_repo(MyApp.Repo) end :ok end ``` -------------------------------- ### get!/3 Source: https://ecto.hexdocs.pm/Ecto.Repo.md Similar to `get/3` but raises `Ecto.NoResultsError` if no record was found. ```APIDOC ## get!/3 ### Description Similar to `c:get/3` but raises `Ecto.NoResultsError` if no record was found. ### Function Signature `get!(queryable :: Ecto.Queryable.t(), id :: term(), opts :: Keyword.t()) :: Ecto.Schema.t() | term()` ### Options * `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This will be applied to all `from` and `join`s in the query that did not have a prefix previously given either via the `:prefix` option on `join`/`from` or via `@schema_prefix` in the schema. For more information see the [Query Prefix section](m:Ecto.Query#module-query-prefix) of the `Ecto.Query` documentation. See the [Shared options section](#module-shared-options) at the module documentation for more options. ### Example MyRepo.get!(Post, 42) MyRepo.get!(Post, 42, prefix: "public") ``` -------------------------------- ### Initialize Adapter Supervision Tree Source: https://ecto.hexdocs.pm/Ecto.Adapter.md The init callback initializes the adapter's supervision tree. It returns the children specifications and adapter metadata as an {:ok, :supervisor.child_spec(), adapter_meta()} tuple. ```elixir @callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec(), adapter_meta()} ``` -------------------------------- ### Schema Reflection: Redact Fields Source: https://ecto.hexdocs.pm/Ecto.Schema.md Get a list of field names that should be redacted. ```elixir __schema__(:redact_fields) ``` -------------------------------- ### Ecto Query Join with Database Hints (MySQL Example) Source: https://ecto.hexdocs.pm/Ecto.Query.md Apply database-specific hints to influence query execution, such as index selection. Hints must be static compile-time strings. ```Elixir from p in Post, join: c in Comment, hints: ["USE INDEX FOO", "USE INDEX BAR"], where: p.id == c.post_id, select: c ``` -------------------------------- ### Schema Reflection: Field Source Source: https://ecto.hexdocs.pm/Ecto.Schema.md Get the alias of the source for a given field. ```elixir __schema__(:field_source, field) ``` -------------------------------- ### Schema Reflection: Embeds Source: https://ecto.hexdocs.pm/Ecto.Schema.md Get a list of all embedded field names defined in the schema. ```elixir __schema__(:embeds) ``` -------------------------------- ### Schema Reflection: Associations Source: https://ecto.hexdocs.pm/Ecto.Schema.md Get a list of all association field names defined in the schema. ```elixir __schema__(:associations) ``` -------------------------------- ### Successful Update Result Source: https://ecto.hexdocs.pm/getting-started.md Example of the successful return value from `Friends.Repo.update`, containing the updated record. ```elixir {"ok", %Friends.Person{__meta__: #Ecto.Schema.Metadata<:loaded, "people">, age: 29, first_name: "Ryan", id: 1, last_name: "Bigg"}} ``` -------------------------------- ### Ecto.Multi.prepend Example Source: https://ecto.hexdocs.pm/Ecto.Multi.md Prepends the second Multi to the first. All names must be unique within both structures. ```elixir iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end) iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end) iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys [:right, :left] ``` -------------------------------- ### get_dynamic_repo Source: https://ecto.hexdocs.pm/Ecto.Repo.md Gets the atom name or PID of the currently configured dynamic repository for the current process. ```APIDOC ## `get_dynamic_repo` ### Description Returns the atom name or pid of the current repository. See `c:put_dynamic_repo/1` for more information. ### Returns - `atom() | pid()`: The name or PID of the current dynamic repository. ``` -------------------------------- ### Get Associated Data with Ecto.assoc/3 Source: https://ecto.hexdocs.pm Uses `Ecto.assoc/3` to retrieve all associated comments for a given post. ```elixir import Ecto # Get all comments for the given post Repo.all assoc(post, :comments) ``` -------------------------------- ### Configure Database Connection Source: https://ecto.hexdocs.pm/getting-started.md Sets up the connection details for the PostgreSQL database in config/config.exs. ```elixir config :friends, Friends.Repo, database: "friends", username: "user", password: "pass", hostname: "localhost" ``` -------------------------------- ### Migration for belongs_to Association Source: https://ecto.hexdocs.pm/Ecto.Schema.md Example migration for a 'comments' table with a 'post_id' column referencing the 'posts' table. ```Elixir add :post_id, references(:posts, on_delete: :delete_all), null: false ``` -------------------------------- ### Using the Encapsulated Dynamic Repository Function Source: https://ecto.hexdocs.pm/replicas-and-dynamic-repositories.md Demonstrates how to call the `with_dynamic_repo/2` function to perform operations on a dynamic repository. The function handles the setup and teardown, allowing the callback to focus on the database operations. ```elixir credentials = [ hostname: "client.example.com", username: "...", password: "..." ] MyApp.Repo.with_dynamic_repo(credentials, fn -> MyApp.Repo.all(Post) end) ``` -------------------------------- ### Ecto Changeset Errors with Length Validation Source: https://ecto.hexdocs.pm/getting-started.md An example of changeset errors including a length validation rule. ```elixir [first_name: {"can't be blank", [validation: :required]}, last_name: {"can't be blank", [validation: :required]}, bio: {"should be at least %{count} character(s)", [count: 15, validation: :length, kind: :min, type: :string]}] ``` -------------------------------- ### Query with Join and prepare_query Source: https://ecto.hexdocs.pm/multi-tenancy-with-foreign-keys.md Illustrates a query that joins posts with comments, highlighting how prepare_query applies to the main query but not the join. ```elixir MyApp.Repo.put_org_id(some_org_id) MyApp.Repo.all( from p in Post, join: c in assoc(p, :comments) ) ``` -------------------------------- ### Ecto Repo insert_all with Placeholders Source: https://ecto.hexdocs.pm/Ecto.Repo.md Demonstrates how to use placeholders with Ecto.Repo.insert_all/3 to reduce data transfer when multiple entries share the same value for a field. Requires a database that supports index parameters (e.g., not MySQL). ```elixir placeholders = %{blob: large_blob_of_text(...)} entries = [ %{title: "v1", body: {:placeholder, :blob}}, %{title: "v2", body: {:placeholder, :blob}} ] Repo.insert_all(Post, entries, placeholders: placeholders) ``` -------------------------------- ### Create a basic changeset Source: https://ecto.hexdocs.pm/Ecto.Changeset.md Demonstrates creating a new changeset from a struct. The changeset is initially valid with no changes. ```elixir iex> changeset = change(%Post{}) %Ecto.Changeset{...} iex> changeset.valid? true iex> changeset.changes %{} ``` -------------------------------- ### Create Sample Table Migration Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md Defines a database migration to create the 'samples' table with a 'name' field and timestamps. ```elixir defmodule MyApp.Repo.Migrations.CreateSample do use Ecto.Migration def change do create table(:samples) do add :name, :string timestamps() end end end ``` -------------------------------- ### Ecto Repo get_by! Example Source: https://ecto.hexdocs.pm/Ecto.Repo.md Similar to get_by but raises Ecto.NoResultsError if no record was found. Raises if more than one entry. ```elixir MyRepo.get_by!(Post, title: "My post") ``` ```elixir MyRepo.get_by!(Post, [title: "My post"], prefix: "public") ``` -------------------------------- ### Configuring Repository with IPv6 Support Source: https://ecto.hexdocs.pm/Ecto.Repo.md Example configuration for a repository when the database host resolves to an IPv6 address. It includes the `socket_options: [:inet6]` to enable IPv6. ```elixir import Mix.Config config :my_app, MyApp.Repo, hostname: "db12.dc0.comp.any", socket_options: [:inet6], ... ``` -------------------------------- ### Preloading has_one :through Association Source: https://ecto.hexdocs.pm/Ecto.Schema.md Demonstrates preloading a `has_one` :through association. This example fetches a comment and preloads its associated permalink. ```Elixir # Get a preloaded comment [comment] = Repo.all(Comment) |> Repo.preload(:post_permalink) comment.post_permalink #=> %Permalink{...} ``` -------------------------------- ### Configure Ecto Repository (Initial) Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md Initial configuration for the Ecto repository, including database credentials and connection pool size. Defaults to the 'public' prefix. ```elixir config :my_app, MyApp.Repo, username: "postgres", password: "postgres", database: "demo", hostname: "localhost", pool_size: 10 ``` -------------------------------- ### Writable Many-to-Many Association Data Source: https://ecto.hexdocs.pm/polymorphic-associations-with-many-to-many.md Example of data structure for writable `many_to_many` associations, suitable for form submissions. ```elixir %{"todo_list" => %{ "title" => "shipping list", "todo_items" => %{ 0 => %{"description" => "bread"}, 1 => %{"description" => "eggs"}, } }} ``` -------------------------------- ### Run Migrations with Specific Prefixes Source: https://ecto.hexdocs.pm/multi-tenancy-with-query-prefixes.md Invoke `mix ecto.migrate` with the `--prefix` option to apply migrations to a specific tenant's database schema. Repeat for each prefix. ```bash $ mix ecto.migrate --prefix "prefix_1" $ mix ecto.migrate --prefix "prefix_2" $ mix ecto.migrate --prefix "prefix_3" ... $ mix ecto.migrate --prefix "prefix_128" ``` -------------------------------- ### Applying Changeset to Repository Source: https://ecto.hexdocs.pm/Ecto.html Demonstrates how to use the `Repo.update/2` function with a changeset to update a user record. It shows how to handle successful updates and errors. ```Elixir case Repo.update(changeset) do {:ok, user} -> # user updated {:error, changeset} -> # an error occurred end ``` -------------------------------- ### Query with Preloaded Self-Referencing Associations Source: https://ecto.hexdocs.pm/self-referencing-many-to-many.md Example of querying Person records and preloading both the direct and reverse many-to-many relationships. ```elixir iex> preloads = [:relationships, :reverse_relationships] iex> people = Repo.all from p in Person, preload: preloads [ MyApp.Accounts.Person< ... relationships: [ MyApp.Accounts.Person< id: ..., ... > ] >, MyApp.Accounts.Person< ... reverse_relationships: [ MyApp.Accounts.Person< id: ..., ... > ] > ] ``` -------------------------------- ### Get Repository Adapter Source: https://ecto.hexdocs.pm/Ecto.Repo.md Returns the Ecto adapter associated with the repository. This is useful for introspection or when interacting directly with the adapter. ```elixir @callback __adapter__() :: Ecto.Adapter.t() ``` -------------------------------- ### Ecto Repo init Callback Signature Source: https://ecto.hexdocs.pm/Ecto.Repo.md Defines the signature for the `init` callback, which is executed when the repository starts or configuration is read. It accepts context and configuration, returning either an updated configuration or `:ignore`. ```elixir @callback init(context :: :supervisor | :runtime, config :: Keyword.t()) :: {:ok, Keyword.t()} | :ignore ``` -------------------------------- ### Schema Reflection: Autogenerate Fields Source: https://ecto.hexdocs.pm/Ecto.Schema.md Get a list of field names that are auto-generated on insert, excluding the primary key. ```elixir __schema__(:autogenerate_fields) ``` -------------------------------- ### Performing LIKE Queries Source: https://ecto.hexdocs.pm/Ecto.Query.API.md Demonstrates the `like/2` function for pattern matching in strings, translating to SQL LIKE. Behavior varies by database (case-sensitive on PostgreSQL). ```Elixir from p in Post, where: like(p.body, "Chapter%") ``` -------------------------------- ### Get Ecto Schema Metadata Source: https://ecto.hexdocs.pm/Ecto.html Retrieves metadata from a given struct. Use to check the persistence state of a struct. ```elixir iex> Ecto.get_meta(changeset.data, :state) :built ``` -------------------------------- ### Ordering with Piped Functions Source: https://ecto.hexdocs.pm/Ecto.Query.md Demonstrates using `order_by` with piped functions and specific sort directions. ```Elixir City |> order_by([c], asc: c.name, desc: c.population) ``` ```Elixir City |> order_by(asc: :name) # Sorts by the cities name ``` ```Elixir City |> order_by(^order_by_param) # Keyword list ``` -------------------------------- ### Query Composition Example Source: https://ecto.hexdocs.pm/Ecto.Query.md Demonstrates composing Ecto queries by building a base query and then extending it with additional conditions or selections. The `from` clause can accept another query as its source. ```Elixir query = from u in User, where: u.age > 18 query = from u in query, select: u.name ``` -------------------------------- ### all Source: https://ecto.hexdocs.pm/Ecto.Repo.md Fetches all entries from the data store matching the given query. It can optionally take a keyword list of options to modify the query's behavior, such as specifying a prefix. ```APIDOC ## all ### Description Fetches all entries from the data store matching the given query. ### Function Signature `all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: [Ecto.Schema.t() | term()] ### Parameters #### Queryable - `queryable` (Ecto.Queryable.t()) - The query to execute. #### Options - `opts` (Keyword.t()) - A keyword list of options. See Options section for details. ### Options - `:prefix` - The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). ### Raises - `Ecto.QueryError` - If query validation fails. ### Example ```elixir # Fetch all post titles query = from p in Post, select: p.title MyRepo.all(query) ``` ``` -------------------------------- ### Intersect All Expression Example (Unordered) Source: https://ecto.hexdocs.pm/Ecto.Query.md Demonstrates an unordered intersect query using Ecto's expression API for select. ```elixir supplier_query = Supplier |> select([s], s.city) Customer |> select([c], c.city) |> intersect_all(^supplier_query) ``` -------------------------------- ### except_all with Simple Select (Unordered) Source: https://ecto.hexdocs.pm/Ecto.Query.md An example of `except_all` used with simple field selections, resulting in an unordered set difference. ```Elixir supplier_query = from s in Supplier, select: s.city from c in Customer, select: c.city, except_all: ^supplier_query ``` -------------------------------- ### Paginate Query with Limit and Offset Source: https://ecto.hexdocs.pm/Ecto.Query.md Dynamically set `limit` and `offset` for pagination using `from`. This example does not use `in` as `limit` and `offset` do not require data source references. ```Elixir def paginate(query, page, size) do from query, limit: ^size, offset: ^((page-1) * size) end ```