OSDN Git Service

Regular updates
[twpd/master.git] / phoenix-migrations.md
1 ---
2 title: "Phoenix: Ecto migrations"
3 category: Elixir
4 layout: 2017/sheet
5 weight: -1
6 updated: 2020-02-23
7 ---
8
9 ### Creating
10
11 ```bash
12 $ mix ecto.gen.migration update_posts_table
13   creating priv/repo/migrations/20160602085927_update_posts_table.exs
14   ยทยทยท
15 ```
16
17 ```bash
18 $ mix ecto.migrate
19 $ mix ecto.rollback
20 ```
21
22 Creates a migration (no models).
23
24 ### Creating models
25
26 ```bash
27 $ mix phoenix.gen.model Message messages user_id:integer content:text
28 ```
29
30 This is only for Phoenix 1.2 or older; models aren't available in Phoenix 1.3+.
31
32 ### Creating context
33
34 ```bash
35 $ mix phx.gen.context Images Album albums title:string subtitle:string privacy:string
36 ```
37  
38 ## Migration functions
39
40 ### Creating tables
41
42 ```elixir
43 create table(:documents) do
44   add :title, :string
45   add :title, :string, size: 40
46   add :title, :string, default: "Hello"
47   add :title, :string, default: fragment("now()")
48   add :title, :string, null: false
49   add :body, :text
50   add :age, :integer
51   add :price, :float
52   add :price, :float
53   add :price, :decimal, precision: 10, scale: 2
54   add :published_at, :utc_datetime
55   add :group_id, references(:groups)
56   add :object, :json
57
58   timestamps  # inserted_at and updated_at
59 end
60
61 create_if_not_exists table(:documents) do: ... end
62 ```
63
64 ### Other operations
65
66 ```elixir
67 alter table(:posts) do
68   add :summary, :text
69   modify :title, :text
70   remove :views
71 end
72 ```
73
74 ```elixir
75 rename table(:posts), :title, to: :summary
76 rename table(:posts), to: table(:new_posts)
77 ```
78
79 ```elixir
80 drop table(:documents)
81 drop_if_exists table(:documents)
82 ```
83
84 ```elixir
85 table(:documents)
86 table(:weather, prefix: :north_america)
87 ```
88
89 ### Indices
90
91 ```elixir
92 create index(:posts, [:slug], concurrently: true)
93 create unique_index(:posts, [:slug])
94 drop index(:posts, [:name])
95 ```
96
97 ### Execute SQL
98
99 ```elixir
100 execute "UPDATE posts SET published_at = NULL"
101 execute create: "posts", capped: true, size: 1024
102 ```
103
104 ## References
105
106 - [Ecto.Migration](http://devdocs.io/phoenix/ecto/ecto.migration)