Skip to content

FindInBatches fail when using composite primary key #7636

@mvysotsky

Description

@mvysotsky

GORM Playground Link

go-gorm/playground#491

FindInBatches reports "primary key required" due to this bug.

This ticket is based on a reported issue by @fanlvG from Jul 8, 2022 (#5495). This issue still exists on the latest version of GORM (tested on v1.31.0).

FindInBatches works depends on sorting primaryKey. when model has more primaryKeys, FindInBatches should use first primaryKeys as sort condition. reference: https://gorm.io/docs/write_plugins.html

while in schema/schema.go:217. set PrioritizedPrimaryField has bug.

if schema.PrioritizedPrimaryField == nil && len(schema.PrimaryFields) == 1 {
	schema.PrioritizedPrimaryField = schema.PrimaryFields[0]
}

in gorm.io docs. PrioritizedPrimaryField described as:

// Prioritized primary key field: field with DB name id or the first defined primary key

in "Write Plugins" chapter.

please check this out.

correct code should be like:

if schema.PrioritizedPrimaryField == nil && len(schema.PrimaryFields) >= 1 {
	schema.PrioritizedPrimaryField = schema.PrimaryFields[0]
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions