Use Sql builder - squirrel#1195
Open
michalkrzyz wants to merge 2 commits into
Open
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
Refactors most read-side MariaDB queries in internal/database/mariadb/* from fmt.Sprintf-templated SQL strings to the Masterminds/squirrel SQL builder. The shared Statement/BuildStatement machinery and DbObject/FilterProperty types are reshaped to operate on a sq.SelectBuilder, while two not-yet-migrated aggregation paths still rely on _tmp-suffixed copies of the old helpers.
Changes:
- Replace raw SQL templates and
EnsureFilter/getXColumnshelpers in 12 entity files withsq.Select(...).From(...).GroupBy(...)builders feeding a unifiedBuildStatement. - Rework
db_object.go: introduceAddJoins/AddFilter/AddCursor, renameFilterPropertyfields toBuildQuery/GetParam/BuildParams, drop theCheck*statement flags, and add*_tmpduplicates of the old join/filter/parameter helpers for the remaining aggregation queries. - Minor cleanups: switch a few
logrus.Warnfto scopedl.Warnf, passctxinstead ofcontext.Background()toperformListScan, and refactorgetXColumns(...)intoappendXColumns([]string, ...) []string.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| internal/database/mariadb/db_object.go | Core refactor: squirrel-based BuildStatement, new AddJoins/AddFilter/AddCursor, renamed FilterProperty fields, plus _tmp duplicates of legacy helpers. |
| internal/database/mariadb/user.go | Switch user queries to squirrel; comment out removed Check* flags. |
| internal/database/mariadb/support_group.go | Same migration for support group queries. |
| internal/database/mariadb/service.go | Migrate service queries; route GetServicesWithAggregations through *_tmp helpers. |
| internal/database/mariadb/service_issue_variant.go | Migrate to squirrel; embed multi-line JoinClause for issue-variant joins. |
| internal/database/mariadb/remediation.go | Migrate remediation queries; minor logger scoping fix. |
| internal/database/mariadb/patch.go | Migrate patch queries. |
| internal/database/mariadb/issue.go | Migrate issue queries; route GetIssuesWithAggregations through *_tmp helpers; rework getIssueColumns to appendIssueColumns. |
| internal/database/mariadb/issue_variant.go | Migrate issue-variant queries. |
| internal/database/mariadb/issue_repository.go | Migrate issue-repository queries. |
| internal/database/mariadb/issue_match.go | Migrate issue-match queries; refactor column helper. |
| internal/database/mariadb/component.go | Migrate component queries; refactor column helper. |
| internal/database/mariadb/component_version.go | Migrate component-version queries; refactor column helper. |
| internal/database/mariadb/component_instance.go | Migrate component-instance queries; adds GroupBy in getComponentInstanceAttr. |
Comments suppressed due to low confidence (3)
internal/database/mariadb/db_object.go:161
AddCursorcallsqb.Having(...)andqb.Where(...)but discards their return values. Squirrel'sSelectBuilderis immutable — these methods return a new builder, so the cursor predicate is never actually attached to the query. Only theLimitcall takes effect because it is in the return statement. This silently drops the cursorWHERE/HAVINGclause for every paginated query that usesBuildStatement. The assignments should beqb = qb.Having(...)andqb = qb.Where(...).
if aggregated {
qb.Having(cursorQuery, cursorParams...)
} else {
qb.Where(cursorQuery, cursorParams...)
}
return qb.Limit(uint64(limit))
internal/database/mariadb/db_object.go:161
uint64(limit)will wrap around to a very large value whenpagFirstis set to a negativeint(e.g.-1used elsewhere in tests/API callers as "no limit"). Consider clampinglimitto a non-negative value before the conversion, or treating non-positive values the same as thenildefault.
return qb.Limit(uint64(limit))
internal/database/mariadb/db_object.go:755
- A large set of
*_tmpduplicates (GetJoins_tmp,Build_tmp,GetFilterWhereClause_tmp,GetFilterQuery_tmp,GetFilterParameters_tmp) has been introduced solely so the not-yet-migratedGetServicesWithAggregations/GetIssuesWithAggregationspaths still compile. This duplicates a lot of non-trivial logic (theBuild_tmpbody is a copy ofBuild) and there is no tracked follow-up or ticket reference. At minimum, please add a// TODO(...)referencing a concrete issue, and consider keeping a single implementation (e.g. by extracting the shared body and re-using it from bothBuildandBuild_tmp) to avoid the two copies drifting apart.
// DEPRECATED: TODO: remove
func (do *DbObject[ET]) GetJoins_tmp(filter any, order *Order) string {
return NewJoinResolver(do.JoinDefs).Build_tmp(filter, order)
}
func (jr *JoinResolver) Build_tmp(filter any, order *Order) string {
for _, def := range jr.defs {
if def.Condition != nil && def.Condition(filter, order) {
jr.require(def.Name)
}
}
var result []string
// This is little tricky part, but we need to deal with that this way
// until we have stateful join pattern which is created for issue.go
// with non-uniq tablename 'IM IssueMatch' which join operation
// depends on filter pattern with precedence for some members (there
// is if...else if which cannot be replaced by if... and if... what
// is a mess and misconception
uniqTableName := make(map[string]struct{})
for _, name := range jr.order {
j, ok := lo.Find(jr.defs, func(jd *JoinDef) bool {
return jd.Name == name
})
if !ok {
panic("JoinResolver::Build(...) Unknown join: " + name)
}
if _, ok := uniqTableName[j.Table]; ok {
continue
}
uniqTableName[j.Table] = struct{}{}
joinSQL := fmt.Sprintf("%s %s ON %s",
j.Type,
j.Table,
j.On,
)
result = append(result, joinSQL)
}
return strings.Join(result, "\n")
}
func (do *DbObject[ET]) GetFilterWhereClause_tmp(filter any, withCursor bool) string {
if filterStr := do.GetFilterQuery_tmp(filter); filterStr != "" || withCursor {
return fmt.Sprintf("WHERE %s", filterStr)
}
return ""
}
func (do *DbObject[ET]) GetFilterQuery_tmp(filter any) string {
var fl []string
for _, v := range do.FilterProperties {
fl = append(fl, v.GetQuery(filter))
}
return combineFilterQueries(fl, OP_AND)
}
func (do *DbObject[ET]) GetFilterParameters_tmp(
filter entity.HasPagination,
withCursor bool,
cursorFields []Field,
) []any {
var filterParameters []any
for _, v := range do.FilterProperties {
filterParameters = append(filterParameters, v.BuildParams(filter)...)
}
if withCursor {
paginated := filter.GetPaginated()
filterParameters = append(
filterParameters,
GetCursorQueryParameters(paginated.First, cursorFields)...)
}
return filterParameters
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
db839ff to
71c1be5
Compare
71c1be5 to
bc86882
Compare
On-behalf-of: SAP Michal Krzyz <michal.krzyz@sap.com> Signed-off-by: Michal Krzyz <michalkrzyz@gmail.com>
08ca009 to
80fd2f0
Compare
80fd2f0 to
fbf9e2e
Compare
On-behalf-of: SAP Michal Krzyz <michal.krzyz@sap.com> Signed-off-by: Michal Krzyz <michalkrzyz@gmail.com>
fbf9e2e to
72dd3ec
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
On-behalf-of: SAP Michal Krzyz michal.krzyz@sap.com
Description
Use squirrel for most querries.
Please include a summary of the changes and the related issue. Please also include relevant motivation and context. List any dependencies that are required for this change.
What type of PR is this? (check all applicable)
Related Tickets & Documents
Added tests?
Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
Added to documentation?
Checklist