ntviet18
ntviet18

Reputation: 792

How to create database schema using slick?

I have tried

val schemas = addresses.schema

val setup = schemas.create

val db = Database.forConfig("h2disk")

Await.result(db.run(setup), Duration.Inf)

but, apparently, it is not working. Here are some logs

[error] Caused by: org.h2.jdbc.JdbcSQLException: Schema "apps" not found; SQL statement:
[error] create table "apps"."t_address" ("name" VARCHAR,"domain" VARCHAR,"t_address_id" VARCHAR NOT NULL PRIMARY KEY) [90079-196]
[error]         at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
[error]         at org.h2.message.DbException.get(DbException.java:179)
[error]         at org.h2.message.DbException.get(DbException.java:155)
[error]         at org.h2.command.Parser.getSchema(Parser.java:688)
[error]         at org.h2.command.Parser.getSchema(Parser.java:694)

Upvotes: 0

Views: 1224

Answers (2)

Flow
Flow

Reputation: 57

I had to use bind variables to make it work as follow : (prefixing the variable with #)

src: https://scala-slick.org/doc/3.3.3/sql.html#splicing-literal-values

 val schemaName = "something"
 val schemas = Cases(schemaName).schema
 val setup = DBIO.seq(
      sqlu"""create schema #${schemaName} AUTHORIZATION postgres""",
      // create table schemas
      schema.createIfNotExists
      //add default data
 ...


      // add rights
...
    )

all the tables are defined like

 class Cases(_tableTag: Tag, schemaName: String) extends profile.api.Table[CasesRow](_tableTag, Some(schemaName), "cases") {
....
}
def Cases(schema: String) = new TableQuery(tag => new Cases(tag,schemaName = schema))

Upvotes: 0

ntviet18
ntviet18

Reputation: 792

We can try

val schemas = addresses.schema

val setup = DBIO.seq(sqlu"""create schema apps;""", schemas.create)

val db = Database.forConfig("h2disk")

Await.result(db.run(setup), Duration.Inf)

Notes: the schema name for some dbms is case sensitive, e.g. H2 will automatically convert schema to APPS

Upvotes: 1

Related Questions