You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Question: best way to use sqlx with connections to two different databases? #121
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?
Reacted by Joshua Adelman, Li X.P., bold, Kevin L., qiuzhanghua, Dustin Bensing, gongdear, Daniel García, Jose Quintana, John Soo and 59 more
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.
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.
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://...
Reacted by qiuzhanghua, weezy, nfedyashev, petru-tazz, Nick Vegean, Jake, Reinis, Stefan Krüger, displexic, asudox and 1 more
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?).
Reacted by Casey Allred, Bo Jeanes, Vladimir Zapparov, John Soo, nfedyashev, John D. Mitchell and d-d
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.
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.
Reacted by Casey Allred, Mario Ortiz Manero, John Soo, Serhii Potapov, VersBinarii, Nick Schmeller, Maxwell Koo, Dave Warnock, John D. Mitchell, Matilda Smeds and 7 more
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:
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.
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:
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).
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'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.
@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.
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.
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:
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.
Reacted by Arcstur, Islom Matnazarov, Evgeniy Tatarkin, LimpSquid, Antonin Amand, Caio Gomes, echozs151, Brendan Devine, Nhat Khanh, Luis Eduardo Brito and 1 more
Reacted by Jesse Stuart, Arcstur, Islom Matnazarov, Paul Hansen, Raphael Höser, Antonin Amand, AMS21, dalu, Caio Gomes, Brendan Devine and 6 more
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.
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. 💓
Reacted by peter-lockhart-pub, Arcstur, Pavlo Myroniuk, esmevane, Cosmic, Austin Case, Thea Heinen, Reinis, FrankReh, Luis Eduardo Brito and 3 more
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!
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.
Reacted by Eliza Zhang, Waylon Jepsen ✨ and aaronpeacock
Activity
mehcode commentedon Mar 14, 2020
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.
PoiScript commentedon Mar 22, 2020
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.mehcode commentedon Apr 3, 2020
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.,
PoiScript commentedon Apr 4, 2020
@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.
will specifies the
DATABASE_URL, orwill tells sqlx to use
DATABASE_URL_barinstead.jsdw commentedon Apr 4, 2020
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?).sbditto85 commentedon Apr 4, 2020
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 theenv=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 andurl=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.
abonander commentedon Apr 4, 2020
The idea with the
sqlx::database!()macro is that it wouldn't be another proc macro, it's just amacro_rules!macro that simply shadows the facade macros insrc/macros.rswith 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:
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.
mehcode commentedon Apr 4, 2020
Another thought is the
databasemacro could configure all sorts of knobs. One in particular could be adding or overriding user-defined types.abonander commentedon Apr 4, 2020
Like setting
tinyintin MySQL to always bebool, maybe.It should probably be called
config!().PoiScript commentedon Apr 5, 2020
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:abonander commentedon Apr 5, 2020
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.
abonander commentedon Apr 5, 2020
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:However, I think the
config!()macro is strictly more useful because you don't have to repeat your customization options every time you callquery!(). I don't see a reason why not to support both except the increased complexity involved (which is already a problem for thequery!()macros).sbditto85 commentedon Apr 6, 2020
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
abonander commentedon Apr 17, 2020
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 likeshadow_macros!()or something.19 remaining items
esmevane commentedon Jun 12, 2024
@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.
Snapstromegon commentedon Jun 12, 2024
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.
jgraef commentedon Jul 7, 2024
For my usecase I want to have multiple crates using different (sqlite) databases in a single workspace.
Using multiple
.envfiles didn't work well for me. The database URL needed to be relative to the workspace root, regardless of where the.envfile was, which works, but is a bit awkward, especially if you also use thesqlx-cli. Also rust-analyzer (in vscodium) didn't like it too much.I had the idea to set the
DATABASE_URLenvironment variable on a per-crate basis with a build-script: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 aschema.dbin/targetwhenmigrationsfolder changes:build.rs
AustinCase commentedon Aug 4, 2024
So excited for that PR @Aderinom !! We were just about to invest in writing that ourselves. Much appreciated!
abonander commentedon Sep 18, 2024
Our intended solution for this (and many different use-cases besides) is to allow multiple crates in the same workspace to rename their
DATABASE_URLvar usingsqlx.toml: #3383I'm working on it as fast as I can, and hope to have it ready for a short alpha cycle for
0.9.0for people to try it out.lednhatkhanh commentedon Nov 7, 2024
It's so good to see it's happening!
liamwh commentedon Nov 13, 2024
i007c commentedon Dec 4, 2024
using env var is just annoying. but i like this approach. this allows more flexibility in the futre as well.
Disable static database checks in library
cognivore commentedon Mar 3, 2025
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. 💓
cognivore commentedon Mar 19, 2025
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!
kevincox commentedon Apr 14, 2025
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.
0xJepsen commentedon Oct 21, 2025
+1 here. I think in a lots of larger scale projects it makes sense to have multiple database's even of the same type.
kamikaze commentedon May 19, 2026
we are not huge, but already have ~10 PostgreSQL databases for the same service