2016-08-15 26 views
1

我正在生成一些測試數據。在一個循環中生成記錄,它們失靈。這是一個藥劑或Postgres的東西?

posts = for i <- 0..10 do 
    :timer.sleep 100 
    {:ok, post} = Post.changeset(%Post{},%{title: "Some Post #{i}"}) |> Repo.insert 
    post.title 
end |> Enum.reverse 
all_posts = Repo.all(from p in Post, order_by: [desc: :inserted_at]) |> Enum.map(&(&1.title)) 
assert all_posts == posts 

然而,這失敗了。

Assertion with == failed 
    code: all_posts == posts 
    lhs: ["Some Post 10", "Some Post 1", "Some Post 2", "Some Post 3", "Some Post 4", "Some Post 0", "Some Post 6", "Some Post 7", "Some Post 8", "Some Post 9", "Some Post 5"] 
    rhs: ["Some Post 10", "Some Post 9", "Some Post 8", "Some Post 7", "Some Post 6", "Some Post 5", "Some Post 4", "Some Post 3", "Some Post 2", "Some Post 1", "Some Post 0"] 
    stacktrace: 
     test/models/post_test.exs:35: (test) 

如果我將睡眠衝擊到1000毫秒,那麼它可以工作,但它確實應該沒有任何睡眠,對嗎?這是一個Postgres或Elixir的東西。或者我不知道Elixir的循環如何工作?這些是按順序生成和保存的?

編輯:它看起來像外生插入一個ERL一次進入DB

INSERT INTO "posts" ("inserted_at", "updated_at", ...) 
VALUES ($1, $2, ...) 
RETURNING "id" [{{2016, 8, 15}, {7, 21, 50, 0}}, {{2016, 8, 15}, {7, 21, 50, 0}}, ...] query=1.2ms 

所以你永遠只能得到精確到秒在這種情況下。有沒有什麼辦法解決這個問題,除了在inserted_at和id上排序(似乎馬虎)

+0

多久一個刀片參加你的數據庫?這個'posts'表中是否有重觸發器或檢查或類似的東西? – JustMichael

+0

@JustMichael有4個索引,但所有這些記錄都是相同的,所以它們的影響是相同的。我認爲這個問題與Ecto有關。如果Ecto.DateTime正在插入erl時間戳,則它們只能精確到秒。這對我來說似乎是一個錯誤。 –

+0

我檢查了ecto時間戳是否有毫秒,顯然他們沒有,所以你可能是對的。 – JustMichael

回答

1

彼得,你帥的惡魔。您可以通過切換解決這個問題:USEC布爾真

defmodule Post do schema "posts" do timestamps(usec: true) end end

相關問題