pq: insert or update on table violates foreign key constraint

740 views Asked by At

Trying to use gqlgen with sqlx. gqlgen generated todo and user structs:

package model

type NewTodo struct {
    Text   string `json:"text" db:"text"`
    UserID int64  `json:"user_id" db:"user_id"`
}

type Todo struct {
    ID   int64  `json:"id"`
    Text string `json:"text" db:"text"`
    Done bool   `json:"done" db:"done"`
    User *User  `json:"user"`
}

type User struct {
    ID   int64  `json:"id"`
    Name string `json:"name" db:"name"`
}

This is the database (postgres) schema:

var Schema = `
    CREATE TABLE users (
        id BIGSERIAL PRIMARY KEY,
        name VARCHAR(255),
        created_at TIMESTAMPTZ NOT NULL DEFAULT (now()),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT (now())
    );

    CREATE TABLE todos (
        id BIGSERIAL PRIMARY KEY,
        text TEXT,
        done BOOLEAN,
        user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT (now()),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT (now())
    );
`

This is the insert mutation/function:

...

func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
    log.Println(" >> input.Text:", input.Text) // One Todo
    log.Println(" >> input.Text.Type:", reflect.TypeOf(input.Text)) // string
    log.Println(" >> input.UserID:", input.UserID) // 1
    log.Println(" >> input.UserID.Type:", reflect.TypeOf(input.UserID)) // int64

    db := db.Connect()
    tx := db.MustBegin()
    id, err := tx.MustExec("INSERT INTO todos (text, user_id) VALUES ($1, $2)", input.Text, input.UserID).LastInsertId()
    if err != nil {
        log.Fatalln(err)
    }
    tx.Commit()
    return &model.Todo{ID: id}, nil
}

And when I made the new todo mutation, it throws internal system error of:

pq: insert or update on table "todos" violates foreign key constraint "todos_user_id_fkey"

Where I am doing wrong?

0

There are 0 answers