Almis
Almis

Reputation: 3809

How to delete table on Cassandra using C# Datastax driver?

var keyspace = "mydb";
var datacentersReplicationFactors = new Dictionary<string, int>(0);
var replication = ReplicationStrategies.CreateNetworkTopologyStrategyReplicationProperty(datacentersReplicationFactors);

using (var cluster = Cluster.Builder().AddContactPoints("my_ip").Build())
using (var session = cluster.Connect())
{
    session.CreateKeyspaceIfNotExists(keyspace, replication, true);
    session.ChangeKeyspace(keyspace);

    var entityTable = new Table<Models.Entity>(session);
    var attributeTable = new Table<Models.Attribute>(session);

    entityTable.CreateIfNotExists(); // Worked
    attributeTable.CreateIfNotExists(); // Worked

    entityTable.Delete(); // Does nothing
    attributeTable.Delete();  // Does nothing
}

EDIT: Without using raw queries session.Execute("DROP TABLE entities;"); working fine.

Upvotes: 1

Views: 510

Answers (2)

Almis
Almis

Reputation: 3809

Unless there is already a method for dropping tables that I not aware of, you can use this extensions.

public static class DastaxTableExtensions
{
    public static void Drop<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE {table.Name};");
    }

    public static void DropIfExists<T>(this Table<T> table)
    {
        table.GetSession().Execute($"DROP TABLE IF EXISTS {table.Name};");
    }
}

Then you can use it like this

entityTable.Drop();
attributeTable.DropIfExists();

Upvotes: 2

CodeFuller
CodeFuller

Reputation: 31312

Delete() method is not intended for drop of the tables. It returns representation of a DELETE cql statement. If you call it, you just get {DELETE FROM entities}.

If you need to drop a table, the easiest way is just to execute DROP statement:

session.Execute("DROP TABLE entities;");

Upvotes: 4

Related Questions