Skip to content

Commit f7ef1ed

Browse files
djarbabonanderjoshka
authored
feat(sqlx.toml): support SQLite extensions in macros and sqlx-cli (#3917)
* feat: create `sqlx.toml` format * feat: add support for ignored_chars config to sqlx_core::migrate * chore: test ignored_chars with `U+FEFF` (ZWNBSP/BOM) https://en.wikipedia.org/wiki/Byte_order_mark * refactor: make `Config` always compiled simplifies usage while still making parsing optional for less generated code * refactor: add origin information to `Column` * feat(macros): implement `type_override` and `column_override` from `sqlx.toml` * refactor(sqlx.toml): make all keys kebab-case, create `macros.preferred-crates` * feat: make macros aware of `macros.preferred-crates` * feat: make `sqlx-cli` aware of `database-url-var` * feat: teach macros about `migrate.table-name`, `migrations-dir` * feat: teach macros about `migrate.ignored-chars` * feat: teach `sqlx-cli` about `migrate.defaults` * feat: teach `sqlx-cli` about `migrate.migrations-dir` * feat: teach `sqlx-cli` about `migrate.table-name` * feat: introduce `migrate.create-schemas` * WIP feat: create multi-tenant database example * SQLite extension loading via sqlx.toml for CLI and query macros * fix: allow start_database to function when the SQLite database file does not already exist * Added example demonstrating migration and compile-time checking with SQLite extensions * remove accidentally included db file * Update sqlx-core/src/config/common.rs Doc formatting tweak Co-authored-by: Josh McKinney <joshka@users.noreply.github.com> * feat: create `sqlx.toml` format * feat: add support for ignored_chars config to sqlx_core::migrate * chore: test ignored_chars with `U+FEFF` (ZWNBSP/BOM) https://en.wikipedia.org/wiki/Byte_order_mark * refactor: make `Config` always compiled simplifies usage while still making parsing optional for less generated code * refactor: add origin information to `Column` * feat(macros): implement `type_override` and `column_override` from `sqlx.toml` * refactor(sqlx.toml): make all keys kebab-case, create `macros.preferred-crates` * feat: make macros aware of `macros.preferred-crates` * feat: make `sqlx-cli` aware of `database-url-var` * feat: teach macros about `migrate.table-name`, `migrations-dir` * feat: teach macros about `migrate.ignored-chars` * feat: teach `sqlx-cli` about `migrate.defaults` * feat: teach `sqlx-cli` about `migrate.migrations-dir` * feat: teach `sqlx-cli` about `migrate.table-name` * feat: introduce `migrate.create-schemas` * fix(postgres): don't fetch `ColumnOrigin` for transparently-prepared statements * feat: progress on axum-multi-tenant example * feat(config): better errors for mislabeled fields * WIP feat: filling out axum-multi-tenant example * feat: multi-tenant example No longer Axum-based because filling out the request routes would have distracted from the purpose of the example. * chore(ci): test multi-tenant example * fixup after merge * fix: CI, README for `multi-tenant` * fix: clippy warnings * fix: multi-tenant README * fix: sequential versioning inference for migrations * fix: migration versioning with explicit overrides * fix: only warn on ambiguous crates if the invocation relies on it * fix: remove unused imports * fix: `sqlx mig add` behavior and tests * fix: restore original type-checking order * fix: deprecation warning in `tests/postgres/macros.rs` * feat: create postgres/multi-database example * fix: examples/postgres/multi-database * fix: cargo fmt * chore: add tests for config `migrate.defaults` * fix: sqlx-cli/tests/add.rs * feat(cli): add `--config` override to all relevant commands * chore: run `sqlx mig add` test with `RUST_BACKTRACE=1` * fix: properly canonicalize config path for `sqlx mig add` test * fix: get `sqlx mig add` test passing * fix(cli): test `migrate.ignored-chars`, fix bugs * feat: create `macros.preferred-crates` example * fix(examples): use workspace `sqlx` * fix: examples * fix: run `cargo fmt` * fix: more example fixes * fix(ci): preferred-crates setup * fix: axum-multi-tenant example locked to specific sqlx version * import anyhow::Context trait in sqlx-cli/src/lib.rs since it was being used and causing a compile error * rebased on upstream/main * make cargo fmt happy * make clippy happy * make clippy happier still * fix: improved error reporting, added parsing test, removed sqlx-toml flag use * switched to kebab-case for the config key * switched to kebab-case for the config key --------- Co-authored-by: Austin Bonander <austin.bonander@gmail.com> Co-authored-by: Josh McKinney <joshka@users.noreply.github.com>
1 parent a3aa942 commit f7ef1ed

File tree

20 files changed

+263
-7
lines changed

20 files changed

+263
-7
lines changed

Cargo.lock

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ members = [
2323
"examples/postgres/todos",
2424
"examples/postgres/transaction",
2525
"examples/sqlite/todos",
26+
"examples/sqlite/extension",
2627
]
2728

2829
[workspace.package]
@@ -65,7 +66,7 @@ macros = ["derive", "sqlx-macros/macros"]
6566
migrate = ["sqlx-core/migrate", "sqlx-macros?/migrate", "sqlx-mysql?/migrate", "sqlx-postgres?/migrate", "sqlx-sqlite?/migrate"]
6667

6768
# Enable parsing of `sqlx.toml` for configuring macros and migrations.
68-
sqlx-toml = ["sqlx-core/sqlx-toml", "sqlx-macros?/sqlx-toml"]
69+
sqlx-toml = ["sqlx-core/sqlx-toml", "sqlx-macros?/sqlx-toml", "sqlx-sqlite?/sqlx-toml"]
6970

7071
# intended mainly for CI and docs
7172
all-databases = ["mysql", "sqlite", "postgres", "any"]

examples/sqlite/extension/Cargo.toml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
[package]
2+
name = "sqlx-example-sqlite-extension"
3+
version = "0.1.0"
4+
license.workspace = true
5+
edition.workspace = true
6+
repository.workspace = true
7+
keywords.workspace = true
8+
categories.workspace = true
9+
authors.workspace = true
10+
11+
[dependencies]
12+
sqlx = { path = "../../../", features = [ "sqlite", "runtime-tokio", "tls-native-tls", "sqlx-toml"] }
13+
tokio = { version = "1.20.0", features = ["rt", "macros"]}
14+
anyhow = "1.0"
15+
16+
[lints]
17+
workspace = true
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/bin/bash
2+
3+
# This grabs a pre-compiled version of the extension used in this
4+
# example, and stores it in a temporary directory. That's a bit
5+
# unusual. Normally, any extensions you need will be installed into a
6+
# directory on the library search path, either by using the system
7+
# package manager or by compiling and installing it yourself.
8+
9+
mkdir /tmp/sqlite3-lib && wget -O /tmp/sqlite3-lib/ipaddr.so https://github.com/nalgeon/sqlean/releases/download/0.15.2/ipaddr.so
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
create table addresses (address text, family integer);
2+
3+
-- The `ipfamily` function is provided by the
4+
-- [ipaddr](https://github.com/nalgeon/sqlean/blob/main/docs/ipaddr.md)
5+
-- sqlite extension, and so this migration can not run if that
6+
-- extension is not loaded.
7+
insert into addresses (address, family) values
8+
('fd04:3d29:9f41::1', ipfamily('fd04:3d29:9f41::1')),
9+
('10.0.0.1', ipfamily('10.0.0.1')),
10+
('10.0.0.2', ipfamily('10.0.0.2')),
11+
('fd04:3d29:9f41::2', ipfamily('fd04:3d29:9f41::2')),
12+
('fd04:3d29:9f41::3', ipfamily('fd04:3d29:9f41::3')),
13+
('10.0.0.3', ipfamily('10.0.0.3')),
14+
('fd04:3d29:9f41::4', ipfamily('fd04:3d29:9f41::4')),
15+
('fd04:3d29:9f41::5', ipfamily('fd04:3d29:9f41::5')),
16+
('fd04:3d29:9f41::6', ipfamily('fd04:3d29:9f41::6')),
17+
('10.0.0.4', ipfamily('10.0.0.4')),
18+
('10.0.0.5', ipfamily('10.0.0.5')),
19+
('10.0.0.6', ipfamily('10.0.0.6')),
20+
('10.0.0.7', ipfamily('10.0.0.7')),
21+
('fd04:3d29:9f41::7', ipfamily('fd04:3d29:9f41::7')),
22+
('fd04:3d29:9f41::8', ipfamily('fd04:3d29:9f41::8')),
23+
('10.0.0.8', ipfamily('10.0.0.8')),
24+
('fd04:3d29:9f41::9', ipfamily('fd04:3d29:9f41::9')),
25+
('10.0.0.9', ipfamily('10.0.0.9'));

examples/sqlite/extension/sqlx.toml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[common.drivers.sqlite]
2+
# Including the full path to the extension is somewhat unusual,
3+
# because normally an extension will be installed in a standard
4+
# directory which is part of the library search path. If that were the
5+
# case here, the load-extensions value could just be `["ipaddr"]`
6+
#
7+
# When the extension file is installed in a non-standard location, as
8+
# in this example, there are two options:
9+
# * Provide the full path the the extension, as seen below.
10+
# * Add the non-standard location to the library search path, which on
11+
# Linux means adding it to the LD_LIBRARY_PATH environment variable.
12+
load-extensions = ["/tmp/sqlite3-lib/ipaddr"]

examples/sqlite/extension/src/main.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use std::str::FromStr;
2+
3+
use sqlx::{
4+
query,
5+
sqlite::{SqliteConnectOptions, SqlitePool},
6+
};
7+
8+
#[tokio::main(flavor = "current_thread")]
9+
async fn main() -> anyhow::Result<()> {
10+
let opts = SqliteConnectOptions::from_str(&std::env::var("DATABASE_URL")?)?
11+
// The sqlx.toml file controls loading extensions for the CLI
12+
// and for the query checking macros, *not* for the
13+
// application while it's running. Thus, if we want the
14+
// extension to be available during program execution, we need
15+
// to load it.
16+
//
17+
// Note that while in this case the extension path is the same
18+
// when checking the program (sqlx.toml) and when running it
19+
// (here), this is not required. The runtime environment can
20+
// be entirely different from the development one.
21+
//
22+
// The extension can be described with a full path, as seen
23+
// here, but in many cases that will not be necessary. As long
24+
// as the extension is installed in a directory on the library
25+
// search path, it is sufficient to just provide the extension
26+
// name, like "ipaddr"
27+
.extension("/tmp/sqlite3-lib/ipaddr");
28+
29+
let db = SqlitePool::connect_with(opts).await?;
30+
31+
// We're not running the migrations here, for the sake of brevity
32+
// and to confirm that the needed extension was loaded during the
33+
// CLI migrate operation. It would not be unusual to run the
34+
// migrations here as well, though, using the database connection
35+
// we just configured.
36+
37+
query!(
38+
"insert into addresses (address, family) values (?1, ipfamily(?1))",
39+
"10.0.0.10"
40+
)
41+
.execute(&db)
42+
.await?;
43+
44+
println!("Query which requires the extension was successfully executed.");
45+
46+
Ok(())
47+
}

examples/x.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,4 @@ def project(name, database=None, driver=None):
8585
project("mysql/todos", driver="mysql_8", database="todos")
8686
project("postgres/todos", driver="postgres_12", database="todos")
8787
project("sqlite/todos", driver="sqlite", database="todos.db")
88+
project("sqlite/extension", driver="sqlite", database="extension.db")

sqlx-cli/src/lib.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::time::Duration;
44

55
use futures_util::TryFutureExt;
66

7-
use sqlx::{AnyConnection, Connection};
7+
use sqlx::AnyConnection;
88
use tokio::{select, signal};
99

1010
use crate::opt::{Command, ConnectOpts, DatabaseCommand, MigrateCommand};
@@ -189,7 +189,28 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
189189

190190
/// Attempt to connect to the database server, retrying up to `ops.connect_timeout`.
191191
async fn connect(opts: &ConnectOpts) -> anyhow::Result<AnyConnection> {
192-
retry_connect_errors(opts, AnyConnection::connect).await
192+
retry_connect_errors(opts, move |url| {
193+
// This only handles the default case. For good support of
194+
// the new command line options, we need to work out some
195+
// way to make the appropriate ConfigOpt available here. I
196+
// suspect that that infrastructure would be useful for
197+
// other things in the future, as well, but it also seems
198+
// like an extensive and intrusive change.
199+
//
200+
// On the other hand, the compile-time checking macros
201+
// can't be configured to use a different config file at
202+
// all, so I believe this is okay for the time being.
203+
let config = Some(std::path::PathBuf::from("sqlx.toml")).and_then(|p| {
204+
if p.exists() {
205+
Some(p)
206+
} else {
207+
None
208+
}
209+
});
210+
211+
async move { AnyConnection::connect_with_config(url, config.clone()).await }
212+
})
213+
.await
193214
}
194215

195216
/// Attempt an operation that may return errors like `ConnectionRefused`,

sqlx-core/src/any/connection/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,24 @@ impl AnyConnection {
4141
})
4242
}
4343

