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

New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
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
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 Postgres...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
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
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement