Getting the records just inserted

I have defined a model Essay which has a title and content.I am inserting the records as Repo.insert_all() with conflict: :nothing.I want to get the title of all the essays which didn’t conflict.Is there any way to get them?

2 Likes

Try passing the returning: :title option. It only works on PG.

4 Likes

Thanks Jose.Does that return a list of titles or the model as in %Module.Essay{} which i have to pattern match then?

1 Like

It will return a map or a struct, depending on the first parameter. In bot cases, you should be able to pattern match it out with %{title: title}.

3 Likes

Thanks again Jose but it’s not working.Here’s what I did

outcome = Repo.all(Essay,listOfEssays,on_conflict: :nothing,returning: :title)

case outcome do
{numberofentries,returnedresult} -> IO.puts “Result is #{inspect returnedresult}”

end

But I am getting FuntionClauseError

2 Likes

When you get an error, please post the stacktrace and error message, it will help us debug it. In any case, I think the fix is that you need to do returning: [:title]. If that doesn’t work, please post the full error. :slight_smile:

2 Likes

Did you mean insert_all?

2 Likes

@hq1 yeah sorry…supposed to write insert_all

2 Likes

@josevalim I am up to here

outcome = Repo.insert_all(Essay,listOfEssays,on_conflict: :nothing,returning: [:title])

case outcome do
{,%Module.Essay{title: showtitle}} -> IO.puts “Title is #{inspect title]”
{0,[]} -> IO.puts “didn’t insert anything”
{
,nil} -> IO.puts “not bothered”
end

But only the second pattern is matching, even though I can see new records in the database.

2 Likes

Weird. However, keep in mind I wouldn’t expect any of those clauses to match in case something is returned, because Module.Essay would be inside of a list. Try removing on_conflict: :nothing and see what happens.

2 Likes

@jose thanks again …it’s working now.My pattern matching was wrong.Time to brush up on pattern matching

https://thumb7.shutterstock.com/display_pic_with_logo/122038/122038,1259697754,1/stock-vector-zebra-and-cow-pattern-41993425.jpg

1 Like