sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.51k stars 810 forks source link

Invalid UUID type is generated for null column with foreign key #3670

Closed illiafox closed 1 month ago

illiafox commented 1 month ago
          > The issue here is not related to the `REFERENCES` constraint, but rather that `sqlc` treats nullable fields differently from not-nullable fields when considering overrides. You can either mark the `user_id` field as `NOT NULL` or you can add an additional override for the nullable type:

I have the same issue with version v1.25.0

https://play.sqlc.dev/p/c0783e2fdd1ba1dfeca0b396bb9f0cbe3ce79a22a552aecd7565bda94ff68cec

sqlc.yaml

version: "2"
sql:
  - engine: "postgresql"
    queries: "query.sql"
    schema: "schema.sql"
    gen:
      go:
        package: "repository"
        out: "."
        sql_package: "pgx/v5"
        emit_all_enum_values: true
        emit_db_tags: true
        emit_interface: true
        emit_prepared_queries: true
        emit_enum_valid_method: true
        emit_empty_slices: true
        emit_params_struct_pointers: true
        emit_result_struct_pointers: true
        emit_pointers_for_null_types: true
        query_parameter_limit: 2
        overrides:
          - db_type: "uuid"
            go_type: "github.com/google/uuid.UUID"
          - db_type: "uuid"
            go_type: "github.com/google/uuid.UUID"
            nullable: true

schema.sql

CREATE TABLE IF NOT EXISTS items
(
    id         UUID PRIMARY KEY           DEFAULT uuid_generate_v4(),
    parent_id  UUID REFERENCES items (id) NULL,
    name TEXT NOT NULL
);

query.sql

-- name: CreateItem :exec
INSERT INTO items (id, parent_id, name)
VALUES (@id,
        @parent_id,
        @name);

Generated models.go

// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.25.0

package repository

import (
    "github.com/google/uuid"
)

type Item struct {
    ID       uuid.UUID `db:"id"`
    ParentID uuid.UUID `db:"parent_id"`
    Name     string    `db:"name"`
}

Generated query.sql.go

// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.25.0
// source: query.sql

package repository

import (
    "context"

    "github.com/google/uuid"
)

const createItem = `-- name: CreateItem :exec
INSERT INTO items (id, parent_id, name)
VALUES ($1,
        $2,
        $3)
`

type CreateItemParams struct {
    ID       uuid.UUID `db:"id"`
    ParentID uuid.UUID `db:"parent_id"`
    Name     string    `db:"name"`
}

func (q *Queries) CreateItem(ctx context.Context, arg *CreateItemParams) error {
    _, err := q.db.Exec(ctx, createItem, arg.ID, arg.ParentID, arg.Name)
    return err
}

I expect sqlc to generate ParentID *uuid.UUID

Originally posted by @illiafox in https://github.com/sqlc-dev/sqlc/issues/2738#issuecomment-2429842964

illiafox commented 1 month ago

duplicate of #3671