k1LoW / tbls

tbls is a CI-Friendly tool for document a database, written in Go.
MIT License
3.34k stars 164 forks source link

Error generating with foreign key in PostgreSQL #476

Closed mdigger closed 1 year ago

mdigger commented 1 year ago

What happened

Does not work when using some variants of the foreign key syntax in PostgreSQL.

create table ticket_logs (
    -- ...
    foreign key (state, reason_id)
        references reasons
        on delete set null (reason_id) -- <- !!!
);

Without the string "on delete set null (reason_id)" it works.

What stack trace or error message from tbls did you see?

not found column 'reason_id) ON DELETE SET NULL (reason_id' on table 'public.reasons'
github.com/k1LoW/tbls/schema.(*Table).FindColumnByName
    /Users/runner/work/tbls/tbls/schema/schema.go:226
github.com/k1LoW/tbls/drivers/postgres.(*Postgres).Analyze
    /Users/runner/work/tbls/tbls/drivers/postgres/postgres.go:343
github.com/k1LoW/tbls/datasource.Analyze
    /Users/runner/work/tbls/tbls/datasource/datasource.go:131
github.com/k1LoW/tbls/cmd.glob..func5
    /Users/runner/work/tbls/tbls/cmd/doc.go:72
github.com/spf13/cobra.(*Command).execute
    /Users/runner/go/pkg/mod/github.com/spf13/cobra@v1.6.1/command.go:916
github.com/spf13/cobra.(*Command).ExecuteC
    /Users/runner/go/pkg/mod/github.com/spf13/cobra@v1.6.1/command.go:1044
github.com/spf13/cobra.(*Command).Execute
    /Users/runner/go/pkg/mod/github.com/spf13/cobra@v1.6.1/command.go:968
github.com/k1LoW/tbls/cmd.Execute
    /Users/runner/work/tbls/tbls/cmd/root.go:194
main.main
    /Users/runner/work/tbls/tbls/main.go:34
runtime.main
    /Users/runner/hostedtoolcache/go/1.19.8/x64/src/runtime/proc.go:250
runtime.goexit
    /Users/runner/hostedtoolcache/go/1.19.8/x64/src/runtime/asm_arm64.s:1172

Anything else we need to know?

The actions SET NULL and SET DEFAULT can take a column list to specify which columns to set. Normally, all columns of the foreign-key constraint are set; setting only a subset is useful in some special cases. Consider the following example:

CREATE TABLE tenants (
    tenant_id integer PRIMARY KEY
);

CREATE TABLE users (
    tenant_id integer REFERENCES tenants ON DELETE CASCADE,
    user_id integer NOT NULL,
    PRIMARY KEY (tenant_id, user_id)
);

CREATE TABLE posts (
    tenant_id integer REFERENCES tenants ON DELETE CASCADE,
    post_id integer NOT NULL,
    author_id integer,
    PRIMARY KEY (tenant_id, post_id),
    FOREIGN KEY (tenant_id, author_id) REFERENCES users ON DELETE SET NULL (author_id)
);

Environment

k1LoW commented 1 year ago

@mdigger Thank you for your report!!