Skip to content

Instantly share code, notes, and snippets.

@pedroxs
Created May 4, 2015 21:08
Show Gist options
  • Save pedroxs/5e8c5a1ac1973c53d265 to your computer and use it in GitHub Desktop.
Save pedroxs/5e8c5a1ac1973c53d265 to your computer and use it in GitHub Desktop.
Validate cassandra schema with model object
package model
import java.util.UUID
import play.api.libs.json.Json
case class Address(
id: Option[UUID],
address: Option[String],
number: Option[Int],
complement: Option[String],
neighborhood: Option[String],
city: Option[String],
state: Option[String],
postalCode: Option[Int],
country: Option[String]
)
object Address {
implicit val reads = Json.reads[Address]
implicit val writes = Json.writes[Address]
}
package model
import org.specs2.mutable._
import util.SchemaLoader
import scala.io.Source
class AddressSpec extends Specification with SchemaLoader {
"A Address 'CREATE TABLE' " should {
"exist in 'inventory_schema.sql' only once " in {
val create = schema.inventory.filter(l => l.contains("CREATE TABLE inventory.address"))
create must have size 1
}
"have the corresponding columns" in {
val fields = extractFieldNames[Address].map {x => x.replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase}
val start = schema.inventory.indexWhere(l => l.contains("inventory.address")) + 1
val end = start + schema.inventory.slice(start, schema.inventory.length).indexWhere(l => l.contains(";"))
val columns = schema.inventory.slice(start, end).flatMap {x => x.split("\\s+").drop(1).take(1)}.toTraversable
columns must not be empty
columns must containTheSameElementsAs(fields)
}
}
}
DROP KEYSPACE inventory;
CREATE KEYSPACE inventory WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};
CREATE TABLE inventory.address (
id timeuuid PRIMARY KEY,
address text,
number int,
complement text,
neighborhood text,
city text,
state text,
postal_code int,
country text
);
package util
import scala.io.Source
trait SchemaLoader {
def schema = new {
private val inventory_stream = getClass.getClassLoader.getResourceAsStream("inventory_schema.sql")
private val inventory_source = Source.fromInputStream(inventory_stream)
val inventory = inventory_source.getLines()
private val invoice_stream = getClass.getClassLoader.getResourceAsStream("invoice_schema.sql")
private val invoice_source = Source.fromInputStream(invoice_stream)
val invoice = invoice_source.getLines()
}
def extractFieldNames[T<:Product](implicit m: Manifest[T]) =
m.erasure.getDeclaredFields.map(_.getName)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment