H2:生成插入脚本初始化脚本

H2: generate insert scripts initialization script

我有完整的 h2 数据库,里面有很多数据。我想针对该数据启动集成测试。

问题 1: 是否可以从完整的 h2 数据库生成 *.sql 插入 files/scripts?

我已经按照 here 的描述尝试了 SCRIPT TO 'fileName'。但它只生成 CREATE/ALTER TABLE/CONSTRAINT 个查询,意味着创建没有数据的模式。

如果第一个问题的答案是 - "Impossible",那么:

问题2: *.sql插入文件是将初始数据集插入h2 db进行集成测试的唯一方法吗?

Question1: Is it possible to generate *.sql insert files/scripts from full h2 database?

我刚刚用我的一个 H2 文件数据库进行了测试,结果导出导出了结构和数据。
我用 H2 的 1.4.193 版本进行了测试。

导出工作的两种方式:

  • 来自 H2 控制台的 SCRIPT 命令
  • org.h2.tools.Script 命令行工具。

1) 我首先测试了 org.h2.tools.Script 工具,因为我已经使用过它。

这是导出结构和数据的最小命令:

java -cp <whereFoundYourH2Jar> org.h2.tools.Script -url <url> 
     -user <user> -password <password>

其中:

  • <whereFoundYourH2Jar> 是您拥有 h2.jar 库的类路径(我使用的是我的 m2 存储库)。
  • <url> 是你的数据库url
  • <user>是数据库的用户
  • <password>数据库密码

您在org.h2.tools.Script工具的官方帮助中有更多详细信息:

Creates a SQL script file by extracting the schema and data of a database.
Usage: java org.h2.tools.Script <options>
Options are case sensitive. Supported options are:
[-help] or [-?]    Print the list of options
[-url "<url>"]     The database URL (jdbc:...)
[-user <user>]     The user name (default: sa)
[-password <pwd>]  The password
[-script <file>]   The target script file name (default: backup.sql)
[-options ...]     A list of options (only for embedded H2, see SCRIPT)
[-quiet]           Do not print progress information
See also http://h2database.com/javadoc/org/h2/tools/Script.html

2) 我已经从 H2 控制台使用 SCRIPT 命令进行了测试。它也有效。

然而,SCRIPT 命令的结果可能会产生误导。
看官方文档:

If no 'TO fileName' clause is specified, the script is returned as a result set. This command can be used to create a backup of the database. For long term storage, it is more portable than copying the database files.

If a 'TO fileName' clause is specified, then the whole script (including insert statements) is written to this file, and a result set without the insert statements is returned.

您使用了SCRIPT TO 'fileName'命令。在这种情况下,整个脚本 (包括插入语句)被写入此文件,结果在 H2 控制台中,除了插入语句之外,您拥有所有内容。
例如,输入 SCRIPT TO 'D:\yourBackup.sql' 命令(或 Unix 友好目录,如果您使用它),然后打开文件,您将看到存在 SQL 插入。

如文档中所述,如果您希望在H2控制台的输出结果中同时获取结构和插入语句,请不要指定TO参数。 只需输入:SCRIPT.

Question2: Are *.sql insert files the only way to insert initial dataset into h2 db for integration tests?

经过长时间的讨论 :) 您可以使用 DBunit 数据集(一种解决方案)。