【发布时间】:2020-02-01 00:47:33
【问题描述】:
希望在 Ecto 架构和迁移中使用 DateTime,而不是默认的 NaiveDateTime,以及 PostgreSQL 中的 timestamptz,而不是默认的 timestamp(又名timestamp without time zone)。
【问题讨论】:
标签: postgresql elixir ecto
希望在 Ecto 架构和迁移中使用 DateTime,而不是默认的 NaiveDateTime,以及 PostgreSQL 中的 timestamptz,而不是默认的 timestamp(又名timestamp without time zone)。
【问题讨论】:
标签: postgresql elixir ecto
timestamptz 和 :utc_datetime
注意:Ecto.Migration.timestamps/1 (source) 全局配置始终可以在本地覆盖。
使用Ecto.Migration docs 中的:migration_timestamps 配置选项:
# in ./config/dev.exs (for example)
config :app, App.Repo, migration_timestamps: [type: :timestamptz]
并且可以像往常一样在迁移中使用Ecto.Migration.timestamps/1:
# ./priv/repo/migrations/20190718195828_create_users.exs
create table(:users) do
add :username, :string, null: false
timestamps()
end
Postgres 适配器将自动切换
将 Elixir 表示为 DateTime 从
NaiveDateTime.
使用Ecto.Migration.timestamps/1 的:type 选项:
defmodule App.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :username, :string, null: false
timestamps(type: :timestamptz)
end
end
end
:utc_datetime
Ecto 模式也需要修改为
使用:utc_datetime,否则他们会期望
NaiveDateTime 默认情况下。稍微修改一下
例如在
Ecto.Schema docs:
# Define a module to be used as base defmodule MyApp.Schema do defmacro __using__(_) do quote do use Ecto.Schema # In case one uses UUIDs @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id # ------------------------------------ @timestamps_opts [type: :utc_datetime] end end end # Now use MyApp.Schema to define new schemas defmodule MyApp.Comment do use MyApp.Schema schema "comments" do belongs_to :post, MyApp.Post timestamps() end end
defmodule ANV.Accounts.User do
use Ecto.Schema
# -- EITHER --------------------------
@timestamps_opts [type: :utc_datetime]
schema "users" do
field :username, :string
# -- OR -----------------------
timestamps(type: :utc_datetime)
end
DateTime
在 Elixir 中“仅处理“Etc/UTC”
日期时间”,但可以使用自定义配置
时区数据库,也就是tzdata
图书馆是
Time zones in PostgreSQL, Elixir and Phoenix 和 How to set timestamps to UTC DateTimes in Ecto
第一篇文章中的一个非常方便的表格:
+----------------------+------------------+------------------------+------------------------------+-----------------------------------+
| Ecto 3 type | Elixir type | Supports microseconds? | Supports DateTime functions? | Supports NaiveDateTime functions? |
+----------------------+------------------+------------------------+------------------------------+-----------------------------------+
| :utc_datetime_usec | DateTime | YES | YES | YES |
| :utc_datetime | DateTime | NO | YES | YES |
| :naive_datetime_usec | NaiveDateTime | YES | NO | YES |
| :naive_datetime | NaiveDateTime | NO | NO | YES |
+----------------------+------------------+------------------------+------------------------------+-----------------------------------+
【讨论】: