sahilpaudel

sahilpaudel

How to close Xandra db connection?

I am using Xandra for Cassandra in my Phoenix application.

My connection looks like

def cass_conn do
    {:ok, conn} = Xandra.start_link(
      nodes: [Application.get_env(:diamond, :env_vars)[:cass_host]],
      authentication: {Xandra.Authenticator.Password, 
        [
          username: Application.get_env(:diamond, :env_vars)[:cass_host], 
          password: Application.get_env(:diamond, :env_vars)[:cass_pass]
        ]},
      pool: DBConnection.Poolboy,
      pool_size: 10)

    conn
  end

To execute a query

def find_by_id(audit_log_id) do
    
    stm = "SELECT * FROM audit_log_keyspace.rules_engine_audit_logs WHERE id=:id;"
    
    conn = cass_conn()

    prepared = conn
      |> Xandra.prepare!(stm)
      
    conn
      |> Xandra.execute!(prepared, %{ "id" => audit_log_id })
      |> Enum.fetch!(0)
  end

So here we will be calling find_by_id multiple of times which in turn calls cass_conn which returns new connection every time it is called.

Now I have doubt if the new connection be closed once the query is executed or do we have to close it manually from code.

Otherwise there might be performance issue due to multiple open db connections.

Any suggestions.

Marked As Solved

joaoevangelista

joaoevangelista

Xandra uses DBConnection under the hood so you can call DBConnection.close/3 like so:

DBConnection.close(conn, prepared)

A better approach is to have the Xandra process managed by the supervision tree. So you can leverage the pool for better use of resources, automatic reconnection, and automatic clean up when the application finishes.

To do that add to your workers list at the application entrypoint:

 workers = [
    ...,
   {Xandra, name: MyXandra, nodes: [Application.get_env(:diamond, :env_vars)[:cass_host]],
      authentication: {Xandra.Authenticator.Password, 
        [
          username: Application.get_env(:diamond, :env_vars)[:cass_host], 
          password: Application.get_env(:diamond, :env_vars)[:cass_pass]
        ]},
      pool: DBConnection.Poolboy,
      pool_size: 10}
     .....,
  ]


Then to use this process to execute the queries you will reference by the name you gave to it, in the example it was MyXandra:

def find_by_id(audit_log_id) do
    
    stm = "SELECT * FROM audit_log_keyspace.rules_engine_audit_logs WHERE id=:id;"

    prepared = MyXandra |> Xandra.prepare!(stm)
   
    MyXandra
    |> Xandra.execute!(prepared, %{ "id" => audit_log_id })
    |> Enum.fetch!(0)
end

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
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
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
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
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
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
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
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement