GORM Playground Link

https://github.com/go-gorm/playground/pull/491

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

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]
}

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: a631807682

In the composite primary key case, the primary key is not only the sorting keyword, but also the starting condition of the next query. We cannot use prioritized primary key to implement batch query in this case. ~~Maybe we need to use subqueries for this case.~~

Comment From: fanlvG

oh I see. If in previous query we couldn't select all records with same primaryKey1, In next query we can't use less condition to select the rest records with primaryKey1 value. So maybe FindInBatches() use ORDER BY OFFSET LIMIT will be better? That can handle most batch query situation. I think.

Comment From: a631807682

@fanlvG If using offset directly will have performance issues with large data volumes, I will try to fix it later.

Comment From: tuhaolam

It seems that the bug has not been fixed, I reproduce this bug on latest version v1.25.8.