Skip to content

Question: best way to use sqlx with connections to two different databases? #121

Closed

Description

@sbditto85

I have a program with two databases. One MySQL and one Postgres where I am syncing data from one to the other. Is that possible with sqlx? What is the best way to do that since the query macro has a hardcoded DATABASE_URL env var to determine the database information?

Activity

  1. added
    enhancement
    on Mar 14, 2020
  2. mehcode commented on Mar 14, 2020

    @mehcode
    Contributor

    We don't currently have a solution to this for the query macros beyond recommending to use multiple crates so the compilation units would be different.


    I know @abonander has some ideas how to make this nicer so I'm marking this as an enhancement.

  3. PoiScript commented on Mar 22, 2020

    @PoiScript
    Contributor

    A workaround is to use cargo workspace: create one crate for MySql, one for Postgres, and third that imports them. So you can have different DATABASE_URLs for each one.

  4. mehcode commented on Apr 3, 2020

    @mehcode
    Contributor

    Copying over my thoughts from #224 as I realized we didn't put these up here.


    We were thinking a decent approach would be to generate a set of macros with a higher level macro.. e.g.,

    mod one { sqlx::database!(env!("ONE_DATABASE_URL")); }
    mod two { sqlx::database!(env!("TWO_DATABASE_URL")); }
    
    one::query!("...") // mysql://...
    two::query!("...") // postgres://...
  5. PoiScript commented on Apr 4, 2020

    @PoiScript
    Contributor

    @mehcode To be honest, I don't like the idea of using macro here. Because it seems to increase both compile time and build size.

    Besides, I think a flexible and extensible approach is using SQL comment. e.g.

    sqlx::query!(
        r#"
            -- DATABASE_URL=postgres://...
            select * from foo
        "#
    )

    will specifies the DATABASE_URL, or

    sqlx::query!(
        r#"
            -- DATABASE=bar
            select * from foo
        "#
    )

    will tells sqlx to use DATABASE_URL_bar instead.

  6. jsdw commented on Apr 4, 2020

    @jsdw

    I ran into this issue as well as I wanted separate postgres databases for a microserverish approach (I've worked around it for now using schemas).

    Using a comment, apart from being pretty verbose, feels too magical to me. Being able to customise or generate the query! and friends macros feels more readable to me (plus it might be nice to also be able to pull the URL from sources other than an env var?).

  7. sbditto85 commented on Apr 4, 2020

    @sbditto85
    Author

    My 0.02. I'd rather just have something like sqlx::query!([sql string], [optional db url or env var], [params]). If you leave it off then it uses the current behavior of DATABASE_URL env var, but if you supply the optional env var it will use that instead or you could just put a const string there and no env vars would be used.

    so perhaps:

    sqlx::query!("select * from table where id=?", env=OTHER_DB, 1); where 1 is the parameter but the env= dictates its not part of the params.

    sqlx::query!("select * from table where id=?", url="mysql://blah:blah@blah/blah", 1); again with 1 as the parameter and url= is some const string known at compile time. Hopefully this would allow us to use a const expression to generate the url if needed.

    Not sure if that would cause the macro to be too complicated, but something like that would be ideal for me. I can easily see that the query is being directed from a place different then the default fairly easily and hopefully doesn't add too much computational size or overhead.

  8. abonander commented on Apr 4, 2020

    @abonander
    Collaborator

    The idea with the sqlx::database!() macro is that it wouldn't be another proc macro, it's just a macro_rules! macro that simply shadows the facade macros in src/macros.rs with ones that tell the proc macro internally which environment variable to look at, so it's actually somewhat of a hybrid approach.

    Have a look back at @mehcode's example usage; the idea is that by invoking the macro in a submodule you can namespace the query macros so you know at a glance which DB it's talking to:

    mod one { sqlx::database!(env!("ONE_DATABASE_URL")); }
    mod two { sqlx::database!(env!("TWO_DATABASE_URL")); }
    
    one::query!("...") // mysql://...
    two::query!("...") // postgres://...

    It doesn't make sense to me to hardcode the database URL at the use site; you'd have to remember to include the URL or the env var every time you write another query!() invocation, which seems extremely cumbersome.

    In fact, I'd like to refactor the proc macro itself so that we don't have 4 separate proc macro definitions which all do about the same thing. Instead, I'm thinking the facade will pass in key-value pairs that dictate its behavior.

  9. mehcode commented on Apr 4, 2020

    @mehcode
    Contributor

    Another thought is the database macro could configure all sorts of knobs. One in particular could be adding or overriding user-defined types.

  10. abonander commented on Apr 4, 2020

    @abonander
    Collaborator

    Like setting tinyint in MySQL to always be bool, maybe.

    It should probably be called config!().

  11. PoiScript commented on Apr 5, 2020

    @PoiScript
    Contributor

    I suggest using sql comment simply because it's extendable. It's is definitely better If we can have a config!() macro with optional named parameters like:

    config!(
      DATABASE_URL = "...",
      // ... more
    )
  12. abonander commented on Apr 5, 2020

    @abonander
    Collaborator

    The comment would be significantly more complex to implement because we would have to parse the SQL in a comment-aware manner, which probably means rolling our own parser. We currently treat the string as opaque and I'd like to keep it that way unless we have a really good reason.

  13. abonander commented on Apr 5, 2020

    @abonander
    Collaborator

    If we did have a compelling reason to implement per-invocation config, I think I'd prefer it as attributes inside the invocation, which we can parse with syn:

    sqlx:;query!(
        #[db(env = "OTHER_ENV_VAR")]
        "select ..."
    );

    However, I think the config!() macro is strictly more useful because you don't have to repeat your customization options every time you call query!(). I don't see a reason why not to support both except the increased complexity involved (which is already a problem for the query!() macros).

  14. sbditto85 commented on Apr 6, 2020

    @sbditto85
    Author

    I can see the benefits of a config macro in a module and then using that module to indicate which config you were trying to use. I just want it to be obvious and hopefully hard to screw up which database you are using for the query.

    I am waaayyy to good and making those mistakes :p

  15. abonander commented on Apr 17, 2020

    @abonander
    Collaborator

    I'm feeling like config!() is perhaps a bit vague; if it's not going to be used very much maybe we should give it a very clear name like shadow_macros!() or something.

  16. 19 remaining items

  17. esmevane commented on Jun 12, 2024

    @esmevane

    @Snapstromegon Oh neat! That's awesome. I've got a question or two, but I'll leave it on your PR :)

    As for macros, when I was starting my macro journey, this article was tremendous for me. I'm not sure where you are on your journey but the testing parts specifically helped me.

  18. Snapstromegon commented on Jun 12, 2024

    @Snapstromegon

    Thanks @esmevane, I'll give it a read. Right now I'm working through Jon Gjengset's Crust of Rust streams around macros and that's ~10h of videos to watch.

  19. jgraef commented on Jul 7, 2024

    @jgraef

    For my usecase I want to have multiple crates using different (sqlite) databases in a single workspace.

    Using multiple .env files didn't work well for me. The database URL needed to be relative to the workspace root, regardless of where the .env file was, which works, but is a bit awkward, especially if you also use the sqlx-cli. Also rust-analyzer (in vscodium) didn't like it too much.

    I had the idea to set the DATABASE_URL environment variable on a per-crate basis with a build-script:

    // my-workspace/some-crate/build.rs
    fn main() {
        println!(
            "cargo::rustc-env=DATABASE_URL=sqlite:{}/schema.db",
            std::env::var("CARGO_MANIFEST_DIR").unwrap(),
        );
    }

    This way I can be sure every crate always uses the right database file.

    Edit: Improved build script that runs sqlx migrate run ... to create a schema.db in /target when migrations folder changes:

    build.rs
    use std::{
        path::PathBuf,
        process::Command,
    };
    
    fn main() {
        let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
        let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    
        let migrations_dir = crate_dir.join("migrations");
        let db_file = out_dir.join("schema.db");
        let db_url = format!("sqlite:{}", db_file.display());
    
        println!("cargo::rerun-if-changed={}", migrations_dir.display());
    
        if db_file.exists() {
            std::fs::remove_file(&db_file).unwrap();
        }
    
        std::fs::write(&db_file, b"").unwrap();
    
        let exit_status = Command::new("sqlx")
            .arg("migrate")
            .arg("run")
            .arg("--source")
            .arg(&migrations_dir)
            .arg("--database-url")
            .arg(&db_url)
            .spawn()
            .unwrap()
            .wait()
            .unwrap();
    
        if !exit_status.success() {
            panic!("sqlx failed: {exit_status}");
        }
    
        println!("cargo::rustc-env=DATABASE_URL={}", db_url,);
    }
  20. AustinCase commented on Aug 4, 2024

    @AustinCase

    So excited for that PR @Aderinom !! We were just about to invest in writing that ourselves. Much appreciated!

  21. abonander commented on Sep 18, 2024

    @abonander
    Collaborator

    Our intended solution for this (and many different use-cases besides) is to allow multiple crates in the same workspace to rename their DATABASE_URL var using sqlx.toml: #3383

    I'm working on it as fast as I can, and hope to have it ready for a short alpha cycle for 0.9.0 for people to try it out.

  22. lednhatkhanh commented on Nov 7, 2024

    @lednhatkhanh

    It's so good to see it's happening!

  23. liamwh commented on Nov 13, 2024

    @liamwh
  24. i007c commented on Dec 4, 2024

    @i007c

    Suppose we have an application to transfer data from PostgreSQL to MySQL, using multiple crates isn't helpful, especial when I use query! to compile or run. I prefer

    mod one { sqlx::database!(env!("ONE_DATABASE_URL")); }
    mod two { sqlx::database!(env!("TWO_DATABASE_URL")); }
    
    one::query!("...") // mysql://...
    two::query!("...") // postgres://...

    using env var is just annoying. but i like this approach. this allows more flexibility in the futre as well.

  25. cognivore commented on Mar 3, 2025

    @cognivore

    Re: #121 (comment)

    I also would love to see this ASAP, but I would like to remind everyone that asking for ETA on features in open-source projects is mauve tonne at least and harmful to mental well-being of contributors at most.

    @abonander, your work is appreciated! You don't owe anyone anything. Thank you. 💓

  26. cognivore commented on Mar 19, 2025

    @cognivore

    It was a big refactoring for us, but my hot take is that after splitting domain models into crates maintainability and discoverability has increased across the codebase. Strongly suggest exploring multi-crate architecture!

  27. kevincox commented on Apr 14, 2025

    @kevincox
    Contributor

    Our intended solution for this (and many different use-cases besides) is to allow multiple crates in the same workspace to rename their DATABASE_URL var using sqlx.toml: #3383

    This seems to have a major drawback that you can't use multiple databases in the same crate. Is there any sort of plan for how to support this?

    It would be useful to have both two databases of the same type, and support two databases of multiple types in the same crate.

  28. 0xJepsen commented on Oct 21, 2025

    @0xJepsen

    +1 here. I think in a lots of larger scale projects it makes sense to have multiple database's even of the same type.

  29. kamikaze commented on May 19, 2026

    @kamikaze

    we are not huge, but already have ~10 PostgreSQL databases for the same service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions