【问题标题】:Create new PostgresSQL schema创建新的 PostgreQL 架构
【发布时间】:2021-04-20 12:10:14
【问题描述】:

在运行时的数据库中创建新的 Postgres 方案以及创建写入 SQL 文件的表的最简单方法是什么?

\这是一个 Spring boot 应用程序,该方法接收需要为 db 创建的模式名称。

【问题讨论】:

  • create schema ....;?

标签: java sql spring-boot


【解决方案1】:

虽然这听起来像是使用 Liquibase 或 Flyway 或任何其他工具的情况,但这里有一个简单(但非常 hacky)的解决方案/起点:

(粗略)步骤:

  • 创建整个 ddl 查询,其中包括“创建和使用架构部分”以及您的 SQL 文件的内容
  • 注入实体管理器
  • 将整个 ddl 查询作为本机查询运行

示例/(hacky)代码:

这里是一个简单的控制器类,它定义了一个 GET 方法,该方法接受一个名为“schema”的参数:

@Controller
public class FooController {

    private static final String SCHEMA_FORMAT = "create schema %s; set schema %s; ";

    @PersistenceContext
    EntityManager entityManager;

    @Value("classpath:foo.sql")
    Resource fooResource;

    @GetMapping("foo")
    @Transactional
    public ResponseEntity<?> foo(@RequestParam("schema") String schema)
            throws IOException {
        File fooFile = new ClassPathResource("foo.sql").getFile();
        String ddl = new String(Files.readAllBytes(fooFile.toPath()));
        String schemaQuery = String.format(SCHEMA_FORMAT, schema, schema);
        String query = String.format("%s %s", schemaQuery, ddl);
        
        entityManager.createNativeQuery(query).executeUpdate();
        return ResponseEntity.noContent().build();
    }

}

【讨论】:

猜你喜欢
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2014-08-13
  • 2015-08-25
相关资源
最近更新 更多