fix(deps): bound SQLx pool maintenance and reserve idle counters
This commit is contained in:
1 parent
7aa854de26
commit
284eb8180e
113 files changed
+21092
-2
No files matched your search
+49
@@ -0,0 +1,49 @@
|
||||
/// Configuration shared by multiple components.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Override the database URL environment variable.
|
||||
///
|
||||
/// This is used by both the macros and `sqlx-cli`.
|
||||
///
|
||||
/// Case-sensitive. Defaults to `DATABASE_URL`.
|
||||
///
|
||||
/// Example: Multi-Database Project
|
||||
/// -------
|
||||
/// You can use multiple databases in the same project by breaking it up into multiple crates,
|
||||
/// then using a different environment variable for each.
|
||||
///
|
||||
/// For example, with two crates in the workspace named `foo` and `bar`:
|
||||
///
|
||||
/// #### `foo/sqlx.toml`
|
||||
/// ```toml
|
||||
/// [common]
|
||||
/// database-url-var = "FOO_DATABASE_URL"
|
||||
/// ```
|
||||
///
|
||||
/// #### `bar/sqlx.toml`
|
||||
/// ```toml
|
||||
/// [common]
|
||||
/// database-url-var = "BAR_DATABASE_URL"
|
||||
/// ```
|
||||
///
|
||||
/// #### `.env`
|
||||
/// ```text
|
||||
/// FOO_DATABASE_URL=postgres://postgres@localhost:5432/foo
|
||||
/// BAR_DATABASE_URL=postgres://postgres@localhost:5432/bar
|
||||
/// ```
|
||||
///
|
||||
/// The query macros used in `foo` will use `FOO_DATABASE_URL`,
|
||||
/// and the ones used in `bar` will use `BAR_DATABASE_URL`.
|
||||
pub database_url_var: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn database_url_var(&self) -> &str {
|
||||
self.database_url_var.as_deref().unwrap_or("DATABASE_URL")
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
use std::error::Error;
|
||||
|
||||
/// Configuration for specific database drivers (**applies to macros and `sqlx-cli` only**).
|
||||
///
|
||||
/// # Note: Does Not Apply at Application Run-Time
|
||||
/// As of writing, these configuration parameters do *not* have any bearing on
|
||||
/// the runtime configuration of SQLx database drivers.
|
||||
///
|
||||
/// Any parameters which overlap with runtime configuration
|
||||
/// (e.g. [`drivers.sqlite.unsafe-load-extensions`][SqliteConfig::unsafe_load_extensions])
|
||||
/// _must_ be configured their normal ways at runtime (e.g. `SqliteConnectOptions::extension()`).
|
||||
///
|
||||
/// See the documentation of individual fields for details.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Configuration for the MySQL database driver.
|
||||
///
|
||||
/// See [`MySqlConfig`] for details.
|
||||
pub mysql: MySqlConfig,
|
||||
|
||||
/// Configuration for the Postgres database driver.
|
||||
///
|
||||
/// See [`PgConfig`] for details.
|
||||
pub postgres: PgConfig,
|
||||
|
||||
/// Configuration for the SQLite database driver.
|
||||
///
|
||||
/// See [`SqliteConfig`] for details.
|
||||
pub sqlite: SqliteConfig,
|
||||
|
||||
/// Configuration for external database drivers.
|
||||
///
|
||||
/// See [`ExternalDriverConfig`] for details.
|
||||
pub external: ExternalDriverConfig,
|
||||
}
|
||||
|
||||
/// Configuration for the MySQL database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct MySqlConfig {
|
||||
// No fields implemented yet. This key is only used to validate parsing.
|
||||
}
|
||||
|
||||
/// Configuration for the Postgres database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct PgConfig {
|
||||
// No fields implemented yet. This key is only used to validate parsing.
|
||||
}
|
||||
|
||||
/// Configuration for the SQLite database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct SqliteConfig {
|
||||
/// Specify extensions to load, either by name or by path.
|
||||
///
|
||||
/// Paths should be relative to the workspace root.
|
||||
///
|
||||
/// See [Loading an Extension](https://www.sqlite.org/loadext.html#loading_an_extension)
|
||||
/// in the SQLite manual for details.
|
||||
///
|
||||
/// The `sqlite-load-extension` feature must be enabled and SQLite must be built
|
||||
/// _without_ [`SQLITE_OMIT_LOAD_EXTENSION`] enabled.
|
||||
///
|
||||
/// [`SQLITE_OMIT_LOAD_EXTENSION`]: https://www.sqlite.org/compile.html#omit_load_extension
|
||||
///
|
||||
/// # Note: Does Not Configure Runtime Extension Loading
|
||||
/// Extensions to be loaded at runtime *must* be separately configured with
|
||||
/// `SqliteConnectOptions::extension()` or `SqliteConnectOptions::extension_with_entrypoint()`.
|
||||
///
|
||||
/// # Safety
|
||||
/// This causes arbitrary DLLs on the filesystem to be loaded at execution time,
|
||||
/// which can easily result in undefined behavior, memory corruption,
|
||||
/// or exploitable vulnerabilities if misused.
|
||||
///
|
||||
/// It is not possible to provide a truly safe version of this API.
|
||||
///
|
||||
/// Use this field with care, and only load extensions that you trust.
|
||||
///
|
||||
/// # Example
|
||||
/// Load the `uuid` and `vsv` extensions from [`sqlean`](https://github.com/nalgeon/sqlean).
|
||||
///
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [common.drivers.sqlite]
|
||||
/// unsafe-load-extensions = ["uuid", "vsv"]
|
||||
/// ```
|
||||
pub unsafe_load_extensions: Vec<SqliteExtension>,
|
||||
}
|
||||
|
||||
/// Extension for the SQLite database driver.
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(untagged, deny_unknown_fields)
|
||||
)]
|
||||
pub enum SqliteExtension {
|
||||
Path(String),
|
||||
PathWithEntrypoint { path: String, entrypoint: String },
|
||||
}
|
||||
|
||||
/// Configuration for external database drivers.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(feature = "sqlx-toml", derive(serde::Deserialize), serde(transparent))]
|
||||
pub struct ExternalDriverConfig {
|
||||
#[cfg(feature = "sqlx-toml")]
|
||||
by_name: std::collections::BTreeMap<String, toml::Table>,
|
||||
}
|
||||
|
||||
/// Type-erased [`toml::de::Error`].
|
||||
pub type TryParseError = Box<dyn Error + Send + Sync + 'static>;
|
||||
|
||||
impl ExternalDriverConfig {
|
||||
/// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist.
|
||||
#[cfg(feature = "sqlx-toml")]
|
||||
pub fn try_parse<T: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> Result<Option<T>, TryParseError> {
|
||||
let Some(config) = self.by_name.get(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// What's really baffling is that `toml` doesn't provide any way to deserialize
|
||||
// from a `&Table` or `&Value`, only owned variants, so cloning is unavoidable here.
|
||||
Ok(Some(config.clone().try_into()?))
|
||||
}
|
||||
|
||||
/// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist.
|
||||
#[cfg(not(feature = "sqlx-toml"))]
|
||||
pub fn try_parse<T>(&self, _name: &str) -> Result<Option<T>, TryParseError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Configuration for the `query!()` family of macros.
|
||||
///
|
||||
/// See also [`common::Config`][crate::config::common::Config] for renaming `DATABASE_URL`.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Specify which crates' types to use when types from multiple crates apply.
|
||||
///
|
||||
/// See [`PreferredCrates`] for details.
|
||||
pub preferred_crates: PreferredCrates,
|
||||
|
||||
/// Specify global overrides for mapping SQL type names to Rust type names.
|
||||
///
|
||||
/// Default type mappings are defined by the database driver.
|
||||
/// Refer to the `sqlx::types` module for details.
|
||||
///
|
||||
/// ## Note: Case-Sensitive
|
||||
/// Currently, the case of the type name MUST match the name SQLx knows it by.
|
||||
/// Built-in types are spelled in all-uppercase to match SQL convention.
|
||||
///
|
||||
/// However, user-created types in Postgres are all-lowercase unless quoted.
|
||||
///
|
||||
/// ## Note: Orthogonal to Nullability
|
||||
/// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
/// or not. They only override the inner type used.
|
||||
///
|
||||
/// ## Note: Schema Qualification (Postgres)
|
||||
/// Type names may be schema-qualified in Postgres. If so, the schema should be part
|
||||
/// of the type string, e.g. `'foo.bar'` to reference type `bar` in schema `foo`.
|
||||
///
|
||||
/// The schema and/or type name may additionally be quoted in the string
|
||||
/// for a quoted identifier (see next section).
|
||||
///
|
||||
/// Schema qualification should not be used for types in the search path.
|
||||
///
|
||||
/// ## Note: Quoted Identifiers (Postgres)
|
||||
/// Type names using [quoted identifiers in Postgres] must also be specified with quotes here.
|
||||
///
|
||||
/// Note, however, that the TOML format parses way the outer pair of quotes,
|
||||
/// so for quoted names in Postgres, double-quoting is necessary,
|
||||
/// e.g. `'"Foo"'` for SQL type `"Foo"`.
|
||||
///
|
||||
/// To reference a schema-qualified type with a quoted name, use double-quotes after the
|
||||
/// dot, e.g. `'foo."Bar"'` to reference type `"Bar"` of schema `foo`, and vice versa for
|
||||
/// quoted schema names.
|
||||
///
|
||||
/// We recommend wrapping all type names in single quotes, as shown below,
|
||||
/// to avoid confusion.
|
||||
///
|
||||
/// MySQL/MariaDB and SQLite do not support custom types, so quoting type names should
|
||||
/// never be necessary.
|
||||
///
|
||||
/// [quoted identifiers in Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
// Note: we wanted to be able to handle this intelligently,
|
||||
// but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761
|
||||
//
|
||||
// We decided to just encourage always quoting type names instead.
|
||||
/// Example: Custom Wrapper Types
|
||||
/// -------
|
||||
/// Does SQLx not support a type that you need? Do you want additional semantics not
|
||||
/// implemented on the built-in types? You can create a custom wrapper,
|
||||
/// or use an external crate.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Override a built-in type
|
||||
/// 'UUID' = "crate::types::MyUuid"
|
||||
///
|
||||
/// # Support an external or custom wrapper type (e.g. from the `isn` Postgres extension)
|
||||
/// # (NOTE: FOR DOCUMENTATION PURPOSES ONLY; THIS CRATE/TYPE DOES NOT EXIST AS OF WRITING)
|
||||
/// 'isbn13' = "isn_rs::sqlx::ISBN13"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Custom Types in Postgres
|
||||
/// -------
|
||||
/// If you have a custom type in Postgres that you want to map without needing to use
|
||||
/// the type override syntax in `sqlx::query!()` every time, you can specify a global
|
||||
/// override here.
|
||||
///
|
||||
/// For example, a custom enum type `foo`:
|
||||
///
|
||||
/// #### Migration or Setup SQL (e.g. `migrations/0_setup.sql`)
|
||||
/// ```sql
|
||||
/// CREATE TYPE foo AS ENUM ('Bar', 'Baz');
|
||||
/// ```
|
||||
///
|
||||
/// #### `src/types.rs`
|
||||
/// ```rust,no_run
|
||||
/// #[derive(sqlx::Type)]
|
||||
/// pub enum Foo {
|
||||
/// Bar,
|
||||
/// Baz
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If you're not using `PascalCase` in your enum variants then you'll want to use
|
||||
/// `#[sqlx(rename_all = "<strategy>")]` on your enum.
|
||||
/// See [`Type`][crate::type::Type] for details.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Map SQL type `foo` to `crate::types::Foo`
|
||||
/// 'foo' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Schema-Qualified Types
|
||||
/// -------
|
||||
/// (See `Note` section above for details.)
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Map SQL type `foo.foo` to `crate::types::Foo`
|
||||
/// 'foo.foo' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Quoted Identifiers
|
||||
/// -------
|
||||
/// If a type or schema uses quoted identifiers,
|
||||
/// it must be wrapped in quotes _twice_ for SQLx to know the difference:
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # `"Foo"` in SQLx
|
||||
/// '"Foo"' = "crate::types::Foo"
|
||||
/// # **NOT** `"Foo"` in SQLx (parses as just `Foo`)
|
||||
/// "Foo" = "crate::types::Foo"
|
||||
///
|
||||
/// # Schema-qualified
|
||||
/// '"foo".foo' = "crate::types::Foo"
|
||||
/// 'foo."Foo"' = "crate::types::Foo"
|
||||
/// '"foo"."Foo"' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// (See `Note` section above for details.)
|
||||
// TODO: allow specifying different types for input vs output
|
||||
// e.g. to accept `&[T]` on input but output `Vec<T>`
|
||||
pub type_overrides: BTreeMap<SqlType, RustType>,
|
||||
|
||||
/// Specify per-table and per-column overrides for mapping SQL types to Rust types.
|
||||
///
|
||||
/// Default type mappings are defined by the database driver.
|
||||
/// Refer to the `sqlx::types` module for details.
|
||||
///
|
||||
/// The supported syntax is similar to [`type_overrides`][Self::type_overrides],
|
||||
/// (with the same caveat for quoted names!) but column names must be qualified
|
||||
/// by a separately quoted table name, which may optionally be schema-qualified.
|
||||
///
|
||||
/// Multiple columns for the same SQL table may be written in the same table in TOML
|
||||
/// (see examples below).
|
||||
///
|
||||
/// ## Note: Orthogonal to Nullability
|
||||
/// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
/// or not. They only override the inner type used.
|
||||
///
|
||||
/// ## Note: Schema Qualification
|
||||
/// Table names may be schema-qualified. If so, the schema should be part
|
||||
/// of the table name string, e.g. `'foo.bar'` to reference table `bar` in schema `foo`.
|
||||
///
|
||||
/// The schema and/or type name may additionally be quoted in the string
|
||||
/// for a quoted identifier (see next section).
|
||||
///
|
||||
/// Postgres users: schema qualification should not be used for tables in the search path.
|
||||
///
|
||||
/// ## Note: Quoted Identifiers
|
||||
/// Schema, table, or column names using quoted identifiers ([MySQL], [Postgres], [SQLite])
|
||||
/// in SQL must also be specified with quotes here.
|
||||
///
|
||||
/// Postgres and SQLite use double-quotes (`"Foo"`) while MySQL uses backticks (`\`Foo\`).
|
||||
///
|
||||
/// Note, however, that the TOML format parses way the outer pair of quotes,
|
||||
/// so for quoted names in Postgres, double-quoting is necessary,
|
||||
/// e.g. `'"Foo"'` for SQL name `"Foo"`.
|
||||
///
|
||||
/// To reference a schema-qualified table with a quoted name, use the appropriate quotation
|
||||
/// characters after the dot, e.g. `'foo."Bar"'` to reference table `"Bar"` of schema `foo`,
|
||||
/// and vice versa for quoted schema names.
|
||||
///
|
||||
/// We recommend wrapping all table and column names in single quotes, as shown below,
|
||||
/// to avoid confusion.
|
||||
///
|
||||
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/identifiers.html
|
||||
/// [Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
/// [SQLite]: https://sqlite.org/lang_keywords.html
|
||||
// Note: we wanted to be able to handle this intelligently,
|
||||
// but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761
|
||||
//
|
||||
// We decided to just encourage always quoting type names instead.
|
||||
///
|
||||
/// Example
|
||||
/// -------
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.table-overrides.'foo']
|
||||
/// # Map column `bar` of table `foo` to Rust type `crate::types::Foo`:
|
||||
/// 'bar' = "crate::types::Bar"
|
||||
///
|
||||
/// # Quoted column name
|
||||
/// # Note: same quoting requirements as `macros.type_overrides`
|
||||
/// '"Bar"' = "crate::types::Bar"
|
||||
///
|
||||
/// # Note: will NOT work (parses as `Bar`)
|
||||
/// # "Bar" = "crate::types::Bar"
|
||||
///
|
||||
/// # Table name may be quoted (note the wrapping single-quotes)
|
||||
/// [macros.table-overrides.'"Foo"']
|
||||
/// 'bar' = "crate::types::Bar"
|
||||
/// '"Bar"' = "crate::types::Bar"
|
||||
///
|
||||
/// # Table name may also be schema-qualified.
|
||||
/// # Note how the dot is inside the quotes.
|
||||
/// [macros.table-overrides.'my_schema.my_table']
|
||||
/// 'my_column' = "crate::types::MyType"
|
||||
///
|
||||
/// # Quoted schema, table, and column names
|
||||
/// [macros.table-overrides.'"My Schema"."My Table"']
|
||||
/// '"My Column"' = "crate::types::MyType"
|
||||
/// ```
|
||||
pub table_overrides: BTreeMap<TableName, BTreeMap<ColumnName, RustType>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case")
|
||||
)]
|
||||
pub struct PreferredCrates {
|
||||
/// Specify the crate to use for mapping date/time types to Rust.
|
||||
///
|
||||
/// The default behavior is to use whatever crate is enabled,
|
||||
/// [`chrono`] or [`time`] (the latter takes precedent).
|
||||
///
|
||||
/// [`chrono`]: crate::types::chrono
|
||||
/// [`time`]: crate::types::time
|
||||
///
|
||||
/// Example: Always Use Chrono
|
||||
/// -------
|
||||
/// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable
|
||||
/// the `time` feature of SQLx which will force it on for all crates using SQLx,
|
||||
/// which will result in problems if your crate wants to use types from [`chrono`].
|
||||
///
|
||||
/// You can use the type override syntax (see `sqlx::query!` for details),
|
||||
/// or you can force an override globally by setting this option.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "chrono"
|
||||
/// ```
|
||||
///
|
||||
/// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification
|
||||
pub date_time: DateTimeCrate,
|
||||
|
||||
/// Specify the crate to use for mapping `NUMERIC` types to Rust.
|
||||
///
|
||||
/// The default behavior is to use whatever crate is enabled,
|
||||
/// [`bigdecimal`] or [`rust_decimal`] (the latter takes precedent).
|
||||
///
|
||||
/// [`bigdecimal`]: crate::types::bigdecimal
|
||||
/// [`rust_decimal`]: crate::types::rust_decimal
|
||||
///
|
||||
/// Example: Always Use `bigdecimal`
|
||||
/// -------
|
||||
/// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable
|
||||
/// the `rust_decimal` feature of SQLx which will force it on for all crates using SQLx,
|
||||
/// which will result in problems if your crate wants to use types from [`bigdecimal`].
|
||||
///
|
||||
/// You can use the type override syntax (see `sqlx::query!` for details),
|
||||
/// or you can force an override globally by setting this option.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "bigdecimal"
|
||||
/// ```
|
||||
///
|
||||
/// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification
|
||||
pub numeric: NumericCrate,
|
||||
}
|
||||
|
||||
/// The preferred crate to use for mapping date/time types to Rust.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DateTimeCrate {
|
||||
/// Use whichever crate is enabled (`time` then `chrono`).
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Always use types from [`chrono`][crate::types::chrono].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "chrono"
|
||||
/// ```
|
||||
Chrono,
|
||||
|
||||
/// Always use types from [`time`][crate::types::time].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "time"
|
||||
/// ```
|
||||
Time,
|
||||
}
|
||||
|
||||
/// The preferred crate to use for mapping `NUMERIC` types to Rust.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum NumericCrate {
|
||||
/// Use whichever crate is enabled (`rust_decimal` then `bigdecimal`).
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Always use types from [`bigdecimal`][crate::types::bigdecimal].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "bigdecimal"
|
||||
/// ```
|
||||
#[cfg_attr(feature = "sqlx-toml", serde(rename = "bigdecimal"))]
|
||||
BigDecimal,
|
||||
|
||||
/// Always use types from [`rust_decimal`][crate::types::rust_decimal].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "rust_decimal"
|
||||
/// ```
|
||||
RustDecimal,
|
||||
}
|
||||
|
||||
/// A SQL type name; may optionally be schema-qualified.
|
||||
///
|
||||
/// See [`macros.type-overrides`][Config::type_overrides] for usages.
|
||||
pub type SqlType = Box<str>;
|
||||
|
||||
/// A SQL table name; may optionally be schema-qualified.
|
||||
///
|
||||
/// See [`macros.table-overrides`][Config::table_overrides] for usages.
|
||||
pub type TableName = Box<str>;
|
||||
|
||||
/// A column in a SQL table.
|
||||
///
|
||||
/// See [`macros.table-overrides`][Config::table_overrides] for usages.
|
||||
pub type ColumnName = Box<str>;
|
||||
|
||||
/// A Rust type name or path.
|
||||
///
|
||||
/// Should be a global path (not relative).
|
||||
pub type RustType = Box<str>;
|
||||
|
||||
/// Internal getter methods.
|
||||
impl Config {
|
||||
/// Get the override for a given type name (optionally schema-qualified).
|
||||
pub fn type_override(&self, type_name: &str) -> Option<&str> {
|
||||
// TODO: make this case-insensitive
|
||||
self.type_overrides.get(type_name).map(|s| &**s)
|
||||
}
|
||||
|
||||
/// Get the override for a given column and table name (optionally schema-qualified).
|
||||
pub fn column_override(&self, table: &str, column: &str) -> Option<&str> {
|
||||
self.table_overrides
|
||||
.get(table)
|
||||
.and_then(|by_column| by_column.get(column))
|
||||
.map(|s| &**s)
|
||||
}
|
||||
}
|
||||
|
||||
impl DateTimeCrate {
|
||||
/// Returns `self == Self::Inferred`
|
||||
#[inline(always)]
|
||||
pub fn is_inferred(&self) -> bool {
|
||||
*self == Self::Inferred
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn crate_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Inferred => None,
|
||||
Self::Chrono => Some("chrono"),
|
||||
Self::Time => Some("time"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NumericCrate {
|
||||
/// Returns `self == Self::Inferred`
|
||||
#[inline(always)]
|
||||
pub fn is_inferred(&self) -> bool {
|
||||
*self == Self::Inferred
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn crate_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Inferred => None,
|
||||
Self::BigDecimal => Some("bigdecimal"),
|
||||
Self::RustDecimal => Some("rust_decimal"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
|
||||
///
|
||||
/// ### Note
|
||||
/// A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these
|
||||
/// configuration options. We recommend using `sqlx::migrate!()` instead.
|
||||
///
|
||||
/// ### Warning: Potential Data Loss or Corruption!
|
||||
/// Many of these options, if changed after migrations are set up,
|
||||
/// can result in data loss or corruption of a production database
|
||||
/// if the proper precautions are not taken.
|
||||
///
|
||||
/// Be sure you know what you are doing and that you read all relevant documentation _thoroughly_.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Specify the names of schemas to create if they don't already exist.
|
||||
///
|
||||
/// This is done before checking the existence of the migrations table
|
||||
/// (`_sqlx_migrations` or overridden `table_name` below) so that it may be placed in
|
||||
/// one of these schemas.
|
||||
///
|
||||
/// ### Example
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate]
|
||||
/// create-schemas = ["foo"]
|
||||
/// ```
|
||||
pub create_schemas: BTreeSet<Box<str>>,
|
||||
|
||||
/// Override the name of the table used to track executed migrations.
|
||||
///
|
||||
/// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.
|
||||
///
|
||||
/// Potentially useful for multi-tenant databases.
|
||||
///
|
||||
/// ### Warning: Potential Data Loss or Corruption!
|
||||
/// Changing this option for a production database will likely result in data loss or corruption
|
||||
/// as the migration machinery will no longer be aware of what migrations have been applied
|
||||
/// and will attempt to re-run them.
|
||||
///
|
||||
/// You should create the new table as a copy of the existing migrations table (with contents!),
|
||||
/// and be sure all instances of your application have been migrated to the new
|
||||
/// table before deleting the old one.
|
||||
///
|
||||
/// ### Example
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate]
|
||||
/// # Put `_sqlx_migrations` in schema `foo`
|
||||
/// table-name = "foo._sqlx_migrations"
|
||||
/// ```
|
||||
pub table_name: Option<Box<str>>,
|
||||
|
||||
/// Override the directory used for migrations files.
|
||||
///
|
||||
/// Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`.
|
||||
pub migrations_dir: Option<Box<str>>,
|
||||
|
||||
/// Specify characters that should be ignored when hashing migrations.
|
||||
///
|
||||
/// Any characters contained in the given array will be dropped when a migration is hashed.
|
||||
///
|
||||
/// ### Warning: May Change Hashes for Existing Migrations
|
||||
/// Changing the characters considered in hashing migrations will likely
|
||||
/// change the output of the hash.
|
||||
///
|
||||
/// This may require manual rectification for deployed databases.
|
||||
///
|
||||
/// ### Example: Ignore Carriage Return (`<CR>` | `\r`)
|
||||
/// Line ending differences between platforms can result in migrations having non-repeatable
|
||||
/// hashes. The most common culprit is the carriage return (`<CR>` | `\r`), which Windows
|
||||
/// uses in its line endings alongside line feed (`<LF>` | `\n`), often written `CRLF` or `\r\n`,
|
||||
/// whereas Linux and macOS use only line feeds.
|
||||
///
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate]
|
||||
/// ignored-chars = ["\r"]
|
||||
/// ```
|
||||
///
|
||||
/// For projects using Git, this can also be addressed using [`.gitattributes`]:
|
||||
///
|
||||
/// ```text
|
||||
/// # Force newlines in migrations to be line feeds on all platforms
|
||||
/// migrations/*.sql text eol=lf
|
||||
/// ```
|
||||
///
|
||||
/// This may require resetting or re-checking out the migrations files to take effect.
|
||||
///
|
||||
/// [`.gitattributes`]: https://git-scm.com/docs/gitattributes
|
||||
///
|
||||
/// ### Example: Ignore all Whitespace Characters
|
||||
/// To make your migrations amenable to reformatting, you may wish to tell SQLx to ignore
|
||||
/// _all_ whitespace characters in migrations.
|
||||
///
|
||||
/// ##### Warning: Beware Syntactically Significant Whitespace!
|
||||
/// If your migrations use string literals or quoted identifiers which contain whitespace,
|
||||
/// this configuration will cause the migration machinery to ignore some changes to these.
|
||||
/// This may result in a mismatch between the development and production versions of
|
||||
/// your database.
|
||||
///
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate]
|
||||
/// # Ignore common whitespace characters when hashing
|
||||
/// ignored-chars = [" ", "\t", "\r", "\n"] # Space, tab, CR, LF
|
||||
/// ```
|
||||
// Likely lower overhead for small sets than `HashSet`.
|
||||
pub ignored_chars: BTreeSet<char>,
|
||||
|
||||
/// Specify default options for new migrations created with `sqlx migrate add`.
|
||||
pub defaults: MigrationDefaults,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case")
|
||||
)]
|
||||
pub struct MigrationDefaults {
|
||||
/// Specify the default type of migration that `sqlx migrate add` should create by default.
|
||||
///
|
||||
/// ### Example: Use Reversible Migrations by Default
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate.defaults]
|
||||
/// migration-type = "reversible"
|
||||
/// ```
|
||||
pub migration_type: DefaultMigrationType,
|
||||
|
||||
/// Specify the default scheme that `sqlx migrate add` should use for version integers.
|
||||
///
|
||||
/// ### Example: Use Sequential Versioning by Default
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [migrate.defaults]
|
||||
/// migration-versioning = "sequential"
|
||||
/// ```
|
||||
pub migration_versioning: DefaultVersioning,
|
||||
}
|
||||
|
||||
/// The default type of migration that `sqlx migrate add` should create by default.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DefaultMigrationType {
|
||||
/// Create the same migration type as that of the latest existing migration,
|
||||
/// or `Simple` otherwise.
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Create non-reversible migrations (`<VERSION>_<DESCRIPTION>.sql`) by default.
|
||||
Simple,
|
||||
|
||||
/// Create reversible migrations (`<VERSION>_<DESCRIPTION>.up.sql` and `[...].down.sql`) by default.
|
||||
Reversible,
|
||||
}
|
||||
|
||||
/// The default scheme that `sqlx migrate add` should use for version integers.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DefaultVersioning {
|
||||
/// Infer the versioning scheme from existing migrations:
|
||||
///
|
||||
/// * If the versions of the last two migrations differ by `1`, infer `Sequential`.
|
||||
/// * If only one migration exists and has version `1`, infer `Sequential`.
|
||||
/// * Otherwise, infer `Timestamp`.
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Use UTC timestamps for migration versions.
|
||||
///
|
||||
/// This is the recommended versioning format as it's less likely to collide when multiple
|
||||
/// developers are creating migrations on different branches.
|
||||
///
|
||||
/// The exact timestamp format is unspecified.
|
||||
Timestamp,
|
||||
|
||||
/// Use sequential integers for migration versions.
|
||||
Sequential,
|
||||
}
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
impl Config {
|
||||
pub fn migrations_dir(&self) -> &str {
|
||||
self.migrations_dir.as_deref().unwrap_or("migrations")
|
||||
}
|
||||
|
||||
pub fn table_name(&self) -> &str {
|
||||
self.table_name.as_deref().unwrap_or("_sqlx_migrations")
|
||||
}
|
||||
|
||||
pub fn to_resolve_config(&self) -> crate::migrate::ResolveConfig {
|
||||
let mut config = crate::migrate::ResolveConfig::new();
|
||||
config.ignore_chars(self.ignored_chars.iter().copied());
|
||||
config
|
||||
}
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
//! (Exported for documentation only) Guide and reference for `sqlx.toml` files.
|
||||
//!
|
||||
//! To use, create a `sqlx.toml` file in your crate root (the same directory as your `Cargo.toml`).
|
||||
//! The configuration in a `sqlx.toml` configures SQLx *only* for the current crate.
|
||||
//!
|
||||
//! Requires the `sqlx-toml` feature (not enabled by default).
|
||||
//!
|
||||
//! `sqlx-cli` will also read `sqlx.toml` when running migrations.
|
||||
//!
|
||||
//! See the [`Config`] type and its fields for individual configuration options.
|
||||
//!
|
||||
//! See the [reference][`_reference`] for the full `sqlx.toml` file.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::Debug;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Configuration shared by multiple components.
|
||||
///
|
||||
/// See [`common::Config`] for details.
|
||||
pub mod common;
|
||||
|
||||
pub mod drivers;
|
||||
|
||||
/// Configuration for the `query!()` family of macros.
|
||||
///
|
||||
/// See [`macros::Config`] for details.
|
||||
pub mod macros;
|
||||
|
||||
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
|
||||
///
|
||||
/// See [`migrate::Config`] for details.
|
||||
pub mod migrate;
|
||||
|
||||
/// Reference for `sqlx.toml` files
|
||||
///
|
||||
/// Source: `sqlx-core/src/config/reference.toml`
|
||||
///
|
||||
/// ```toml
|
||||
#[doc = include_str!("reference.toml")]
|
||||
/// ```
|
||||
pub mod _reference {}
|
||||
|
||||
#[cfg(all(test, feature = "sqlx-toml"))]
|
||||
mod tests;
|
||||
|
||||
/// The parsed structure of a `sqlx.toml` file.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Configuration shared by multiple components.
|
||||
///
|
||||
/// See [`common::Config`] for details.
|
||||
pub common: common::Config,
|
||||
|
||||
/// Configuration for database drivers.
|
||||
///
|
||||
/// See [`drivers::Config`] for details.
|
||||
pub drivers: drivers::Config,
|
||||
|
||||
/// Configuration for the `query!()` family of macros.
|
||||
///
|
||||
/// See [`macros::Config`] for details.
|
||||
pub macros: macros::Config,
|
||||
|
||||
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
|
||||
///
|
||||
/// See [`migrate::Config`] for details.
|
||||
pub migrate: migrate::Config,
|
||||
}
|
||||
|
||||
/// Error returned from various methods of [`Config`].
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum ConfigError {
|
||||
/// The loading method expected `CARGO_MANIFEST_DIR` to be set and it wasn't.
|
||||
///
|
||||
/// This is necessary to locate the root of the crate currently being compiled.
|
||||
///
|
||||
/// See [the "Environment Variables" page of the Cargo Book][cargo-env] for details.
|
||||
///
|
||||
/// [cargo-env]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates
|
||||
#[error("environment variable `CARGO_MANIFEST_DIR` must be set and valid")]
|
||||
Env(
|
||||
#[from]
|
||||
#[source]
|
||||
std::env::VarError,
|
||||
),
|
||||
|
||||
/// No configuration file was found. Not necessarily fatal.
|
||||
#[error("config file {path:?} not found")]
|
||||
NotFound { path: PathBuf },
|
||||
|
||||
/// An I/O error occurred while attempting to read the config file at `path`.
|
||||
///
|
||||
/// If the error is [`io::ErrorKind::NotFound`], [`Self::NotFound`] is returned instead.
|
||||
#[error("error reading config file {path:?}")]
|
||||
Io {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
error: io::Error,
|
||||
},
|
||||
|
||||
/// An error in the TOML was encountered while parsing the config file at `path`.
|
||||
///
|
||||
/// The error gives line numbers and context when printed with `Display`/`ToString`.
|
||||
///
|
||||
/// Only returned if the `sqlx-toml` feature is enabled.
|
||||
#[error("error parsing config file {path:?}")]
|
||||
Parse {
|
||||
path: PathBuf,
|
||||
/// Type-erased [`toml::de::Error`].
|
||||
#[source]
|
||||
error: Box<dyn Error + Send + Sync + 'static>,
|
||||
},
|
||||
|
||||
/// A `sqlx.toml` file was found or specified, but the `sqlx-toml` feature is not enabled.
|
||||
#[error("SQLx found config file at {path:?} but the `sqlx-toml` feature was not enabled")]
|
||||
ParseDisabled { path: PathBuf },
|
||||
}
|
||||
|
||||
impl ConfigError {
|
||||
/// Create a [`ConfigError`] from a [`std::io::Error`].
|
||||
///
|
||||
/// Maps to either `NotFound` or `Io`.
|
||||
pub fn from_io(path: impl Into<PathBuf>, error: io::Error) -> Self {
|
||||
if error.kind() == io::ErrorKind::NotFound {
|
||||
Self::NotFound { path: path.into() }
|
||||
} else {
|
||||
Self::Io {
|
||||
path: path.into(),
|
||||
error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// If this error means the file was not found, return the path that was attempted.
|
||||
pub fn not_found_path(&self) -> Option<&Path> {
|
||||
if let Self::NotFound { path } = self {
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal methods for loading a `Config`.
|
||||
#[allow(clippy::result_large_err)]
|
||||
impl Config {
|
||||
/// Read `$CARGO_MANIFEST_DIR/sqlx.toml` or return `Config::default()` if it does not exist.
|
||||
///
|
||||
/// # Errors
|
||||
/// * If `CARGO_MANIFEST_DIR` is not set.
|
||||
/// * If the file exists but could not be read or parsed.
|
||||
/// * If the file exists but the `sqlx-toml` feature is disabled.
|
||||
pub fn try_from_crate_or_default() -> Result<Self, ConfigError> {
|
||||
Self::try_from_path_or_default(get_crate_path()?)
|
||||
}
|
||||
|
||||
/// Attempt to read `Config` from the path given, or return `Config::default()` if it does not exist.
|
||||
///
|
||||
/// # Errors
|
||||
/// * If the file exists but could not be read or parsed.
|
||||
/// * If the file exists but the `sqlx-toml` feature is disabled.
|
||||
pub fn try_from_path_or_default(path: PathBuf) -> Result<Self, ConfigError> {
|
||||
Self::read_from(path).or_else(|e| {
|
||||
if let ConfigError::NotFound { .. } = e {
|
||||
Ok(Config::default())
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Attempt to read `Config` from the path given.
|
||||
///
|
||||
/// # Errors
|
||||
/// * If the file does not exist.
|
||||
/// * If the file exists but could not be read or parsed.
|
||||
/// * If the file exists but the `sqlx-toml` feature is disabled.
|
||||
pub fn try_from_path(path: PathBuf) -> Result<Self, ConfigError> {
|
||||
Self::read_from(path)
|
||||
}
|
||||
|
||||
#[cfg(feature = "sqlx-toml")]
|
||||
fn read_from(path: PathBuf) -> Result<Self, ConfigError> {
|
||||
// The `toml` crate doesn't provide an incremental reader.
|
||||
let toml_s = match std::fs::read_to_string(&path) {
|
||||
Ok(toml) => toml,
|
||||
Err(error) => {
|
||||
return Err(ConfigError::from_io(path, error));
|
||||
}
|
||||
};
|
||||
|
||||
// TODO: parse and lint TOML structure before deserializing
|
||||
// Motivation: https://github.com/toml-rs/toml/issues/761
|
||||
tracing::debug!("read config TOML from {path:?}:\n{toml_s}");
|
||||
|
||||
toml::from_str(&toml_s).map_err(|error| ConfigError::Parse {
|
||||
path,
|
||||
error: Box::new(error),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "sqlx-toml"))]
|
||||
fn read_from(path: PathBuf) -> Result<Self, ConfigError> {
|
||||
match path.try_exists() {
|
||||
Ok(true) => Err(ConfigError::ParseDisabled { path }),
|
||||
Ok(false) => Err(ConfigError::NotFound { path }),
|
||||
Err(e) => Err(ConfigError::from_io(path, e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_crate_path() -> Result<PathBuf, ConfigError> {
|
||||
let mut path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
|
||||
path.push("sqlx.toml");
|
||||
Ok(path)
|
||||
}
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
# `sqlx.toml` reference.
|
||||
#
|
||||
# Note: shown values are *not* defaults.
|
||||
# They are explicitly set to non-default values to test parsing.
|
||||
# Refer to the comment for a given option for its default value.
|
||||
|
||||
###############################################################################################
|
||||
|
||||
# Configuration shared by multiple components.
|
||||
[common]
|
||||
# Change the environment variable to get the database URL.
|
||||
#
|
||||
# This is used by both the macros and `sqlx-cli`.
|
||||
#
|
||||
# If not specified, defaults to `DATABASE_URL`
|
||||
database-url-var = "FOO_DATABASE_URL"
|
||||
|
||||
###############################################################################################
|
||||
|
||||
# Configuration of SQLx database drivers (**applies to macros and sqlx-cli only**)
|
||||
[drivers]
|
||||
|
||||
# Configure MySQL databases in macros and sqlx-cli.
|
||||
[drivers.mysql]
|
||||
# No fields implemented yet. This key is only used to validate parsing.
|
||||
|
||||
# Configure Postgres databases in macros and sqlx-cli.
|
||||
[drivers.postgres]
|
||||
# No fields implemented yet. This key is only used to validate parsing.
|
||||
|
||||
# Configure Postgres databases in macros and sqlx-cli.
|
||||
[drivers.sqlite]
|
||||
# Load extensions into SQLite when running macros or migrations
|
||||
#
|
||||
# Defaults to an empty list, which has no effect.
|
||||
#
|
||||
# Must be specified separately at run-time using `SqliteConnectOptions::extension()` or `::extension_with_entrypoint()`.
|
||||
#
|
||||
# Safety
|
||||
# This causes arbitrary DLLs on the filesystem to be loaded at runtime,
|
||||
# which can easily result in undefined behavior, memory corruption,
|
||||
# or exploitable vulnerabilities if misused.
|
||||
#
|
||||
# It is not possible to provide a truly safe version of this API.
|
||||
#
|
||||
# Use this field with care, and only load extensions that you trust.
|
||||
unsafe-load-extensions = [
|
||||
"uuid",
|
||||
{ path = "vsv_renamed", entrypoint = "sqlite3_vsv_init" },
|
||||
]
|
||||
|
||||
# Configure external drivers in macros and sqlx-cli.
|
||||
#
|
||||
# These keys are only validated when the external driver tries to parse them,
|
||||
# unlike config for built-in drivers which is validated directly.
|
||||
[drivers.external."<external driver name>"]
|
||||
foo = 'foo'
|
||||
bar = true
|
||||
|
||||
###############################################################################################
|
||||
|
||||
# Configuration for the `query!()` family of macros.
|
||||
[macros]
|
||||
|
||||
[macros.preferred-crates]
|
||||
# Force the macros to use the `chrono` crate for date/time types, even if `time` is enabled.
|
||||
#
|
||||
# Defaults to "inferred": use whichever crate is enabled (`time` takes precedence over `chrono`).
|
||||
date-time = "chrono"
|
||||
|
||||
# Or, ensure the macros always prefer `time`
|
||||
# in case new date/time crates are added in the future:
|
||||
# date-time = "time"
|
||||
|
||||
# Force the macros to use the `rust_decimal` crate for `NUMERIC`, even if `bigdecimal` is enabled.
|
||||
#
|
||||
# Defaults to "inferred": use whichever crate is enabled (`bigdecimal` takes precedence over `rust_decimal`).
|
||||
numeric = "rust_decimal"
|
||||
|
||||
# Or, ensure the macros always prefer `bigdecimal`
|
||||
# in case new decimal crates are added in the future:
|
||||
# numeric = "bigdecimal"
|
||||
|
||||
# Set global overrides for mapping SQL types to Rust types.
|
||||
#
|
||||
# Default type mappings are defined by the database driver.
|
||||
# Refer to the `sqlx::types` module for details.
|
||||
#
|
||||
# Postgres users: schema qualification should not be used for types in the search path.
|
||||
#
|
||||
# ### Note: Orthogonal to Nullability
|
||||
# These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
# or not. They only override the inner type used.
|
||||
[macros.type-overrides]
|
||||
# Override a built-in type (map all `UUID` columns to `crate::types::MyUuid`)
|
||||
# Note: currently, the case of the type name MUST match.
|
||||
# Built-in types are spelled in all-uppercase to match SQL convention.
|
||||
'UUID' = "crate::types::MyUuid"
|
||||
|
||||
# Support an external or custom wrapper type (e.g. from the `isn` Postgres extension)
|
||||
# (NOTE: FOR DOCUMENTATION PURPOSES ONLY; THIS CRATE/TYPE DOES NOT EXIST AS OF WRITING)
|
||||
'isbn13' = "isn_rs::isbn::ISBN13"
|
||||
|
||||
# SQL type `foo` to Rust type `crate::types::Foo`:
|
||||
'foo' = "crate::types::Foo"
|
||||
|
||||
# SQL type `"Bar"` to Rust type `crate::types::Bar`; notice the extra pair of quotes:
|
||||
'"Bar"' = "crate::types::Bar"
|
||||
|
||||
# Will NOT work (the first pair of quotes are parsed by TOML)
|
||||
# "Bar" = "crate::types::Bar"
|
||||
|
||||
# Schema qualified
|
||||
'foo.bar' = "crate::types::Bar"
|
||||
|
||||
# Schema qualified and quoted
|
||||
'foo."Bar"' = "crate::schema::foo::Bar"
|
||||
|
||||
# Quoted schema name
|
||||
'"Foo".bar' = "crate::schema::foo::Bar"
|
||||
|
||||
# Quoted schema and type name
|
||||
'"Foo"."Bar"' = "crate::schema::foo::Bar"
|
||||
|
||||
# Set per-table and per-column overrides for mapping SQL types to Rust types.
|
||||
#
|
||||
# Note: table name is required in the header.
|
||||
#
|
||||
# Postgres users: schema qualification should not be used for types in the search path.
|
||||
#
|
||||
# ### Note: Orthogonal to Nullability
|
||||
# These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
# or not. They only override the inner type used.
|
||||
[macros.table-overrides.'foo']
|
||||
# Map column `bar` of table `foo` to Rust type `crate::types::Foo`:
|
||||
'bar' = "crate::types::Bar"
|
||||
|
||||
# Quoted column name
|
||||
# Note: same quoting requirements as `macros.type_overrides`
|
||||
'"Bar"' = "crate::types::Bar"
|
||||
|
||||
# Note: will NOT work (parses as `Bar`)
|
||||
# "Bar" = "crate::types::Bar"
|
||||
|
||||
# Table name may be quoted (note the wrapping single-quotes)
|
||||
[macros.table-overrides.'"Foo"']
|
||||
'bar' = "crate::types::Bar"
|
||||
'"Bar"' = "crate::types::Bar"
|
||||
|
||||
# Table name may also be schema-qualified.
|
||||
# Note how the dot is inside the quotes.
|
||||
[macros.table-overrides.'my_schema.my_table']
|
||||
'my_column' = "crate::types::MyType"
|
||||
|
||||
# Quoted schema, table, and column names
|
||||
[macros.table-overrides.'"My Schema"."My Table"']
|
||||
'"My Column"' = "crate::types::MyType"
|
||||
|
||||
###############################################################################################
|
||||
|
||||
# Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
|
||||
#
|
||||
# ### Note
|
||||
# A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these
|
||||
# configuration options. We recommend using `sqlx::migrate!()` instead.
|
||||
#
|
||||
# ### Warning: Potential Data Loss or Corruption!
|
||||
# Many of these options, if changed after migrations are set up,
|
||||
# can result in data loss or corruption of a production database
|
||||
# if the proper precautions are not taken.
|
||||
#
|
||||
# Be sure you know what you are doing and that you read all relevant documentation _thoroughly_.
|
||||
[migrate]
|
||||
# Override the name of the table used to track executed migrations.
|
||||
#
|
||||
# May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.
|
||||
#
|
||||
# Potentially useful for multi-tenant databases.
|
||||
#
|
||||
# ### Warning: Potential Data Loss or Corruption!
|
||||
# Changing this option for a production database will likely result in data loss or corruption
|
||||
# as the migration machinery will no longer be aware of what migrations have been applied
|
||||
# and will attempt to re-run them.
|
||||
#
|
||||
# You should create the new table as a copy of the existing migrations table (with contents!),
|
||||
# and be sure all instances of your application have been migrated to the new
|
||||
# table before deleting the old one.
|
||||
table-name = "foo._sqlx_migrations"
|
||||
|
||||
# Override the directory used for migrations files.
|
||||
#
|
||||
# Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`.
|
||||
migrations-dir = "foo/migrations"
|
||||
|
||||
# Specify characters that should be ignored when hashing migrations.
|
||||
#
|
||||
# Any characters contained in the given set will be dropped when a migration is hashed.
|
||||
#
|
||||
# Defaults to an empty array (don't drop any characters).
|
||||
#
|
||||
# ### Warning: May Change Hashes for Existing Migrations
|
||||
# Changing the characters considered in hashing migrations will likely
|
||||
# change the output of the hash.
|
||||
#
|
||||
# This may require manual rectification for deployed databases.
|
||||
# ignored-chars = []
|
||||
|
||||
# Ignore Carriage Returns (`<CR>` | `\r`)
|
||||
# Note that the TOML format requires double-quoted strings to process escapes.
|
||||
# ignored-chars = ["\r"]
|
||||
|
||||
# Ignore common whitespace characters (beware syntactically significant whitespace!)
|
||||
# Space, tab, CR, LF, zero-width non-breaking space (U+FEFF)
|
||||
#
|
||||
# U+FEFF is added by some editors as a magic number at the beginning of a text file indicating it is UTF-8 encoded,
|
||||
# where it is known as a byte-order mark (BOM): https://en.wikipedia.org/wiki/Byte_order_mark
|
||||
ignored-chars = [" ", "\t", "\r", "\n", "\uFEFF"]
|
||||
|
||||
# Set default options for new migrations.
|
||||
[migrate.defaults]
|
||||
# Specify reversible migrations by default (for `sqlx migrate create`).
|
||||
#
|
||||
# Defaults to "inferred": uses the type of the last migration, or "simple" otherwise.
|
||||
migration-type = "reversible"
|
||||
|
||||
# Specify simple (non-reversible) migrations by default.
|
||||
# migration-type = "simple"
|
||||
|
||||
# Specify sequential versioning by default (for `sqlx migrate create`).
|
||||
#
|
||||
# Defaults to "inferred": guesses the versioning scheme from the latest migrations,
|
||||
# or "timestamp" otherwise.
|
||||
migration-versioning = "sequential"
|
||||
|
||||
# Specify timestamp versioning by default.
|
||||
# migration-versioning = "timestamp"
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
use crate::config::{self, Config};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn reference_parses_as_config() {
|
||||
let config: Config = toml::from_str(include_str!("reference.toml"))
|
||||
// The `Display` impl of `toml::Error` is *actually* more useful than `Debug`
|
||||
.unwrap_or_else(|e| panic!("expected reference.toml to parse as Config: {e}"));
|
||||
|
||||
assert_common_config(&config.common);
|
||||
assert_drivers_config(&config.drivers);
|
||||
assert_macros_config(&config.macros);
|
||||
assert_migrate_config(&config.migrate);
|
||||
}
|
||||
|
||||
fn assert_common_config(config: &config::common::Config) {
|
||||
assert_eq!(config.database_url_var.as_deref(), Some("FOO_DATABASE_URL"));
|
||||
}
|
||||
|
||||
fn assert_drivers_config(config: &config::drivers::Config) {
|
||||
assert_eq!(
|
||||
config.sqlite.unsafe_load_extensions,
|
||||
vec![
|
||||
config::drivers::SqliteExtension::Path("uuid".to_string()),
|
||||
config::drivers::SqliteExtension::PathWithEntrypoint {
|
||||
path: "vsv_renamed".to_string(),
|
||||
entrypoint: "sqlite3_vsv_init".to_string()
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
struct TestExternalDriverConfig {
|
||||
foo: String,
|
||||
bar: bool,
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
config.external.try_parse("<external driver name>").unwrap(),
|
||||
Some(TestExternalDriverConfig {
|
||||
foo: "foo".to_string(),
|
||||
bar: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_macros_config(config: &config::macros::Config) {
|
||||
use config::macros::*;
|
||||
|
||||
assert_eq!(config.preferred_crates.date_time, DateTimeCrate::Chrono);
|
||||
assert_eq!(config.preferred_crates.numeric, NumericCrate::RustDecimal);
|
||||
|
||||
// Type overrides
|
||||
// Don't need to cover everything, just some important canaries.
|
||||
assert_eq!(config.type_override("UUID"), Some("crate::types::MyUuid"));
|
||||
|
||||
assert_eq!(config.type_override("foo"), Some("crate::types::Foo"));
|
||||
|
||||
assert_eq!(config.type_override(r#""Bar""#), Some("crate::types::Bar"),);
|
||||
|
||||
assert_eq!(
|
||||
config.type_override(r#""Foo".bar"#),
|
||||
Some("crate::schema::foo::Bar"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.type_override(r#""Foo"."Bar""#),
|
||||
Some("crate::schema::foo::Bar"),
|
||||
);
|
||||
|
||||
// Column overrides
|
||||
assert_eq!(
|
||||
config.column_override("foo", "bar"),
|
||||
Some("crate::types::Bar"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.column_override("foo", r#""Bar""#),
|
||||
Some("crate::types::Bar"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.column_override(r#""Foo""#, "bar"),
|
||||
Some("crate::types::Bar"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.column_override(r#""Foo""#, r#""Bar""#),
|
||||
Some("crate::types::Bar"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.column_override("my_schema.my_table", "my_column"),
|
||||
Some("crate::types::MyType"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
config.column_override(r#""My Schema"."My Table""#, r#""My Column""#),
|
||||
Some("crate::types::MyType"),
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_migrate_config(config: &config::migrate::Config) {
|
||||
use config::migrate::*;
|
||||
|
||||
assert_eq!(config.table_name.as_deref(), Some("foo._sqlx_migrations"));
|
||||
assert_eq!(config.migrations_dir.as_deref(), Some("foo/migrations"));
|
||||
|
||||
let ignored_chars = BTreeSet::from([' ', '\t', '\r', '\n', '\u{FEFF}']);
|
||||
|
||||
assert_eq!(config.ignored_chars, ignored_chars);
|
||||
|
||||
assert_eq!(
|
||||
config.defaults.migration_type,
|
||||
DefaultMigrationType::Reversible
|
||||
);
|
||||
assert_eq!(
|
||||
config.defaults.migration_versioning,
|
||||
DefaultVersioning::Sequential
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user