gbaird

gbaird

Using Postgrex and SQL for bank transfers in PostgreSQL. epgsql erlang as alternative

I am trying to code a bank transfer service using Elixir/Erlang, Postgrex and PostgreSQL.

Erlang v 26
Elixir v 1.16.0
Postgrex v 0.17.4

The logic I am trying to build is the following, wrapped in a transaction BEGIN - COMMIT.

Party A seeks to transfer $50 from his account to Party B, her account. Think a Venmo transfer from Party A to Party B for $50.

Initialize

  1. Store the transfer amount in an Elixir variable *transfer_amount
  2. Store the from account UID in an Elixir variable from_account
  3. Store the to account UID in an Elixir Variable to_account
  4. Store the authorization token in an Elixir variable auth_token

BEGIN the transaction

  1. Read the master token value from the authorization data table and if the auth_token = master_token, then continue, else quit
  2. Read the balance from Party A’s account using the from_account UID
  3. If from_account** balance is >= than transfer_amount, then continue, else quit
  4. Update from_account balance by subtracting transfer_amount
  5. Update to_account balance by adding transfer_amount to balance
    COMMIT the transaction

What I tried is wrapping the SQL statement built from the above into a query and then use Postgrex.query - see below. The code returns an error.

My question for the group is this the correct/best design pattern to try and accomplish the objective - a P2P bank transfer, to wrap the SQL logic into a SQL statement that has a series of “reads” and then a “read / write” using Postgrex.query! Does Postgres support “Transaction” syntax? Can the read, write, comparisons all be included into a single statement and then sent using Postgrex.query?

24)> Postgrex.query!(pid3, "BEGIN; SELECT token_masterid FROM token; IF token_id = master_token THEN SELECT from_account, balance_avail FROM main_account … [note not……; COMMIT", [])

** (Postgrex.Error) ERROR 42601 

A more simple version produces this error

iex(14)> Postgrex.query!(pid3, "BEGIN transaction; SELECT * FROM account; COMMIT;", [])
** (Postgrex.Error) ERROR 42601 (syntax_error) cannot insert multiple commands into a prepared statement

    iex(14)> Postgrex.query!(pid3, "BEGIN transaction; SELECT * FROM account; COMMIT;", [])
** (Postgrex.Error) ERROR 42601 (syntax_error) cannot insert multiple commands into a prepared statement

Thank you in advance any thoughts and help !!

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hi @gbaird this seems more to do with a general comfort level with how Elixir works. All functions will only return one value, that isn’t related to Postgrex. If you want to return the information from multiple queries, bind each result to a variable and return a tuple:

{:ok, res} = Postgrex.transaction(pid3, fn(pid3) ->
  result1 = Postgrex.query!(pid3, "SELECT owner_id, balance_avail FROM account", [])
  result2 = Postgrex.query!(pid3, "SELECT owner_id, balance_book FROM account", [])
  {result1, result2}
end)

Keep in mind with Postgres that transactions are by default merely READ COMMITTED. Your use case may require stricter transaction modes.

sbuttgereit

sbuttgereit

Actually, should be possible to use a DO block (PostgreSQL: Documentation: 16: DO); this is effectively treated as a single SQL statement even though we may be doing more (possibly much more) work than that.

This is not so different than the stored procedure route, except that the DO block is implicitly ephemeral; no need to change the schema.

al2o3cr

al2o3cr

I don’t think multistatement queries like the above are supported - see also:

If you’re absolutely 100% required to do it SQL-side, you could make a stored procedure and then call that with Postgrex.query in a single statement.

The more-idiomatic approach would be to use Postgrex.transaction and then do the steps you’ve described using Elixir (and more DB queries) inside that transaction block.

tj0

tj0

Ecto maintains a database pool and parses / creates queries. There is some overhead in casting and validating data, but it is unavoidable as you would have to do that in any homegrown solution anyway. Ecto does this via Ecto.ChangeSet.

The major difference would be that there is a cost in converting from an Ecto.Struct to raw sql. This would be on the order of 5-10us and should be heavily outweighed by any networking variance. These benchmarks are from the Ecto Sqlite repo:

So, I don’t think there should be much of a practical negatives in performance difference in using Ecto over raw, but I have been surprised before.

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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
gazoon
I want to know absolute current module path. In python i could do that: os.path.abspath(__file__) Does elixir have anything similar?
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New

We're in Beta

About us Mission Statement