44+
/// UNSTABLE: for use with `sqlx-cli`
45+
///
46+
/// Connect to the database, and instruct the nested driver to
47+
/// read options from the sqlx.toml file as appropriate.
48+
#[cfg(feature = "sqlx-toml")]
49+
#[doc(hidden)]
50+
pub fn connect_with_config(
51+
url: &str,
52+
path: Option<std::path::PathBuf>,
53+
) -> BoxFuture<'static, Result<Self, Error>>
54+
where
55+
Self: Sized,
56+
{
57+
let options: Result<AnyConnectOptions, Error> = url.parse();
58+
59+
Box::pin(async move { Self::connect_with(&options?.with_config_file(path)).await })
60+
}
61+
4462
pub(crate) fn connect_with_db<DB: Database>(
4563
options: &AnyConnectOptions,
4664
) -> BoxFuture<'_, crate::Result<Self>>

sqlx-core/src/any/options.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use url::Url;
1919
pub struct AnyConnectOptions {
2020
pub database_url: Url,
2121
pub log_settings: LogSettings,
22+
pub enable_config: Option<std::path::PathBuf>,
2223
}
2324
impl FromStr for AnyConnectOptions {
2425
type Err = Error;
@@ -29,6 +30,7 @@ impl FromStr for AnyConnectOptions {
2930
.parse::<Url>()
3031
.map_err(|e| Error::Configuration(e.into()))?,
3132
log_settings: LogSettings::default(),
33+
enable_config: None,
3234
})
3335
}
3436
}
@@ -40,6 +42,7 @@ impl ConnectOptions for AnyConnectOptions {
4042
Ok(AnyConnectOptions {
4143
database_url: url.clone(),
4244
log_settings: LogSettings::default(),
45+
enable_config: None,
4346
})
4447
}
4548

