Warm tip: This article is reproduced from stackoverflow.com, please click
playframework scala slick slick-codegen

Can slick automatically create tables in the database (generate SQL and execute) from the models?

发布于 2020-04-05 00:22:43

I've understood that slick-codegen can generate scala classes from the database tables. Can we do the opposite, creating tables if they don't exist in the database from the models?

Questioner
Amandeep Chugh
Viewed
33
Richard Dallaway 2020-01-31 22:52

You can create tables in Slick from a model: it's not related to the codegen tool, though.

When you define a model in Slick, you can use the .schema method to generate the database schema commands. There are examples of this in The Slick Manual:

 // Assuming we have coffees and suppliers queries, we combine the schemas:
 val schema = coffees.schema ++ suppliers.schema


 // Now we can run a variety of commands to CREATE TABLE etc:
 db.run(DBIO.seq(
   schema.create,
   schema.createIfNotExists,
   schema.drop,
   schema.dropIfExists
))

However, that's not automatic: you'd need to write something in your start-up code to decide to run the DDL commands or not.