简体   繁体   English

单元测试 SQL 脚本

[英]Unit testing SQL scripts

For below script written in .sql files:对于以下用.sql文件编写的脚本:

if not exists (select * from sys.tables where name='abc_form')
    CREATE TABLE abc_forms (
        x BIGINT IDENTITY, 
        y VARCHAR(60), 
        PRIMARY KEY (x)
    )

Above script has a bug in table name.上面的脚本在表名中有一个错误。

For programming languages like Java/C, compiler help resolve most of the name resolutions对于 Java/C 等编程语言,编译器帮助解决大部分名称解析

For any SQL script, How should one approach unit testing it?对于任何 SQL 脚本,应该如何对其进行单元测试? static analysis...静态分析...

15 years ago I did something like you request via a lot of scripting. 15 年前,我通过大量脚本编写了类似您请求的内容。 But we had special formats for the statements.但是我们有特殊的报表格式。

We had three different kinds of files:我们有三种不同类型的文件:

  • One SQL file to setup the latest version of the complete database schema一个用于设置最新版本的完整数据库架构的 SQL 文件
  • One file for all the changes to apply to older database schema's (custom format like version;SQL)适用于旧数据库模式的所有更改的一个文件(自定义格式,如版本;SQL)
  • One file for SQL statements the code uses on the database (custom format like statementnumber;statement)代码在数据库上使用的 SQL 语句的一个文件(自定义格式,如 statementnumber;statement)

It was required that every statement was on one line so that it could be extracted with awk!要求每条语句都在一行上,以便可以使用 awk 提取它!

1) At first I set up the latest version of the database by executing from statement after the other and logging the errors to a file. 1) 首先,我通过依次执行 from 语句并将错误记录到文件中来设置最新版本的数据库。

2) Secondly I did the same for all changes to have a second schema 2)其次,我对所有更改都做了同样的事情以获得第二个架构

3) I compared the two database schemas to find any differences 3)我比较了两个数据库模式以发现任何差异

4) I filled in some dummy test values in the complete latest schema for testing 4)我在完整的最新模式中填写了一些虚拟测试值进行测试

5) Last but not least I executed every SQL statement against the latest schema with test data and logged every error again. 5)最后但并非最不重要的一点是,我使用测试数据针对最新模式执行了每个 SQL 语句,并再次记录了每个错误。

At the end the whole thing runs every night and there was no morning without new errors that one of 20 developers had put into the version control.最后,整个过程每晚都在运行,20 位开发人员中的一位已将新错误放入版本控制中,没有一个早晨没有新错误。 But it saved us a lot of time during the next install at a new customer.但它为我们在新客户的下一次安装过程中节省了大量时间。

You could also generate the SQL scripts from your code.您还可以从您的代码生成 SQL 脚本。

Code first avoids these kinds of problems.代码首先避免了这些类型的问题。 Choosing between code first or database first usually depends on whether your main focus is on your data or on your application.在先代码还是先数据库之间进行选择通常取决于您的主要关注点是数据还是应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM