Prashant Bhardwaj
Prashant Bhardwaj

Reputation: 176

Generating DDL CQL create table scripts using spring-data-cassandra

For an application, I am managing Cassandra table definitions in a json file. Definition is something like array of partition key, array of clustering key, array of all the columns then array of column definitions, each column definition has column name and its data type. We were asked to create a tool which can read this json file and create a file containing CQL DDL create table scripts.

{
   "tableDefinitions":[
       {
         "tableName":"employee"
         "partitionKeyColumns":["department"],
         "clusteringKeyColumns":["name"],
         "columns":["id","address"]
       }
   ],
   "columnDefinitions":[
       {"name":"id","type":"text"},
       {"name":"name","type":"text"},
       {"name":"department","type":"text"},
       {"name":"address","type":"text"}
   ]
}

To achieve this, we used CreateTableSpecification. To set the column in this, method we have is -

public T column(String name, DataType type) {
    return this.column(CqlIdentifier.of(name), type);
}

where DataType is com.datastax.driver.core.DataType.

Before calling this method, I convert string dataType to com.datastax.driver.core.DataType. It was fine till we just had primitive data types on our columns. When we changed data type of one of our column to set, we were in trouble because there is no way available to change this string to corresponding com.datastax.driver.core.DataType. Because if you check this class, it doesn't expose SET datatype.

I am unable to convert string set into com.datastax.driver.core.DataType

Any other way to generate DDL create table CQL script on the fly when you have table definitions available?

Upvotes: 1

Views: 1076

Answers (1)

Alex Ott
Alex Ott

Reputation: 87174

You can use SchemaBuilder from the underlying DataStax Java driver. And DataType type has corresponding methods for sets/maps/lists - you only need to pass correct nested type to it...

Something like this (not tested):

String cql = SchemaBuilder.create("ks", "tbl")
  .addPartitionKey("id", DataType.cint)
  .addColumn("value", DataType.set(DataType.cint))
  .buildInternal();

Upvotes: 1

Related Questions