scalaplayframeworkslickslick-codegen

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


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?


Solution

  • 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.