Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: create sqlx.toml format #3383

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
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
9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,19 @@ authors.workspace = true
repository.workspace = true

[package.metadata.docs.rs]
features = ["all-databases", "_unstable-all-types"]
features = ["all-databases", "_unstable-all-types", "_unstable-doc"]
rustdoc-args = ["--cfg", "docsrs"]

[features]
default = ["any", "macros", "migrate", "json"]
default = ["any", "macros", "migrate", "json", "sqlx-toml"]

derive = ["sqlx-macros/derive"]
macros = ["derive", "sqlx-macros/macros"]
migrate = ["sqlx-core/migrate", "sqlx-macros?/migrate", "sqlx-mysql?/migrate", "sqlx-postgres?/migrate", "sqlx-sqlite?/migrate"]

# Enable parsing of `sqlx.toml` for configuring macros and migrations.
sqlx-toml = ["sqlx-core/sqlx-toml", "sqlx-macros?/sqlx-toml"]

# intended mainly for CI and docs
all-databases = ["mysql", "sqlite", "postgres", "any"]
_unstable-all-types = [
Expand All @@ -73,6 +76,8 @@ _unstable-all-types = [
"uuid",
"bit-vec",
]
# Render documentation that wouldn't otherwise be shown (e.g. `sqlx_core::config`).
_unstable-doc = []

# Base runtime features without TLS
runtime-async-std = ["_rt-async-std", "sqlx-core/_rt-async-std", "sqlx-macros?/_rt-async-std"]
Expand Down
5 changes: 4 additions & 1 deletion sqlx-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ filetime = "0.2"
backoff = { version = "0.4.0", features = ["futures", "tokio"] }

[features]
default = ["postgres", "sqlite", "mysql", "native-tls", "completions"]
default = ["postgres", "sqlite", "mysql", "native-tls", "completions", "sqlx-toml"]

rustls = ["sqlx/runtime-tokio-rustls"]
native-tls = ["sqlx/runtime-tokio-native-tls"]

Expand All @@ -64,6 +65,8 @@ openssl-vendored = ["openssl/vendored"]

completions = ["dep:clap_complete"]

sqlx-toml = ["sqlx/sqlx-toml"]

[dev-dependencies]
assert_cmd = "2.0.11"
tempfile = "3.10.1"
Expand Down
8 changes: 4 additions & 4 deletions sqlx-cli/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ pub async fn create(connect_opts: &ConnectOpts) -> anyhow::Result<()> {
std::sync::atomic::Ordering::Release,
);

Any::create_database(connect_opts.required_db_url()?).await?;
Any::create_database(connect_opts.expect_db_url()?).await?;
}

Ok(())
}

