Skip to content

Expanding sql VIEWs at generation to reuse queries (query fragments, query templates) #2491

Open

Description

@Emyrk

What do you want to change?

Related:

SQLc supports VIEWs which are essentially tables. Views however are static, and sqlc updates according to the underlying schema.

A helpful feature that could DRY up some queries is to handle VIEWs as reusable queries and never committing them to postgres.

Postgres views are already not every materialized.

CREATE VIEW defines a view of a query. The view is not physically materialized. Instead, the query is run every time the view is referenced in a query.

It should be possible then to handle views within the sqlc generation. This would allow reusing queries, and even allowing things like sqlc.embed to better generate structs for any given VIEW.

Example playground:


There probably should be a way to mark a VIEW so sqlc knows to expand it rather than rely on the database's set of views.

-- name: book_with_author :view
CREATE VIEW book_with_author AS
 SELECT 
 	sqlc.embed(authors), 
	sqlc.embed(books)
 FROM
	books
LEFT JOIN
	authors
ON 
	books.author_id == authors.id;


-- name: GetBook :one
SELECT * FROM sqlc.view(book_with_author)
WHERE id = $1 LIMIT 1;

What database engines need to be changed?

PostgreSQL

What programming language backends need to be changed?

Go

Activity

  1. added
    enhancement
    triage
    on Jul 21, 2023
  2. added and removed
    triage
    on Oct 2, 2023
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

    📚 postgresqlenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions