简体   繁体   中英

Rails 5, Replace a Join Table With A Postgres Array

Let's say we have a system that executes 'jobs'. These jobs can be wired up into sequences we call 'integrations' which are effectively an ordered set of jobs.

The classic solution would be a join table:

integrations: id, name
jobs: id, name, commands
integrations_jobs: id, integration_id, job_id, integration_order

where integration_order is the position of that integration_job within the integration.

What if instead we just used a postgres array?

integrations: id, name, [job_id1, job_id2, job_id3]
jobs: id, name, commands

Are there any obvious drawbacks I'm missing with using an array instead of a join table? We are using Rails 5 and Postgres on Heroku.

You can use Postgres array or JSON or enum field but it will affect performance.
Look here

The first drawback is you can not query to find a job in integrations, example:

jobs table
id
1
2

integrations table
id, name, job_ids
1, i1, [1,2]
2, i2, [2]

so, if you want to find integrations of a job which has id 2 , you need to scan integrations table and check if job_ids has value of 2 . If integrations table has a lot of records, it's a big perfomance problem.

If you have a join table, that is just a very simple query and faster. I don't see what wrong if you use a join table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM