Skip to content

Prefix table names with database name when running join queries on mysql to support cross database joins - #10281

Closed
foysalit wants to merge 5 commits into
sequelize:masterfrom
foysalit:master
Closed

foysalit wants to merge 5 commits into
sequelize:masterfrom
foysalit:master

Conversation

@foysalit

@foysalit foysalit commented Dec 18, 2018 •

Copy link
Copy Markdown

Pull Request check-list

Please make sure to review and check all of these items:

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Did you follow the commit message conventions explained in CONTRIBUTING.md?

Description of change

This is my first contribution to sequelize and I tried to follow all the guidelines but feel free to let me know if any change is needed.
This PR attempts to fix #2049 which is right now the only barrier between cross database join queries.

I have not added any new tests since the current test setup does not seem to support multi databases and I do not want to (read, too scared to) poke around the entire test env setup at the moment. However, it does adjust the existing tests to make sure the change is accounted for.

Fixes #2049

@codecov

codecov Bot commented Dec 18, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #10281 into master will decrease coverage by 21.5%.
The diff coverage is 67.3%.

Impacted file tree graph

@@             Coverage Diff             @@
##           master   #10281       +/-   ##
===========================================
- Coverage   96.27%   74.77%   -21.51%     
===========================================
  Files          68       85       +17     
  Lines        9777     8282     -1495     
===========================================
- Hits         9413     6193     -3220     
- Misses        364     2089     +1725
Impacted Files Coverage Δ
lib/transaction.js 93.05% <ø> (-6.95%) ⬇️
lib/dialects/mysql/index.js 100% <ø> (ø) ⬆️
lib/dialects/mariadb/query-generator.js 20% <ø> (-77.92%) ⬇️
...b/dialects/abstract/query-generator/transaction.js 18.75% <ø> (-68.75%) ⬇️
lib/dialects/postgres/query-generator.js 1.82% <0%> (-92.27%) ⬇️
lib/dialects/mysql/query-generator.js 5.72% <0%> (-92.19%) ⬇️
lib/associations/base.js 95% <0%> (-5%) ⬇️
lib/dialects/sqlite/query-interface.js 15.62% <0%> (-84.38%) ⬇️
lib/deferrable.js 14.28% <0%> (-59.05%) ⬇️
lib/dialects/sqlite/query-generator.js 2.91% <0%> (-93.54%) ⬇️
... and 129 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5af93e7...c03dbf0. Read the comment docs.


