LoginSignup
4
1

More than 3 years have passed since last update.

Phoenix Frameworkでデータベースを使う

Last updated at Posted at 2019-04-20

Phoenix Framework を導入からの続き

動作環境

elixir1.8
Phoenix Framework1.4.3

PostgreSQL

MySQLなど他のデータベースを使用することも可能ですが、
Phoenix FrameworkのデフォルトデータベースはPostgreSQLのため、
PostgreSQLを使用します。

※WSL2でPostgreSQLを使用する場合、下の設定が必要

postgresql.conf
 data_sync_retry = on
 fsync = off

Ecto

Phoenix Frameworkで使用されているElixir用のクエリ作成ツールとデータベースラッパーです。
mixからectoを実行してデータベースを作成します。

mixから利用できるectoのコマンドは下のコマンドで確認ができます。

mix help | grep ecto
mix ecto               # Prints Ecto help information
mix ecto.create        # Creates the repository storage
mix ecto.drop          # Drops the repository storage
mix ecto.dump          # Dumps the repository database structure
mix ecto.gen.migration # Generates a new migration for the repo
mix ecto.gen.repo      # Generates a new repository
mix ecto.load          # Loads previously dumped database structure
mix ecto.migrate       # Runs the repository migrations
mix ecto.migrations    # Displays the repository migration status
mix ecto.reset         # Alias defined in mix.exs
mix ecto.rollback      # Rolls back the repository migrations
mix ecto.setup         # Alias defined in mix.exs
mix phx.new.ecto       # Creates a new Ecto project within an umbrella project

初期設定

config/dev.exs にDBへの接続設定を記入します。

PostgreSQLを使う場合下のコマンドでユーザーとデータベースを作成しておく必要があります。

createuser --createdb --username=postgres --pwprompt ユーザー名
createdb データベース名 --encoding=UTF-8 --lc-collate=C --lc-ctype=C --owner=ユーザー名 --template=template0
config/dev.exs
config :app, App.Repo,
  username: "ユーザー名",
  password: "パスワード",
  database: "データベース名",
  hostname: "ホスト名",
  pool_size: 10

データベース作成

下のコマンドでデータベースを作成します。

mix ecto.create

初期設定で設定したdatabaseの値でデータベースが作成されます。

データベース削除

データベースを削除する場合は下のコマンドで削除できます。

mix ecto.drop

テーブル作成

Phoenix Frameworkのリファレンスに書かれているテーブルをそのまま作成してみます。
下のコマンドで下の2ファイルが作成されます。

mix phx.gen.schema Blog.Post blog_posts title:string views:integer

lib/app/blog/post.ex ⇒モデルファイル
priv/repo/migrations/xxxxxxxxxxxxxx_create_blog_posts.exs⇒マイグレーションファイル

下のコマンドでマイグレーションファイルを元にテーブルを作成します。

mix ecto.migrate

Phoenix Frameworkがサポートしているデータ型などは下のページに掲載されています。
https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Schema.html

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1