script

script

How to increment database table column

I know in elixir data types are immutable. I have a column name failed_login_tries. which is integer and i want to increment it every time user put incorrect password. this is the code

 defp check_chromatic_password(plaintext, %User{} = user) do
   if Bcrypt.checkpw(plaintext, user.local_password_hash) do
      {:ok, user}
   else
     {:error, :invalid_password}
   end
 end

failed_login_tries is inside the %User struct

Marked As Solved

minhajuddin

minhajuddin

You can change the user struct by using user = %{ user | failed_login_tries: user.failed_login_tries + 1} and to persist this in the database use Repo.update by passing it an updated ecto changeset. Immutability refers to the fact that the previous struct remains the same. e.g.

defmodule User do
  defstruct [:email]
end

u1 = %User{email: "mujju"}
u2 = u1
u2 = %{u2 | email: "danny"}

IO.inspect(u1)
# => %User{email: "mujju"}
IO.inspect(u2)
# => %User{email: "danny"}

Also Liked

LostKobrakai

LostKobrakai

There’s an even simpler option to write that query:

from(u in User, update: [inc: [failed_login_tries: 1]], where: u.id == user.id) )
25
Post #4
aseigo

aseigo

Just be aware that there is an inherent race condition with that approach: if the user fails auth in quick succession twice both may have the user record with the current count prior to either auth attempt, and so both will increment the old value by one and update the db with that, causing the N attempts to be counted as just 1!

The correct way to do this is in the database itself using a fragment as in:

from(u in User, 
     update: [set: [failed_login_tries: fragment("failed_login_tries + 1")]],
     where: u.id == user.id) )
|> MyRepo.update_all([])

This way the db sorts out the concurrent updates and you will always end up with the correct count.

11
Post #3
aseigo

aseigo

I always forget about inc (and friends) … thanks for the reminder!

LostKobrakai

LostKobrakai

Timestamps use the autogenerate functionality of ecto schema fields, which is runtime functionality. So those are not set on the db.

snofang

snofang

You can use Optimistic Lock feature; This keeps you away from races invalid results and also let you have timestamps functionality in place.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement