Skip to content

goctl generated code issue with partial index on PostgreSQL model #3841

Description

@hoshi200

I have a table structure defined as follows:

CREATE TABLE "public"."Untitled" (
  "id" int8 NOT NULL,
  "user_id" int8 NOT NULL,
  "user_nickname" varchar(255) COLLATE "pg_catalog"."default" NOT NULL,
  "password" varchar(255) COLLATE "pg_catalog"."default" NOT NULL,
  "birth" varchar(255) COLLATE "pg_catalog"."default",
  "created_at" timestamp(6) NOT NULL,
  "updated_at" timestamp(6) NOT NULL,
  "mobile" varchar(255) COLLATE "pg_catalog"."default" NOT NULL,
  "deleted_at" timestamp(6),
  "metadata" json,
  PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "idx_user_id_deleted_at_null_copy1" ON "public"."Untitled" USING btree (
  "user_id" "pg_catalog"."int8_ops" DESC NULLS LAST
) WHERE deleted_at IS NULL;

The above is the structure of my table. Below is a part of the code that was generated using goctl:

func (m *defaultSysUserCopy1Model) FindOneByUserId(ctx context.Context, userId int64) (*SysUserCopy1, error) {
	publicSysUserCopy1UserIdKey := fmt.Sprintf("%s%v", cachePublicSysUserCopy1UserIdPrefix, userId)
	var resp SysUserCopy1
	err := m.QueryRowIndexCtx(ctx, &resp, publicSysUserCopy1UserIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
		query := fmt.Sprintf("select %s from %s where user_id = \$1 limit 1", sysUserCopy1Rows, m.table)
		if err := conn.QueryRowCtx(ctx, &resp, query, userId); err != nil {
			return nil, err
		}
		return resp.Id, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

The generated code seems to assume that user_id is a unique key. However, in reality, a single user_id may correspond to multiple records where deleted_at is not null. When a query is made for the first time, if it encounters incorrect data, it will cache that incorrect data, leading to consistently incorrect results.

Is it possible to modify the autogenerated code to include a condition to check if deleted_at is null?

The above English translations are from ChatGPT, and my English proficiency is not very good. Please understand

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