refactor: reduce quality findings

This commit is contained in:
2026-06-28 15:42:12 +08:00
parent 02716d3ccd
commit 3c00659691
11 changed files with 189 additions and 135 deletions
+48 -29
View File
@@ -2,7 +2,7 @@
use crate::error::{CasError, Result};
use crate::hash::Hash;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions, SqliteQueryResult};
use sqlx::SqlitePool;
use std::path::Path;
use std::str::FromStr;
@@ -54,43 +54,50 @@ impl SqliteRefCounter {
}
async fn init_schema(&self) -> Result<()> {
sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS cas_objects (
hash TEXT PRIMARY KEY NOT NULL,
size INTEGER NOT NULL CHECK(size >= 0),
ref_count INTEGER NOT NULL CHECK(ref_count >= 0),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
zero_ref_at INTEGER
)
"#,
let _schema_result = Self::execute_query(
&self.pool,
sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS cas_objects (
hash TEXT PRIMARY KEY NOT NULL,
size INTEGER NOT NULL CHECK(size >= 0),
ref_count INTEGER NOT NULL CHECK(ref_count >= 0),
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
zero_ref_at INTEGER
)
"#,
),
)
.execute(&self.pool)
.await?;
sqlx::query(
r#"
CREATE INDEX IF NOT EXISTS idx_cas_objects_ref_count
ON cas_objects(ref_count)
"#,
let _index_result = Self::execute_query(
&self.pool,
sqlx::query(
r#"
CREATE INDEX IF NOT EXISTS idx_cas_objects_ref_count
ON cas_objects(ref_count)
"#,
),
)
.execute(&self.pool)
.await?;
Ok(())
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs() as i64)
.unwrap_or_default()
async fn execute_query<'q>(
pool: &SqlitePool,
query: sqlx::query::Query<'q, sqlx::Sqlite, sqlx::sqlite::SqliteArguments<'q>>,
) -> Result<SqliteQueryResult> {
let result = query.execute(pool).await?;
Ok(result)
}
/// 注册对象元数据。如果对象已存在,仅更新大小和更新时间。
pub async fn ensure_object(&self, hash: &Hash, size: u64) -> Result<()> {
let now = Self::now();
fn insert_or_update_object_query(
hash: &Hash,
size: u64,
now: i64,
) -> sqlx::query::Query<'_, sqlx::Sqlite, sqlx::sqlite::SqliteArguments<'_>> {
sqlx::query(
r#"
INSERT INTO cas_objects(hash, size, ref_count, created_at, updated_at, zero_ref_at)
@@ -103,8 +110,20 @@ impl SqliteRefCounter {
.bind(hash.to_string())
.bind(size as i64)
.bind(now)
.execute(&self.pool)
.await?;
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs() as i64)
.unwrap_or_default()
}
/// 注册对象元数据。如果对象已存在,仅更新大小和更新时间。
pub async fn ensure_object(&self, hash: &Hash, size: u64) -> Result<()> {
let now = Self::now();
let query = Self::insert_or_update_object_query(hash, size, now);
let _upsert_result = Self::execute_query(&self.pool, query).await?;
Ok(())
}