Ecto.Migration.execute
execute
, go back to Ecto.Migration module for more information.
Executes arbitrary SQL, anonymous function or a keyword command.
The argument is typically a string, containing the SQL command to be executed. Keyword commands exist for non-SQL adapters and are not used in most situations.
Supplying an anonymous function does allow for arbitrary code to execute as
part of the migration. This is most often used in combination with repo/0
by library authors who want to create high-level migration helpers.
Reversible commands can be defined by calling execute/2
.
Examples
execute "CREATE EXTENSION postgres_fdw"
execute create: "posts", capped: true, size: 1024
execute(fn -> repo().query!("SELECT $1::integer + $2", [40, 2], [log: :info]) end)
execute(fn -> repo().update_all("posts", set: [published: true]) end)
Executes reversible SQL commands.
This is useful for database-specific functionality that does not
warrant special support in Ecto, for example, creating and dropping
a PostgreSQL extension. The execute/2
form avoids having to define
separate up/0
and down/0
blocks that each contain an execute/1
expression.
The allowed parameters are explained in execute/1
.
Examples
defmodule MyApp.MyMigration do
use Ecto.Migration
def change do
execute "CREATE EXTENSION postgres_fdw", "DROP EXTENSION postgres_fdw"
execute(&execute_up/0, &execute_down/0)
end
defp execute_up, do: repo().query!("select 'Up query …';", [], [log: :info])
defp execute_down, do: repo().query!("select 'Down query …';", [], [log: :info])
end