pub async fn drop(connect_opts: &ConnectOpts, confirm: bool, force: bool) -> anyhow::Result<()> {
if confirm && !ask_to_continue_drop(connect_opts.required_db_url()?) {
if confirm && !ask_to_continue_drop(connect_opts.expect_db_url()?) {
return Ok(());
}

Expand All @@ -34,9 +34,9 @@ pub async fn drop(connect_opts: &ConnectOpts, confirm: bool, force: bool) -> any

if exists {
if force {
Any::force_drop_database(connect_opts.required_db_url()?).await?;
Any::force_drop_database(connect_opts.expect_db_url()?).await?;
} else {
Any::drop_database(connect_opts.required_db_url()?).await?;
Any::drop_database(connect_opts.expect_db_url()?).await?;
}
}

Expand Down
81 changes: 59 additions & 22 deletions sqlx-cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::io;
use std::path::{PathBuf};
use std::time::Duration;

use anyhow::Result;
use anyhow::{Context, Result};
use futures::{Future, TryFutureExt};

use sqlx::{AnyConnection, Connection};
Expand All @@ -20,23 +21,23 @@ mod prepare;

pub use crate::opt::Opt;

pub use sqlx::_unstable::config::{self, Config};

pub async fn run(opt: Opt) -> Result<()> {
let config = config_from_current_dir().await?;

match opt.command {
Command::Migrate(migrate) => match migrate.command {
MigrateCommand::Add {
source,
description,
reversible,
sequential,
timestamp,
} => migrate::add(&source, &description, reversible, sequential, timestamp).await?,
MigrateCommand::Add(opts)=> migrate::add(config, opts).await?,
MigrateCommand::Run {
source,
dry_run,
ignore_missing,
connect_opts,
mut connect_opts,
target_version,
} => {
connect_opts.populate_db_url(config)?;

migrate::run(
&source,
&connect_opts,
Expand All @@ -50,9 +51,11 @@ pub async fn run(opt: Opt) -> Result<()> {
source,
dry_run,
ignore_missing,
connect_opts,
mut connect_opts,
target_version,
} => {
connect_opts.populate_db_url(config)?;

migrate::revert(
&source,
&connect_opts,
Expand All @@ -64,37 +67,56 @@ pub async fn run(opt: Opt) -> Result<()> {
}
MigrateCommand::Info {
source,
connect_opts,
} => migrate::info(&source, &connect_opts).await?,
mut connect_opts,
} => {
connect_opts.populate_db_url(config)?;

migrate::info(&source, &connect_opts).await?
},
MigrateCommand::BuildScript { source, force } => migrate::build_script(&source, force)?,
},

Command::Database(database) => match database.command {
DatabaseCommand::Create { connect_opts } => database::create(&connect_opts).await?,
DatabaseCommand::Create { mut connect_opts } => {
connect_opts.populate_db_url(config)?;
database::create(&connect_opts).await?
},
DatabaseCommand::Drop {
confirmation,
connect_opts,
mut connect_opts,
force,
} => database::drop(&connect_opts, !confirmation.yes, force).await?,
} => {
connect_opts.populate_db_url(config)?;
database::drop(&connect_opts, !confirmation.yes, force).await?
},
DatabaseCommand::Reset {
confirmation,
source,
connect_opts,
mut connect_opts,
force,
} => database::reset(&source, &connect_opts, !confirmation.yes, force).await?,
} => {
connect_opts.populate_db_url(config)?;
database::reset(&source, &connect_opts, !confirmation.yes, force).await?
},
DatabaseCommand::Setup {
source,
connect_opts,
} => database::setup(&source, &connect_opts).await?,
mut connect_opts,
} => {
connect_opts.populate_db_url(config)?;
database::setup(&source, &connect_opts).await?
},
},

Command::Prepare {
check,
all,
workspace,
connect_opts,
mut connect_opts,
args,
} => prepare::run(check, all, workspace, connect_opts, args).await?,
} => {
connect_opts.populate_db_url(config)?;
prepare::run(check, all, workspace, connect_opts, args).await?
},

#[cfg(feature = "completions")]
Command::Completions { shell } => completions::run(shell),
Expand Down Expand Up @@ -122,7 +144,7 @@ where
{
sqlx::any::install_default_drivers();

let db_url = opts.required_db_url()?;
let db_url = opts.expect_db_url()?;

backoff::future::retry(
backoff::ExponentialBackoffBuilder::new()
Expand All @@ -147,3 +169,18 @@ where
)
.await
}

async fn config_from_current_dir() -> anyhow::Result<&'static Config> {
// Tokio does file I/O on a background task anyway
tokio::task::spawn_blocking(|| {
let path = PathBuf::from("sqlx.toml");

if path.exists() {
eprintln!("Found `sqlx.toml` in current directory; reading...");
}

Config::read_with_or_default(move || Ok(path))
})
.await
.context("unexpected error loading config")
}
110 changes: 20 additions & 90 deletions sqlx-cli/src/migrate.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::opt::ConnectOpts;
use crate::opt::{AddMigrationOpts, ConnectOpts};
use anyhow::{bail, Context};
use chrono::Utc;
use console::style;
use sqlx::migrate::{AppliedMigration, Migrate, MigrateError, MigrationType, Migrator};
use sqlx::Connection;
Expand All @@ -10,6 +9,7 @@ use std::fmt::Write;
use std::fs::{self, File};
use std::path::Path;
use std::time::Duration;
use crate::config::Config;

fn create_file(
migration_source: &str,
Expand Down Expand Up @@ -37,116 +37,46 @@ fn create_file(
Ok(())
}

enum MigrationOrdering {
Timestamp(String),
Sequential(String),
}

impl MigrationOrdering {
fn timestamp() -> MigrationOrdering {
Self::Timestamp(Utc::now().format("%Y%m%d%H%M%S").to_string())
}

fn sequential(version: i64) -> MigrationOrdering {
Self::Sequential(format!("{version:04}"))
}

fn file_prefix(&self) -> &str {
match self {
MigrationOrdering::Timestamp(prefix) => prefix,
MigrationOrdering::Sequential(prefix) => prefix,
}
}

fn infer(sequential: bool, timestamp: bool, migrator: &Migrator) -> Self {
match (timestamp, sequential) {
(true, true) => panic!("Impossible to specify both timestamp and sequential mode"),
(true, false) => MigrationOrdering::timestamp(),
(false, true) => MigrationOrdering::sequential(
migrator
.iter()
.last()
.map_or(1, |last_migration| last_migration.version + 1),
),
(false, false) => {
// inferring the naming scheme
let migrations = migrator
.iter()
.filter(|migration| migration.migration_type.is_up_migration())
.rev()
.take(2)
.collect::<Vec<_>>();
if let [last, pre_last] = &migrations[..] {
// there are at least two migrations, compare the last twothere's only one existing migration
if last.version - pre_last.version == 1 {
// their version numbers differ by 1, infer sequential
MigrationOrdering::sequential(last.version + 1)
} else {
MigrationOrdering::timestamp()
}
} else if let [last] = &migrations[..] {
// there is only one existing migration
if last.version == 0 || last.version == 1 {
// infer sequential if the version number is 0 or 1
MigrationOrdering::sequential(last.version + 1)
} else {
MigrationOrdering::timestamp()
}
} else {
MigrationOrdering::timestamp()
}
}
}
}
}

pub async fn add(
migration_source: &str,
description: &str,
reversible: bool,
sequential: bool,
timestamp: bool,
config: &Config,
opts: AddMigrationOpts,
) -> anyhow::Result<()> {
fs::create_dir_all(migration_source).context("Unable to create migrations directory")?;
fs::create_dir_all(&opts.source).context("Unable to create migrations directory")?;

let migrator = Migrator::new(Path::new(migration_source)).await?;
// Type of newly created migration will be the same as the first one
// or reversible flag if this is the first migration
let migration_type = MigrationType::infer(&migrator, reversible);
let migrator = Migrator::new(opts.source.as_ref()).await?;

let ordering = MigrationOrdering::infer(sequential, timestamp, &migrator);
let file_prefix = ordering.file_prefix();
let version_prefix = opts.version_prefix(config, &migrator);

if migration_type.is_reversible() {
if opts.reversible(config, &migrator) {
create_file(
migration_source,
file_prefix,
description,
&opts.source,
&version_prefix,
&opts.description,
MigrationType::ReversibleUp,
)?;
create_file(
migration_source,
file_prefix,
description,
&opts.source,
&version_prefix,
&opts.description,
MigrationType::ReversibleDown,
)?;
} else {
create_file(
migration_source,
file_prefix,
description,
&opts.source,
&version_prefix,
&opts.description,
MigrationType::Simple,
)?;
}

// if the migrations directory is empty
let has_existing_migrations = fs::read_dir(migration_source)
let has_existing_migrations = fs::read_dir(&opts.source)
.map(|mut dir| dir.next().is_some())
.unwrap_or(false);

if !has_existing_migrations {
let quoted_source = if migration_source != "migrations" {
format!("{migration_source:?}")
let quoted_source = if *opts.source != "migrations" {
format!("{:?}", *opts.source)
} else {
"".to_string()
};
Expand Down
Loading
Loading