• Stars
    star
    161
  • Rank 233,470 (Top 5 %)
  • Language
    Elixir
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An adapter for using Timex DateTimes with Ecto

Timex Plugin for Ecto

Master Hex.pm Version

Getting Started

Learn how to add timex_ecto to your Elixir project and start using it.

NOTE: You must use Timex 3.0.2 or greater with timex_ecto 3.x!

Adding timex_ecto To Your Project

To use timex_ecto with your projects, edit your mix.exs file and add it as a dependency:

def application do
 [ applications: [:timex_ecto, ...], ...]
end

defp deps do
  [{:timex, "~> 3.0"},
   {:timex_ecto, "~> 3.0"}]
end

Adding Timex types to your Ecto models

defmodule User do
  use Ecto.Schema

  schema "users" do
    field :name, :string
    # Stored as an ISO date (year-month-day), reified as Date
    field :a_date,        Timex.Ecto.Date # Timex version of :date
    # Stored as an ISO time (hour:minute:second.fractional), reified as Timex.Duration
    field :a_time,        Timex.Ecto.Time # Timex version of :time
    # Stored as an ISO 8601 datetime in UTC (year-month-day hour:minute:second.fractional),
    # reified as DateTime in UTC
    field :a_datetime,    Timex.Ecto.DateTime # Timex version of :datetime
    # DateTimeWithTimezone is a special case, please see the `Using DateTimeWithTimezone` section!
    # Stored as a tuple of ISO 8601 datetime and timezone name ((year-month-day hour:minute:second.fractional, timezone)),
    # reified as DateTime in stored timezone
    field :a_datetimetz,  Timex.Ecto.DateTimeWithTimezone # A custom datatype (:datetimetz) implemented by Timex
    # Stored as an ISO 8601 datetime in UTC (year-month-day hour:minute:second.fractional),
    # reified as DateTime in local timezone
    field :a_timestamptz, Timex.Ecto.TimestampWithTimezone # Timex version of :timestamptz
  end
end

Using DateTimeWithTimezone

Please see the documentation here.

Change the default timestamps type of Ecto's timestamps macro

According to the documentation for Ecto.Schema.timestamps/1, it is simple to change the default timestamps type to others by setting @timestamps_opts. For example, you can use Timex.Ecto.TimestampWithTimezone with the following options.

defmodule User do
  use Ecto.Schema

  @timestamps_opts [type: Timex.Ecto.TimestampWithTimezone,
                    autogenerate: {Timex.Ecto.TimestampWithTimezone, :autogenerate, []}]

  schema "users" do
    field :name, :string
    timestamps()
  end
end

Using Timex with Ecto's timestamps macro

Super simple! Your timestamps will now be Timex.Ecto.DateTime structs instead of Ecto.DateTime structs.

defmodule User do
  use Ecto.Schema

  @timestamps_opts [type: Timex.Ecto.DateTime]

  schema "users" do
    field :name, :string
    timestamps()
  end
end

Using with Phoenix

Phoenix allows you to apply defaults globally to Ecto models via web/web.ex by changing the model function like so:

def model do
  quote do
    use Ecto.Schema

    @timestamps_opts [type: Timex.Ecto.DateTime]
  end
end

By doing this, you bring the Timex timestamps into scope in all your models.

Precision

By default Timex will generate a timestamp to the nearest second. If you would like to generate a timestamp with more precision you can pass the option usec: true to the macro. This will configure Timex to generate timestamps down to the microsecond level of precision.

@timestamps_opts [type: Timex.Ecto.DateTime,
                  autogenerate: {Timex.Ecto.DateTime, :autogenerate, [:usec]}]

Example Usage

The following is a simple test app I built for vetting this plugin:

defmodule EctoTest.Repo do
  use Ecto.Repo, otp_app: :timex_ecto_test
end

