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 <[email protected]> * 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 <[email protected]> Co-authored-by: Josh McKinney <[email protected]>
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>>

0 commit comments

Comments
 (0)