Skip to content

Joined table variable names should include source table name for disambiguation #560

Closed

Description

@johanbrandhorst

Hi, great library!

When using an SQL JOIN statement, we can end up with tables that have the same column name in the same variable interpolation. Currently, this results in names such as Name and Name_2. For example, given the following schema:

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE users (
  id UUID gen_random_uuid (),
  name TEXT
)

CREATE TABLE posts (
  id UUID gen_random_uuid (),
  user_id UUID REFERENCES users (id),
  name TEXT
)

And the following query:

-- name: GetPostsByUserByName :one
SELECT * FROM posts
LEFT JOIN users ON posts.user_id = users.id
WHERE posts.name = $1 AND users.name = $2

We end up with the following parameter type:

type GetPostsByUserByNameParams struct {
	Name   uuid.UUID
	Name_2 uuid.UUID
}

This is obviously not ideal, and I think we should do what SQL does for disambiguation; use the table names. It could look something like this (using the existing algorithm for de-pluralising table names):

type GetPostsByUserByNameParams struct {
	PostName uuid.UUID
	UserName uuid.UUID
}

Alternatively, if that is too heavy handed, I tried using the rename functionality to override the variable name, but it doesn't seem to work as expected; the following accomplished nothing:

rename:
  posts.name: "PostName"
  users.name: "UserName"

Any thoughts appreciated!

Activity

  1. kyleconroy commented on Jun 22, 2020

    @kyleconroy
    Collaborator

    The renaming functionality is poorly documented. It actually doesn't work for parameters.

    But I have a solution for you: named parameters. You can used either sqlc.arg() or @.

    -- name: GetPostsByUserByName :one
    SELECT * FROM posts
    LEFT JOIN users ON posts.user_id = users.id
    WHERE posts.name = sqlc.arg('post_name') AND users.name = sqlc.arg('user_name') 
    -- name: GetPostsByUserByName :one
    SELECT * FROM posts
    LEFT JOIN users ON posts.user_id = users.id
    WHERE posts.name = @post_name AND users.name = @user_name

    I do agree that we should be able to generate these better names automatically, but it's not something I'm focusing on right now.

  2. johanbrandhorst commented on Jun 22, 2020

    @johanbrandhorst
    ContributorAuthor

    Fantastic, thanks for the workaround!

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

    futureIn the year 3000...

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions