Noel
Noel

Reputation: 2091

Test for table/view existence with Scalaquery & create if not present

I am writing some tests to automate checking if a database (a MS SQL Server instance) has certain views, and if it does not, creating those views using the BasicTable object. Something like:

  @Test def CheckAndBuildViewsOnDB() = { 
    VerifyViewExists(FooTable, BarTable) //FooTable et al defined as: 
FooTable extends BasicTable[Foo], where Foo is a case class & FooTable 
has a DDL create defined. 
  } 

Based on this and cribbing from Stefan Zeiger's assertTablesExist example, I made a little method to check the db for a view, and if the check throws an exception call that view's BasicTable ddl.create:

  def VerifyViewExists(views:BasicTable*) = { 
    DatabaseSession.session() withSession { //helper class which 
initiates a db connection & session 
      views map { 
        v => (try queryNA[Int]("select 1 from '"+ v.tableName +"' 
where 1<0").list 
            catch {case _: Exception => v.ddl.create; 
println("Couldn't find view "+v.tableName+", creating it 
now...");}) 
      } } } 

Which seems reasonable to me, but has two problems:

  1. this isn't the right way to type the views parameter as BasicTable, resulting in "error: class BasicTable takes type parameters"
  2. something funky is happening with the map argument v's scope, resulting in "error: value tableName is not a member of type parameter T0".

Pardon my ignorance with this question, as I suspect that the root of my issue lies with not understanding Scala's type system. Along with those two problems is the nagging feeling that I haven't really done VerifyViewExists in the most succinct or readable style.

Upvotes: 0

Views: 227

Answers (1)

nafg
nafg

Reputation: 2534

Since you don't care what the type parameter is, you should be able to solve #1 by adding [_]:

def VerifyViewExists(views:BasicTable[_]*) = { 

My guess is that fixing #1 will cause #2 to disappear.

By the way it may be better to write foreach rather than map, since the latter will collect the results into a new collection, which I don't think you want.

Upvotes: 1

Related Questions