if (options.include) {
// To support cross database joins on mysql, prefix the database name of the model in case the model is for a different database
if (this.dialect === 'mysql') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a rather crude approach, how will this API work? Can you show an example of include that you can use to cross join with current proposed changes?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it's a bit crude and seems hacky but I don't see another way of doing this reliably without affecting a lot of the apis and breaking existing features.

In an app I'm working on that uses multiple databases, I have multiple sequelize instances like below:

const Sequelize = require('Sequelize');
const userDb = new Sequelize(/* ... */);
const contentDb = new Sequelize(/* ... */);
// more databases here....

Then, I have several models for each database that are related to each other such as userDb.ClientModel, contentDb.PostModel where each client can have multiple posts so the relationship is defined as below:

userDb.ClientModel.hasMany(contentDb.PostModel, {foreign_key: 'client_id', sourceKey: 'id', constraints: false});
contentDb.PostModel.belongsTo(userDb.ClientModel, {foreign_key: 'client_id`, targetKey: 'id', constraints: false});

Now if I want to query all posts belonging to a user with

userDb.ClientModel.findAll({
  include: { model: contentDb.PostModel }, 
  limit: 5
});

it will NOT work since the query will try to look for the PostModel table in the userDb database. However, I made it work with my implementation of prefixing the table name with the db name.

It only becomes an issue when a query includes joins or subqueries however, I'm not super confident if my fix will work for subqueries that run on another table but from my tests. it does work for join queries such as the above explained scenario.

All the above code are somewhat pseudo code and not exactly as the actual code from my project since I'm not at liberty of sharing those code. So if something doesn't add up or not clear enough, feel free to let me know.

@foysalit

Copy link
Copy Markdown
Author

Any updates on merging this? Would love to help out removing any blocker if there are any?

@foysalit

foysalit commented Jul 9, 2019

Copy link
Copy Markdown
Author

Just FYI, I have been using this in a production app for the last 3 months and haven't found any issues caused by this addition. @sushantdhiman

@papb

papb commented Jul 10, 2019

Copy link
Copy Markdown
Member

Hi @foysalit! Thanks for taking the time for this. It's unfortunate that so much time has passed without a response for you.

In my opinion, a documentation change is important for this PR. As @sushantdhiman said:

Can you show an example of include that you can use to cross join with current proposed changes?

I think a MCVE showing the usage would be great (not only as a comment, but as real sequelize docs).


let joinTableName = this.quoteTable(tableRight, asRight);

// For mysql, embe

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is embe?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry that's probably just a type i left in instead of finishing the comment. Can't recall what i wanted to write there after so long.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. Please just remove the comment then in order not to confuse others 👍

@papb

papb commented Jul 10, 2019

Copy link
Copy Markdown
Member

Another thing - how does this relate to MariaDB? Since MariaDB and MySQL are closely related, perhaps this could/should be implemented for MariaDB as well?

(Sorry if this question does not make sense, I am not very familiar with mysql/mariadb)

@foysalit

Copy link
Copy Markdown
Author

Another thing - how does this relate to MariaDB? Since MariaDB and MySQL are closely related, perhaps this could/should be implemented for MariaDB as well?

(Sorry if this question does not make sense, I am not very familiar with mysql/mariadb)

I think my implementation works on both? The app where I am using this connects to a mariadb instance and it's working fine so far.

@foysalit

Copy link
Copy Markdown
Author

Hi @foysalit! Thanks for taking the time for this. It's unfortunate that so much time has passed without a response for you.

In my opinion, a documentation change is important for this PR. As @sushantdhiman said:

Can you show an example of include that you can use to cross join with current proposed changes?

I think a MCVE showing the usage would be great (not only as a comment, but as real sequelize docs).

Ok I can add documentation but for the MCVE, do you want me to create a repo showing how it works? or just describing it through documentation is good enough?

@papb

papb commented Jul 10, 2019

Copy link
Copy Markdown
Member

Another thing - how does this relate to MariaDB? Since MariaDB and MySQL are closely related, perhaps this could/should be implemented for MariaDB as well?
(Sorry if this question does not make sense, I am not very familiar with mysql/mariadb)

I think my implementation works on both? The app where I am using this connects to a mariadb instance and it's working fine so far.

Ah! Great. Sorry for the confusion. By seeing only mysql there I thought for some reason more configuration would be needed for it to work on MariaDB... Excellent!

@papb

papb commented Jul 10, 2019

Copy link
Copy Markdown
Member

Hi @foysalit! Thanks for taking the time for this. It's unfortunate that so much time has passed without a response for you.
In my opinion, a documentation change is important for this PR. As @sushantdhiman said:

Can you show an example of include that you can use to cross join with current proposed changes?

I think a MCVE showing the usage would be great (not only as a comment, but as real sequelize docs).

Ok I can add documentation but for the MCVE, do you want me to create a repo showing how it works? or just describing it through documentation is good enough?

Just including self-contained code and instructions in the documentation is enough 👍

@Phyziik

Phyziik commented Jul 16, 2019

Copy link
Copy Markdown

When will this be merged? And what would be a workaround until then?
A big thanks for implementing this.

@papb

papb commented Jul 16, 2019

Copy link
Copy Markdown
Member

@Phyziik - We can't predict foysalit's availability, so we don't know when this will be merged.

But if you are in a big hurry, this is what you could do at your own risk:

  1. Clone foysalit's github repo locally
  2. Rebase his changes to the official sequelize master branch, as follows:
git remote add upstream https://github.com/sequelize/sequelize.git
git fetch upstream
git rebase upstream/master
  1. Instead of using the official sequelize in your project, use your local repo instead, until this is merged

@Phyziik

Phyziik commented Jul 16, 2019

Copy link
Copy Markdown

@Phyziik - We can't predict foysalit's availability, so we don't know when this will be merged.

But if you are in a big hurry, this is what you could do at your own risk:

  1. Clone foysalit's github repo locally
  2. Rebase his changes to the official sequelize master branch, as follows:
git remote add upstream https://github.com/sequelize/sequelize.git
git fetch upstream
git rebase upstream/master
  1. Instead of using the official sequelize in your project, use your local repo instead, until this is merged

Thanks for such a quick reply. I agree that this could work, but aside from foysalit's implementation, is there no other way to do joins, using Sequelize, even if its with queries?

I tried playing with queries, but the issue comes with targeting the second database. It seems like the query is always made in the scope of the first database, omitting that the second database is there and synced.

I'm fairly new with Sequelize, so I could be understanding this all wrong.

@papb

papb commented Jul 16, 2019

Copy link
Copy Markdown
Member

@Phyziik Well, I think you could probably make it work using raw queries? You can make a raw query that replicates what the work of foysalit would do automatically. Would this work for you?

@papb papb added the waiting label Jul 20, 2019
@papb papb added status: awaiting response For issues and PRs. OP must respond (or change something, if it is a PR). Maintainers have no action type: feature DEPRECATED: replace with the "feature" issue type and removed waiting labels Jul 24, 2019
@foysalit

foysalit commented Aug 8, 2019

Copy link
Copy Markdown
Author

Hey @papb sorry for the late response but could you point me to an example that i can replicate for adding example/instruction? should it go somewhere in the /docs folder? if yes, which file? or should i just add more details in the comment near my code in the PR?

@papb

papb commented Aug 8, 2019

Copy link
Copy Markdown
Member

@foysalit Hmm... Don't worry about the docs itself for now. Please fix this and post a MCVE. And by MCVE in this case I just mean improving your code here making it a single code block that I can copy-paste and run (assuming I have setup a local mysql runner correctly).

@papb

papb commented Aug 8, 2019

Copy link
Copy Markdown
Member

Also please rebase your branch to fix the conflict in select.test.js that github is pointing out. Let me know if you have trouble rebasing.

@dchaur

dchaur commented Aug 20, 2019

Copy link
Copy Markdown

Hi all,

This could be a great development however I'm not sure if it fits within the Sequelize philosophy. For example, in mySQL you can query tables from different databases using the same connection (with the right permissions):

SELECT * FROM myDatabaseOne.tableOne mdbOne INNER JOIN myDatabaseTwo.myCustomTable mdbTwo ON mdOne.myGuid = mdbTwo.guid

As far as I understand Sequelize needs an instance per database... lets see if this can work without breaking anything.

Anyway thanks!

@foysalit

Copy link
Copy Markdown
Author

Hey @papb so I created a gist for MCVE : https://gist.github.com/foysalit/a3176c3d588b27606a0d3a064fd56970 this should help you replicate and confirm that the fix works.
Also, tried to fix the conflicts directly on github not sure if that helped?
For rebase, do you want me to just squash the commits into one or is there something else you want me to do?

@foysalit

Copy link
Copy Markdown
Author

Is there anything else I can provide to get this PR considered? Appreciate any help with the rebase as well.

@papb

papb commented Sep 26, 2019

Copy link
Copy Markdown
Member

Hi @foysalit thanks for the heads up! I will change it from awaiting response to awaiting maintainer. I don't have time to look into it right now but hopefully will do at the weekend.

@papb papb added status: awaiting maintainer and removed status: awaiting response For issues and PRs. OP must respond (or change something, if it is a PR). Maintainers have no action labels Sep 26, 2019
@papb papb self-assigned this Sep 26, 2019
@papb

papb commented Oct 13, 2019

Copy link
Copy Markdown
Member

Just passing by to say I didn't forget about this... Please hold on

@mateuo

mateuo commented Dec 4, 2019

Copy link
Copy Markdown

Just passing by to say I didn't forget about this... Please hold on

Any news about this interesting feature?
Thanks

@foysalit

foysalit commented Jan 3, 2020

Copy link
Copy Markdown
Author

Hey @papb hope you're having a great 2020 so far. any updates on this? It's now one of the oldest PRs in the queue. Would love to get the ball rolling towards a merge.

@foysalit

foysalit commented Jan 3, 2020

Copy link
Copy Markdown
Author

With my last commit, cross db joins now work for has many through relationships.

@ouraios

ouraios commented Feb 11, 2020

Copy link
Copy Markdown

I agree with @foysalit i'm facing this issue with Sequelize not being able to use "schema" in Mysql, would it be possible @papb to check it asap ?
I think a lot of people would like "schema" to work in Mysql.

@sdepold

sdepold commented Oct 24, 2021

Copy link
Copy Markdown
Member

Hey there :)

First of all: Thanks a bunch for your contribution to Sequelize! Much appreciated!
Second: Unfortunately we haven't had the chance to look into this ever since you created it. Sorry for that!

A couple of months ago, we have switched from master to main branch as our primary development branch and hence this PR is now outdated :(

If you still think this change is making sense, please consider recreating the PR against main. Thanks in advance and sorry for the additional work.

✌️

@github-actions github-actions Bot added the stale label Nov 16, 2021
@WikiRik

WikiRik commented Jan 31, 2022

Copy link
Copy Markdown
Member

Closing this since it is still against master. Can be reopened if that changes.

@WikiRik WikiRik closed this Jan 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale type: feature DEPRECATED: replace with the "feature" issue type

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prepend database to table name (Cross database joins)

9 participants