···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+# The directory Mix will write compiled artifacts to.
66+/_build/
77+88+# If you run "mix test --cover", coverage assets end up here.
99+/cover/
1010+1111+# The directory Mix downloads your dependencies sources to.
1212+/deps/
1313+1414+# Where third-party dependencies like ExDoc output generated docs.
1515+/doc/
1616+1717+# Ignore .fetch files in case you like to edit your project deps locally.
1818+/.fetch
1919+2020+# If the VM crashes, it generates a dump, let's ignore it too.
2121+erl_crash.dump
2222+2323+# Also ignore archive artifacts (built via "mix archive.build").
2424+*.ez
2525+2626+# Ignore package tarball (built via "mix hex.build").
2727+ecto_view-*.tar
2828+2929+# Temporary files, for example, from tests.
3030+/tmp/
+73
LICENSES/Apache-2.0.txt
···11+Apache License
22+Version 2.0, January 2004
33+http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
1010+1111+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
1212+1313+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
1414+1515+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
1616+1717+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
1818+1919+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
2020+2121+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
2222+2323+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
2424+2525+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
2626+2727+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2828+2929+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3030+3131+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
3232+3333+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
3434+3535+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
3636+3737+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
3838+3939+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
4040+4141+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
4242+4343+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
4444+4545+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
4646+4747+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
4848+4949+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
5050+5151+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
5252+5353+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
5454+5555+END OF TERMS AND CONDITIONS
5656+5757+APPENDIX: How to apply the Apache License to your work.
5858+5959+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
6060+6161+Copyright [yyyy] [name of copyright owner]
6262+6363+Licensed under the Apache License, Version 2.0 (the "License");
6464+you may not use this file except in compliance with the License.
6565+You may obtain a copy of the License at
6666+6767+http://www.apache.org/licenses/LICENSE-2.0
6868+6969+Unless required by applicable law or agreed to in writing, software
7070+distributed under the License is distributed on an "AS IS" BASIS,
7171+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7272+See the License for the specific language governing permissions and
7373+limitations under the License.
+62
README.md
···11+<!--
22+SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
33+44+SPDX-License-Identifier: Apache-2.0
55+-->
66+77+# EctoView
88+99+Helper functions for creating database views using `Ecto.Query` helpers.
1010+1111+## Installation
1212+1313+Add `ecto_view` to your list of dependencies in `mix.exs`:
1414+1515+```elixir
1616+def deps do
1717+ [
1818+ {:ecto_view, "~> 1.0"}
1919+ ]
2020+end
2121+```
2222+2323+## Usage
2424+2525+```elixir
2626+defmodule MyApplication.Repo.Migration.CreateViewFoo do
2727+ use Ecto.Migration
2828+ use EctoView.Migration # This line **MUST** be after `use Ecto.Migration`
2929+3030+ def change do
3131+ query = from foo in "foos", # This **MUST** select from table name, no schemas allowed
3232+ where: foo.bar == 2137,
3333+ select: %{ # This **MUST** be a map of selected fields
3434+ a: foo.a,
3535+ b: foo.b
3636+ }
3737+3838+ create view("foos_view", query)
3939+ end
4040+end
4141+```
4242+4343+If you want, you can also create materialised view using `materialized_view/2`
4444+function.
4545+4646+If you create materialised view, then you can use `EctoView.refresh_materialized_view/3`
4747+function to refresh content of given view. If you will add:
4848+4949+```elixir
5050+defmodule MyApplication.Repo do
5151+ use Ecto.Repo, …
5252+ use EctoView
5353+5454+ # …
5555+end
5656+```
5757+5858+Then there will be a helper function `Repo.refresh_materialised_view/2` that
5959+will call respective function for that repo.
6060+6161+The docs can be found at [https://hexdocs.pm/ecto_view](https://hexdocs.pm/ecto_view).
6262+
···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+defmodule EctoView do
66+ @moduledoc """
77+ Helper functions for refreshing materialised views
88+ """
99+1010+ defmacro __using__([]) do
1111+ quote do
1212+ @behaviour unquote(__MODULE__)
1313+1414+ @impl unquote(__MODULE__)
1515+ def refresh_materialized_view(queryable, opts \\ []) do
1616+ unquote(__MODULE__).refresh_materialized_view(__MODULE__, queryable)
1717+ end
1818+ end
1919+ end
2020+2121+ @doc """
2222+ Refresh materialised view
2323+ """
2424+ @callback refresh_materialized_view(table :: Ecto.Queryable.t()) ::
2525+ :ok | {:error, term()}
2626+2727+ ## Implementation functions
2828+ @doc """
2929+ Refresh materialised view for given `queryable`.
3030+ """
3131+ def refresh_materialized_view(repo, queryable, opts \\ []) do
3232+ # This way we ensure that `schema` is properly escaped
3333+ schema = schema_for_query(Ecto.Queryable.to_query(queryable))
3434+3535+ repo.query("REFRESH MATERIALIZED VIEW \"#{schema}\"", opts)
3636+ end
3737+3838+ defp schema_for_query(%Ecto.Query{from: %Ecto.Query.FromExpr{source: {schema, _}}}) do
3939+ schema
4040+ end
4141+end
+145
lib/ecto_view/migration.ex
···11+defmodule EctoView.Migration do
22+ @moduledoc """
33+44+ """
55+66+ defmodule View do
77+ @moduledoc false
88+99+ defstruct [:name, :query, materialized?: false]
1010+ end
1111+1212+ defmodule InvalidSource do
1313+ defexception [:schema]
1414+1515+ @impl true
1616+ def message(%__MODULE__{schema: schema}) do
1717+ "You cannot query the schema module (#{inspect(schema)}) in migration, as it can fail in future. Use schema name as binary instead"
1818+ end
1919+ end
2020+2121+ defmodule InvalidSelect do
2222+ defexception [:ast]
2323+2424+ @impl true
2525+ def message(%__MODULE__{ast: ast}) do
2626+ "Selected values must be a map, got #{Macro.to_string(ast)}"
2727+ end
2828+ end
2929+3030+ defmodule MissingQuery do
3131+ defexception message: "Query is required for creating view"
3232+ end
3333+3434+ @doc false
3535+ defmacro __using__(_opts) do
3636+ create_mod =
3737+ case Macro.Env.lookup_import(__ENV__, {:create, 1}) do
3838+ [{_, mod}] -> mod
3939+ [] -> raise "Ecto.Migration is not imported"
4040+ end
4141+4242+ quote do
4343+ import unquote(create_mod), except: [create: 1, drop: 1, drop_if_exists: 1]
4444+ import unquote(__MODULE__)
4545+4646+ def create(%unquote(View){} = view), do: unquote(__MODULE__).__create_view__(view, false)
4747+ def create(other), do: unquote(create_mod).create(other)
4848+4949+ def create_or_replace(%unquote(View){} = view), do: unquote(__MODULE__).__create_view__(view, true)
5050+5151+ def drop(%View{} = view), do: unquote(__MODULE__).__drop__(view, false)
5252+ def drop(other), do: unquote(create_mod).drop(other)
5353+5454+ def drop_if_exists(%View{} = view), do: unquote(__MODULE__).__drop__(view, true)
5555+ def drop_if_exists(other), do: unquote(create_mod).drop(other)
5656+ end
5757+ end
5858+5959+ @doc false
6060+ def __create_view__(%View{name: name, query: query} = view, or_replace?) when query != nil do
6161+ {sql, []} = Ecto.Migration.repo().to_sql(:all, query)
6262+ or_replace = if or_replace?, do: "OR REPLACE ", else: ""
6363+ if_exist = if or_replace?, do: "IF NOT EXIST ", else: ""
6464+ materialized = if view.materialized?, do: "MATERIALIZED ", else: ""
6565+6666+ Ecto.Migration.execute(
6767+ "CREATE #{or_replace}#{materialized}VIEW #{name} AS #{sql}",
6868+ "DROP #{if_exist}#{materialized}VIEW #{name}"
6969+ )
7070+ end
7171+7272+ def __create_view__(_, _) do
7373+ raise MissingQuery
7474+ end
7575+7676+ @doc false
7777+ def __drop__(%View{name: name}, if_exists?) do
7878+ if_exist = if if_exists?, do: "IF NOT EXIST ", else: ""
7979+8080+ Ecto.Migration.execute("DROP #{if_exist}VIEW #{name}")
8181+ end
8282+8383+ @doc """
8484+ Returns view struct that can be given to `Ecto.Migration.create/1`
8585+8686+ ```elixir
8787+ create view("products_with_discount",
8888+ from(p in "products",
8989+ inner_join: d in "discounts",
9090+ on: d.product_id == p.id,
9191+ select: %{name: p.name}))
9292+ ```
9393+9494+ Passed `query` will be checked if that query:
9595+9696+ - Uses raw table name (usage of schemas is disallowed)
9797+9898+ This is required to prevent making migration in future by editing schema.
9999+ Each migration should be independent from the application code.
100100+101101+ - Uses `Ecto.Query.select/3` with map
102102+103103+ This is required to be able to set proper names for all columns in created
104104+ view. So in case of `%{foo: a.foo, bar: b.bar}` resulting view with 2
105105+ columns (`foo` and `bar`) containing respective selected fields.
106106+107107+ If any of the above is false, then it will be rejected.
108108+ """
109109+ def view(name), do: %View{name: name, query: nil}
110110+111111+ def view(name, query), do: %View{name: name, query: expand_select(query)}
112112+113113+ @doc """
114114+ Returns materialized view struct that can be given to `Ecto.Migration.create/1`
115115+116116+ See `view/2` for details.
117117+ """
118118+ def materialized_view(name, query),
119119+ do: %View{name: name, query: expand_select(query), materialized?: true}
120120+121121+ defp expand_select(
122122+ %Ecto.Query{select: %Ecto.Query.SelectExpr{expr: {:%{}, _, fields}} = select} = query
123123+ ) do
124124+ validate_source(query)
125125+126126+ encoded =
127127+ for {name, value} <- fields do
128128+ {:fragment, [], expr: value, raw: "AS #{name}"}
129129+ end
130130+131131+ %Ecto.Query{query | select: %Ecto.Query.SelectExpr{select | expr: encoded}}
132132+ end
133133+134134+ defp expand_select(%Ecto.Query{select: %Ecto.Query.SelectExpr{expr: ast}}) do
135135+ raise InvalidSelect, ast: ast
136136+ end
137137+138138+ defp validate_source(%Ecto.Query{from: %Ecto.Query.FromExpr{source: source}}) do
139139+ case source do
140140+ {schema, nil} when is_binary(schema) -> :ok
141141+ {_schema, mod} when is_atom(mod) ->
142142+ raise InvalidSource, schema: mod
143143+ end
144144+ end
145145+end
+54
mix.exs
···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+defmodule EctoView.MixProject do
66+ use Mix.Project
77+88+ def project do
99+ [
1010+ app: :ecto_view,
1111+ description: "Ecto helpers for creating and refreshing SQL views",
1212+ package: [
1313+ licenses: ["Apache-2.0"],
1414+ links: %{
1515+ "Tangled" => "https://tangled.org/hauleth.dev/ecto_view"
1616+ }
1717+ ],
1818+ version: "1.0.0",
1919+ elixir: "~> 1.12",
2020+ start_permanent: Mix.env() == :prod,
2121+ elixirc_paths: paths(Mix.env()),
2222+ deps: deps(),
2323+ docs: docs()
2424+ ]
2525+ end
2626+2727+ # Run "mix help compile.app" to learn about applications.
2828+ def application do
2929+ [
3030+ extra_applications: [:logger]
3131+ ]
3232+ end
3333+3434+ defp docs do
3535+ [
3636+ main: "readme",
3737+ extras: ["README.md"]
3838+ ]
3939+ end
4040+4141+ defp paths(env) when env in ~w[dev test]a, do: ~w[lib test/support]
4242+ defp paths(_), do: ~w[lib]
4343+4444+ # Run "mix help deps" to learn about dependencies.
4545+ defp deps do
4646+ [
4747+ {:ecto_sql, "~> 3.0"},
4848+ {:postgrex, ">= 0.0.0", only: [:dev]},
4949+ {:ex_doc, ">= 0.0.0", only: [:dev]}
5050+ # {:dep_from_hexpm, "~> 0.3.0"},
5151+ # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
5252+ ]
5353+ end
5454+end
···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+defmodule EctoView.MigrationTest do
66+ use ExUnit.Case
77+88+ import Ecto.Query
99+1010+ @subject EctoView.Migration
1111+1212+ doctest @subject
1313+1414+ defmodule ExampleSchema do
1515+ use Ecto.Schema
1616+1717+ schema "example_schema", do: nil
1818+ end
1919+2020+ test "using schema as a source for view fails" do
2121+ query = from(e in ExampleSchema, select: %{})
2222+2323+ assert_raise @subject.InvalidSource, fn ->
2424+ @subject.view("foo", query)
2525+ end
2626+ end
2727+2828+ test "using schema as a source for materialized view fails" do
2929+ query = from(e in ExampleSchema, select: %{})
3030+3131+ assert_raise @subject.InvalidSource, fn ->
3232+ @subject.materialized_view("foo", query)
3333+ end
3434+ end
3535+end
+9
test/ecto_view_test.exs
···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+defmodule EctoViewTest do
66+ use ExUnit.Case
77+88+ doctest EctoView
99+end
+12
test/support/repo.ex
···11+# SPDX-FileCopyrightText: 2026 Łukasz Niemier <~@hauleth.dev>
22+#
33+# SPDX-License-Identifier: Apache-2.0
44+55+defmodule EctoView.Repo do
66+ @moduledoc false
77+88+ use Ecto.Repo,
99+ otp_app: :ecto_view,
1010+ adapter: Ecto.Adapters.Postgres
1111+ use EctoView
1212+end