概述
介绍了 api 的各类写法之后,下边介绍创设 api 时与数据库连接的章程。
注 下边接受的工程的完整代码已主管解在:
http://git.oschina.net/wangyubin/phoenix-api
ecto 简介
ecto 其实是独立于 phoenix framework 的,它是 elixir
语言实现的用来访谈数据库的框架,相像于 ORM 可是和理念的 ORM
又稍稍不等同。 能够这么精晓,它是应用了 elixir
语言的动态性和函数式的天性,参照他事他说加以考察了守旧的 ORM
的优势后而开垦的新一代数据库访谈层。
ecto 的多个主要组件
- Ecto.Repo 数据库包装器, 通过它能够实践数据库的增删改查,
通过它配备数据库连接 - 埃克托.Schema 那是 ORM 的为主,定义了操作对象和尾部数据库表之间的映照
- 埃克托.Changeset 那是 Ecto 的叁个翻新的地点,在 Changeset
中,能够定义校验数据层合法性的点子,在真正写入数据库以前,对数据开展校验 - Ecto.Query 以 elixir 语法编写的询问,可防止止 SQL 注入等科学普及难点
ecto 使用示例
开创示范工程
-
新建筑工程程
$ mix new ecto_sample
-
增加正视 (mix.exs卡塔尔国
defp deps do
[{:postgrex, ">= 0.0.0"}, {:ecto, "~> 2.0.0"}
]
end -
设置使用音信 (mix.exs卡塔尔
def application do
[applications: [:logger, :postgrex, :ecto]]
end -
得到正视包
$ mix deps.get
数据库连接配置
# vi config/config.exs
config :ecto_sample, ecto_repos: [EctoSample.Repo]
config :ecto_sample, EctoSample.Repo,
adapter: Ecto.Adapters.Postgres,
database: "ecto_sample",
username: "iotalab",
password: "iotalab",
hostname: "localhost"
布置好数据库连接之后,就足以在指令行下创制数据库了
$ mix ecto.create
创建 model 和 migration 代码
首先,通过命令行创立三个用来生成表的的 users module。
$ mix ecto.gen.migration users
本条命令会在 priv/repo/migrations 下自动生成 migration
脚本,只然则脚本是空的。 下边先创设 users 表的内容,然后填充 migration
脚本的内容
# vi lib/ecto_models.ex
defmodule EctoSample.User do
use Ecto.Schema
schema "users" do
field :name, :string
field :password, :string
field :age, :integer
timestamps
end
end
# vi priv/repo/migrations/20160912131700_users.exs 这个文件是由上一条命令产生的
defmodule EctoSample.Repo.Migrations.Users do
use Ecto.Migration
def up do
create table(:users) do
add :name, :string
add :password, :string
add :age, :integer
timestamps
end
end
def down do
drop table(:users)
end
end
制造数量库表
始建命令特简单
$ mix ecto.migrate
行使示例
创制了四个粗略的表之后,就足以在指令行下测验是还是不是能够操作数据库了。
下边演示了增加生产数量三个 user 和 删除叁个 user 的经过。
$ iex -S mix
Erlang/OTP 19 [erts-8.0.2] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.3.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> u = %EctoSample.User{name: "wyb", password: "passwd", age: 33}
%EctoSample.User{__meta__: #Ecto.Schema.Metadata<:built, "users">, age: 33,
id: nil, inserted_at: nil, name: "wyb", password: "passwd", updated_at: nil}
iex(2)> EctoSample.Repo.insert(u)
22:09:51.433 [debug] QUERY OK db=4.4ms
INSERT INTO "users" ("age","name","password","inserted_at","updated_at") VALUES ($1,$2,$3,$4,$5) RETURNING "id" [33, "wyb", "passwd", {{2016, 9, 12}, {14, 9, 51, 0}}, {{2016, 9, 12}, {14, 9, 51, 0}}]
{:ok,
%EctoSample.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, age: 33,
id: 3, inserted_at: #Ecto.DateTime<2016-09-12 14:09:51>, name: "wyb",
password: "passwd", updated_at: #Ecto.DateTime<2016-09-12 14:09:51>}}
iex(3)> u = %EctoSample.User{id: 3}
%EctoSample.User{__meta__: #Ecto.Schema.Metadata<:built, "users">, age: nil,
id: 3, inserted_at: nil, name: nil, password: nil, updated_at: nil}
iex(4)> EctoSample.Repo.delete(u)
22:11:28.960 [debug] QUERY OK db=3.4ms
DELETE FROM "users" WHERE "id" = $1 [3]
{:ok,
%EctoSample.User{__meta__: #Ecto.Schema.Metadata<:deleted, "users">, age: nil,
id: 3, inserted_at: nil, name: nil, password: nil, updated_at: nil}}
增加补充表达
而外纠正上边的文书之外,还会有下边2个地点须求修正,不然 EctoSample
模块不会加载:
# vi lib/ecto_sample.ex
defmodule EctoSample do
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
worker(EctoSample.Repo, []),
]
opts = [strategy: :one_for_one, name: EctoTest.Supervisor]
Supervisor.start_link(children, opts)
end
end
def application do
[applications: [:logger, :postgrex, :ecto],
mod: {EctoSample, []}] # <=== IMPORTANT !!!
end
api with postgresql
postgresql 安装与构造
以下安装配置是依附 CentOS7 的
# 安装 package
$ sudo yum install postgresql-server
# init db
$ sudo su - postgres
$ initdb -D /var/lib/pgsql/data
# start db
$ sudo systemctl start postgresql
# create user and database
$ sudo su - postgres
$ psql -U postgres -W # password is also "postgres"
postgres=# CREATE USER iotalab WITH PASSWORD 'iotalab';
postgres=# CREATE DATABASE test OWNER iotalab ENCODING 'UTF8';
安装能够局域网内访问
$ sudo su - postgres
$ cd /var/lib/pgsql/data
vim pg_hba.conf
host all all 0.0.0.0/0 md5
vim postgresql.conf
listen_addresses = '*'
长间距连接不上时试试禁止使用 iptables
$ sudo systemctl stop iptables
始建 数据库和表
-
给这一个工程加上 数据库的扶植其实创制的工程的时候,私下认可便是永葆数据库的。可是前边的亲自过问无需数据库,所以创制那一个工程的时候用了
–no-ecto 的参数。
重新创建工程,并将已写的代码复制进去就可以,此番创设工程时不加
–no-ecto 参数。$ mix phoenix.new phoenix_api
-
构造数据库连接并创造数据库 改正文件 config/dev.exs
# Configure your database config :phoenix_api, PhoenixApi.Repo, adapter: Ecto.Adapters.Postgres, username: "iotalab", password: "iotalab", database: "dev_db", hostname: "localhost", pool_size: 10
开创数据库
$ mix ecto.create
-
创办一张用来测验的表
$ mix phoenix.gen.model User users name:string email:string age:integer * creating web/models/user.ex * creating test/models/user_test.exs * creating priv/repo/migrations/20160913230129_create_user.exs
查看生成的文书,已经根据命令行的中参数,生成了相应的指标,能够窥见内部自动增添了
timestamps 方法,那些形式是自动抬高一些 updated_at, inserted_at
等通用时间字段。 然后经过命令行创立表:$ mix ecto.migrate 07:10:52.527 [info] == Running PhoenixApi.Repo.Migrations.CreateUser.change/0 forward 07:10:52.527 [info] create table users 07:10:52.537 [info] == Migrated in 0.0s
增加和删除改查 示例
在测验代码中布局了 增加和删除改查 的测量检验 case,然后用 mix test
命令来打开测量试验。
具体代码能够参见:http://git.oschina.net/wangyubin/phoenix-api/blob/master/test/models/user_test.exs
总结
使用 ecto 模块,操作数据库非常轻易,但是,写岀出色 api 的最首要照旧在于
api
的安排上,学习这些框架的意义是在意把一些通用繁杂的做事付出框架来拍卖,可以让大家把第后生可畏的精力放在专门的工作代码的打造上。
从那之后,phoenix framework api 连串的3篇也终结了。