Separate database connections from file-backed host information and document handoff
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m25s
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m25s
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
# storage
|
||||
|
||||
宿主元数据存储,依赖 SQLx/Tokio,不依赖 VM 内核。一个 Storage 选择 SQLite 或 PostgreSQL;明确配置 PostgreSQL 后失败不回退。
|
||||
按需数据库连接适配层,供将来需要数据库的特殊类或宿主适配器使用。依赖 SQLx/Tokio,不依赖 VM 内核;普通对象、CLI 和 Server 不连接这层。
|
||||
|
||||
| 内容 | 入口 |
|
||||
| --- | --- |
|
||||
| Cargo.toml | SQLx、Tokio 和检查所需依赖 |
|
||||
| [src](src/README.md) | 配置解析、连接池、元数据表和操作 |
|
||||
| [tests](tests/README.md) | 配置、持久化、隔离与专用 PostgreSQL 检查 |
|
||||
| Cargo.toml | SQLx、Tokio 与远端检查依赖 |
|
||||
| [src](src/README.md) | 显式 DatabaseConfig、连接池与关闭 |
|
||||
| [tests](tests/README.md) | 连接不建表、调用方 SQL、隔离/持久化、真实 PostgreSQL |
|
||||
|
||||
Storage 仅保存 key/value 元数据,不保存 EndorObject 或执行帧。运行与连接规则见 [运行指南](../../docs/operations/README.md),环境优先级与错误规则见 [配置](../../docs/operations/configuration.md),生产数据与迁移边界见 [部署](../../docs/operations/deployment.md)。返回 [工作区](../README.md)。
|
||||
没有默认数据库、自动环境变量读取、基础信息表或通用元数据 put/get。特殊类的名称、布局与查询接口尚未定义;当前只保留连接能力。设计边界见 [数据库对象](../../docs/runtime/database-objects.md),参数见 [配置](../../docs/operations/configuration.md)。返回 [工作区](../README.md)。
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
# Storage 源码导航
|
||||
# 数据库连接源码导航
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| [lib.rs](lib.rs) | StorageConfig::from_values/from_env、StorageError、SQLite/PostgreSQL 连接池、schema 初始化、ping/put/get/close |
|
||||
| [schema.sql](schema.sql) | 当前 aster_metadata 文本 key/value 表,幂等建表 |
|
||||
[lib.rs](lib.rs) 是唯一实现文件:DatabaseConfig 显式选择 SQLite 文件/内存或 PostgreSQL;DatabaseConnection 提供 connect、sqlite_pool/postgres_pool、backend_name、ping 和 close;DatabaseError 对公开错误脱敏。
|
||||
|
||||
配置改动同步 [配置表](../../../docs/operations/configuration.md) 与 storage 测试。schema 改动须考虑已有数据库,当前没有版本化迁移;不得将 CREATE IF NOT EXISTS 当作已有结构升级。Storage 克隆共享连接池,close 影响所有克隆。
|
||||
connect 只建立连接池,不执行应用 DDL,不保存基础信息。没有 schema.sql、初始化表、put/get 或 from_env。业务表和查询由未来的数据库特殊类决定;本层不替它定义数据模型。
|
||||
|
||||
连接与持久化契约见 [运行指南](../../../docs/operations/README.md),测试定位见 [tests](../tests/README.md)。返回 [storage](../README.md)。
|
||||
克隆共享连接池,close 会关闭所有克隆;具体生命周期及限制见 [数据库对象](../../../docs/runtime/database-objects.md)。配置变动同步 [配置](../../../docs/operations/configuration.md) 和 [tests](../tests/README.md)。返回 [storage](../README.md)。
|
||||
|
||||
+41
-109
@@ -1,4 +1,5 @@
|
||||
//! Host metadata storage; deliberately has no dependency on core.
|
||||
//! Explicit database connections for database-backed objects.
|
||||
//! Connecting never creates application tables or stores VM/host metadata.
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
@@ -8,17 +9,15 @@ use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
|
||||
use sqlx::{PgPool, SqlitePool};
|
||||
|
||||
const SCHEMA: &str = include_str!("schema.sql");
|
||||
|
||||
/// An explicit PostgreSQL configuration never falls back to SQLite.
|
||||
#[derive(Clone)]
|
||||
pub enum StorageConfig {
|
||||
pub enum DatabaseConfig {
|
||||
SqliteFile(PathBuf),
|
||||
SqliteMemory,
|
||||
Postgres(String),
|
||||
}
|
||||
|
||||
impl fmt::Debug for StorageConfig {
|
||||
impl fmt::Debug for DatabaseConfig {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::SqliteFile(path) => f.debug_tuple("SqliteFile").field(path).finish(),
|
||||
@@ -28,57 +27,14 @@ impl fmt::Debug for StorageConfig {
|
||||
}
|
||||
}
|
||||
|
||||
impl StorageConfig {
|
||||
/// DATABASE_URL accepts PostgreSQL only; SQLITE_PATH selects file or :memory:.
|
||||
/// Empty/invalid explicit values are errors rather than default selection.
|
||||
pub fn from_values(
|
||||
database_url: Option<&str>,
|
||||
sqlite_path: Option<&str>,
|
||||
) -> Result<Self, StorageError> {
|
||||
if let Some(url) = database_url {
|
||||
if !(url.starts_with("postgres://") || url.starts_with("postgresql://")) {
|
||||
return Err(StorageError::Config(
|
||||
"DATABASE_URL must be a PostgreSQL URL",
|
||||
));
|
||||
}
|
||||
return Ok(Self::Postgres(url.into()));
|
||||
}
|
||||
match sqlite_path.unwrap_or("data/aster.db") {
|
||||
"" => Err(StorageError::Config("SQLITE_PATH cannot be empty")),
|
||||
":memory:" => Ok(Self::SqliteMemory),
|
||||
path => Ok(Self::SqliteFile(path.into())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_env() -> Result<Self, StorageError> {
|
||||
let database_url = read_env("DATABASE_URL")?;
|
||||
// Irrelevant SQLite settings must not prevent PostgreSQL configuration.
|
||||
if database_url.is_some() {
|
||||
return Self::from_values(database_url.as_deref(), None);
|
||||
}
|
||||
let sqlite_path = read_env("SQLITE_PATH")?;
|
||||
Self::from_values(None, sqlite_path.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
fn read_env(name: &str) -> Result<Option<String>, StorageError> {
|
||||
match std::env::var(name) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(StorageError::Config(
|
||||
"storage environment must be valid Unicode",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StorageError {
|
||||
pub enum DatabaseError {
|
||||
Config(&'static str),
|
||||
Directory(std::io::Error),
|
||||
Database(sqlx::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for StorageError {
|
||||
impl fmt::Display for DatabaseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Config(message) => f.write_str(message),
|
||||
@@ -91,7 +47,7 @@ impl fmt::Display for StorageError {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for StorageError {
|
||||
impl std::error::Error for DatabaseError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Config(_) => None,
|
||||
@@ -101,7 +57,7 @@ impl std::error::Error for StorageError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for StorageError {
|
||||
impl From<sqlx::Error> for DatabaseError {
|
||||
fn from(error: sqlx::Error) -> Self {
|
||||
Self::Database(error)
|
||||
}
|
||||
@@ -113,20 +69,26 @@ enum Backend {
|
||||
Postgres(PgPool),
|
||||
}
|
||||
|
||||
/// Clones share a pool. A memory SQLite store uses exactly one connection, so
|
||||
/// initialization and every operation see the same database for its lifetime.
|
||||
/// Created only on explicit request by an object or host adapter. Clones share
|
||||
/// a pool; close() closes it for all users. There is no automatic schema or data.
|
||||
/// In-memory SQLite uses one connection to preserve its database lifetime.
|
||||
#[derive(Clone)]
|
||||
pub struct Storage {
|
||||
pub struct DatabaseConnection {
|
||||
backend: Backend,
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
/// Connects eagerly and initializes the v1 metadata schema before returning.
|
||||
pub async fn connect(config: &StorageConfig) -> Result<Self, StorageError> {
|
||||
impl DatabaseConnection {
|
||||
/// Connects eagerly to the explicit backend without executing application DDL.
|
||||
pub async fn connect(config: &DatabaseConfig) -> Result<Self, DatabaseError> {
|
||||
let backend = match config {
|
||||
StorageConfig::Postgres(url) => {
|
||||
DatabaseConfig::Postgres(url) => {
|
||||
if !(url.starts_with("postgres://") || url.starts_with("postgresql://")) {
|
||||
return Err(DatabaseError::Config(
|
||||
"expected a PostgreSQL connection URL",
|
||||
));
|
||||
}
|
||||
let options = PgConnectOptions::from_str(url)
|
||||
.map_err(|_| StorageError::Config("invalid PostgreSQL connection URL"))?;
|
||||
.map_err(|_| DatabaseError::Config("invalid PostgreSQL connection URL"))?;
|
||||
Backend::Postgres(
|
||||
PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
@@ -135,16 +97,16 @@ impl Storage {
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
StorageConfig::SqliteFile(path) => {
|
||||
DatabaseConfig::SqliteFile(path) => {
|
||||
if path.as_os_str().is_empty() || path == std::path::Path::new(":memory:") {
|
||||
return Err(StorageError::Config(
|
||||
"use SqliteMemory for an in-memory database",
|
||||
return Err(DatabaseError::Config(
|
||||
"expected a nonempty file path; use SqliteMemory for :memory:",
|
||||
));
|
||||
}
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(StorageError::Directory)?;
|
||||
.map_err(DatabaseError::Directory)?;
|
||||
}
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
@@ -159,7 +121,7 @@ impl Storage {
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
StorageConfig::SqliteMemory => {
|
||||
DatabaseConfig::SqliteMemory => {
|
||||
let options = SqliteConnectOptions::new().in_memory(true);
|
||||
Backend::Sqlite(
|
||||
SqlitePoolOptions::new()
|
||||
@@ -172,21 +134,22 @@ impl Storage {
|
||||
)
|
||||
}
|
||||
};
|
||||
let storage = Self { backend };
|
||||
storage.initialize().await?;
|
||||
Ok(storage)
|
||||
Ok(Self { backend })
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), StorageError> {
|
||||
/// Backend-specific access for the database-backed object implementation.
|
||||
pub fn sqlite_pool(&self) -> Option<&SqlitePool> {
|
||||
match &self.backend {
|
||||
Backend::Sqlite(pool) => {
|
||||
sqlx::query(SCHEMA).execute(pool).await?;
|
||||
}
|
||||
Backend::Postgres(pool) => {
|
||||
sqlx::query(SCHEMA).execute(pool).await?;
|
||||
}
|
||||
Backend::Sqlite(pool) => Some(pool),
|
||||
Backend::Postgres(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn postgres_pool(&self) -> Option<&PgPool> {
|
||||
match &self.backend {
|
||||
Backend::Postgres(pool) => Some(pool),
|
||||
Backend::Sqlite(_) => None,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn backend_name(&self) -> &'static str {
|
||||
@@ -196,7 +159,7 @@ impl Storage {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn ping(&self) -> Result<(), StorageError> {
|
||||
pub async fn ping(&self) -> Result<(), DatabaseError> {
|
||||
match &self.backend {
|
||||
Backend::Sqlite(pool) => {
|
||||
sqlx::query("SELECT 1").execute(pool).await?;
|
||||
@@ -208,38 +171,7 @@ impl Storage {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn put(&self, key: &str, value: &str) -> Result<(), StorageError> {
|
||||
match &self.backend {
|
||||
Backend::Sqlite(pool) => {
|
||||
sqlx::query("INSERT INTO aster_metadata (key, value) VALUES (?1, ?2) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
|
||||
.bind(key).bind(value).execute(pool).await?;
|
||||
}
|
||||
Backend::Postgres(pool) => {
|
||||
sqlx::query("INSERT INTO aster_metadata (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
|
||||
.bind(key).bind(value).execute(pool).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
|
||||
Ok(match &self.backend {
|
||||
Backend::Sqlite(pool) => {
|
||||
sqlx::query_scalar("SELECT value FROM aster_metadata WHERE key = ?1")
|
||||
.bind(key)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
}
|
||||
Backend::Postgres(pool) => {
|
||||
sqlx::query_scalar("SELECT value FROM aster_metadata WHERE key = $1")
|
||||
.bind(key)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Explicitly closes the shared pool, including all Storage clones.
|
||||
/// Explicitly closes the shared pool, including all DatabaseConnection clones.
|
||||
pub async fn close(&self) {
|
||||
match &self.backend {
|
||||
Backend::Sqlite(pool) => pool.close().await,
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS aster_metadata (
|
||||
key TEXT PRIMARY KEY NOT NULL,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
@@ -1,8 +1,8 @@
|
||||
# Storage 行为检查
|
||||
# 数据库连接检查
|
||||
|
||||
| 文件 | 覆盖与前提 |
|
||||
| --- | --- |
|
||||
| [storage.rs](storage.rs) | 配置默认值/优先级/错误、内存共享与实例隔离、临时文件重连、目录错误;不处理 PostgreSQL 协议的 socket 仅检查连接超时和不降级 |
|
||||
| [postgres.rs](postgres.rs) | 真实 PostgreSQL 写入/覆盖/缺失键/重连;默认 ignore,显式运行需 ASTER_TEST_POSTGRES_URL 指向专用测试库 |
|
||||
| [storage.rs](storage.rs) | 显式错误配置、凭据脱敏、SQLite 连接后无应用表、克隆共享与独立内存隔离、调用方自建数据跨文件重连、目录错误、PostgreSQL 失败不降级 |
|
||||
| [postgres.rs](postgres.rs) | 真实连接后 public 无表;测试在事务中创建临时 class_rows、参数绑定和读取,提交自动删除临时表,再连接;默认 ignore,需全新专用 ASTER_TEST_POSTGRES_URL |
|
||||
|
||||
SQLite 文件检查使用临时目录;PostgreSQL 成功路径不使用生产数据库。ces-control 脚本提供一次性的测试数据库,见 [验证](../../../docs/operations/validation.md) 和 [scripts](../../../scripts/README.md)。不在本地运行或为测试下载 SQLite 依赖。返回 [storage](../README.md)。
|
||||
所有业务表都由测试自己创建,连接层不得自动初始化基础信息表。临时 SQLite 文件和 PostgreSQL 测试库由远端 CI 隔离,不使用生产数据。检查命令见 [验证](../../../docs/operations/validation.md),原生连接能力边界见 [数据库对象](../../../docs/runtime/database-objects.md)。本地不运行测试或下载依赖。返回 [storage](../README.md)。
|
||||
|
||||
@@ -1,35 +1,53 @@
|
||||
use storage::{Storage, StorageConfig};
|
||||
use storage::{DatabaseConfig, DatabaseConnection};
|
||||
|
||||
/// Run explicitly against a disposable database; never silently skip a missing URL.
|
||||
/// Run against a fresh disposable database, never a production or shared schema.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires ASTER_TEST_POSTGRES_URL pointing to a test PostgreSQL database"]
|
||||
async fn postgres_roundtrip_and_reconnect() {
|
||||
#[ignore = "requires ASTER_TEST_POSTGRES_URL pointing to a fresh disposable PostgreSQL database"]
|
||||
async fn postgres_connects_without_schema_and_executes_caller_owned_sql() {
|
||||
let url = std::env::var("ASTER_TEST_POSTGRES_URL")
|
||||
.expect("set ASTER_TEST_POSTGRES_URL to a disposable PostgreSQL database");
|
||||
let config = StorageConfig::from_values(Some(&url), None).unwrap();
|
||||
let store = Storage::connect(&config).await.unwrap();
|
||||
assert_eq!(store.backend_name(), "postgresql");
|
||||
store.ping().await.unwrap();
|
||||
let key = format!(
|
||||
"test.{}.{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
);
|
||||
assert_eq!(store.get(&key).await.unwrap(), None);
|
||||
store.put(&key, "你好 ' ; $1").await.unwrap();
|
||||
assert_eq!(
|
||||
store.get(&key).await.unwrap().as_deref(),
|
||||
Some("你好 ' ; $1")
|
||||
);
|
||||
store.put(&key, "updated").await.unwrap();
|
||||
store.close().await;
|
||||
let reopened = Storage::connect(&config).await.unwrap();
|
||||
assert_eq!(
|
||||
reopened.get(&key).await.unwrap().as_deref(),
|
||||
Some("updated")
|
||||
);
|
||||
.expect("set ASTER_TEST_POSTGRES_URL to a fresh disposable PostgreSQL database");
|
||||
let config = DatabaseConfig::Postgres(url);
|
||||
let database = DatabaseConnection::connect(&config).await.unwrap();
|
||||
assert_eq!(database.backend_name(), "postgresql");
|
||||
assert!(database.sqlite_pool().is_none());
|
||||
database.ping().await.unwrap();
|
||||
let pool = database.postgres_pool().unwrap();
|
||||
let tables: i64 = sqlx::query_scalar(
|
||||
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(tables, 0, "connecting must not create application tables");
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query(
|
||||
"CREATE TEMP TABLE class_rows (id INTEGER PRIMARY KEY, value TEXT NOT NULL) ON COMMIT DROP",
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO class_rows (id, value) VALUES ($1, $2)")
|
||||
.bind(1_i64)
|
||||
.bind("你好 ' ; $1")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
let value: String = sqlx::query_scalar("SELECT value FROM class_rows WHERE id = $1")
|
||||
.bind(1_i64)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(value, "你好 ' ; $1");
|
||||
transaction.commit().await.unwrap();
|
||||
database.close().await;
|
||||
let reopened = DatabaseConnection::connect(&config).await.unwrap();
|
||||
reopened.ping().await.unwrap();
|
||||
let tables: i64 = sqlx::query_scalar(
|
||||
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'",
|
||||
)
|
||||
.fetch_one(reopened.postgres_pool().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(tables, 0);
|
||||
reopened.close().await;
|
||||
}
|
||||
|
||||
@@ -1,69 +1,104 @@
|
||||
use storage::{Storage, StorageConfig};
|
||||
use storage::{DatabaseConfig, DatabaseConnection};
|
||||
|
||||
#[test]
|
||||
fn configuration_defaults_precedence_and_errors() {
|
||||
assert!(
|
||||
matches!(StorageConfig::from_values(None, None).unwrap(), StorageConfig::SqliteFile(p) if p.to_str() == Some("data/aster.db"))
|
||||
);
|
||||
assert!(matches!(
|
||||
StorageConfig::from_values(None, Some(":memory:")).unwrap(),
|
||||
StorageConfig::SqliteMemory
|
||||
));
|
||||
assert!(matches!(
|
||||
StorageConfig::from_values(Some("postgresql://localhost/aster"), Some("")).unwrap(),
|
||||
StorageConfig::Postgres(_)
|
||||
));
|
||||
assert!(StorageConfig::from_values(Some(""), None).is_err());
|
||||
assert!(StorageConfig::from_values(Some("mysql://localhost/aster"), None).is_err());
|
||||
assert!(StorageConfig::from_values(None, Some("")).is_err());
|
||||
let config = StorageConfig::Postgres("postgres://user:secret@localhost/db".into());
|
||||
fn postgres_configuration_debug_redacts_credentials() {
|
||||
let config = DatabaseConfig::Postgres("postgres://user:secret@localhost/db".into());
|
||||
assert!(!format!("{config:?}").contains("secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_store_is_shared_by_clones_but_isolated_between_stores() {
|
||||
let store = Storage::connect(&StorageConfig::SqliteMemory)
|
||||
async fn explicit_invalid_backends_fail_without_fallback() {
|
||||
for config in [
|
||||
DatabaseConfig::Postgres(String::new()),
|
||||
DatabaseConfig::Postgres("mysql://localhost/db".into()),
|
||||
DatabaseConfig::SqliteFile("".into()),
|
||||
DatabaseConfig::SqliteFile(":memory:".into()),
|
||||
] {
|
||||
assert!(DatabaseConnection::connect(&config).await.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_connections_start_without_tables_and_clones_share_the_pool() {
|
||||
let database = DatabaseConnection::connect(&DatabaseConfig::SqliteMemory)
|
||||
.await
|
||||
.unwrap();
|
||||
let other = Storage::connect(&StorageConfig::SqliteMemory)
|
||||
let other = DatabaseConnection::connect(&DatabaseConfig::SqliteMemory)
|
||||
.await
|
||||
.unwrap();
|
||||
store.ping().await.unwrap();
|
||||
assert_eq!(store.get("missing").await.unwrap(), None);
|
||||
store.put("message", "你好 ' ? $1 ;").await.unwrap();
|
||||
assert_eq!(
|
||||
store.clone().get("message").await.unwrap().as_deref(),
|
||||
Some("你好 ' ? $1 ;")
|
||||
);
|
||||
assert_eq!(other.get("message").await.unwrap(), None);
|
||||
store.put("message", "updated").await.unwrap();
|
||||
assert_eq!(
|
||||
store.get("message").await.unwrap().as_deref(),
|
||||
Some("updated")
|
||||
);
|
||||
store.close().await;
|
||||
assert!(database.postgres_pool().is_none());
|
||||
let pool = database.sqlite_pool().unwrap();
|
||||
let tables: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(tables, 0, "connecting must not create application tables");
|
||||
// This schema belongs to the test's simulated database-backed object.
|
||||
sqlx::query("CREATE TABLE class_rows (id INTEGER PRIMARY KEY, value TEXT NOT NULL)")
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO class_rows (id, value) VALUES (?, ?)")
|
||||
.bind(1_i64)
|
||||
.bind("你好 ' ? $1 ;")
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let cloned = database.clone();
|
||||
let value: String = sqlx::query_scalar("SELECT value FROM class_rows WHERE id = ?")
|
||||
.bind(1_i64)
|
||||
.fetch_one(cloned.sqlite_pool().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(value, "你好 ' ? $1 ;");
|
||||
let other_tables: i64 =
|
||||
sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'")
|
||||
.fetch_one(other.sqlite_pool().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(other_tables, 0);
|
||||
database.close().await;
|
||||
assert!(cloned.ping().await.is_err());
|
||||
other.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlite_file_creates_parents_and_survives_reopen() {
|
||||
async fn explicit_sqlite_file_preserves_only_caller_created_data_across_reconnects() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested/data/metadata.db");
|
||||
let config = StorageConfig::SqliteFile(path.clone());
|
||||
let store = Storage::connect(&config).await.unwrap();
|
||||
store.put("project", "Aster VM").await.unwrap();
|
||||
store.close().await;
|
||||
let path = dir.path().join("nested/data/class.db");
|
||||
let config = DatabaseConfig::SqliteFile(path.clone());
|
||||
let database = DatabaseConnection::connect(&config).await.unwrap();
|
||||
let pool = database.sqlite_pool().unwrap();
|
||||
let tables: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(tables, 0);
|
||||
sqlx::query("CREATE TABLE class_rows (id INTEGER PRIMARY KEY, value TEXT NOT NULL)")
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO class_rows (id, value) VALUES (?, ?)")
|
||||
.bind(1_i64)
|
||||
.bind("caller-owned data")
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
database.close().await;
|
||||
assert!(path.is_file());
|
||||
let reopened = Storage::connect(&config).await.unwrap();
|
||||
assert_eq!(
|
||||
reopened.get("project").await.unwrap().as_deref(),
|
||||
Some("Aster VM")
|
||||
);
|
||||
reopened.put("project", "v2").await.unwrap();
|
||||
assert_eq!(
|
||||
reopened.get("project").await.unwrap().as_deref(),
|
||||
Some("v2")
|
||||
);
|
||||
let reopened = DatabaseConnection::connect(&config).await.unwrap();
|
||||
let value: String = sqlx::query_scalar("SELECT value FROM class_rows WHERE id = ?")
|
||||
.bind(1_i64)
|
||||
.fetch_one(reopened.sqlite_pool().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(value, "caller-owned data");
|
||||
let tables: Vec<String> =
|
||||
sqlx::query_scalar("SELECT name FROM sqlite_master WHERE type = 'table'")
|
||||
.fetch_all(reopened.sqlite_pool().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(tables, vec!["class_rows"]);
|
||||
reopened.close().await;
|
||||
}
|
||||
|
||||
@@ -73,7 +108,7 @@ async fn invalid_sqlite_directory_reports_error() {
|
||||
let file = dir.path().join("file");
|
||||
std::fs::write(&file, "occupied").unwrap();
|
||||
assert!(
|
||||
Storage::connect(&StorageConfig::SqliteFile(file.join("aster.db")))
|
||||
DatabaseConnection::connect(&DatabaseConfig::SqliteFile(file.join("class.db")))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
@@ -81,14 +116,12 @@ async fn invalid_sqlite_directory_reports_error() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn postgres_connection_failure_is_an_error() {
|
||||
// Hold a TCP port without serving PostgreSQL: deterministic local failure.
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
"postgres://aster:secret@{}/aster?sslmode=disable",
|
||||
listener.local_addr().unwrap()
|
||||
);
|
||||
let result = Storage::connect(&StorageConfig::Postgres(url)).await;
|
||||
let error = match result {
|
||||
let error = match DatabaseConnection::connect(&DatabaseConfig::Postgres(url)).await {
|
||||
Ok(_) => panic!("unreachable PostgreSQL must fail"),
|
||||
Err(error) => error,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user