Files
core/test/rust/runtime/database/mod.rs
T
2026-11-27 06:03:56 +00:00

414 lines
15 KiB
Rust
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 使用真实临时 SQLite 文件与池验证事务、资源退出和隔离,不复制执行逻辑。
use dever_runtime::{
database::{Context, Database, Error, Kind, Options, Parameter, Sql},
task,
};
use std::{path::PathBuf, time::Duration};
mod postgres;
mod postgres_tenant;
mod schema;
mod stream;
pub(super) struct File(pub(super) PathBuf);
impl File {
pub(super) fn new(name: &str) -> Self {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/next-database-tests");
std::fs::create_dir_all(&root).unwrap();
let path = root.join(format!("{}-{name}.sqlite", std::process::id()));
assert!(!path.exists(), "test database must be fresh");
Self(path)
}
}
impl Drop for File {
fn drop(&mut self) {
for suffix in ["", "-wal", "-shm"] {
let path = PathBuf::from(format!("{}{suffix}", self.0.display()));
if path.exists() {
std::fs::remove_file(path).unwrap();
}
}
}
}
pub(super) fn options() -> Options {
Options {
max_page_size: 100,
max_connections: 1,
wait_timeout: Duration::from_millis(100),
io_timeout: Duration::from_secs(2),
}
}
const CREATE: Sql = Sql::same(
"CREATE TABLE article(id INTEGER PRIMARY KEY, title TEXT NOT NULL UNIQUE, published BOOLEAN NOT NULL CHECK(published IN (0,1)))",
);
const INSERT: Sql = Sql::same("INSERT INTO article(title,published) VALUES ($1,$2)");
const COUNT: Sql = Sql::same("SELECT COUNT(*) FROM article");
fn values(title: &str) -> Vec<Parameter> {
vec![Parameter::Text(title.into()), Parameter::Bool(false)]
}
#[test]
fn model_text_normalization_trims_unicode_in_place_and_preserves_modes() {
use dever_runtime::value::text::{TextMode, normalize};
for (input, expected) in [
("", ""),
("plain", "plain"),
(" \t\r\n  ", ""),
("  中文 ", "中文"),
("\tleft", "left"),
("right\r\n", "right"),
(" inner space kept ", "inner space kept"),
] {
let input = input.to_owned();
let pointer = input.as_ptr();
let capacity = input.capacity();
let result = normalize(input, TextMode::Trim);
assert_eq!(result, expected);
assert_eq!(result.as_ptr(), pointer);
assert_eq!(result.capacity(), capacity);
}
assert_eq!(normalize(" 原文 ".into(), TextMode::Raw), " 原文 ");
assert_eq!(normalize(" AbCß ".into(), TextMode::Lower), "abcß");
assert_eq!(normalize(" AbCß ".into(), TextMode::Upper), "ABCSS");
}
#[test]
fn sqlite_native_cache_budget_reaches_every_pooled_connection() {
let file = File::new("cache-budget");
let value = serde_json::json!({"type":"sqlite","path":file.0.file_name().unwrap().to_str().unwrap(),"max_connections":2,"cache_size_kib":512});
let config: dever_runtime::database::config::Config =
serde_json::from_value(value.clone()).unwrap();
task::run(false, 16, async |scope| {
let database = config.open(file.0.parent().unwrap(), true).await?;
let mut first = database.acquire().await?;
let mut second = database.acquire().await?;
for executor in [&mut first, &mut second] {
assert_eq!(
executor
.query_one(scope, Sql::same("PRAGMA cache_size"), vec![], |row| row
.get::<i64>(0))
.await?,
Some(-512)
);
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
let mut invalid = value.clone();
invalid["cache_size_kib"] = serde_json::json!(0);
assert!(serde_json::from_value::<dever_runtime::database::config::Config>(invalid).is_err());
assert!(serde_json::from_value::<dever_runtime::database::config::Config>(serde_json::json!({
"type":"postgres","url":"postgres://localhost/test","tls":"disabled","cache_size_kib":512
})).is_err());
let excessive = File::new("excessive-cache");
task::execute(false, async {
let error = Database::sqlite(
&excessive.0,
true,
options(),
std::num::NonZeroU32::new(u32::MAX),
)
.await
.err()
.unwrap();
assert_eq!(error.kind, Kind::Pool);
assert!(!excessive.0.exists());
})
.unwrap();
}
#[test]
fn sqlite_path_keeps_unicode_and_uri_delimiters_in_the_filename() {
let file = File::new("中文?mode=ro#part%20");
task::run(false, 16, async |scope| {
assert!(
Database::sqlite(&file.0, false, options(), None)
.await?
.acquire()
.await
.is_err()
);
assert!(!file.0.exists());
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
executor
.execute(scope, INSERT, values("保存实际文件"))
.await?;
drop(executor);
drop(database);
assert!(file.0.exists());
let database = Database::sqlite(&file.0, false, options(), None).await?;
assert_eq!(
database
.acquire()
.await?
.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
Some(1),
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn single_rows_preserve_absence_decode_failure_and_transaction_rollback() {
let file = File::new("single-row");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
assert_eq!(
executor
.query_one(
scope,
Sql::same("SELECT id FROM article WHERE id=1"),
vec![],
|row| row.get::<i64>(0)
)
.await?,
None
);
let owner = executor.begin(scope).await?;
let inserted = executor
.query_one(
scope,
Sql::same("INSERT INTO article(title,published) VALUES ($1,$2) RETURNING id"),
values("created"),
|row| row.get::<i64>(0),
)
.await?;
assert_eq!(inserted, Some(1));
executor.finish(scope, owner, true).await?;
let owner = executor.begin(scope).await?;
executor.execute(scope, INSERT, values("rollback")).await?;
let error = executor
.query_one(
scope,
Sql::same("SELECT title FROM article WHERE id=1"),
vec![],
|row| row.get::<i64>(0),
)
.await
.unwrap_err();
assert_eq!(error.kind, Kind::InvalidData);
assert!(executor.finish(scope, owner, true).await.is_err());
drop(executor);
assert_eq!(
database
.acquire()
.await?
.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
Some(1)
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn sqlite_parameter_binding_typed_rows_transactions_and_reuse() {
let file = File::new("transactions");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut executor = database.acquire().await?;
executor.execute(scope, CREATE, vec![]).await?;
let owner = executor.begin(scope).await?;
executor
.execute(scope, INSERT, values("中文'; DROP TABLE article;--"))
.await?;
executor.finish(scope, owner, true).await?;
let rows = executor
.query(
scope,
Sql::same("SELECT title,published FROM article"),
vec![],
|row| Ok((row.get::<String>(0)?, row.get::<bool>(1)?)),
)
.await?;
assert_eq!(rows, [("中文'; DROP TABLE article;--".into(), false)]);
let owner = executor.begin(scope).await?;
executor.execute(scope, INSERT, values("rollback")).await?;
executor.finish(scope, owner, false).await?;
assert_eq!(
executor
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
drop(executor);
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[1]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn nested_failure_cannot_be_caught_and_committed_and_drop_rolls_back() {
let file = File::new("nested");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), None).await?;
let mut context = Context::default();
context
.on(scope, &database)
.await?
.execute(scope, CREATE, vec![])
.await?;
let outer = context.enter();
context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("first"))
.await?;
let nested = context.enter();
assert!(!nested);
let error = context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("first"))
.await
.unwrap_err();
assert_eq!(error.kind, Kind::Constraint);
assert!(std::error::Error::source(&error).is_some());
context.finish(scope, nested, false).await?;
assert!(context.finish(scope, outer, true).await.is_err());
assert_eq!(
context
.on(scope, &database)
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
context.enter();
context
.on(scope, &database)
.await?
.execute(scope, INSERT, values("abandoned"))
.await?;
drop(context);
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn physical_database_boundary_rejects_cross_database_transactions() {
let one = File::new("tenant-one");
let two = File::new("tenant-two");
task::run(false, 16, async |scope| {
let one = Database::sqlite(&one.0, true, options(), None).await?;
let two = Database::sqlite(&two.0, true, options(), None).await?;
one.acquire().await?.execute(scope, CREATE, vec![]).await?;
two.acquire().await?.execute(scope, CREATE, vec![]).await?;
let mut context = Context::default();
let owner = context.enter();
context
.on(scope, &one)
.await?
.execute(scope, INSERT, values("private"))
.await?;
let error = context.on(scope, &two).await.err().unwrap();
assert!(error.message.contains("physical databases"));
assert!(context.finish(scope, owner, true).await.is_err());
for database in [&one, &two] {
assert_eq!(
database
.acquire()
.await?
.query(scope, COUNT, vec![], |row| row.get::<i64>(0))
.await?,
[0]
);
}
Ok::<_, Error>(())
})
.unwrap()
.unwrap();
}
#[test]
fn existing_database_mode_never_creates_a_missing_tenant_file() {
let file = File::new("missing");
task::execute(false, async {
let error = Database::sqlite(&file.0, false, options(), None)
.await
.unwrap()
.acquire()
.await
.err()
.unwrap();
assert_eq!(error.kind, Kind::Connection);
assert!(!file.0.exists());
})
.unwrap();
}
#[test]
fn sqlite_operation_deadline_rolls_back_before_the_pool_is_reused() {
let file = File::new("sql-deadline");
task::run(false, 16, async |scope| {
let mut settings = options();
settings.io_timeout = Duration::from_millis(100);
let database = Database::sqlite(&file.0, true, settings, None).await?;
database.acquire().await?.execute(scope, CREATE, vec![]).await?;
scope.within(async |boundary| {
let mut executor = database.acquire().await?;
executor.begin(boundary).await?;
executor.execute(boundary, INSERT, values("expired transaction")).await?;
let error = executor.query_one(boundary, Sql::same(
"WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<1000000000) SELECT sum(value) FROM n"
), vec![], |row| row.get::<i64>(0)).await.unwrap_err();
assert_eq!(error.kind, Kind::Timeout);
Ok::<_, Error>(())
}).await?;
let mut executor = database.acquire().await?;
assert_eq!(executor.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(0));
executor.execute(scope, INSERT, values("after deadline")).await?;
Ok::<_, Error>(())
}).unwrap().unwrap();
}
#[test]
fn cancelling_sql_waits_for_worker_exit_and_replaces_the_connection() {
let file = File::new("cancel");
task::run(false, 16, async |scope| {
let database = Database::sqlite(&file.0, true, options(), std::num::NonZeroU32::new(512)).await?;
database.acquire().await?.execute(scope, CREATE, vec![]).await?;
scope.within(async |boundary| {
let mut executor = database.acquire().await?;
executor.begin(boundary).await?;
executor.execute(boundary, INSERT, values("cancelled transaction")).await?;
assert_eq!(executor.query_one(boundary, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(1));
let work = executor.query(boundary, Sql::same("WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value+1 FROM n WHERE value<1000000000) SELECT sum(value) FROM n"), vec![], |row| row.get::<i64>(0));
assert!(tokio::time::timeout(Duration::from_millis(30), work).await.is_err());
assert_eq!(executor.execute(boundary, INSERT, values("discarded lease")).await.unwrap_err().kind, Kind::Cancelled);
Ok::<_, Error>(())
}).await?;
let mut executor = database.acquire().await?;
assert_eq!(executor.query_one(scope, Sql::same("PRAGMA cache_size"), vec![], |row| row.get::<i64>(0)).await?, Some(-512));
assert_eq!(executor.query_one(scope, COUNT, vec![], |row| row.get::<i64>(0)).await?, Some(0));
executor.execute(scope, INSERT, values("after cancellation")).await?;
Ok::<_, Error>(())
}).unwrap().unwrap();
}