Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add MapColumns method #6901

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions chainable_api.go
Expand Up @@ -185,6 +185,13 @@ func (db *DB) Omit(columns ...string) (tx *DB) {
return
}

// MapColumns modify the column names in the query results to facilitate align to the corresponding structural fields
func (db *DB) MapColumns(m map[string]string) (tx *DB) {
tx = db.getInstance()
tx.Statement.ColumnMapping = m
return
}

// Where add conditions
//
// See the [docs] for details on the various formats that where clauses can take. By default, where clauses chain with AND.
Expand Down
9 changes: 9 additions & 0 deletions scan.go
Expand Up @@ -131,6 +131,15 @@ func Scan(rows Rows, db *DB, mode ScanMode) {
onConflictDonothing = mode&ScanOnConflictDoNothing != 0
)

if len(db.Statement.ColumnMapping) > 0 {
for i, column := range columns {
v, ok := db.Statement.ColumnMapping[column]
if ok {
columns[i] = v
}
}
}

db.RowsAffected = 0

switch dest := db.Statement.Dest.(type) {
Expand Down
5 changes: 3 additions & 2 deletions statement.go
Expand Up @@ -30,8 +30,9 @@ type Statement struct {
Clauses map[string]clause.Clause
BuildClauses []string
Distinct bool
Selects []string // selected columns
Omits []string // omit columns
Selects []string // selected columns
Omits []string // omit columns
ColumnMapping map[string]string // map columns
Joins []join
Preloads map[string][]interface{}
Settings sync.Map
Expand Down