jeudi 8 janvier 2015

Adding tables to SQLite database using Slick and Scala

So I have SQLite database using Slick and I want to add and remove tables from it. Here is what I have now:


Here is the database element class:



class Data(tag: Tag)
extends Table[(Int, String)](tag, "myDB") {
// This is the primary key column:
def id = column[Int]("ID", O.PrimaryKey)
def name = column[String]("NAME")
// Every table needs a * projection with the same type as the table's type parameter
def * : ProvenShape[(Int, String)] = (id, name)
}


I need to be able to create multiple tables using the class above. Something like this:



def addTable(name:String){
db withSession { implicit session =>
val newTable = TableQuery[Data]
newTable.ddl.create
}
}


Problem is that I cant create new table because one already exists with name "myDB". I tried to add a parameter for the name of the Table in the class Data like so:



class Data(tag: Tag,tableName:String)


But then I couldn't create a table at all and got an error



unspecified value parameter tableName


And how can I query a specific table from the database given the table name? I tried to Implement this using Map with table name pointing to a table, but it doesnt work because the Map is not saved anywhere and is reset everytime the program starts.


This is what I had for querying a table:



def getDataFromTable(tableName:String)
{
var res = ""
db withSession { implicit session =>
tables(tableName) foreach{
case (id,name)=>
res += id + " " + name + " "
}
}
res
}


Any help is appreciated!


Thanks!


Aucun commentaire:

Enregistrer un commentaire