【问题标题】:Can slick automatically create tables in the database (generate SQL and execute) from the models?slick 可以从模型中自动在数据库中创建表(生成 SQL 并执行)吗?
【发布时间】:2020-05-02 04:55:14
【问题描述】:

我知道 slick-codegen 可以从数据库表中生成 scala 类。我们可以做相反的事情,如果它们在模型中的数据库中不存在,则创建表?

【问题讨论】:

标签: scala playframework slick slick-codegen


【解决方案1】:

您可以在 Slick 中从模型创建表:不过,它与 codegen 工具无关。

在 Slick 中定义模型时,可以使用.schema 方法生成数据库模式命令。 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
))

但是,这不是自动的:您需要在启动代码中编写一些内容来决定是否运行 DDL 命令。

【讨论】:

  • 我要补充一点,slick 创建表的能力不应该被用作任何类型的数据库迁移框架。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 2010-11-07
  • 2011-07-10
  • 2019-07-18
相关资源
最近更新 更多