Tiberius DB Tester
English
A Rust library for SQL Server database testing based on the Tiberius driver.
Features
- Automatically creates randomly named temporary test databases
- Supports executing SQL migration scripts to initialize the database
- Automatically closes all connections and cleans up database resources after testing
- Simple and easy-to-use API, suitable for integration testing scenarios
Installation
Add the dependency to your Cargo.toml:
[]
= "0.1.0"
Usage
Basic Usage
use DBTester;
async
Migration Script Example
Migration scripts are regular SQL files, for example:
-- migrations/init.sql
(
id INT PRIMARY KEY,
name NVARCHAR(100) NOT NULL
);
INSERT INTO test (id, name) VALUES (1, 'Test 1');
INSERT INTO test (id, name) VALUES (2, 'Test 2');
How It Works
DBTester::new()creates a randomly named database (format:testdb_uuid)- Executes the specified SQL migration script to initialize the database structure and test data
- Provides the
get_client()method to get a configured database connection - When the
DBTesterinstance is destroyed, it:- Switches to the
masterdatabase - Uses
ALTER DATABASE SET SINGLE_USER WITH ROLLBACK IMMEDIATEto close all existing connections - Deletes the test database
- Switches to the
Notes
- Requires a SQL Server user with permissions to create and delete databases
- Ensure the migration script path is correct and the script content is valid
- Pay attention to resource management when using in multi-threaded environments
Dependencies
- tiberius: SQL Server driver for Rust
- tokio: Asynchronous runtime
- tokio-util: Provides compatibility layer
- uuid: Generates unique identifiers
License
MIT
Contributions
Welcome to submit issue reports and pull requests!
中文
一个用于SQL Server数据库测试的Rust工具库,基于Tiberius驱动。
功能特点
- 自动创建随机命名的临时测试数据库
- 支持执行SQL迁移脚本初始化数据库
- 测试完成后自动关闭所有连接并清理数据库资源
- 简单易用的API,适合集成测试场景
安装
在Cargo.toml中添加依赖:
[]
= "0.1.0"
使用方法
基本用法
use DBTester;
async
迁移脚本示例
迁移脚本是普通的SQL文件,例如:
-- migrations/init.sql
(
id INT PRIMARY KEY,
name NVARCHAR(100) NOT NULL
);
INSERT INTO test (id, name) VALUES (1, '测试1');
INSERT INTO test (id, name) VALUES (2, '测试2');
工作原理
DBTester::new()创建一个随机命名的数据库(格式为testdb_uuid)- 执行指定的SQL迁移脚本来初始化数据库结构和测试数据
- 提供
get_client()方法来获取已配置好的数据库连接 - 当
DBTester实例被销毁时,它会:- 切换到
master数据库 - 使用
ALTER DATABASE SET SINGLE_USER WITH ROLLBACK IMMEDIATE关闭所有现有连接 - 删除测试数据库
- 切换到
注意事项
- 需要提供具有创建和删除数据库权限的SQL Server用户
- 确保迁移脚本路径正确,且脚本内容有效
- 在多线程环境中使用时需要注意资源管理
依赖项
- tiberius: SQL Server的Rust驱动
- tokio: 异步运行时
- tokio-util: 提供兼容层
- uuid: 生成唯一标识符
许可证
MIT
贡献
欢迎提交问题报告和拉取请求!