Skip to content

Upsert fails with sql.ErrNoRows #84

Closed
@oystedal

Description

@oystedal

Upsert fails, returning sql.ErrNoRows, because Postgres does not return any values when DO NOTHING is used as the conflict action. This happens when there is a conflict on the tuple to be inserted, such as when trying to insert a duplicate primary key/unique.

The expected result would be that Upsert returns no error and updates the object on which Upsert was called.

Schema:

CREATE TABLE video
(
    id serial PRIMARY KEY,
    youtube_id varchar(64) NOT NULL,
    title text NOT NULL
);

ALTER TABLE video ADD CONSTRAINT youtube_id_uniq UNIQUE (youtube_id);

Call:

// A record with YoutubeID="foo" already exists in the database
video := models.Video{YoutubeID: "foo", Title: "abc"} 
if err = video.UpsertG(false, []string{"youtube_id"}, nil); err != nil {
	return nil, err
}

SQL query + parameters:

INSERT INTO "video" ("youtube_id", "title") VALUES ($1,$2) ON CONFLICT DO NOTHING RETURNING "id"
[foo abc]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions