在一个循环中生成记录,它们失灵。这是一个药剂或Postgres的东西?

问题描述:

我正在生成一些测试数据。在一个循环中生成记录,它们失灵。这是一个药剂或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

彼得,你帅的恶魔。您可以通过切换解决这个问题:USEC布尔真

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