sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Enabling pointer in config file for a custom type, doesn't work with `NOT NULL`

Open adoublef opened this issue 3 years ago • 1 comments

Version

1.14.0

What happened?

Reading the docs here that its possible to override column type. For an in-built type like time.Time using the following configuration:

{
  "db_type": "timestamp",
  "go_type": {
    "import": "time",
    "type": "Time",
    "pointer": true
  },
  "nullable": true
}

Allows me to have a pointer as a struct field if I dont include NOT NULL in my schema.sql file:

create table example1 (
    /*...*/    
    createdAt timestamp
)

create table example2 (
    /*...*/    
    createdAt timestamp not null
)

produce these types:

type Example1 struct {
    /*...*/
    CreatedAt *time.Time
}

type Example2 struct {
    /*...*/
    CreatedAt time.Time
}

This does not work when overriding a column type with a package level type:


package mypkg

type Username string
{
    "column": "user.username",
    "go_type": {
        "import": "github.com/.../mypkg",
        "type": "Username",
        "pointer": true
    },
    "nullable": true
}
create table example3 (
    /*...*/    
    username varchar(255)
)

create table example4 (
    /*...*/    
    username varchar(255) not null
)

the generated types are both using pointers, even though, I would have expected, as with the previous example, it only be a pointer only if it could be nullable.

type Example3 struct {
    /*...*/
    Username *mypkg.Username
}

type Example4 struct {
    /*...*/
    Username *mypkg.Username
}

Is there a config missing or is this something that could be fixed as I am unsure via the documentation, if this is intended behaviour or not. This affects both mysql and psql engine.

Relevant log output

No response

Database schema

create table example4 (   
    username varchar(255) not null
)

SQL queries

No response

Configuration

{
    "column": "user.username",
    "go_type": {
        "import": "github.com/myrepo/mypkg",
        "type": "Username",
        "pointer": true
    },
    "nullable": true
}

Playground URL

No response

What operating system are you using?

Linux

What database engines are you using?

MySQL

What type of code are you generating?

Go

adoublef avatar Aug 01 '22 07:08 adoublef

Reproduced on the playground

kyleconroy avatar Aug 29 '22 03:08 kyleconroy

Reading over this again, this is working as intended. By using a column override, you're telling sqlc to always use the go_type specified. The nullable field is ignored for columns. Since nickname can never be null, you can remove the pointer field and get the code that you want.

https://play.sqlc.dev/p/01ee02b8f16afeb2788ae7d44c258b619fd348dcd921e06dd82947a9d89d7a86

kyleconroy avatar Sep 26 '23 08:09 kyleconroy