Skip to content

Commit

Permalink
Support specify select/omit columns with table
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Oct 8, 2021
1 parent d4c838c commit 6312d86
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"database/sql/driver"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -627,6 +628,8 @@ func (stmt *Statement) Changed(fields ...string) bool {
return false
}

var nameMatcher = regexp.MustCompile(`\.[\W]?(.+?)[\W]?$`)

// SelectAndOmitColumns get select and omit columns, select -> true, omit -> false
func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (map[string]bool, bool) {
results := map[string]bool{}
Expand All @@ -647,6 +650,8 @@ func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (
}
} else if field := stmt.Schema.LookUpField(column); field != nil && field.DBName != "" {
results[field.DBName] = true
} else if matches := nameMatcher.FindStringSubmatch(column); len(matches) == 2 {
results[matches[1]] = true
} else {
results[column] = true
}
Expand All @@ -662,6 +667,8 @@ func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (
}
} else if field := stmt.Schema.LookUpField(omit); field != nil && field.DBName != "" {
results[field.DBName] = false
} else if matches := nameMatcher.FindStringSubmatch(omit); len(matches) == 2 {
results[matches[1]] = false
} else {
results[omit] = false
}
Expand Down
13 changes: 13 additions & 0 deletions statement_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,16 @@ func TestWhereCloneCorruption(t *testing.T) {
})
}
}

func TestNameMatcher(t *testing.T) {
for k, v := range map[string]string{
"table.name": "name",
"`table`.`name`": "name",
"'table'.'name'": "name",
"'table'.name": "name",
} {
if matches := nameMatcher.FindStringSubmatch(k); len(matches) < 2 || matches[1] != v {
t.Errorf("failed to match value: %v, got %v, expect: %v", k, matches, v)
}
}
}

0 comments on commit 6312d86

Please sign in to comment.