Builds a cache key for the given SQL and context container. A key is only built if the given SQL/templates are cacheable, which means all template values must be stable. The second return value is a boolean indicating whether a cache key was built or not. If false, the input is not eligible for cac
(sql string, container *contextContainer)
| 286 | // indicating whether a cache key was built or not. If false, the input is not |
| 287 | // eligible for caching, and no check against the cache should be made. |
| 288 | func replacerCacheKeyFrom(sql string, container *contextContainer) (replacerCacheKey, bool) { |
| 289 | // Only eligible for caching if all replacements are stable. |
| 290 | for _, replacement := range container.Replacements { |
| 291 | if !replacement.Stable { |
| 292 | return replacerCacheKey{}, false |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | var ( |
| 297 | namedArgsBuilder strings.Builder |
| 298 | |
| 299 | // Named args must be sorted for key stability because Go maps don't |
| 300 | // provide any ordering guarantees. |
| 301 | sortedNamedArgs = maputil.Keys(container.NamedArgs) |
| 302 | ) |
| 303 | slices.Sort(sortedNamedArgs) |
| 304 | for _, namedArg := range sortedNamedArgs { |
| 305 | namedArgsBuilder.WriteRune('@') // useful as separator because not valid in the name of a named arg |
| 306 | namedArgsBuilder.WriteString(namedArg) |
| 307 | } |
| 308 | |
| 309 | var ( |
| 310 | replacementValuesBuilder strings.Builder |
| 311 | sortedReplacements = maputil.Keys(container.Replacements) |
| 312 | ) |
| 313 | slices.Sort(sortedReplacements) |
| 314 | for _, template := range sortedReplacements { |
| 315 | replacementValuesBuilder.WriteRune('•') // use a separator that SQL would reject under most circumstances (this may be imperfect) |
| 316 | replacementValuesBuilder.WriteString(container.Replacements[template].Value) |
| 317 | } |
| 318 | |
| 319 | return replacerCacheKey{ |
| 320 | namedArgs: namedArgsBuilder.String(), |
| 321 | replacementValues: replacementValuesBuilder.String(), |
| 322 | sql: sql, |
| 323 | }, true |
| 324 | } |