Use postgres views to reduce database calls in api (allow JOIN
s in pg queries)
#2201
Labels
api
Area: HTTP API
design needed
Request for more beauty
needs decision
Needs a higher-level decision to be unblocked.
stale
This issue is like stale bread.
Uh oh!
There was an error while loading. Please reload this page.
This is just tracking a suggestion and making a place for discussion.
Branch that implements this suggestion:
stevenmasley/build_initiator_username
PR that started conversation: #2137
Enable use of
JOIN
in sqlc queriesCurrently the UI requires additional information regarding data structures returned by the database. An example is the
workspace_build
table does not include the following fields that the UI wants and usesconvertWorkspaceBuild
to add these fields.provisioner job(although included, going to not JOIN this data in right now)This requires 2 extra database calls (fetch users, and workspace). Ideally we could fetch this information with a
JOIN
.The solution to using joins is to make a migration that makes the above a VIEW in our database that can be reused. This simplifies all the queries around
workspace_builds
as we do not need to copy theJOIN
more than once (DRY).Downsides to views
Maintaining the view
If a column is added to
workspace_build
, that column is not automatically added to the view. So your migration will look like this:The biggest downside is that is adds some complexity to our migrations. The developer writing the migration needs to know which views to also update. Postgres will fail if a view is a dependency and the underlying table is changed. They will likely have to copy the
CREATE VIEW ...
code block from migration to migration.This is just the cost of the views.
Con: Defaulting to using joins
One downside is that all our queries now use joins. In the example above, the data being joined is only used by the UI. So internal usage doesn't require the join (at the moment). However, having the additional context could be nice for logging purposes, so it might not be a total waste.
I don't think join performance will be so bad that this is really an issue, but it does cause over-fetching.
If we use the sqlc.embed fork of sqlc, we can make db calls with the join, and some db calls without the join. Having this mix can prevent overfetching if we hit performance issues. Using the
embed
means we can nest data-structs and have the UI data-structure be something like:The upside
database.Type
shared by all sqlc queriesAlternative (Status Quo)
The alternative is to do the status quo, where we make multiple db calls and merge the resulting structs.
convertWorkspaceBuild
function.Extra links
SQLc implementations that could help. But gated since these features do not exist yet :(.
sqlc.embed()
fork: feat: addsqlc.embed
to allow model re-use sqlc-dev/sqlc#1615.template: workspace_build_initiator
support for putting the views in the queries.sqlThe text was updated successfully, but these errors were encountered: