Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion crates/database/src/db/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,10 @@ impl Backend for sqlx::Sqlite {
if host.is_some() {
return Err(crate::error::fail("SQLite doesn't support database host overrides"));
}
let options = connect_options::<Self>(source)?;
let options = match source {
Source::Url(url) => sqlite_url_options(url)?,
native => connect_options::<Self>(native)?,
};
let path = options.get_filename();
if path == Path::new(":memory:") || path.is_absolute() {
return Ok(options);
Expand All @@ -246,3 +249,44 @@ impl Backend for sqlx::Sqlite {
.is_some_and(|code| matches!(code & 0xff, 5 | 6))
}
}

/// Parses a SQLite URL, applying the `journal_mode`, `synchronous`, and `busy_timeout` (in
/// milliseconds) options that Laravel PHP accepts and `SQLx` doesn't.
#[cfg(feature = "database-sqlite")]
fn sqlite_url_options(url: &str) -> Result<sqlx::sqlite::SqliteConnectOptions> {
const PRAGMAS: [&str; 3] = ["journal_mode", "synchronous", "busy_timeout"];

let Some((database, query)) = url.split_once('?') else {
return Ok(url.parse()?);
};
let (pragmas, rest): (Vec<_>, Vec<_>) =
url::form_urlencoded::parse(query.as_bytes()).partition(|(key, _)| PRAGMAS.contains(&&**key));
if pragmas.is_empty() {
return Ok(url.parse()?);
}

let mut url = database.to_owned();
if !rest.is_empty() {
url.push('?');
url.push_str(
&url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(rest)
.finish(),
);
}
let mut options: sqlx::sqlite::SqliteConnectOptions = url.parse()?;
for (key, value) in pragmas {
options = match &*key {
"journal_mode" => options.journal_mode(value.parse()?),
"synchronous" => options.synchronous(value.parse()?),
_ => {
let millis = value
.parse()
.map_err(|_| crate::error::fail(format!("unknown value {value:?} for `busy_timeout`")))?;
options.busy_timeout(std::time::Duration::from_millis(millis))
}
};
}

Ok(options)
}
6 changes: 6 additions & 0 deletions docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc

The path is relative to your application's root directory. `mode=rwc` creates the file on first use, provided the parent directory already exists.

You may also set SQLite's [`journal_mode`](https://www.sqlite.org/pragma.html#pragma_journal_mode), [`synchronous`](https://www.sqlite.org/pragma.html#pragma_synchronous), and `busy_timeout` (in milliseconds) in the URL. Options you leave out keep their defaults. For example, the `wal` journal mode lets reads continue while another connection writes:

```ini
DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc&journal_mode=wal&synchronous=normal
```

<a name="defining-more-connections"></a>
### Defining more connections

Expand Down
40 changes: 39 additions & 1 deletion tests/database_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::time::Duration;

use laravel::config::Env;
use laravel::config::database::{ConnectionConfig, Database, Endpoint, Host, Source};
use laravel::db::sqlx::{self, Row, Sqlite, sqlite::SqliteConnectOptions};
use laravel::db::sqlx::{self, ConnectOptions as _, Row, Sqlite, sqlite::SqliteConnectOptions};
use laravel::db::{Backend, DatabaseManager, Driver};

fn manager() -> DatabaseManager {
Expand Down Expand Up @@ -63,6 +63,44 @@ fn native_paths_are_relative_to_base_and_hosts_are_rejected() -> laravel::Result
Ok(())
}

#[tokio::test]
async fn sqlite_urls_accept_journal_mode_synchronous_and_busy_timeout() -> laravel::Result<()> {
let directory = tempfile::tempdir()?;
let connection = manager().connect(ConnectionConfig::new(format!(
"sqlite://{}?mode=rwc&journal_mode=wal&synchronous=normal&busy_timeout=1500",
directory.path().join("app.sqlite").display()
)))?;
assert_eq!(
connection
.query("PRAGMA journal_mode")
.scalar::<String>()
.await?
.as_deref(),
Some("wal")
);
assert_eq!(connection.query("PRAGMA synchronous").scalar::<i64>().await?, Some(1));
assert_eq!(
connection.query("PRAGMA busy_timeout").scalar::<i64>().await?,
Some(1500)
);

let options = |url: &str| Sqlite::options(&ConnectionConfig::new(url).source, Path::new("/"), None);
let memory = options("sqlite://?mode=memory&cache=shared&synchronous=off")?.to_url_lossy();
assert!(memory.as_str().contains("mode=memory"), "{memory}");
assert!(memory.as_str().contains("cache=shared"), "{memory}");
assert_eq!(
options("sqlite::memory:?busy_timeout=5s").unwrap_err().to_string(),
r#"unknown value "5s" for `busy_timeout`"#
);
assert!(
options("sqlite::memory:?journal_mode=sideways")
.unwrap_err()
.to_string()
.contains("journal_mode")
);
Ok(())
}

#[tokio::test]
async fn typed_options_select_their_driver() -> laravel::Result<()> {
let manager = manager();
Expand Down