Reputation: 349
I'm trying to hash the current ID of every book I insert in the database, so that every book will be recognized by such 'code'.
Is there is a way in Ecto to display value of fragment("nextval('books_id_seq')")
in a changeset or Ecto.insert() ?
So far all I can do is get the last id by calling it from this function :
...
def get_currval() do
from(b in Book,
select: fragment("nextval('books_id_seq')"),
limit: 1
)
|> Repo.one
end
I'd love to have something more reliable, like a fragment in the insert query.
Upvotes: 0
Views: 3612
Reputation: 1356
There is a way to get ID back in the same query: RETURNING, that allows you
# \d+ tmp_play
Table "pg_temp_11.tmp_play"
Column | Type | Modifiers | Storage | Stats target | Description
--------+-----------------------+-------------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('tmp_play_id_seq'::regclass) | plain | |
name | character varying(32) | | extended | |
Indexes:
"tmp_play_pkey" PRIMARY KEY, btree (id)
# INSERT INTO tmp_play (name) VALUES ('Hello') RETURNING id;
id
----
1
(1 row)
INSERT 0 1
# INSERT INTO tmp_play (name) VALUES ('world') RETURNING id;
id
----
2
(1 row)
INSERT 0 1
Upvotes: 0