use std::time::Duration;
use laravel::Application;
use laravel::cache::{self, CacheManager, Repository};
use laravel::config::Env;
use laravel::config::cache::DatabaseStore;
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, AnyConnection, DatabaseManager, Driver};
use laravel::testing::MakesConsoleRequests;
use crate::cache::eventually;
use crate::support::TempDir;
const MINUTE: Duration = Duration::from_secs(60);
const HOUR: Duration = Duration::from_secs(60 * 60);
fn time(connection: &AnyConnection) -> &'static str {
match connection.driver() {
Driver::MySql | Driver::MariaDb => "DATETIME(6)",
_ => "TIMESTAMP(6)",
}
}
fn create_table(connection: &AnyConnection, table: &str) -> String {
let (key, value) = match connection.driver() {
Driver::MySql | Driver::MariaDb => ("`key` VARCHAR(255) NOT NULL PRIMARY KEY", "`value` MEDIUMTEXT NOT NULL"),
_ => ("\"key\" VARCHAR(255) NOT NULL PRIMARY KEY", "\"value\" TEXT NOT NULL"),
};
format!(
"CREATE TABLE {table} ({key}, {value}, expiration {} NOT NULL)",
time(connection)
)
}
fn create_lock_table(connection: &AnyConnection, table: &str) -> String {
let key = match connection.driver() {
Driver::MySql | Driver::MariaDb => "`key` VARCHAR(255) NOT NULL PRIMARY KEY",
_ => "\"key\" VARCHAR(255) NOT NULL PRIMARY KEY",
};
format!(
"CREATE TABLE {table} ({key}, owner VARCHAR(255) NOT NULL, expiration {} NOT NULL)",
time(connection)
)
}
async fn recreate_tables(connection: &AnyConnection, tables: &[&str]) -> laravel::Result<()> {
for table in tables {
let create = if table.ends_with("_locks") {
create_lock_table(connection, table)
} else {
create_table(connection, table)
};
connection
.query(db::sqlx::AssertSqlSafe(format!("DROP TABLE IF EXISTS {table}")))
.statement()
.await?;
connection.query(db::sqlx::AssertSqlSafe(create)).statement().await?;
}
Ok(())
}
async fn application(connection: ConnectionConfig, store: DatabaseStore) -> laravel::Result<Application> {
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "database")]))
.with_config(move |config, _| {
config.database.default = "cache".into();
config.database.add_connection("cache", connection);
config
.cache
.add_store(
"database",
store.table("laravel_cache").lock_table("laravel_cache_locks"),
)
.add_store(
"reports",
DatabaseStore::new()
.table("laravel_report_cache")
.lock_table("laravel_cache_locks")
.without_pruning(),
);
})
.create();
recreate_tables(
&db_connection(&app).await?,
&["laravel_cache", "laravel_report_cache", "laravel_cache_locks"],
)
.await?;
Ok(app)
}
fn sqlite(directory: &TempDir) -> ConnectionConfig {
ConnectionConfig::new(format!(
"sqlite://{}?mode=rwc",
directory.join("cache.sqlite").display()
))
}
async fn db_connection(app: &Application) -> laravel::Result<AnyConnection> {
app.resolve::<DatabaseManager>().await.default_connection()
}
async fn store(app: &Application, name: &str) -> laravel::Result<Repository> {
app.resolve::<CacheManager>().await.store(name)
}
async fn count_rows(app: &Application, table: &str) -> laravel::Result<i64> {
let count = db_connection(app)
.await?
.query(db::sqlx::AssertSqlSafe(format!("SELECT COUNT(*) FROM {table}")))
.scalar::<i64>()
.await?;
Ok(count.unwrap_or_default())
}
async fn count_expired(app: &Application, table: &str) -> laravel::Result<i64> {
let now = app.scope(async || laravel::now().timestamp()).await;
let connection = db_connection(app).await?;
let placeholder = if connection.driver() == Driver::Postgres {
"$1"
} else {
"?"
};
let count = connection
.query(db::sqlx::AssertSqlSafe(format!(
"SELECT COUNT(*) FROM {table} WHERE expiration <= {placeholder}"
)))
.bind(now)
.scalar::<i64>()
.await?;
Ok(count.unwrap_or_default())
}
async fn store_contract(app: &Application) -> laravel::Result<()> {
let cache = store(app, "database").await?;
let reports = store(app, "reports").await?;
crate::cache::store_contract(app, &cache).await?;
let (removed, stored) = tokio::join!(biased; cache.forget("report"), cache.put("report", 42, MINUTE));
stored?;
assert_eq!(cache.get::<i64>("report").await?, (!removed?).then_some(42));
cache.put("user", 1, MINUTE).await?;
assert_eq!(
reports.get::<i64>("user").await?,
None,
"stores sharing a connection keep their own tables"
);
reports.put("kept", 1, MINUTE).await?;
cache.flush().await?;
assert!(!cache.has("user").await?);
assert!(reports.has("kept").await?, "flushing empties only the store's table");
assert!(cache.lock("shared", MINUTE).acquire().await?);
assert!(
!reports.lock("shared", MINUTE).acquire().await?,
"stores sharing a lock table share their locks"
);
cache.lock("shared", MINUTE).force_release().await?;
prune_contract(app, &cache).await?;
app.travel_back();
Ok(())
}
async fn prune_contract(app: &Application, cache: &Repository) -> laravel::Result<()> {
let expiring: Vec<(String, i64)> = (0..1500).map(|n| (format!("expiring:{n}"), n)).collect();
cache.put_many(expiring, Duration::from_secs(1)).await?;
cache.put("kept", true, HOUR).await?;
assert!(cache.lock("expiring", Duration::from_secs(1)).acquire().await?);
app.travel(Duration::from_secs(2));
assert!(count_expired(app, "laravel_cache").await? >= 1500);
cache.prune().await?;
assert_eq!(count_expired(app, "laravel_cache").await?, 0, "every batch was pruned");
assert_eq!(count_expired(app, "laravel_cache_locks").await?, 0);
assert_eq!(cache.get::<bool>("kept").await?, Some(true));
Ok(())
}
#[tokio::test]
async fn sqlite_stores_values_in_their_tables() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite");
let mut connection = sqlite(&directory);
connection.max_connections = 1;
let app = application(connection, DatabaseStore::new().without_pruning()).await?;
app.scope(async || store_contract(&app).await).await
}
#[tokio::test]
async fn cache_writes_join_a_transaction_on_their_connection_and_roll_back_with_it() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-transaction");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.scope(async || {
db::transaction(async |tx| {
tx.query("SELECT 1").statement().await?;
cache::put("committed", 1, MINUTE).await?;
let rows = tx.query("SELECT COUNT(*) FROM laravel_cache").scalar::<i64>().await?;
assert_eq!(rows, Some(1), "the cache wrote in the transaction");
Ok(())
})
.await?;
let rolled_back: laravel::Result<()> = db::transaction(async |_| {
cache::put("rolled-back", 2, MINUTE).await?;
assert_eq!(cache::get::<i64>("rolled-back").await?, Some(2));
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
let cache = cache::store("database")?;
assert_eq!(cache.get::<i64>("committed").await?, Some(1));
assert_eq!(cache.get::<i64>("rolled-back").await?, None);
Ok(())
})
.await
}
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn transaction_lock_contract(app: &Application) -> laravel::Result<()> {
let cache = store(app, "database").await?;
let outside = db::default_connection()?.outside_transaction();
let locks = async || -> laravel::Result<Option<i64>> {
outside
.query("SELECT COUNT(*) FROM laravel_cache_locks")
.scalar::<i64>()
.await
};
let rolled_back: laravel::Result<()> = db::transaction(async |tx| {
tx.query("SELECT COUNT(*) FROM laravel_cache").select().await?;
assert!(cache.lock("invoice", MINUTE).acquire().await?);
assert_eq!(
locks().await?,
Some(1),
"other connections see the lock before the commit"
);
Err(laravel::abort_with(409, "Roll back"))
})
.await;
let error = rolled_back.unwrap_err();
assert_eq!(error.status().as_u16(), 409, "{error:?}");
assert_eq!(locks().await?, Some(1), "the rollback doesn't release the lock");
assert!(!cache.lock("invoice", MINUTE).acquire().await?);
Ok(())
}
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
async fn transaction_increment_contract() -> laravel::Result<()> {
let connection = db::default_connection()?;
let mariadb = matches!(connection.driver(), Driver::MySql | Driver::MariaDb)
&& connection
.query("SELECT VERSION() LIKE '%MariaDB%'")
.scalar::<i64>()
.await?
== Some(1);
cache::put("hits", 1, MINUTE).await?;
let attempts = std::sync::atomic::AtomicU32::new(0);
connection
.transaction_with_attempts(2, async |_| {
let first = attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0;
assert_eq!(cache::get::<i64>("hits").await?, Some(if first { 1 } else { 5 }));
if first {
db::default_connection()?
.outside_transaction()
.query("UPDATE laravel_cache SET value = '5'")
.update()
.await?;
}
let incremented = tokio::time::timeout(std::time::Duration::from_secs(5), cache::increment("hits", 1))
.await
.expect("the increment must not retry a stale read forever")?;
assert_eq!(incremented, Some(6));
Ok(())
})
.await?;
assert_eq!(attempts.into_inner(), if mariadb { 2 } else { 1 });
assert_eq!(cache::get::<i64>("hits").await?, Some(6));
Ok(())
}
#[tokio::test]
async fn sqlite_locks_join_transactions_instead_of_waiting_for_them() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-locks");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.scope(async || {
let cache = store(&app, "database").await?;
let rolled_back: laravel::Result<()> = db::transaction(async |tx| {
tx.query(
"INSERT INTO laravel_cache (key, value, expiration) VALUES ('written', '1', '2000-01-01 00:00:00')",
)
.insert()
.await?;
let acquired = tokio::time::timeout(
std::time::Duration::from_secs(2),
cache.lock("invoice", MINUTE).acquire(),
)
.await
.expect("the lock doesn't wait for the transaction it runs in")?;
assert!(acquired);
assert!(
!cache.lock("invoice", MINUTE).acquire().await?,
"the lock is held inside the transaction"
);
Err(laravel::abort_with(409, "Roll back"))
})
.await;
assert_eq!(rolled_back.unwrap_err().status().as_u16(), 409);
assert!(
cache.lock("invoice", MINUTE).acquire().await?,
"the rollback released the lock"
);
Ok(())
})
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn sqlite_counters_and_claims_are_atomic() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-concurrency");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.scope(crate::cache::concurrency_contract).await
}
#[tokio::test]
async fn rows_hold_prefixed_keys_json_values_and_expirations() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-rows");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.travel_to("2026-10-12T12:00:00Z".parse::<laravel::time::Timestamp>()?);
let cache = store(&app, "database").await?;
app.scope(async || {
cache
.put("user", serde_json::json!({ "name": "Taylor" }), MINUTE)
.await?;
cache.put("hour", 1, HOUR).await
})
.await?;
let rows = db_connection(&app)
.await?
.query("SELECT \"key\", \"value\", expiration FROM laravel_cache ORDER BY \"key\"")
.select()
.await?;
let rows: Vec<(String, String, laravel::time::Timestamp)> = rows
.iter()
.map(|row| Ok((row.try_get(0_usize)?, row.try_get(1_usize)?, row.try_get(2_usize)?)))
.collect::<laravel::Result<_>>()?;
assert_eq!(
rows,
[
(
"laravel_cache_hour".to_owned(),
"1".to_owned(),
"2026-10-12T13:00:00Z".parse()?
),
(
"laravel_cache_user".to_owned(),
r#"{"name":"Taylor"}"#.to_owned(),
"2026-10-12T12:01:00Z".parse()?
),
]
);
Ok(())
}
#[tokio::test]
async fn the_connection_is_chosen_for_each_operation() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-scoped");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
let manager = app.resolve::<DatabaseManager>().await;
let tenant = TempDir::new("cache-sqlite-tenant");
manager.add_connection("tenant", sqlite(&tenant));
recreate_tables(&manager.connection("tenant")?, &["laravel_report_cache"]).await?;
app.scope(async || {
let reports = store(&app, "reports").await?;
reports.put("key", "default", MINUTE).await?;
manager
.using_connection("tenant", reports.put("key", "tenant", MINUTE))
.await?;
assert_eq!(reports.get::<String>("key").await?.as_deref(), Some("default"));
assert_eq!(
manager
.using_connection("tenant", reports.get::<String>("key"))
.await?
.as_deref(),
Some("tenant")
);
Ok(())
})
.await
}
#[tokio::test]
async fn database_stores_open_nothing_until_used() -> laravel::Result<()> {
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "database")]))
.with_config(|config, _| {
config.database.default = "unreachable".into();
let mut unreachable = ConnectionConfig::new("postgres://laravel@127.0.0.1:1/laravel");
unreachable.acquire_timeout = Duration::from_millis(100).into();
config.database.add_connection("unreachable", unreachable);
})
.create();
app.command("route:list --json").await.assert_successful();
assert!(app.scope(async || cache::get::<i64>("key").await).await.is_err());
Ok(())
}
#[tokio::test]
async fn missing_tables_and_invalid_table_names_are_errors() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-invalid");
let connection = sqlite(&directory);
let app = Application::configure()
.replace_env(Env::from_iter([("CACHE_STORE", "database")]))
.with_config(move |config, _| {
config.database.add_connection("sqlite", connection);
config.database.default = "sqlite".into();
config
.cache
.add_store("invalid", DatabaseStore::new().table("cache; DROP TABLE users"));
})
.create();
assert!(app.scope(async || cache::get::<i64>("key").await).await.is_err());
let invalid = app.resolve::<CacheManager>().await.store("invalid").unwrap_err();
assert!(invalid.to_string().contains("must be letters, digits and underscores"));
Ok(())
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_stores_values_in_their_tables() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL")?;
let app = application(ConnectionConfig::new(url), DatabaseStore::new().without_pruning()).await?;
app.scope(async || store_contract(&app).await).await?;
app.scope(crate::cache::concurrency_contract).await?;
recreate_tables(&db_connection(&app).await?, &["laravel_cache_locks"]).await?;
app.scope(async || transaction_lock_contract(&app).await).await?;
app.scope(transaction_increment_contract).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_stores_values_in_their_tables() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL")?;
let app = application(ConnectionConfig::new(url), DatabaseStore::new().without_pruning()).await?;
app.scope(async || store_contract(&app).await).await?;
app.scope(crate::cache::concurrency_contract).await?;
recreate_tables(&db_connection(&app).await?, &["laravel_cache_locks"]).await?;
app.scope(async || transaction_lock_contract(&app).await).await?;
app.scope(transaction_increment_contract).await
}
#[tokio::test]
async fn cache_prune_deletes_expired_values_and_locks() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-prune");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.freeze_time();
app.scope(async || {
let cache = laravel::cache::store("database")?;
let expiring: Vec<(String, i64)> = (0..2500).map(|n| (format!("expiring:{n}"), n)).collect();
cache.put_many(expiring, Duration::from_secs(1)).await?;
cache.put("kept", 1, HOUR).await?;
cache.lock("expiring", Duration::from_secs(1)).acquire().await?;
cache.lock("held", HOUR).acquire().await
})
.await?;
app.travel(Duration::from_secs(2));
app.command("cache:prune database")
.await
.assert_successful()
.assert_error_output_contains("Expired entries pruned from cache store `database`.");
assert_eq!(count_rows(&app, "laravel_cache").await?, 1);
assert_eq!(count_rows(&app, "laravel_cache_locks").await?, 1);
Ok(())
}
#[tokio::test]
async fn servers_sharing_the_tables_prune_once_per_interval() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-background-prune");
let first = application(sqlite(&directory), DatabaseStore::new()).await?;
let second = application(sqlite(&directory), DatabaseStore::new()).await?;
let connection = db_connection(&first).await?;
let start = "2026-10-12T12:00:00Z".parse::<laravel::time::Timestamp>()?;
let travel = |offset: Duration| {
first.travel_to(start + offset);
second.travel_to(start + offset);
};
connection
.query(db::sqlx::AssertSqlSafe(format!(
"INSERT INTO laravel_cache VALUES ('laravel_cache_old', '1', '{}')",
(start + Duration::from_secs(1)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
)))
.statement()
.await?;
connection
.query(db::sqlx::AssertSqlSafe(format!(
"INSERT INTO laravel_cache_locks VALUES ('laravel:cache:prune:laravel_cache', 'elsewhere', '{}')",
(start + HOUR).strftime("%Y-%m-%dT%H:%M:%S+00:00")
)))
.statement()
.await?;
travel(Duration::from_secs(2));
second
.scope(async || laravel::cache::put("new", 1, HOUR * 2).await)
.await?;
first
.scope(async || laravel::cache::put("newer", 1, HOUR * 2).await)
.await?;
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(
count_expired(&first, "laravel_cache").await?,
1,
"the expired value is still there"
);
travel(HOUR + Duration::from_secs(3));
first
.scope(async || laravel::cache::put("latest", 1, HOUR).await)
.await?;
assert!(
eventually(async || Ok(count_expired(&first, "laravel_cache").await? == 0)).await?,
"the expired value is pruned"
);
assert_eq!(count_rows(&first, "laravel_cache").await?, 3);
Ok(())
}
#[tokio::test]
async fn stores_without_pruning_leave_expired_rows() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-no-prune");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
app.freeze_time();
app.scope(async || laravel::cache::put("old", 1, Duration::from_secs(1)).await)
.await?;
app.travel(Duration::from_secs(2));
app.scope(async || laravel::cache::put("new", 1, HOUR).await).await?;
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(count_expired(&app, "laravel_cache").await?, 1);
assert_eq!(count_rows(&app, "laravel_cache_locks").await?, 0);
Ok(())
}
#[tokio::test]
async fn background_pruning_clears_a_backlog_in_one_pass() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-prune-backlog");
let app = application(sqlite(&directory), DatabaseStore::new()).await?;
app.freeze_time();
app.scope(async || {
let cache = laravel::cache::store("database")?;
for batch in 0..5 {
let expiring: Vec<(String, i64)> = (0..2500).map(|n| (format!("expiring:{batch}:{n}"), n)).collect();
cache.put_many(expiring, Duration::from_secs(1)).await?;
}
Ok::<_, laravel::Error>(())
})
.await?;
app.travel(HOUR + Duration::from_secs(2));
app.scope(async || laravel::cache::put("new", 1, HOUR).await).await?;
assert!(
eventually(async || Ok(count_expired(&app, "laravel_cache").await? == 0)).await?,
"{} expired values are left after one prune",
count_expired(&app, "laravel_cache").await?
);
Ok(())
}
#[tokio::test]
async fn values_and_locks_last_at_least_their_lifetime() -> laravel::Result<()> {
let directory = TempDir::new("cache-sqlite-whole-lifetime");
let app = application(sqlite(&directory), DatabaseStore::new().without_pruning()).await?;
let start = "2026-10-28T12:00:00.990Z".parse::<laravel::time::Timestamp>()?;
app.travel_to(start);
let first = app
.scope(async || {
laravel::cache::put("value", 1, Duration::from_secs(1)).await?;
laravel::cache::lock("job", Duration::from_secs(1))?.acquire().await
})
.await?;
app.travel_to(start + Duration::from_millis(10));
let (value, second) = app
.scope(async || {
let value = laravel::cache::get::<i64>("value").await?;
Ok::<_, laravel::Error>((
value,
laravel::cache::lock("job", Duration::from_secs(1))?.acquire().await?,
))
})
.await?;
assert!(first);
assert_eq!(value, Some(1), "a one-second value expired after 10 milliseconds");
assert!(!second, "a second owner took a one-second lock 10 milliseconds later");
Ok(())
}