schema_migration.ex (2090B)
1 defmodule Ecto.Migration.SchemaMigration do 2 # Defines a schema that works with a table that tracks schema migrations. 3 # The table name defaults to `schema_migrations`. 4 @moduledoc false 5 use Ecto.Schema 6 7 import Ecto.Query, only: [from: 2] 8 9 @primary_key false 10 schema "schema_migrations" do 11 field :version, :integer 12 timestamps updated_at: false 13 end 14 15 # The migration flag is used to signal to the repository 16 # we are in a migration operation. 17 @default_opts [ 18 timeout: :infinity, 19 log: false, 20 schema_migration: true, 21 telemetry_options: [schema_migration: true] 22 ] 23 24 def ensure_schema_migrations_table!(repo, config, opts) do 25 {repo, source} = get_repo_and_source(repo, config) 26 table_name = String.to_atom(source) 27 table = %Ecto.Migration.Table{name: table_name, prefix: opts[:prefix]} 28 meta = Ecto.Adapter.lookup_meta(repo.get_dynamic_repo()) 29 30 commands = [ 31 {:add, :version, :bigint, primary_key: true}, 32 {:add, :inserted_at, :naive_datetime, []} 33 ] 34 35 repo.__adapter__().execute_ddl(meta, {:create_if_not_exists, table, commands}, @default_opts) 36 end 37 38 def versions(repo, config, prefix) do 39 {repo, source} = get_repo_and_source(repo, config) 40 {repo, from(m in source, select: type(m.version, :integer)), [prefix: prefix] ++ @default_opts} 41 end 42 43 def up(repo, config, version, opts) do 44 {repo, source} = get_repo_and_source(repo, config) 45 46 %__MODULE__{version: version} 47 |> Ecto.put_meta(source: source) 48 |> repo.insert(default_opts(opts)) 49 end 50 51 def down(repo, config, version, opts) do 52 {repo, source} = get_repo_and_source(repo, config) 53 54 from(m in source, where: m.version == type(^version, :integer)) 55 |> repo.delete_all(default_opts(opts)) 56 end 57 58 def get_repo_and_source(repo, config) do 59 {Keyword.get(config, :migration_repo, repo), 60 Keyword.get(config, :migration_source, "schema_migrations")} 61 end 62 63 defp default_opts(opts) do 64 Keyword.merge( 65 @default_opts, 66 [prefix: opts[:prefix], log: Keyword.get(opts, :log_migrator_sql, false)] 67 ) 68 end 69 end