Skip to content

Query templates#112

@kyleconroy

Description

@kyleconroy

A sqlc user asked how it would be possible to share a set of select expressions across queries. There isn't a way to do this in the SQL standard, so I came up with the following idea. A given query would be marked as a template. This query must be a certain shape, specifically a select from a single table with no additional clauses. You could then refer to that template from subsequent queries to that same table.

Here's an example using the setup from the README

CREATETABLEauthors ( id BIGSERIALPRIMARY KEY, name textNOT NULL, bio text ); -- template: named_authorSELECT id, lower(name) as fullname, coalese(bio, 'none') as bio_default, 1as one FROM authors; -- name: GetAuthor :oneSELECTsqlc.named_author.*FROM authors WHERE id = $1LIMIT1; -- name: CreateAuthor :oneINSERT INTO authors ( name, bio ) VALUES ( $1, $2 ) RETURNING sqlc.named_author.*;
package db import ( "context""database/sql" ) typeNamedAuthorstruct{IDint64FullnamestringBioDefaultstringOneint64 } constcreateAuthor=`-- name: CreateAuthor :oneINSERT INTO authors ( name, bio) VALUES ( $1, $2)RETURNING id, lower(name) as fullname, coalese(bio, 'none') as bio_default, 1 as one`typeCreateAuthorParamsstruct{NamestringBio sql.NullString } func (q*Queries) CreateAuthor(ctx context.Context, argCreateAuthorParams) (NamedAuthor, error){row:=q.db.QueryRowContext(ctx, createAuthor, arg.Name, arg.Bio) variNamedAuthorerr:=row.Scan(&i.ID, &i.Fullname, &i.BioDefault, &i.One) returni, err } constgetAuthor=`-- name: GetAuthor :oneSELECT id, lower(name) as fullname, coalese(bio, 'none') as bio_default, 1 as oneFROM authorsWHERE id = $1 LIMIT 1`func (q*Queries) GetAuthor(ctx context.Context, idint64) (NamedAuthor, error){row:=q.db.QueryRowContext(ctx, getAuthor, id) variNamedAuthorerr:=row.Scan(&i.ID, &i.Fullname, &i.BioDefault, &i.One) returni, err }

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions