Helpers for using SQL views with Ecto
at master 62 lines 1.4 kB view raw view rendered
1<!-- 2SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev> 3 4SPDX-License-Identifier: Apache-2.0 5--> 6 7# EctoView 8 9Helper functions for creating database views using `Ecto.Query` helpers. 10 11## Installation 12 13Add `ecto_view` to your list of dependencies in `mix.exs`: 14 15```elixir 16def deps do 17 [ 18 {:ecto_view, "~> 1.0"} 19 ] 20end 21``` 22 23## Usage 24 25```elixir 26defmodule MyApplication.Repo.Migration.CreateViewFoo do 27 use Ecto.Migration 28 use EctoView.Migration # This line **MUST** be after `use Ecto.Migration` 29 30 def change do 31 query = from foo in "foos", # This **MUST** select from table name, no schemas allowed 32 where: foo.bar == 2137, 33 select: %{ # This **MUST** be a map of selected fields 34 a: foo.a, 35 b: foo.b 36 } 37 38 create view("foos_view", query) 39 end 40end 41``` 42 43If you want, you can also create materialised view using `materialized_view/2` 44function. 45 46If you create materialised view, then you can use `EctoView.refresh_materialized_view/3` 47function to refresh content of given view. If you will add: 48 49```elixir 50defmodule MyApplication.Repo do 51 use Ecto.Repo, 52 use EctoView 53 54 # … 55end 56``` 57 58Then there will be a helper function `Repo.refresh_materialised_view/2` that 59will call respective function for that repo. 60 61The docs can be found at [https://hexdocs.pm/ecto_view](https://hexdocs.pm/ecto_view). 62