Has many preload in chunks to avoid mssql parameter limit
This commit is contained in:
parent
77fc126a0d
commit
ba791c8b56
@ -186,12 +186,36 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{})
|
||||
return
|
||||
}
|
||||
|
||||
uniquePrimaryKeysMap := map[interface{}]bool{}
|
||||
for _, key := range toQueryValues(primaryKeys) {
|
||||
uniquePrimaryKeysMap[indirect(reflect.ValueOf(key)).Interface()] = true
|
||||
}
|
||||
|
||||
uniquePrimaryKeys := make([]interface{}, 0, len(uniquePrimaryKeysMap))
|
||||
for key := range uniquePrimaryKeysMap {
|
||||
uniquePrimaryKeys = append(uniquePrimaryKeys, key)
|
||||
}
|
||||
|
||||
// preload conditions
|
||||
preloadDB, preloadConditions := scope.generatePreloadDBWithConditions(conditions)
|
||||
|
||||
indirectScopeValue := scope.IndirectValue()
|
||||
|
||||
// need to query relations in chunk of 2000
|
||||
// to avoid exceeding the mssql parameter limit of 2100
|
||||
chunkSize := 2000
|
||||
for i := 0; i < len(uniquePrimaryKeys); i += chunkSize {
|
||||
var primaryKeyChunk []interface{}
|
||||
if chunkSize > len(uniquePrimaryKeys)-i {
|
||||
primaryKeyChunk = uniquePrimaryKeys[i:]
|
||||
} else {
|
||||
primaryKeyChunk = uniquePrimaryKeys[i : i+chunkSize]
|
||||
}
|
||||
|
||||
// find relations
|
||||
query := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relation.ForeignDBNames), toQueryMarks(primaryKeys))
|
||||
values := toQueryValues(primaryKeys)
|
||||
queryMarks := "?" + strings.Repeat(",?", len(primaryKeyChunk)-1)
|
||||
query := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relation.ForeignDBNames), queryMarks)
|
||||
values := primaryKeyChunk
|
||||
if relation.PolymorphicType != "" {
|
||||
query += fmt.Sprintf(" AND %v = ?", scope.Quote(relation.PolymorphicDBName))
|
||||
values = append(values, relation.PolymorphicValue)
|
||||
@ -201,10 +225,7 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{})
|
||||
scope.Err(preloadDB.Where(query, values...).Find(results, preloadConditions...).Error)
|
||||
|
||||
// assign find results
|
||||
var (
|
||||
resultsValue = indirect(reflect.ValueOf(results))
|
||||
indirectScopeValue = scope.IndirectValue()
|
||||
)
|
||||
resultsValue := indirect(reflect.ValueOf(results))
|
||||
|
||||
if indirectScopeValue.Kind() == reflect.Slice {
|
||||
preloadMap := make(map[string][]reflect.Value)
|
||||
@ -227,6 +248,7 @@ func (scope *Scope) handleHasManyPreload(field *Field, conditions []interface{})
|
||||
} else {
|
||||
scope.Err(field.Set(resultsValue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleBelongsToPreload used to preload belongs to associations
|
||||
|
Loading…
x
Reference in New Issue
Block a user