defmodule EctoTest.User do
  use Ecto.Schema

  @timestamps_opts [type: Timex.Ecto.DateTime,
                    autogenerate: {Timex.Ecto.DateTime, :autogenerate, []}]

  schema "users" do
    field :name, :string
    field :date_test,        Timex.Ecto.Date
    field :time_test,        Timex.Ecto.Time
    field :datetime_test,    Timex.Ecto.DateTime
    field :datetimetz_test,  Timex.Ecto.DateTimeWithTimezone
    field :timestamptz_test, Timex.Ecto.TimestampWithTimezone

    timestamps()
  end
end

defmodule EctoTest do
  import Ecto.Query
  use Timex

  alias EctoTest.User
  alias EctoTest.Repo

  def seed do
    time        = Duration.now
    date        = Timex.today
    datetime    = Timex.now
    datetimetz  = Timezone.convert(datetime, "Europe/Copenhagen")
    timestamptz = Timex.local
    u = %User{name: "Paul", date_test: date, time_test: time, datetime_test: datetime, datetimetz_test: datetimetz, timestamptz_test: timestamptz}
    Repo.insert!(u)
  end

  def all do
    query = from u in User,
            select: u
    Repo.all(query)
  end
end

defmodule EctoTest.App do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec
    tree = [worker(EctoTest.Repo, [])]
    opts = [name: EctoTest.Sup, strategy: :one_for_one]
    Supervisor.start_link(tree, opts)
  end
end

And the results:

iex(1)> EctoTest.seed

14:45:43.461 [debug] INSERT INTO "users" ("date_test", "datetime_test", "datetimetz_test", "name", "time_test") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [{2015, 6, 25}, {{2015, 6, 25}, {19, 45, 43, 457000}}, {{{2015, 6, 25}, {21, 45, 43, 457000}}, "Europe/Copenhagen"}, "Paul", {19, 45, 43, 457000}] OK query=3.9ms
%EctoTest.User{__meta__: %Ecto.Schema.Metadata{source: "users",
  state: :loaded},
 date_test: ~D[2015-06-25],
 datetime_test: #<DateTime(2015-06-25T21:45:43.457Z Etc/UTC)>,
 datetimetz_test: #<DateTime(2015-06-25T21:45:43.457+02:00 Europe/Copenhagen)>,
 timestamptz_test: #<DateTime(2015-06-25T13:45:43.457-06:00 America/Chicago)>,
 name: "Paul", time_test: #<Duration(P45Y6M6DT19H45M43.456856S)>}
iex(2)> EctoTest.all

14:45:46.721 [debug] SELECT u0."id", u0."name", u0."date_test", u0."time_test", u0."datetime_test", u0."datetimetz_test" FROM "users" AS u0 [] OK query=0.7ms
[%EctoTest.User{__meta__: %Ecto.Schema.Metadata{source: "users",
   state: :loaded},
  date_test: ~D[2015-06-25],
  datetime_test: #<DateTime(2015-06-25T21:45:43.457Z Etc/UTC)>,
  datetimetz_test: #<DateTime(2015-06-25T21:45:43.457+02:00 Europe/Copenhagen)>,
  timestamptz_test: #<DateTime(2015-06-25T13:45:43.457-06:00 America/Chicago)>,
  name: "Paul", time_test: #<Duration(PT19H45M43S)>}]
iex(3)>

Additional Documentation

Documentation for Timex and timex_ecto are available here, and on hexdocs.

License

This project is MIT licensed. See the LICENSE file in this repo.

More Repositories

1

distillery

Simplify deployments in Elixir with OTP releases!
Elixir
2,944
star
2

timex

A complete date/time library for Elixir projects.
Elixir
1,732
star
3

swarm

Easy clustering, registration, and distribution of worker processes for Erlang/Elixir
Elixir
1,201
star
4

exrm

Automatically generate a release for your Elixir project!
Elixir
923
star
5

exprotobuf

Protocol Buffers in Elixir made easy!
Elixir
485
star
6

libgraph

A graph data structure library for Elixir projects
Elixir
454
star
7

conform

Easy, powerful, and extendable configuration tooling for releases.
Elixir
378
star
8

keys.js

Easy keybindings for browser applications!
JavaScript
360
star
9

alpine-elixir-phoenix

An Alpine Linux base image containing Elixir, Erlang, Node, Hex, and Rebar. Ready for Phoenix applications!
Makefile
349
star
10

alpine-elixir

A Dockerfile based on my alpine-erlang image for Elixir applications
Makefile
202
star
11

toml-elixir

An implementation of TOML for Elixir projects, compliant with the latest specification
Elixir
196
star
12

combine

A parser combinator library for Elixir projects
Elixir
194
star
13

libring

A fast consistent hash ring implementation in Elixir
Elixir
192
star
14

exirc

IRC client adapter for Elixir projects
Elixir
152
star
15

artificery

A toolkit for creating terminal user interfaces in Elixir
Elixir
121
star
16

alpine-erlang

An alpine image with Erlang installed, intended for releases
Dockerfile
82
star
17

strukt

Extends defstruct with schemas, changeset validation, and more
Elixir
71
star
18

ex_unit_clustered_case

An extension for ExUnit for simplifying tests against a clustered application
Elixir
57
star
19

uniq

Provides UUID generation, parsing, and formatting. Supports RFC 4122, and the v6 draft extension
Elixir
52
star
20

distillery-aws-example

An example application to go with the AWS guide in the Distillery documentation
Elixir
50
star
21

distillery-umbrella-test

An example Elixir application for working with umbella apps and Distillery.
Elixir
49
star
22

pluginhost

An example C# application which provides runtime extensibility via plugins
C#
31
star
23

picosat_elixir

Elixir + Erlang bindings for the PicoSAT solver
C
17
star
24

docker-release-toolkit

My personal toolkit for building releases with Docker
Makefile
16
star
25

distillery-test

Elixir application which demonstrates a bare-minimum release-ready app using Distillery.
Elixir
16
star
26

8bit-background

A sweet series of 8-bit backgrounds, which changes based on the time of day.
Shell
15
star
27

libswagger

A Swagger client library for Elixir projects
Elixir
15
star
28

stringex

A string extensions library for node.js
JavaScript
15
star
29

scaladiff

A diff library built in Scala, for Scala projects
Scala
13
star
30

dotfiles

My assorted dotfiles
Shell
10
star
31

resume

The TeX source for my current resume.
TeX
7
star
32

fogbugz-cli

FogBugz Command Line Client
Ruby
7
star
33

aria

An experiment in programming language design
7
star
34

s2i-alpine-base

An S2I base image using Alpine Linux
Python
5
star
35

RPNCalculator

Reverse Polish Notation calculator built in Scala for a impromptu code challenge at work
Scala
5
star
36

uniq_compat

A compatibility shim for ::elixir_uuid when used with :uniq
Elixir
4
star
37

aws-dist-test

Clone of distillery-aws-example to illustrate distribution
Elixir
4
star
38

centos7-elixir

A CentOS7 base image for use with the Distillery AWS guide
Dockerfile
4
star
39

firefly

TBD
Elixir
3
star
40

conform_exrm

Conform plugin for ExRM
Elixir
3
star
41

alpine-toolbox

A toolbox image based on Alpine Linux for when I want to troubleshoot things in my OpenShift cluster
Makefile
3
star
42

SharpTools

A collection of practical C# code to build upon
C#
2
star
43

functools

Functional programming tools for Go
Go
2
star
44

toolbox.js

A general purpose javascript utility library. Contains everything you need, and most anything worth having (other than DOM manipulation).
JavaScript
1
star
45

erl_tar2

A re-implementation of erl_tar to support common tar archive formats
Erlang
1
star
46

s2i-elixir

An S2I image which provides Elixir, Erlang, and Node.js
Shell
1
star
47

blog

My personal blog source
CSS
1
star
48

s2i-erlang

An S2I image which provides Erlang and Node.js
Shell
1
star