I used following migration to add timestamps to existing table and fill them with current time:
defmodule MyApp.AddTimestampsToChannels do
use Ecto.Migration
def up do
alter table(:channels) do
timestamps null: true
end
execute """
UPDATE channels
SET updated_at=NOW(), inserted_at=NOW()
"""
alter table(:channels) do
modify :inserted_at, :utc_datetime, null: false
modify :updated_at, :utc_datetime, null: false
end
end
def down do
alter table(:channels) do
remove :inserted_at
remove :updated_at
end
end
end
And there are other ways to do it. For example, if you have some related table, you can borrow initial timestamps from it:
execute """
UPDATE channels
SET inserted_at=u.inserted_at,
updated_at=u.updated_at
FROM
(SELECT id,
inserted_at,
updated_at
FROM accounts) AS u
WHERE u.id=channels.user_id;
"""