sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

Consider generating enums for check constraints

Open mfridman opened this issue 2 years ago • 5 comments

What do you want to change?

Consider generating enums for check constraints (in a similar way as if postgres enums were defined). For example, given this table:

CREATE TABLE books (
    name text NOT NULL,
    status text NOT NULL CHECK (status in ('available', 'unavailable', 'lost'))
);

The generated code would be:

type Book struct {
	Name   string
	Status string
}

But if it were

CREATE TYPE book_status AS ENUM (
  'available',
  'unavailable',
  'lost'
);

CREATE TABLE books (
    name text NOT NULL,
    status book_status
);

the generated code now contains a Go constant type

type BookStatus string

const (
	BookStatusAvailable   BookStatus = "available"
	BookStatusUnavailable BookStatus = "unavailable"
	BookStatusLost        BookStatus = "lost"
)

[...]

Could sqlc also generate these enums based on check constraints?

What database engines need to be changed?

PostgreSQL

What programming language backends need to be changed?

Go

mfridman avatar Oct 27 '23 20:10 mfridman

not sure if i should piggy back here, but using the same check constraint in sqlite is generating an interface{} type.

baabcantcode avatar Jan 02 '24 02:01 baabcantcode

changing the data type from char(1) to text helped get rid of the interface{} at least.

ex:

create table if not exists x (
    id integer primary key,
    constrains text not null,
    applies_to_user char(1) not null check(applies_to_user in ('y', 'n')) default 'y',
    default_weight integer not null default 1
);

baabcantcode avatar Jan 02 '24 02:01 baabcantcode

it also doesnt appear to be parsing the affinities into the model correctly, for e.g. boolean. https://www.sqlite.org/datatype3.html - specifically 3.1 & 3.1.1

baabcantcode avatar Jan 02 '24 02:01 baabcantcode