Starting Xandra process for migrations

Hi everyone, I have been trying to setup xandra in order to use Cassandra in my phoenix project. The xandra connection with Cassandra is made in my application.ex file, by specifying it as a child in my supervision tree like {Xandra, name: :xandra_connection} now I can execute queries like …

statement =
      "CREATE KEYSPACE test WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};"

    Xandra.execute(:xander_connection, statement, [])

This works but in case of migrations involving xandra I need to establish the xandra connection every time like…

defmodule Test.Repo.Migrations.CreateKeyspace do
  use Ecto.Migration

  def up do
    Xandra.start_link(name: :xander_connection)
    statement =
      "CREATE KEYSPACE test WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};"

    Xandra.execute(:xander_connection, statement, [])

  def down do
    Xandra.start_link(name: :xander_connection)
    statement = "DROP KEYSPACE test"
    Xandra.execute(:xander_connection, statement, [])

I want to establish the connection once before running the migrations and avoid writing Xandra.start_link(name: :xander_connection) every time in the migrations.
Can anyone help me with this?

How do you start Xandra normally? If you’re using an application entry in mix.exs, you could try adding a start_apps_before_migration entry referring to it to your Repo’s configuration.

Thanks for the reply, I already saw this but I am confused, how do I specify Xandra.start_link(name: :xander_connection) in start_apps_before_migration since it only accepts a list of atoms where the atoms are .app files.

I added this in my config
config :app, App.Repo, start_apps_before_migration: [:xandra]
This will try to start the app defined in
but does this actually do Xandra.start_link() ?
Also I need to specify a name to the Xandra process like Xandra.start_link(name: :xander_connection)
So that later I can use this name to execute queries like
Xandra.execute(:xander_connection, query, [])
without the name I don’t know the pid of the Xandra process even if it is started.

Here xandra is a child process for the Your Application Supervisor, So you can start the Xandra before migration, by writing this line start_apps_before_migration: [:my_app] in your Repo configuration. This means you are starting your application before migration. Your config.exs may look like -

config :my_app, MyApp.Repo,
  username: .....,
  password: .....,
  database: "my_app_db,
  hostname: "localhost",
  pool_size: 10,
  start_apps_before_migration: [:my_app]
1 Like