@@ -63,3 +66,15 @@ impl ConnectOptions for AnyConnectOptions {
6366
self
6467
}
6568
}
69+
70+
impl AnyConnectOptions {
71+
/// UNSTABLE: for use with `sqlx-cli`
72+
///
73+
/// Allow nested drivers to extract configuration information from
74+
/// the sqlx.toml file.
75+
#[doc(hidden)]
76+
pub fn with_config_file(mut self, path: Option<impl Into<std::path::PathBuf>>) -> Self {
77+
self.enable_config = path.map(|p| p.into());
78+
self
79+
}
80+
}

sqlx-core/src/config/common.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,49 @@ pub struct Config {
4040
/// The query macros used in `foo` will use `FOO_DATABASE_URL`,
4141
/// and the ones used in `bar` will use `BAR_DATABASE_URL`.
4242
pub database_url_var: Option<String>,
43+
44+
/// Settings for specific database drivers.
45+
///
46+
/// These settings apply when checking queries, or when applying
47+
/// migrations via `sqlx-cli`. These settings *do not* apply when
48+
/// applying migrations via the macro, as that uses the run-time
49+
/// database connection configured by the application.
50+
pub drivers: Drivers,
4351
}
4452

4553
impl Config {
4654
pub fn database_url_var(&self) -> &str {
4755
self.database_url_var.as_deref().unwrap_or("DATABASE_URL")
4856
}
4957
}
58+
59+
/// Configuration for specific database drivers.
60+
#[derive(Debug, Default)]
61+
#[cfg_attr(
62+
feature = "sqlx-toml",
63+
derive(serde::Deserialize),
64+
serde(default, rename_all = "kebab-case", deny_unknown_fields)
65+
)]
66+
pub struct Drivers {
67+
/// Specify options for the SQLite driver.
68+
pub sqlite: SQLite,
69+
}
70+
71+
/// Configuration for the SQLite database driver.
72+
#[derive(Debug, Default)]
73+
#[cfg_attr(
74+
feature = "sqlx-toml",
75+
derive(serde::Deserialize),
76+
serde(default, rename_all = "kebab-case", deny_unknown_fields)
77+
)]
78+
pub struct SQLite {
79+
/// Specify extensions to load.
80+
///
81+
/// # Example: Load the "uuid" and "vsv" extensions
82+
/// `sqlx.toml`:
83+
/// ```toml
84+
/// [common.drivers.sqlite]
85+
/// load-extensions = ["uuid", "vsv"]
86+
/// ```
87+
pub load_extensions: Vec<String>,
88+
}

sqlx-core/src/config/reference.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515
# If not specified, defaults to `DATABASE_URL`
1616
database-url-var = "FOO_DATABASE_URL"
1717

18+
[common.drivers.sqlite]
19+
# Load extensions into SQLite when running macros or migrations
20+
#
21+
# Defaults to an empty list, which has no effect.
22+
load-extensions = ["uuid", "vsv"]
23+
1824
###############################################################################################
1925

2026
# Configuration for the `query!()` family of macros.

sqlx-core/src/config/tests.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ fn reference_parses_as_config() {
1414

1515
fn assert_common_config(config: &config::common::Config) {
1616
assert_eq!(config.database_url_var.as_deref(), Some("FOO_DATABASE_URL"));
17+
assert_eq!(config.drivers.sqlite.load_extensions[1].as_str(), "vsv");
1718
}
1819

1920
fn assert_macros_config(config: &config::macros::Config) {

sqlx-core/src/error.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ pub struct UnexpectedNullError;
3030
#[derive(Debug, thiserror::Error)]
3131
#[non_exhaustive]
3232
pub enum Error {
33+
/// Error occurred while reading configuration file
34+
#[error("error reading configuration file: {0}")]
35+
ConfigFile(#[source] crate::config::ConfigError),
36+
3337
/// Error occurred while parsing a connection string.
3438
#[error("error with configuration: {0}")]
3539
Configuration(#[source] BoxDynError),

sqlx-macros-core/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ derive = []
2727
macros = []
2828
migrate = ["sqlx-core/migrate"]
2929

30-
sqlx-toml = ["sqlx-core/sqlx-toml"]
30+
sqlx-toml = ["sqlx-core/sqlx-toml", "sqlx-sqlite?/sqlx-toml"]
3131

3232
# database
3333
mysql = ["sqlx-mysql"]

sqlx-sqlite/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ preupdate-hook = ["libsqlite3-sys/preupdate_hook"]
2727
bundled = ["libsqlite3-sys/bundled"]
2828
unbundled = ["libsqlite3-sys/buildtime_bindgen"]
2929

30+
sqlx-toml = ["sqlx-core/sqlx-toml"]
31+
3032
# Note: currently unused, only to satisfy "unexpected `cfg` condition" lint
3133
bigdecimal = []
3234
rust_decimal = []

sqlx-sqlite/src/any.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,23 @@ impl<'a> TryFrom<&'a AnyConnectOptions> for SqliteConnectOptions {
198198
fn try_from(opts: &'a AnyConnectOptions) -> Result<Self, Self::Error> {
199199
let mut opts_out = SqliteConnectOptions::from_url(&opts.database_url)?;
200200
opts_out.log_settings = opts.log_settings.clone();
201+
202+
if let Some(ref path) = opts.enable_config {
203+
if path.exists() {
204+
let config = match sqlx_core::config::Config::try_from_path(path.to_path_buf()) {
205+
Ok(cfg) => cfg,
206+
Err(sqlx_core::config::ConfigError::NotFound { path: _ }) => {
207+
return Ok(opts_out)
208+
}
209+
Err(err) => return Err(Self::Error::ConfigFile(err)),
210+
};
211+
212+
for extension in config.common.drivers.sqlite.load_extensions.iter() {
213+
opts_out = opts_out.extension(extension.to_owned());
214+
}
215+
}
216+
}
217+
201218
Ok(opts_out)
202219
}
203220
}

0 commit comments

Comments
 (0)