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: 2017-09-04
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, precision: 10, scale: 2
53   add :published_at, :utc_datetime
54   add :group_id, references(:groups)
55   add :object, :json
56
57   timestamps  # inserted_at and updated_at
58 end
59
60 create_if_not_exists table(:documents) do: ... end
61 ```
62
63 ### Other operations
64
65 ```elixir
66 alter table(:posts) do
67   add :summary, :text
68   modify :title, :text
69   remove :views
70 end
71 ```
72
73 ```elixir
74 rename table(:posts), :title, to: :summary
75 rename table(:posts), to: table(:new_posts)
76 ```
77
78 ```elixir
79 drop table(:documents)
80 drop_if_exists table(:documents)
81 ```
82
83 ```elixir
84 table(:documents)
85 table(:weather, prefix: :north_america)
86 ```
87
88 ### Indices
89
90 ```elixir
91 create index(:posts, [:slug], concurrently: true)
92 create unique_index(:posts, [:slug])
93 drop index(:posts, [:name])
94 ```
95
96 ### Execute SQL
97
98 ```elixir
99 execute "UPDATE posts SET published_at = NULL"
100 execute create: "posts", capped: true, size: 1024
101 ```
102
103 ## References
104
105 - [Ecto.Migration](http://devdocs.io/phoenix/ecto/ecto.migration)