Compare commits
29 Commits
104f8b5459
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 176fadbceb | |||
| 86f4550b08 | |||
| f50aaca44d | |||
| f7cf63c2bf | |||
| 30714bb3da | |||
| 8a81173fc8 | |||
| 43824af97c | |||
| 326866dc49 | |||
| 450345ba6b | |||
| bdc978aec1 | |||
| 3dc8d0d79f | |||
| 4615d55309 | |||
| c2bcbea5d2 | |||
| ff51420b71 | |||
| 9958e9103b | |||
| bd510d958b | |||
| 295e915f89 | |||
| 642ac4fba7 | |||
| 39757cde34 | |||
| c371cbf042 | |||
| 0fda3f6ef6 | |||
| 13fe2222dd | |||
| 9db7265733 | |||
| b427747745 | |||
| 81d51c0bb5 | |||
| 6e31c8eb98 | |||
| 35082b1f6a | |||
| b67bc14e5e | |||
| 14bc29d7e3 |
172
app/main.go
172
app/main.go
@ -10,6 +10,7 @@ import (
|
|||||||
"repo-pattern/app/repository/smartfilter"
|
"repo-pattern/app/repository/smartfilter"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -18,6 +19,34 @@ var (
|
|||||||
FALSE = false
|
FALSE = false
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type CertFilter struct {
|
||||||
|
Alive *bool `filterfield:"field=alive;operator=EQ"`
|
||||||
|
SerialNumber *string `filterfield:"field=serial_number;operator=NE"`
|
||||||
|
SerialNumberContains *string `filterfield:"field=serial_number;operator=LIKE"`
|
||||||
|
IssuerContains *string `filterfield:"field=issuer;operator=ILIKE"`
|
||||||
|
Id *uuid.UUID `filterfield:"field=id;operator=EQ"`
|
||||||
|
Ids *[]uuid.UUID `filterfield:"field=id;operator=IN"`
|
||||||
|
IdsNot *[]string `filterfield:"field=id;operator=NOT_IN"`
|
||||||
|
CreatedAt_Lt *time.Time `filterfield:"field=created_at;operator=LT"`
|
||||||
|
Timestamps *[]time.Time `filterfield:"field=created_at;operator=IN"`
|
||||||
|
CompanyIsActive *bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f CertFilter) ApplyQuery(query *gorm.DB) *gorm.DB {
|
||||||
|
if f.CompanyIsActive != nil {
|
||||||
|
query = query.Joins(
|
||||||
|
fmt.Sprintf(
|
||||||
|
"JOIN companies ON certificates.company_id = companies.id WHERE companies.is_active = %t",
|
||||||
|
*f.CompanyIsActive,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompanyFilter struct {
|
||||||
|
IsActive *bool `filterfield:"field=is_active;operator=EQ"`
|
||||||
|
}
|
||||||
|
|
||||||
func doMagic(db *gorm.DB) {
|
func doMagic(db *gorm.DB) {
|
||||||
var err error
|
var err error
|
||||||
query := db
|
query := db
|
||||||
@ -29,16 +58,23 @@ func doMagic(db *gorm.DB) {
|
|||||||
location, _ := time.LoadLocation("UTC")
|
location, _ := time.LoadLocation("UTC")
|
||||||
createdTime := time.Date(2024, 5, 26, 16, 8, 0, 0, location)
|
createdTime := time.Date(2024, 5, 26, 16, 8, 0, 0, location)
|
||||||
|
|
||||||
f := smartfilter.SmartCertFilter[models.Cert]{
|
id1, _ := uuid.Parse("eb2bcac6-5173-4dbb-93b7-e7c03b924a03")
|
||||||
|
id2, _ := uuid.Parse("db9fb837-3483-4736-819d-f427dc8cda23")
|
||||||
|
id3, _ := uuid.Parse("1fece5e7-8e8d-4828-8298-3b1f07fd29ff")
|
||||||
|
|
||||||
|
ids := []uuid.UUID{id1, id2, id3}
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
// Alive: &FALSE,
|
// Alive: &FALSE,
|
||||||
// Id: &id,
|
// Id: &id,
|
||||||
// SerialNumber: &serialNumber,
|
// SerialNumber: &serialNumber,
|
||||||
// SerialNumberContains: &serialNumberContains,
|
// SerialNumberContains: &serialNumberContains,
|
||||||
|
Ids: &ids,
|
||||||
// IssuerContains: &issuer,
|
// IssuerContains: &issuer,
|
||||||
CreatedAt_Lt: &createdTime,
|
CreatedAt_Lt: &createdTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
query, err = f.ToQuery(query)
|
query, err = smartfilter.ToQuery(models.Cert{}, filter, query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
@ -51,15 +87,139 @@ func doMagic(db *gorm.DB) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func doList(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
|
Alive: &TRUE,
|
||||||
|
}
|
||||||
|
|
||||||
|
certs, err := repo.List(filter, nil)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for n, cert := range *certs {
|
||||||
|
fmt.Printf(">> [%d] %+v %s (alive %t)\n", n, cert.Id, cert.CreatedAt, cert.Alive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func doListWithJoins(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
|
CompanyIsActive: &FALSE,
|
||||||
|
}
|
||||||
|
|
||||||
|
certs, err := repo.List(filter, nil)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for n, cert := range *certs {
|
||||||
|
fmt.Printf(">> [%d] %+v %s (alive %t)\n", n, cert.Id, cert.CreatedAt, cert.Alive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func doCount(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
|
Alive: &TRUE,
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err := repo.Count(filter)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf(">>> count: %d\n", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func doGet(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id, _ := uuid.Parse("db9fb837-3483-4736-819d-f427dc8cda23")
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
cert, err := repo.Get(filter, nil)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf(">> %+v %s (alive %t)\n", cert.Id, cert.CreatedAt, cert.Alive)
|
||||||
|
}
|
||||||
|
|
||||||
|
func doSave(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Company]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
company := models.Company{
|
||||||
|
Name: "Test company",
|
||||||
|
Address: "Some address",
|
||||||
|
City: "Some city",
|
||||||
|
Email: "email@example.org",
|
||||||
|
Oib: "123456",
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := repo.Save(&company)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("New company id: %s\n", company.Id.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func doDelete(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Company]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := CompanyFilter{
|
||||||
|
IsActive: &FALSE,
|
||||||
|
}
|
||||||
|
|
||||||
|
deletedCount, err := repo.Delete(filter)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf(">> DELETED: %d\n", deletedCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
func doExists(db *gorm.DB) {
|
||||||
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id, _ := uuid.Parse("db9fb837-3483-4736-819d-f427dc8cda23")
|
||||||
|
|
||||||
|
filter := CertFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
exists, err := repo.Exists(filter)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf(">> EXISTS: %t\n", exists)
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
cfg.Init()
|
cfg.Init()
|
||||||
logging.Init()
|
logging.Init()
|
||||||
defer logging.Log.Sync()
|
defer logging.Log.Sync()
|
||||||
|
|
||||||
db := db.InitDB()
|
db := db.InitDB()
|
||||||
repository.Dao = repository.CreateDAO(db)
|
|
||||||
|
|
||||||
doMagic(db)
|
// doMagic(db)
|
||||||
|
// doList(db)
|
||||||
fmt.Println("Running...")
|
doListWithJoins(db)
|
||||||
|
// doCount(db)
|
||||||
|
// doSave(db)
|
||||||
|
// doDelete(db)
|
||||||
|
// doGet(db)
|
||||||
|
// doExists(db)
|
||||||
|
// inheritance.DoInheritanceTest()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,23 +0,0 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ApiKey struct {
|
|
||||||
Key uuid.UUID `gorm:"type(uuid);unique;default:uuid_generate_v4()"`
|
|
||||||
CompanyId uuid.UUID `gorm:"type(uuid)" faker:"-"`
|
|
||||||
ActiveFrom *time.Time `faker:"-"`
|
|
||||||
ActiveTo *time.Time `faker:"-"`
|
|
||||||
LastUsed *time.Time
|
|
||||||
CreatedAt time.Time `faker:"-"`
|
|
||||||
UpdatedAt time.Time `faker:"-"`
|
|
||||||
|
|
||||||
Company Company `faker:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ApiKey) TableName() string {
|
|
||||||
return "api_keys"
|
|
||||||
}
|
|
||||||
@ -21,7 +21,7 @@ type Company struct {
|
|||||||
UpdatedAt time.Time `faker:"-"`
|
UpdatedAt time.Time `faker:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Company) TableName() string {
|
func (m Company) TableName() string {
|
||||||
return "companies"
|
return "companies"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,27 +0,0 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/datatypes"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FiskLogItem struct {
|
|
||||||
Id uuid.UUID `gorm:"type(uuid);unique"`
|
|
||||||
ApiKeyId uuid.UUID `gorm:"type(uuid)"`
|
|
||||||
CompanyId uuid.UUID `gorm:"type(uuid)"`
|
|
||||||
IsDemo bool
|
|
||||||
RequestData datatypes.JSONMap `gorm:"type:jsonb;not null"`
|
|
||||||
ResponseData *datatypes.JSONMap `gorm:"type:jsonb"`
|
|
||||||
IznosUkupno int
|
|
||||||
Zki *string
|
|
||||||
Jir *uuid.UUID `gorm:"type(uuid)"`
|
|
||||||
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *FiskLogItem) TableName() string {
|
|
||||||
return "fisk_log"
|
|
||||||
}
|
|
||||||
@ -1,89 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"repo-pattern/app/lib/helpers"
|
|
||||||
"repo-pattern/app/models"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ApiKeysRepository struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
type ApiKeysFilter struct {
|
|
||||||
Key *uuid.UUID
|
|
||||||
CompanyId *uuid.UUID
|
|
||||||
IsActive *bool
|
|
||||||
CompanyIsActive *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateApiKeysRepository(db *gorm.DB) *ApiKeysRepository {
|
|
||||||
return &ApiKeysRepository{db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyApiKeyFilter(db *gorm.DB, query *gorm.DB, filter *ApiKeysFilter) *gorm.DB {
|
|
||||||
if filter.Key != nil {
|
|
||||||
query.Where("key = ?", *filter.Key)
|
|
||||||
}
|
|
||||||
if filter.IsActive != nil {
|
|
||||||
now := helpers.UTCNow()
|
|
||||||
if *filter.IsActive {
|
|
||||||
query.Where("active_from IS NULL OR active_from <= ?", now)
|
|
||||||
query.Where("active_to IS NULL OR active_to >= ?", now)
|
|
||||||
} else {
|
|
||||||
query.Where(
|
|
||||||
"active_from IS NOT NULL AND active_from >= ?", now,
|
|
||||||
).Or(
|
|
||||||
"active_to IS NOT NULL AND active_to =< ?", now,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if filter.CompanyId != nil {
|
|
||||||
query.Where("company_id = ?", *filter.CompanyId)
|
|
||||||
}
|
|
||||||
if filter.CompanyIsActive != nil {
|
|
||||||
query.Joins("Company").Where(
|
|
||||||
map[string]interface{}{"Company.is_active": *filter.CompanyIsActive},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return query
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ApiKeysRepository) New(companyId uuid.UUID) *models.ApiKey {
|
|
||||||
now := helpers.UTCNow()
|
|
||||||
return &models.ApiKey{
|
|
||||||
CompanyId: companyId,
|
|
||||||
ActiveFrom: &now,
|
|
||||||
CreatedAt: now,
|
|
||||||
UpdatedAt: now,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ApiKeysRepository) Get(filter *ApiKeysFilter) *models.ApiKey {
|
|
||||||
var api_key models.ApiKey
|
|
||||||
|
|
||||||
query := r.db.Model(&models.ApiKey{})
|
|
||||||
applyApiKeyFilter(r.db, query, filter)
|
|
||||||
|
|
||||||
result := query.First(&api_key).Joins("Company")
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &api_key
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ApiKeysRepository) Save(model *models.ApiKey) {
|
|
||||||
model.UpdatedAt = helpers.UTCNow()
|
|
||||||
|
|
||||||
// we don't have standard model Id, but Key as primary key.
|
|
||||||
// this could be possible reason for save not assigning generated key uuid
|
|
||||||
// to model.Key. but this works.
|
|
||||||
if model.Key == uuid.Nil {
|
|
||||||
r.db.Create(model)
|
|
||||||
} else {
|
|
||||||
r.db.Save(model)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,101 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"repo-pattern/app/lib/helpers"
|
|
||||||
"repo-pattern/app/models"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CertRepository struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
type CertFilter struct {
|
|
||||||
Alive *bool
|
|
||||||
Id *uuid.UUID
|
|
||||||
CompanyId *uuid.UUID
|
|
||||||
CompanyIsActive *bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateCertRepository(db *gorm.DB) *CertRepository {
|
|
||||||
return &CertRepository{db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyCertFilter(db *gorm.DB, query *gorm.DB, filter *CertFilter) *gorm.DB {
|
|
||||||
if filter.Id != nil {
|
|
||||||
query.Where("certificates.id = ?", *filter.Id)
|
|
||||||
}
|
|
||||||
if filter.Alive == nil {
|
|
||||||
query.Where("certificates.alive = TRUE")
|
|
||||||
} else {
|
|
||||||
query.Where("certificates.alive = ?", *filter.Alive)
|
|
||||||
}
|
|
||||||
if filter.CompanyId != nil {
|
|
||||||
query.Where("certificates.company_id = ?", *filter.CompanyId)
|
|
||||||
}
|
|
||||||
if filter.CompanyIsActive != nil {
|
|
||||||
query.Joins("LEFT JOIN companies on companies.is_active = TRUE")
|
|
||||||
// query.Joins("Company").Where(
|
|
||||||
// map[string]interface{}{"Company.is_active": *filter.CompanyIsActive},
|
|
||||||
// )
|
|
||||||
}
|
|
||||||
return query
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) New(companyId uuid.UUID) *models.Cert {
|
|
||||||
now := helpers.UTCNow()
|
|
||||||
return &models.Cert{
|
|
||||||
Alive: true,
|
|
||||||
CompanyId: companyId,
|
|
||||||
CreatedAt: now,
|
|
||||||
UpdatedAt: now,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) Get(filter *CertFilter) *models.Cert {
|
|
||||||
var cert models.Cert
|
|
||||||
|
|
||||||
query := r.db.Model(&models.Cert{})
|
|
||||||
applyCertFilter(r.db, query, filter)
|
|
||||||
|
|
||||||
result := query.First(&cert).Joins("Company")
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &cert
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) GetForCompany(companyId uuid.UUID) *models.Cert {
|
|
||||||
isAlive := true
|
|
||||||
filter := CertFilter{
|
|
||||||
Alive: &isAlive,
|
|
||||||
CompanyId: &companyId,
|
|
||||||
}
|
|
||||||
return r.Get(&filter)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) Save(model *models.Cert) {
|
|
||||||
model.UpdatedAt = helpers.UTCNow()
|
|
||||||
r.db.Save(model)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) Exists(filter *CertFilter) bool {
|
|
||||||
var row models.Cert
|
|
||||||
|
|
||||||
query := r.db.Model(&models.Cert{})
|
|
||||||
query = applyCertFilter(r.db, query, filter)
|
|
||||||
result := query.Select("certificates.id").First(&row)
|
|
||||||
|
|
||||||
return !errors.Is(result.Error, gorm.ErrRecordNotFound) && result.Error == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CertRepository) Delete(filter *CertFilter) {
|
|
||||||
query := r.db.Model(&models.Cert{})
|
|
||||||
applyCertFilter(r.db, query, filter)
|
|
||||||
|
|
||||||
query.Update("alive", false).Joins("Company")
|
|
||||||
}
|
|
||||||
@ -1,57 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"repo-pattern/app/lib/helpers"
|
|
||||||
"repo-pattern/app/models"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type CompanyRepository struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompanyFilter struct {
|
|
||||||
Id *uuid.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateCompanyRepository(db *gorm.DB) *CompanyRepository {
|
|
||||||
return &CompanyRepository{db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyCompanyFilter(db *gorm.DB, query *gorm.DB, filter *CompanyFilter) *gorm.DB {
|
|
||||||
if filter.Id != nil {
|
|
||||||
query.Where("id = ?", *filter.Id)
|
|
||||||
}
|
|
||||||
query.Where("is_active = ?", true)
|
|
||||||
return query
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CompanyRepository) New() *models.Company {
|
|
||||||
now := helpers.UTCNow()
|
|
||||||
return &models.Company{
|
|
||||||
IsActive: true,
|
|
||||||
CreatedAt: now,
|
|
||||||
UpdatedAt: now,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CompanyRepository) Get(filter *CompanyFilter) *models.Company {
|
|
||||||
var company models.Company
|
|
||||||
|
|
||||||
query := r.db.Model(&models.Company{})
|
|
||||||
applyCompanyFilter(r.db, query, filter)
|
|
||||||
|
|
||||||
result := query.First(&company)
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &company
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *CompanyRepository) Save(model *models.Company) {
|
|
||||||
model.UpdatedAt = helpers.UTCNow()
|
|
||||||
r.db.Save(model)
|
|
||||||
}
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import "gorm.io/gorm"
|
|
||||||
|
|
||||||
type DAO struct {
|
|
||||||
db *gorm.DB
|
|
||||||
ApiKeysRepository *ApiKeysRepository
|
|
||||||
CertRepository *CertRepository
|
|
||||||
CompanyRepository *CompanyRepository
|
|
||||||
FiskLogRepository *FiskLogRepository
|
|
||||||
}
|
|
||||||
|
|
||||||
var Dao DAO
|
|
||||||
|
|
||||||
func CreateDAO(db *gorm.DB) DAO {
|
|
||||||
return DAO{
|
|
||||||
db: db,
|
|
||||||
ApiKeysRepository: CreateApiKeysRepository(db),
|
|
||||||
CertRepository: CreateCertRepository(db),
|
|
||||||
CompanyRepository: CreateCompanyRepository(db),
|
|
||||||
FiskLogRepository: CreateFiskLogRepository(db),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"repo-pattern/app/lib/helpers"
|
|
||||||
"repo-pattern/app/models"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FiskLogRepository struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateFiskLogRepository(db *gorm.DB) *FiskLogRepository {
|
|
||||||
return &FiskLogRepository{db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *FiskLogRepository) New(model models.FiskLogItem) *models.FiskLogItem {
|
|
||||||
now := helpers.UTCNow()
|
|
||||||
model.CreatedAt = now
|
|
||||||
model.UpdatedAt = now
|
|
||||||
return &model
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *FiskLogRepository) Save(model *models.FiskLogItem) error {
|
|
||||||
model.UpdatedAt = helpers.UTCNow()
|
|
||||||
result := r.db.Save(model)
|
|
||||||
return result.Error
|
|
||||||
}
|
|
||||||
32
app/repository/method_count.go
Normal file
32
app/repository/method_count.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CountMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *CountMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m CountMethod[T]) Count(filter interface{}) (int64, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
count int64
|
||||||
|
)
|
||||||
|
|
||||||
|
query := m.repo.dbConn.Model(model)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, query)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
query.Count(&count)
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
60
app/repository/method_count_test.go
Normal file
60
app/repository/method_count_test.go
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCountMethod(t *testing.T) {
|
||||||
|
t.Run("Count without filter", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
|
||||||
|
sql := "SELECT count(*) FROM my_models"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql)))
|
||||||
|
|
||||||
|
result, err := repo.Count(filter)
|
||||||
|
assert.Equal(t, result, int64(0))
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Count with filter", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id1 := uuid.New()
|
||||||
|
id2 := uuid.New()
|
||||||
|
id3 := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Ids: &[]uuid.UUID{id1, id2, id3},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT count(*) FROM my_models WHERE my_models.id IN ($1,$2,$3)"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id1, id2, id3)
|
||||||
|
|
||||||
|
result, err := repo.Count(filter)
|
||||||
|
assert.Equal(t, result, int64(0))
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
31
app/repository/method_delete.go
Normal file
31
app/repository/method_delete.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DeleteMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *DeleteMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m DeleteMethod[T]) Delete(filter interface{}) (int64, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, m.repo.dbConn)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
result := query.Delete(&model)
|
||||||
|
if result.Error != nil {
|
||||||
|
return 0, result.Error
|
||||||
|
}
|
||||||
|
return result.RowsAffected, nil
|
||||||
|
}
|
||||||
73
app/repository/method_delete_test.go
Normal file
73
app/repository/method_delete_test.go
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeleteMethod(t *testing.T) {
|
||||||
|
t.Run("With filter", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "DELETE FROM my_models WHERE my_models.id = $1"
|
||||||
|
mock.ExpectBegin()
|
||||||
|
mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id).
|
||||||
|
WillReturnResult(sqlmock.NewResult(1, 111))
|
||||||
|
mock.ExpectCommit()
|
||||||
|
|
||||||
|
deleted, err := repo.Delete(filter)
|
||||||
|
assert.Equal(t, int64(111), deleted)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With multiple filters", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id1 := uuid.New()
|
||||||
|
id2 := uuid.New()
|
||||||
|
id3 := uuid.New()
|
||||||
|
cnt := 3456
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Ids: &[]uuid.UUID{id1, id2, id3},
|
||||||
|
CntGT: &cnt,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "DELETE FROM my_models WHERE my_models.id IN ($1,$2,$3) AND my_models.cnt > $4"
|
||||||
|
mock.ExpectBegin()
|
||||||
|
mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id1, id2, id3, cnt).
|
||||||
|
WillReturnResult(sqlmock.NewResult(1, 123))
|
||||||
|
mock.ExpectCommit()
|
||||||
|
|
||||||
|
deleted, err := repo.Delete(filter)
|
||||||
|
assert.Equal(t, int64(123), deleted)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
35
app/repository/method_exists.go
Normal file
35
app/repository/method_exists.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ExistsMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *ExistsMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m ExistsMethod[T]) Exists(filter interface{}) (bool, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
)
|
||||||
|
|
||||||
|
query := m.repo.dbConn.Model(model)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, query)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := query.Select(m.repo.IdField).Take(&model)
|
||||||
|
|
||||||
|
exists := !errors.Is(result.Error, gorm.ErrRecordNotFound) && result.Error == nil
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
60
app/repository/method_exists_test.go
Normal file
60
app/repository/method_exists_test.go
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExistsMethod(t *testing.T) {
|
||||||
|
t.Run("Without repo options", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT id FROM my_models WHERE my_models.id = $1 LIMIT $2"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).WithArgs(id, 1)
|
||||||
|
|
||||||
|
result, err := repo.Exists(filter)
|
||||||
|
assert.False(t, result)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With id field set in repo options", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, &RepoOptions{IdField: "some_other_pk"})
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT some_other_pk FROM my_models WHERE my_models.id = $1 LIMIT $2"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).WithArgs(id, 1)
|
||||||
|
|
||||||
|
result, err := repo.Exists(filter)
|
||||||
|
assert.False(t, result)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
45
app/repository/method_get.go
Normal file
45
app/repository/method_get.go
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetOptions struct {
|
||||||
|
Only *[]string
|
||||||
|
RaiseError *bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *GetMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m GetMethod[T]) Get(filter interface{}, options *GetOptions) (*T, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, m.repo.dbConn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if options != nil {
|
||||||
|
query = applyOptionOnly(query, options.Only)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := query.First(&model)
|
||||||
|
if result.Error == nil {
|
||||||
|
return &model, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if options != nil && options.RaiseError != nil && *options.RaiseError {
|
||||||
|
return nil, result.Error
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
67
app/repository/method_get_test.go
Normal file
67
app/repository/method_get_test.go
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetMethod(t *testing.T) {
|
||||||
|
t.Run("With id filter, suppress errors", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
options := GetOptions{}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models WHERE my_models.id = $1 ORDER BY my_models.id LIMIT $2"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).WithArgs(id, 1)
|
||||||
|
|
||||||
|
result, err := repo.Get(filter, &options)
|
||||||
|
assert.Nil(t, result)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With id filter, raise error", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
raiseError := true
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
options := GetOptions{
|
||||||
|
RaiseError: &raiseError,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models WHERE my_models.id = $1 ORDER BY my_models.id LIMIT $2"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id, 1).
|
||||||
|
WillReturnError(nil)
|
||||||
|
|
||||||
|
result, err := repo.Get(filter, &options)
|
||||||
|
assert.Nil(t, result)
|
||||||
|
assert.NotNil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
42
app/repository/method_list.go
Normal file
42
app/repository/method_list.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ListOptions struct {
|
||||||
|
Only *[]string
|
||||||
|
Ordering *[]Order
|
||||||
|
Pagination *Pagination
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *ListMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m ListMethod[T]) List(filter interface{}, options *ListOptions) (*[]T, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
models []T
|
||||||
|
)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, m.repo.dbConn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if options != nil {
|
||||||
|
query = applyOptionOnly(query, options.Only)
|
||||||
|
query = applyOptionOrdering(query, options.Ordering)
|
||||||
|
query = applyOptionPagination(query, options.Pagination)
|
||||||
|
}
|
||||||
|
|
||||||
|
query.Find(&models)
|
||||||
|
return &models, nil
|
||||||
|
}
|
||||||
275
app/repository/method_list_test.go
Normal file
275
app/repository/method_list_test.go
Normal file
@ -0,0 +1,275 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewMockDB() (*sql.DB, *gorm.DB, sqlmock.Sqlmock) {
|
||||||
|
sqldb, mock, err := sqlmock.New()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("An error '%s' was not expected when opening a stub database connection", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gormdb, err := gorm.Open(postgres.New(postgres.Config{
|
||||||
|
WithoutQuotingCheck: true,
|
||||||
|
Conn: sqldb,
|
||||||
|
}), &gorm.Config{})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("An error '%s' was not expected when opening gorm database", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return sqldb, gormdb, mock
|
||||||
|
}
|
||||||
|
|
||||||
|
type MyModel struct {
|
||||||
|
Id *uuid.UUID `gorm:"type(uuid);unique"`
|
||||||
|
Value string
|
||||||
|
Cnt int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m MyModel) TableName() string {
|
||||||
|
return "my_models"
|
||||||
|
}
|
||||||
|
|
||||||
|
type MyModelFilter struct {
|
||||||
|
Id *uuid.UUID `filterfield:"field=id;operator=EQ"`
|
||||||
|
Ids *[]uuid.UUID `filterfield:"field=id;operator=IN"`
|
||||||
|
Value *string `filterfield:"field=value;operator=EQ"`
|
||||||
|
CntGT *int `filterfield:"field=cnt;operator=GT"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListMethod(t *testing.T) {
|
||||||
|
t.Run("With ordering", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
options := ListOptions{
|
||||||
|
Ordering: &[]Order{
|
||||||
|
{
|
||||||
|
Field: "id",
|
||||||
|
Direction: OrderASC,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Field: "cnt",
|
||||||
|
Direction: OrderDESC,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models ORDER BY id,cnt DESC"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql)))
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With limit", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
options := ListOptions{
|
||||||
|
Pagination: &Pagination{
|
||||||
|
Limit: 111,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models LIMIT $1"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(options.Pagination.Limit)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With offset", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
options := ListOptions{
|
||||||
|
Pagination: &Pagination{
|
||||||
|
Offset: 222,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models OFFSET $1"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(options.Pagination.Offset)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("With limit and offset", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
options := ListOptions{
|
||||||
|
Pagination: &Pagination{
|
||||||
|
Limit: 111,
|
||||||
|
Offset: 222,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models LIMIT $1 OFFSET $2"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(options.Pagination.Limit, options.Pagination.Offset)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Simple filter", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models WHERE my_models.id = $1"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, nil)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Multiple filter values", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
count := 456
|
||||||
|
value := "some value"
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
Value: &value,
|
||||||
|
CntGT: &count,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models WHERE my_models.id = $1 AND my_models.value = $2 AND my_models.cnt > $3"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id, value, count)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, nil)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Multiple filter values and pagination", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
count := 456
|
||||||
|
value := "some value"
|
||||||
|
filter := MyModelFilter{
|
||||||
|
Id: &id,
|
||||||
|
Value: &value,
|
||||||
|
CntGT: &count,
|
||||||
|
}
|
||||||
|
options := ListOptions{
|
||||||
|
Pagination: &Pagination{
|
||||||
|
Offset: 111,
|
||||||
|
Limit: 222,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT * FROM my_models WHERE my_models.id = $1 AND my_models.value = $2 AND my_models.cnt > $3 LIMIT $4 OFFSET $5"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(id, value, count, options.Pagination.Limit, options.Pagination.Offset)
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Only id and count", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
filter := MyModelFilter{}
|
||||||
|
options := ListOptions{
|
||||||
|
Only: &[]string{
|
||||||
|
"id",
|
||||||
|
"cnt",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "SELECT id,cnt FROM my_models"
|
||||||
|
mock.ExpectQuery(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql)))
|
||||||
|
|
||||||
|
_, err := repo.List(filter, &options)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
18
app/repository/method_save.go
Normal file
18
app/repository/method_save.go
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SaveMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *SaveMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m SaveMethod[T]) Save(model *T) (*T, error) {
|
||||||
|
result := m.repo.dbConn.Save(model)
|
||||||
|
return model, result.Error
|
||||||
|
}
|
||||||
69
app/repository/method_save_test.go
Normal file
69
app/repository/method_save_test.go
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSaveMethod(t *testing.T) {
|
||||||
|
t.Run("Save new model", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
model := MyModel{
|
||||||
|
Value: "some value",
|
||||||
|
Cnt: 123,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "INSERT INTO my_models (id,value,cnt) VALUES ($1,$2,$3)"
|
||||||
|
mock.ExpectBegin()
|
||||||
|
mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(model.Id, model.Value, model.Cnt).
|
||||||
|
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||||
|
mock.ExpectCommit()
|
||||||
|
|
||||||
|
_, err := repo.Save(&model)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Update existing model", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
id := uuid.New()
|
||||||
|
model := MyModel{
|
||||||
|
Id: &id,
|
||||||
|
Value: "some value",
|
||||||
|
Cnt: 123,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "UPDATE my_models SET value=$1,cnt=$2 WHERE id = $3"
|
||||||
|
mock.ExpectBegin()
|
||||||
|
mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(model.Value, model.Cnt, model.Id).
|
||||||
|
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||||
|
mock.ExpectCommit()
|
||||||
|
|
||||||
|
_, err := repo.Save(&model)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
31
app/repository/method_update.go
Normal file
31
app/repository/method_update.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"repo-pattern/app/repository/smartfilter"
|
||||||
|
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UpdateMethod[T schema.Tabler] struct {
|
||||||
|
repo *RepoBase[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *UpdateMethod[T]) Init(repo *RepoBase[T]) {
|
||||||
|
m.repo = repo
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m UpdateMethod[T]) Update(filter interface{}, values map[string]any) (int64, error) {
|
||||||
|
var (
|
||||||
|
model T
|
||||||
|
)
|
||||||
|
|
||||||
|
query, err := smartfilter.ToQuery(model, filter, m.repo.dbConn)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
result := query.Model(&model).Updates(values)
|
||||||
|
if result.Error != nil {
|
||||||
|
return 0, result.Error
|
||||||
|
}
|
||||||
|
return result.RowsAffected, nil
|
||||||
|
}
|
||||||
43
app/repository/method_update_test.go
Normal file
43
app/repository/method_update_test.go
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpdateMethod(t *testing.T) {
|
||||||
|
t.Run("Update", func(t *testing.T) {
|
||||||
|
sqldb, db, mock := NewMockDB()
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
repo := RepoBase[MyModel]{}
|
||||||
|
repo.Init(db, nil)
|
||||||
|
|
||||||
|
cnt := 10
|
||||||
|
filter := MyModelFilter{
|
||||||
|
CntGT: &cnt,
|
||||||
|
}
|
||||||
|
values := map[string]any{
|
||||||
|
"cnt": 111,
|
||||||
|
"value": 222,
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := "UPDATE my_models SET cnt=$1,value=$2 WHERE my_models.cnt > $3"
|
||||||
|
mock.ExpectBegin()
|
||||||
|
mock.ExpectExec(fmt.Sprintf("^%s$", regexp.QuoteMeta(sql))).
|
||||||
|
WithArgs(values["cnt"], values["value"], cnt).
|
||||||
|
WillReturnResult(sqlmock.NewResult(1, 1))
|
||||||
|
mock.ExpectCommit()
|
||||||
|
|
||||||
|
_, err := repo.Update(filter, values)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
61
app/repository/options.go
Normal file
61
app/repository/options.go
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Pagination struct {
|
||||||
|
Offset int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type OrderDirection string
|
||||||
|
|
||||||
|
const (
|
||||||
|
OrderASC OrderDirection = "ASC"
|
||||||
|
OrderDESC OrderDirection = "DESC"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Order struct {
|
||||||
|
Field string
|
||||||
|
Direction OrderDirection
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyOptionOnly(query *gorm.DB, only *[]string) *gorm.DB {
|
||||||
|
if only == nil || len(*only) == 0 {
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
query = query.Select(*only)
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyOptionOrdering(query *gorm.DB, ordering *[]Order) *gorm.DB {
|
||||||
|
if ordering == nil || len(*ordering) == 0 {
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, order := range *ordering {
|
||||||
|
if len(order.Direction) == 0 || order.Direction == OrderASC {
|
||||||
|
query = query.Order(order.Field)
|
||||||
|
} else {
|
||||||
|
query = query.Order(fmt.Sprintf("%s %s", order.Field, order.Direction))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyOptionPagination(query *gorm.DB, pagination *Pagination) *gorm.DB {
|
||||||
|
if pagination == nil {
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
if pagination.Limit != 0 {
|
||||||
|
query = query.Limit(pagination.Limit)
|
||||||
|
}
|
||||||
|
if pagination.Offset != 0 {
|
||||||
|
query = query.Offset(pagination.Offset)
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
59
app/repository/repository.go
Normal file
59
app/repository/repository.go
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/schema"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DEFAULT_ID_FIELD = "id"
|
||||||
|
|
||||||
|
type MethodInitInterface[T schema.Tabler] interface {
|
||||||
|
Init(repo *RepoBase[T])
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepoOptions struct {
|
||||||
|
IdField string
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepoBase[T schema.Tabler] struct {
|
||||||
|
IdField string
|
||||||
|
dbConn *gorm.DB
|
||||||
|
|
||||||
|
ListMethod[T]
|
||||||
|
GetMethod[T]
|
||||||
|
ExistsMethod[T]
|
||||||
|
CountMethod[T]
|
||||||
|
SaveMethod[T]
|
||||||
|
UpdateMethod[T]
|
||||||
|
DeleteMethod[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (repo *RepoBase[T]) InitMethods(methods []MethodInitInterface[T]) {
|
||||||
|
for _, method := range methods {
|
||||||
|
method.Init(repo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *RepoBase[T]) Init(dbConn *gorm.DB, options *RepoOptions) {
|
||||||
|
m.dbConn = dbConn
|
||||||
|
|
||||||
|
if options == nil {
|
||||||
|
// no options provided? set defaults
|
||||||
|
m.IdField = DEFAULT_ID_FIELD
|
||||||
|
} else {
|
||||||
|
if len(options.IdField) > 0 {
|
||||||
|
m.IdField = options.IdField
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
methods := []MethodInitInterface[T]{
|
||||||
|
&m.ListMethod,
|
||||||
|
&m.GetMethod,
|
||||||
|
&m.ExistsMethod,
|
||||||
|
&m.CountMethod,
|
||||||
|
&m.SaveMethod,
|
||||||
|
&m.UpdateMethod,
|
||||||
|
&m.DeleteMethod,
|
||||||
|
}
|
||||||
|
m.InitMethods(methods)
|
||||||
|
}
|
||||||
@ -4,6 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
type FilterField struct {
|
type FilterField struct {
|
||||||
@ -16,7 +18,11 @@ type FilterField struct {
|
|||||||
uintValue *uint64
|
uintValue *uint64
|
||||||
floatValue *float64
|
floatValue *float64
|
||||||
strValue *string
|
strValue *string
|
||||||
timeValue *time.Time
|
boolValues *[]bool
|
||||||
|
intValues *[]int64
|
||||||
|
uintValues *[]uint64
|
||||||
|
floatValues *[]float64
|
||||||
|
strValues *[]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ff *FilterField) setValueFromReflection(v reflect.Value) {
|
func (ff *FilterField) setValueFromReflection(v reflect.Value) {
|
||||||
@ -24,17 +30,70 @@ func (ff *FilterField) setValueFromReflection(v reflect.Value) {
|
|||||||
fn(ff, v)
|
fn(ff, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// func (ff *FilterField) getValueWithOperator(v reflect.Value) string {
|
func (ff *FilterField) appendStr(value string) {
|
||||||
// value := ff.getValue(v)
|
var valueArray []string
|
||||||
|
|
||||||
// switch ff.valueKind {
|
if ff.strValues == nil {
|
||||||
// case reflect.Bool:
|
valueArray = make([]string, 0)
|
||||||
// return fmt.Sprintf("IS %s", value)
|
} else {
|
||||||
// case reflect.Int, reflect.Uint, reflect.Float32, reflect.Float64, reflect.String:
|
valueArray = *ff.strValues
|
||||||
// return fmt.Sprintf("= %s", value)
|
}
|
||||||
// }
|
valueArray = append(valueArray, value)
|
||||||
// return "???"
|
ff.strValues = &valueArray
|
||||||
// }
|
ff.valueKind = reflect.String
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ff *FilterField) appendBool(value bool) {
|
||||||
|
var valueArray []bool
|
||||||
|
|
||||||
|
if ff.boolValues == nil {
|
||||||
|
valueArray = make([]bool, 0)
|
||||||
|
} else {
|
||||||
|
valueArray = *ff.boolValues
|
||||||
|
}
|
||||||
|
valueArray = append(valueArray, value)
|
||||||
|
ff.boolValues = &valueArray
|
||||||
|
ff.valueKind = reflect.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ff *FilterField) appendInt(value int64) {
|
||||||
|
var valueArray []int64
|
||||||
|
|
||||||
|
if ff.boolValues == nil {
|
||||||
|
valueArray = make([]int64, 0)
|
||||||
|
} else {
|
||||||
|
valueArray = *ff.intValues
|
||||||
|
}
|
||||||
|
valueArray = append(valueArray, value)
|
||||||
|
ff.intValues = &valueArray
|
||||||
|
ff.valueKind = reflect.Int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ff *FilterField) appendUint(value uint64) {
|
||||||
|
var valueArray []uint64
|
||||||
|
|
||||||
|
if ff.boolValues == nil {
|
||||||
|
valueArray = make([]uint64, 0)
|
||||||
|
} else {
|
||||||
|
valueArray = *ff.uintValues
|
||||||
|
}
|
||||||
|
valueArray = append(valueArray, value)
|
||||||
|
ff.uintValues = &valueArray
|
||||||
|
ff.valueKind = reflect.Int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ff *FilterField) appendFloat(value float64) {
|
||||||
|
var valueArray []float64
|
||||||
|
|
||||||
|
if ff.boolValues == nil {
|
||||||
|
valueArray = make([]float64, 0)
|
||||||
|
} else {
|
||||||
|
valueArray = *ff.floatValues
|
||||||
|
}
|
||||||
|
valueArray = append(valueArray, value)
|
||||||
|
ff.floatValues = &valueArray
|
||||||
|
ff.valueKind = reflect.Int
|
||||||
|
}
|
||||||
|
|
||||||
type valueGetterFunc func(ff *FilterField, v reflect.Value) error
|
type valueGetterFunc func(ff *FilterField, v reflect.Value) error
|
||||||
|
|
||||||
@ -74,17 +133,41 @@ func strValueGetter(ff *FilterField, v reflect.Value) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func timeValueGetter(ff *FilterField, v reflect.Value) error {
|
func timeValueGetter(ff *FilterField, v reflect.Value) error {
|
||||||
timeValue, ok := v.Interface().(time.Time)
|
value, err := timeValueToStr(v)
|
||||||
if !ok {
|
if err != nil {
|
||||||
return fmt.Errorf("error converting interface to time")
|
return err
|
||||||
}
|
}
|
||||||
value := timeValue.Format(time.RFC3339)
|
|
||||||
|
|
||||||
ff.strValue = &value
|
ff.strValue = &value
|
||||||
ff.valueKind = reflect.String
|
ff.valueKind = reflect.String
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func uuidValueGetter(ff *FilterField, v reflect.Value) error {
|
||||||
|
value, err := uuidValueToStr(v)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ff.strValue = &value
|
||||||
|
ff.valueKind = reflect.String
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func timeValueToStr(v reflect.Value) (string, error) {
|
||||||
|
value, ok := v.Interface().(time.Time)
|
||||||
|
if !ok {
|
||||||
|
return "", fmt.Errorf("error converting interface to time")
|
||||||
|
}
|
||||||
|
return value.Format(time.RFC3339), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func uuidValueToStr(v reflect.Value) (string, error) {
|
||||||
|
value, ok := v.Interface().(uuid.UUID)
|
||||||
|
if !ok {
|
||||||
|
return "", fmt.Errorf("error converting interface to uuid")
|
||||||
|
}
|
||||||
|
return value.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
func unsupportedValueGetter(ff *FilterField, v reflect.Value) error {
|
func unsupportedValueGetter(ff *FilterField, v reflect.Value) error {
|
||||||
return fmt.Errorf("unsupported type: %v", v.Type())
|
return fmt.Errorf("unsupported type: %v", v.Type())
|
||||||
}
|
}
|
||||||
@ -126,16 +209,18 @@ func newTypeGetter(t reflect.Type, allowAddr bool) valueGetterFunc {
|
|||||||
// return interfaceEncoder
|
// return interfaceEncoder
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
// check if value type is time
|
// check if value type is time
|
||||||
timeType := reflect.TypeOf(time.Time{})
|
if t == reflect.TypeOf(time.Time{}) {
|
||||||
if t == timeType {
|
|
||||||
return timeValueGetter
|
return timeValueGetter
|
||||||
}
|
}
|
||||||
// case reflect.Map:
|
// case reflect.Map:
|
||||||
// return newMapEncoder(t)
|
// return newMapEncoder(t)
|
||||||
// case reflect.Slice:
|
case reflect.Slice:
|
||||||
// return newSliceEncoder(t)
|
return newSliceGetter(t)
|
||||||
// case reflect.Array:
|
case reflect.Array:
|
||||||
// return newArrayEncoder(t)
|
if t == reflect.TypeOf(uuid.UUID{}) {
|
||||||
|
return uuidValueGetter
|
||||||
|
}
|
||||||
|
return newArrayGetter(t)
|
||||||
case reflect.Pointer:
|
case reflect.Pointer:
|
||||||
return newPtrValueGetter(t)
|
return newPtrValueGetter(t)
|
||||||
}
|
}
|
||||||
@ -143,15 +228,74 @@ func newTypeGetter(t reflect.Type, allowAddr bool) valueGetterFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ptrValueGetter struct {
|
type ptrValueGetter struct {
|
||||||
elemEnc valueGetterFunc
|
elemGetter valueGetterFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pvg ptrValueGetter) getValue(ff *FilterField, v reflect.Value) error {
|
func (pvg ptrValueGetter) getValue(ff *FilterField, v reflect.Value) error {
|
||||||
pvg.elemEnc(ff, v.Elem())
|
pvg.elemGetter(ff, v.Elem())
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPtrValueGetter(t reflect.Type) valueGetterFunc {
|
func newPtrValueGetter(t reflect.Type) valueGetterFunc {
|
||||||
enc := ptrValueGetter{elemEnc: typeGetter(t.Elem())}
|
enc := ptrValueGetter{elemGetter: typeGetter(t.Elem())}
|
||||||
|
return enc.getValue
|
||||||
|
}
|
||||||
|
|
||||||
|
type arrayGetter struct {
|
||||||
|
elemGetter valueGetterFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ag arrayGetter) getValue(ff *FilterField, v reflect.Value) error {
|
||||||
|
ag.elemGetter(ff, v.Elem())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newArrayGetter(t reflect.Type) valueGetterFunc {
|
||||||
|
enc := arrayGetter{elemGetter: typeGetter(t.Elem())}
|
||||||
|
return enc.getValue
|
||||||
|
}
|
||||||
|
|
||||||
|
type sliceGetter struct {
|
||||||
|
elemGetter valueGetterFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sg sliceGetter) getValue(ff *FilterField, v reflect.Value) error {
|
||||||
|
for n := range v.Len() {
|
||||||
|
element := v.Index(n)
|
||||||
|
|
||||||
|
switch element.Kind() {
|
||||||
|
case reflect.Bool:
|
||||||
|
ff.appendBool(element.Bool())
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
ff.appendInt(element.Int())
|
||||||
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||||
|
ff.appendUint(element.Uint())
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
ff.appendFloat(element.Float())
|
||||||
|
case reflect.String:
|
||||||
|
ff.appendStr(element.String())
|
||||||
|
case reflect.Struct:
|
||||||
|
if element.Type() == reflect.TypeOf(time.Time{}) {
|
||||||
|
value, err := timeValueToStr(element)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ff.appendStr(value)
|
||||||
|
}
|
||||||
|
case reflect.Array:
|
||||||
|
if element.Type() == reflect.TypeOf(uuid.UUID{}) {
|
||||||
|
value, err := uuidValueToStr(element)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ff.appendStr(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSliceGetter(t reflect.Type) valueGetterFunc {
|
||||||
|
enc := sliceGetter{elemGetter: newArrayGetter(t)}
|
||||||
return enc.getValue
|
return enc.getValue
|
||||||
}
|
}
|
||||||
|
|||||||
@ -49,3 +49,15 @@ func applyFilterLE[T bool | int64 | uint64 | float64 | string](
|
|||||||
) *gorm.DB {
|
) *gorm.DB {
|
||||||
return query.Where(fmt.Sprintf("%s.%s <= ?", tableName, filterField.Name), value)
|
return query.Where(fmt.Sprintf("%s.%s <= ?", tableName, filterField.Name), value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func applyFilterIN[T bool | int64 | uint64 | float64 | string](
|
||||||
|
query *gorm.DB, tableName string, filterField *FilterField, value *[]T,
|
||||||
|
) *gorm.DB {
|
||||||
|
return query.Where(fmt.Sprintf("%s.%s IN (?)", tableName, filterField.Name), *value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyFilterNOT_IN[T bool | int64 | uint64 | float64 | string](
|
||||||
|
query *gorm.DB, tableName string, filterField *FilterField, value *[]T,
|
||||||
|
) *gorm.DB {
|
||||||
|
return query.Where(fmt.Sprintf("%s.%s NOT IN (?)", tableName, filterField.Name), *value)
|
||||||
|
}
|
||||||
|
|||||||
143
app/repository/smartfilter/handlers.go
Normal file
143
app/repository/smartfilter/handlers.go
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
package smartfilter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handleOperatorEQ(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Bool:
|
||||||
|
return applyFilterEQ(query, tableName, filterField, *filterField.boolValue)
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterEQ(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterEQ(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterEQ(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterEQ(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorNE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Bool:
|
||||||
|
return applyFilterNE(query, tableName, filterField, *filterField.boolValue)
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterNE(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterNE(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterNE(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterNE(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorLIKE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterLIKE(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorILIKE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterILIKE(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorGT(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterGT(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterGT(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterGT(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterGT(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorGE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterGE(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterGE(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterGE(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterGE(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorLT(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterLT(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterLT(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterLT(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterLT(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorLE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterLE(query, tableName, filterField, *filterField.intValue)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterLE(query, tableName, filterField, *filterField.uintValue)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterLE(query, tableName, filterField, *filterField.floatValue)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterLE(query, tableName, filterField, *filterField.strValue)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorIN(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Bool:
|
||||||
|
return applyFilterIN(query, tableName, filterField, filterField.boolValues)
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterIN(query, tableName, filterField, filterField.intValues)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterIN(query, tableName, filterField, filterField.uintValues)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterIN(query, tableName, filterField, filterField.floatValues)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterIN(query, tableName, filterField, filterField.strValues)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleOperatorNOT_IN(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
||||||
|
switch filterField.valueKind {
|
||||||
|
case reflect.Bool:
|
||||||
|
return applyFilterNOT_IN(query, tableName, filterField, filterField.boolValues)
|
||||||
|
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||||
|
return applyFilterNOT_IN(query, tableName, filterField, filterField.intValues)
|
||||||
|
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||||
|
return applyFilterNOT_IN(query, tableName, filterField, filterField.uintValues)
|
||||||
|
case reflect.Float32, reflect.Float64:
|
||||||
|
return applyFilterNOT_IN(query, tableName, filterField, filterField.floatValues)
|
||||||
|
case reflect.String:
|
||||||
|
return applyFilterNOT_IN(query, tableName, filterField, filterField.strValues)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
610
app/repository/smartfilter/handlers_test.go
Normal file
610
app/repository/smartfilter/handlers_test.go
Normal file
@ -0,0 +1,610 @@
|
|||||||
|
package smartfilter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/go-playground/assert"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewMockDB() (*gorm.DB, sqlmock.Sqlmock) {
|
||||||
|
db, mock, err := sqlmock.New()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("An error '%s' was not expected when opening a stub database connection", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gormDB, err := gorm.Open(postgres.New(postgres.Config{
|
||||||
|
WithoutQuotingCheck: true,
|
||||||
|
Conn: db,
|
||||||
|
}), &gorm.Config{})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("An error '%s' was not expected when opening gorm database", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return gormDB, mock
|
||||||
|
}
|
||||||
|
|
||||||
|
type MyModel struct {
|
||||||
|
Id int
|
||||||
|
Value string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m MyModel) TableName() string {
|
||||||
|
return "my_models"
|
||||||
|
}
|
||||||
|
|
||||||
|
type HandleOperatorTestCase struct {
|
||||||
|
name string
|
||||||
|
filterField FilterField
|
||||||
|
expected string
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
boolTrue bool = true
|
||||||
|
boolFalse bool = false
|
||||||
|
int64Value int64 = -123456
|
||||||
|
uint64Value uint64 = 123456
|
||||||
|
floatValue float64 = -123456.789
|
||||||
|
strValue string = "Some Value"
|
||||||
|
|
||||||
|
boolValues = []bool{true, false}
|
||||||
|
int64Values = []int64{-123456, 1, 123456}
|
||||||
|
uint64Values = []uint64{123456, 1234567, 1234568}
|
||||||
|
floatValues = []float64{-123456.789, -1, 123456.789}
|
||||||
|
strValues = []string{"First Value", "Second Value", "Third Value"}
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHandleOperatorEQ(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorEQ
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ bool true",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValue: &boolTrue,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = true ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ bool false",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValue: &boolFalse,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = false ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorEQ string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field = 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorNE(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorNE
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE bool true",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValue: &boolTrue,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != true ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE bool false",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValue: &boolFalse,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != false ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNE string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field != 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorLIKE(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorLIKE
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorLIKE",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field LIKE '%Some Value%' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorILIKE(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorILIKE
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorILIKE",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field ILIKE '%Some Value%' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorGT(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorGT
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorGT int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field > -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGT uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field > 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGT float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field > -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGT string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field > 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorGE(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorGE
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorGE int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field >= -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGE uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field >= 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGE float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field >= -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorGE string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field >= 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorLT(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorLT
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorLT int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field < -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLT uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field < 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLT float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field < -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLT string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field < 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorLE(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorLE
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorLE int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValue: &int64Value,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field <= -123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLE uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValue: &uint64Value,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field <= 123456 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLE float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValue: &floatValue,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field <= -123456.789 ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorLE string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValue: &strValue,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field <= 'Some Value' ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorIN(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorIN
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorIN bool",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValues: &boolValues,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field IN (true,false) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorIN int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValues: &int64Values,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field IN (-123456,1,123456) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorIN uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValues: &uint64Values,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field IN (123456,1234567,1234568) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorIN float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValues: &floatValues,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field IN (-123456.789,-1,123456.789) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorIN string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValues: &strValues,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field IN ('First Value','Second Value','Third Value') ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandleOperatorNOT_IN(t *testing.T) {
|
||||||
|
db, _ := NewMockDB()
|
||||||
|
testFunc := handleOperatorNOT_IN
|
||||||
|
|
||||||
|
testCases := []HandleOperatorTestCase{
|
||||||
|
{
|
||||||
|
name: "handleOperatorNOT_IN bool",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
boolValues: &boolValues,
|
||||||
|
valueKind: reflect.Bool,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field NOT IN (true,false) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNOT_IN int64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
intValues: &int64Values,
|
||||||
|
valueKind: reflect.Int64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field NOT IN (-123456,1,123456) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNOT_IN uint64",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
uintValues: &uint64Values,
|
||||||
|
valueKind: reflect.Uint64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field NOT IN (123456,1234567,1234568) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNOT_IN float",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
floatValues: &floatValues,
|
||||||
|
valueKind: reflect.Float64,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field NOT IN (-123456.789,-1,123456.789) ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "handleOperatorNOT_IN string",
|
||||||
|
filterField: FilterField{
|
||||||
|
Name: "my_field",
|
||||||
|
strValues: &strValues,
|
||||||
|
valueKind: reflect.String,
|
||||||
|
},
|
||||||
|
expected: "SELECT * FROM my_models WHERE my_table.my_field NOT IN ('First Value','Second Value','Third Value') ORDER BY my_models.id LIMIT 1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||||
|
query := tx.Model(&MyModel{})
|
||||||
|
query = testFunc(query, "my_table", &testCase.filterField)
|
||||||
|
return query.First(&MyModel{})
|
||||||
|
})
|
||||||
|
assert.Equal(t, testCase.expected, sql)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -12,11 +12,12 @@ const (
|
|||||||
OperatorLIKE Operator = "LIKE"
|
OperatorLIKE Operator = "LIKE"
|
||||||
OperatorILIKE Operator = "ILIKE"
|
OperatorILIKE Operator = "ILIKE"
|
||||||
OperatorIN Operator = "IN"
|
OperatorIN Operator = "IN"
|
||||||
|
OperatorNOT_IN Operator = "NOT_IN"
|
||||||
)
|
)
|
||||||
|
|
||||||
var OPERATORS = []Operator{
|
var OPERATORS = []Operator{
|
||||||
OperatorEQ, OperatorNE,
|
OperatorEQ, OperatorNE,
|
||||||
OperatorGT, OperatorGE, OperatorLT, OperatorLE,
|
OperatorGT, OperatorGE, OperatorLT, OperatorLE,
|
||||||
OperatorLIKE, OperatorILIKE,
|
OperatorLIKE, OperatorILIKE,
|
||||||
OperatorIN,
|
OperatorIN, OperatorNOT_IN,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,17 +5,22 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/schema"
|
"gorm.io/gorm/schema"
|
||||||
)
|
)
|
||||||
|
|
||||||
const TAG_NAME = "filterfield"
|
const TAG_NAME = "filterfield"
|
||||||
const TAG_VALUE_SEPARATOR = ","
|
const TAG_PAIRS_SEPARATOR = ";"
|
||||||
|
const TAG_LIST_SEPARATOR = ","
|
||||||
|
const TAG_KEYVALUE_SEPARATOR = "="
|
||||||
|
|
||||||
type handlerFunc func(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB
|
type handlerFunc func(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB
|
||||||
|
|
||||||
|
type QueryApplier interface {
|
||||||
|
ApplyQuery(query *gorm.DB) *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
var operatorHandlers = map[Operator]handlerFunc{
|
var operatorHandlers = map[Operator]handlerFunc{
|
||||||
OperatorEQ: handleOperatorEQ,
|
OperatorEQ: handleOperatorEQ,
|
||||||
OperatorNE: handleOperatorNE,
|
OperatorNE: handleOperatorNE,
|
||||||
@ -25,28 +30,21 @@ var operatorHandlers = map[Operator]handlerFunc{
|
|||||||
OperatorLE: handleOperatorLE,
|
OperatorLE: handleOperatorLE,
|
||||||
OperatorLIKE: handleOperatorLIKE,
|
OperatorLIKE: handleOperatorLIKE,
|
||||||
OperatorILIKE: handleOperatorILIKE,
|
OperatorILIKE: handleOperatorILIKE,
|
||||||
|
OperatorIN: handleOperatorIN,
|
||||||
|
OperatorNOT_IN: handleOperatorNOT_IN,
|
||||||
}
|
}
|
||||||
|
|
||||||
type SmartCertFilter[T schema.Tabler] struct {
|
type ReflectedStructField struct {
|
||||||
Model T
|
name string
|
||||||
Alive *bool `filterfield:"alive,EQ"`
|
value reflect.Value
|
||||||
SerialNumber *string `filterfield:"serial_number,NE"`
|
tagValue string
|
||||||
SerialNumberContains *string `filterfield:"serial_number,LIKE"`
|
|
||||||
IssuerContains *string `filterfield:"issuer,ILIKE"`
|
|
||||||
Id *string `filterfield:"id,EQ"`
|
|
||||||
Ids *[]string `filterfield:"id,IN"`
|
|
||||||
CreatedAt_Lt *time.Time `filterfield:"created_at,LT"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f SmartCertFilter[T]) ToQuery(query *gorm.DB) (*gorm.DB, error) {
|
func getFilterFields(filter interface{}) []ReflectedStructField {
|
||||||
tableName := f.Model.TableName()
|
res := make([]ReflectedStructField, 0)
|
||||||
|
|
||||||
fmt.Printf("Table name: %s\n", tableName)
|
st := reflect.TypeOf(filter)
|
||||||
// fmt.Printf("%+v\n", f)
|
reflectValue := reflect.ValueOf(filter)
|
||||||
|
|
||||||
st := reflect.TypeOf(f)
|
|
||||||
modelName := st.Name()
|
|
||||||
reflectValue := reflect.ValueOf(f)
|
|
||||||
|
|
||||||
for i := 0; i < st.NumField(); i++ {
|
for i := 0; i < st.NumField(); i++ {
|
||||||
field := st.Field(i)
|
field := st.Field(i)
|
||||||
@ -57,23 +55,46 @@ func (f SmartCertFilter[T]) ToQuery(query *gorm.DB) (*gorm.DB, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
fieldReflect := reflectValue.FieldByName(field.Name)
|
// get field value
|
||||||
|
fieldValue := reflectValue.FieldByName(field.Name)
|
||||||
|
|
||||||
// skip field if value is nil
|
// skip field if value is nil
|
||||||
if fieldReflect.IsNil() {
|
if fieldValue.IsNil() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
t := fieldReflect.Type()
|
res = append(res, ReflectedStructField{
|
||||||
fmt.Printf(">>> %+v --- %+v\n", field, t)
|
name: field.Name,
|
||||||
|
tagValue: tagValue,
|
||||||
|
value: fieldValue,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
filterField, err := newFilterField(tagValue)
|
func getQueryApplierInterface(filter interface{}) QueryApplier {
|
||||||
|
queryApplier, ok := filter.(QueryApplier)
|
||||||
|
if ok {
|
||||||
|
return queryApplier
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ToQuery(model schema.Tabler, filter interface{}, query *gorm.DB) (*gorm.DB, error) {
|
||||||
|
st := reflect.TypeOf(filter)
|
||||||
|
|
||||||
|
tableName := model.TableName()
|
||||||
|
modelName := st.Name()
|
||||||
|
|
||||||
|
fields := getFilterFields(filter)
|
||||||
|
for _, field := range fields {
|
||||||
|
filterField, err := newFilterField(field.tagValue)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s.%s: %s", modelName, field.Name, err)
|
return nil, fmt.Errorf("%s.%s: %s", modelName, field.name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// must be called!
|
// must be called!
|
||||||
filterField.setValueFromReflection(fieldReflect)
|
filterField.setValueFromReflection(field.value)
|
||||||
|
|
||||||
operatorHandler, ok := operatorHandlers[filterField.Operator]
|
operatorHandler, ok := operatorHandlers[filterField.Operator]
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -86,127 +107,57 @@ func (f SmartCertFilter[T]) ToQuery(query *gorm.DB) (*gorm.DB, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// apply custom filters, if interface exists
|
||||||
|
queryApplier := getQueryApplierInterface(filter)
|
||||||
|
if queryApplier != nil {
|
||||||
|
query = queryApplier.ApplyQuery(query)
|
||||||
|
}
|
||||||
|
|
||||||
return query, nil
|
return query, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFilterField(tagValue string) (*FilterField, error) {
|
func splitTrim(value string, separator string) []string {
|
||||||
values := strings.Split(tagValue, TAG_VALUE_SEPARATOR)
|
var out []string = []string{}
|
||||||
if len(values) != 2 {
|
for _, s := range strings.Split(value, separator) {
|
||||||
return nil, fmt.Errorf("incorrect number of tag values: %s", tagValue)
|
if len(s) == 0 {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
out = append(out, strings.TrimSpace(s))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
operator := Operator(values[1])
|
func newFilterField(tagValue string) (*FilterField, error) {
|
||||||
|
filterField := FilterField{}
|
||||||
|
|
||||||
|
for _, pair := range splitTrim(tagValue, TAG_PAIRS_SEPARATOR) {
|
||||||
|
kvs := splitTrim(pair, TAG_KEYVALUE_SEPARATOR)
|
||||||
|
if len(kvs) != 2 {
|
||||||
|
return nil, fmt.Errorf("invalid tag value: %s", strings.TrimSpace(pair))
|
||||||
|
}
|
||||||
|
key := kvs[0]
|
||||||
|
value := kvs[1]
|
||||||
|
|
||||||
|
switch key {
|
||||||
|
case "field":
|
||||||
|
filterField.Name = value
|
||||||
|
case "operator":
|
||||||
|
operator := Operator(value)
|
||||||
if !slices.Contains(OPERATORS, operator) {
|
if !slices.Contains(OPERATORS, operator) {
|
||||||
return nil, fmt.Errorf("unknown operator: %s", operator)
|
return nil, fmt.Errorf("unknown operator: %s", operator)
|
||||||
}
|
}
|
||||||
|
filterField.Operator = operator
|
||||||
f := FilterField{
|
default:
|
||||||
Name: values[0],
|
return nil, fmt.Errorf("invalid value key: %s", key)
|
||||||
Operator: operator,
|
|
||||||
}
|
}
|
||||||
return &f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorEQ(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.Bool:
|
|
||||||
return applyFilterEQ(query, tableName, filterField, *filterField.boolValue)
|
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return applyFilterEQ(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterEQ(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterEQ(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterEQ(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorNE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
if len(filterField.Name) == 0 {
|
||||||
switch filterField.valueKind {
|
return nil, fmt.Errorf("missing field name in tag: %s", tagValue)
|
||||||
case reflect.Bool:
|
}
|
||||||
return applyFilterNE(query, tableName, filterField, *filterField.boolValue)
|
if len(filterField.Operator) == 0 {
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
return nil, fmt.Errorf("missing operator in tag: %s", tagValue)
|
||||||
return applyFilterNE(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterNE(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterNE(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterNE(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorLIKE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
return &filterField, nil
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterLIKE(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorILIKE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterILIKE(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorGT(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return applyFilterGT(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterGT(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterGT(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterGT(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorGE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return applyFilterGE(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterGE(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterGE(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterGE(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorLT(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return applyFilterLT(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterLT(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterLT(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterLT(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func handleOperatorLE(query *gorm.DB, tableName string, filterField *FilterField) *gorm.DB {
|
|
||||||
switch filterField.valueKind {
|
|
||||||
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
||||||
return applyFilterLE(query, tableName, filterField, *filterField.intValue)
|
|
||||||
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
||||||
return applyFilterLE(query, tableName, filterField, *filterField.uintValue)
|
|
||||||
case reflect.Float32, reflect.Float64:
|
|
||||||
return applyFilterLE(query, tableName, filterField, *filterField.floatValue)
|
|
||||||
case reflect.String:
|
|
||||||
return applyFilterLE(query, tableName, filterField, *filterField.strValue)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
229
app/repository/smartfilter/smartfilter_test.go
Normal file
229
app/repository/smartfilter/smartfilter_test.go
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
package smartfilter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetFilterFields(t *testing.T) {
|
||||||
|
type TestFilter struct {
|
||||||
|
Alive *bool `filterfield:"alive,EQ"`
|
||||||
|
Id *int64 `filterfield:"id,EQ"`
|
||||||
|
Ids *[]uint `filterfield:"id,IN"`
|
||||||
|
IdsNot *[]uint `filterfield:"id,NOT_IN"`
|
||||||
|
FirstName *string `filterfield:"first_name,EQ"`
|
||||||
|
NotFirstName *string `filterfield:"first_name,NE"`
|
||||||
|
FirstNameLike *string `filterfield:"first_name,LIKE"`
|
||||||
|
CreatedAt_GE *time.Time `filterfield:"created_at,GE"`
|
||||||
|
CreatedAt_GT *time.Time `filterfield:"created_at,GT"`
|
||||||
|
CreatedAt_LE *time.Time `filterfield:"created_at,LE"`
|
||||||
|
CreatedAt_LT *time.Time `filterfield:"created_at,LT"`
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("Parse filter fields", func(t *testing.T) {
|
||||||
|
utc, _ := time.LoadLocation("UTC")
|
||||||
|
|
||||||
|
var (
|
||||||
|
alive bool = true
|
||||||
|
id int64 = 123456
|
||||||
|
ids []uint = []uint{111, 222, 333, 444, 555}
|
||||||
|
idsNot []uint = []uint{666, 777, 888, 999}
|
||||||
|
firstName string = "Mirko"
|
||||||
|
notFirstName string = "Pero"
|
||||||
|
firstNameLike string = "irko"
|
||||||
|
createdTime time.Time = time.Date(2024, 5, 26, 16, 8, 0, 0, utc)
|
||||||
|
)
|
||||||
|
filter := TestFilter{
|
||||||
|
Alive: &alive,
|
||||||
|
Id: &id,
|
||||||
|
Ids: &ids,
|
||||||
|
IdsNot: &idsNot,
|
||||||
|
FirstName: &firstName,
|
||||||
|
NotFirstName: ¬FirstName,
|
||||||
|
FirstNameLike: &firstNameLike,
|
||||||
|
CreatedAt_GE: &createdTime,
|
||||||
|
CreatedAt_GT: &createdTime,
|
||||||
|
CreatedAt_LE: &createdTime,
|
||||||
|
CreatedAt_LT: &createdTime,
|
||||||
|
}
|
||||||
|
result := getFilterFields(filter)
|
||||||
|
|
||||||
|
fmt.Printf("%+v\n", result[0].value)
|
||||||
|
fmt.Printf("%+v\n", &alive)
|
||||||
|
|
||||||
|
assert.Equal(t, "Alive", result[0].name)
|
||||||
|
assert.Equal(t, alive, result[0].value.Elem().Bool())
|
||||||
|
assert.Equal(t, "alive,EQ", result[0].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "Id", result[1].name)
|
||||||
|
assert.Equal(t, id, result[1].value.Elem().Int())
|
||||||
|
assert.Equal(t, "id,EQ", result[1].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "Ids", result[2].name)
|
||||||
|
assert.Equal(t, ids, result[2].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "id,IN", result[2].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "IdsNot", result[3].name)
|
||||||
|
assert.Equal(t, idsNot, result[3].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "id,NOT_IN", result[3].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "FirstName", result[4].name)
|
||||||
|
assert.Equal(t, firstName, result[4].value.Elem().String())
|
||||||
|
assert.Equal(t, "first_name,EQ", result[4].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "NotFirstName", result[5].name)
|
||||||
|
assert.Equal(t, notFirstName, result[5].value.Elem().String())
|
||||||
|
assert.Equal(t, "first_name,NE", result[5].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "FirstNameLike", result[6].name)
|
||||||
|
assert.Equal(t, firstNameLike, result[6].value.Elem().String())
|
||||||
|
assert.Equal(t, "first_name,LIKE", result[6].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "CreatedAt_GE", result[7].name)
|
||||||
|
assert.Equal(t, createdTime, result[7].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "created_at,GE", result[7].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "CreatedAt_GT", result[8].name)
|
||||||
|
assert.Equal(t, createdTime, result[8].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "created_at,GT", result[8].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "CreatedAt_LE", result[9].name)
|
||||||
|
assert.Equal(t, createdTime, result[9].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "created_at,LE", result[9].tagValue)
|
||||||
|
|
||||||
|
assert.Equal(t, "CreatedAt_LT", result[10].name)
|
||||||
|
assert.Equal(t, createdTime, result[10].value.Elem().Interface())
|
||||||
|
assert.Equal(t, "created_at,LT", result[10].tagValue)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Skip nil fields", func(t *testing.T) {
|
||||||
|
type TestFilter struct {
|
||||||
|
Alive *bool `filterfield:"alive;EQ"`
|
||||||
|
Id *int64 `filterfield:"id;EQ"`
|
||||||
|
Ids *[]uint `filterfield:"id;IN"`
|
||||||
|
IdsNot *[]uint `filterfield:"id;NOT_IN"`
|
||||||
|
FirstName *string `filterfield:"first_name;EQ"`
|
||||||
|
}
|
||||||
|
filter := TestFilter{}
|
||||||
|
result := getFilterFields(filter)
|
||||||
|
assert.Equal(t, 0, len(result))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Skip fields without filterfield tag", func(t *testing.T) {
|
||||||
|
var (
|
||||||
|
alive bool = true
|
||||||
|
id int64 = 123456
|
||||||
|
)
|
||||||
|
type TestFilter struct {
|
||||||
|
Alive *bool
|
||||||
|
Id *int64 `funnytag:"created_at;LT"`
|
||||||
|
}
|
||||||
|
filter := TestFilter{
|
||||||
|
Alive: &alive,
|
||||||
|
Id: &id,
|
||||||
|
}
|
||||||
|
result := getFilterFields(filter)
|
||||||
|
assert.Equal(t, 0, len(result))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type TagParseTestCase struct {
|
||||||
|
name string
|
||||||
|
tagValue string
|
||||||
|
expected FilterField
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterField(t *testing.T) {
|
||||||
|
testCases := []TagParseTestCase{
|
||||||
|
{
|
||||||
|
name: "Parse without spaces",
|
||||||
|
tagValue: "field=field_1;operator=EQ",
|
||||||
|
expected: FilterField{
|
||||||
|
Name: "field_1",
|
||||||
|
Operator: OperatorEQ,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Parse spaces between pairs",
|
||||||
|
tagValue: " field=field_2 ; operator=LT ",
|
||||||
|
expected: FilterField{
|
||||||
|
Name: "field_2",
|
||||||
|
Operator: OperatorLT,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Parse spaces between around keys and values",
|
||||||
|
tagValue: "operator = LIKE ; field = field_3",
|
||||||
|
expected: FilterField{
|
||||||
|
Name: "field_3",
|
||||||
|
Operator: OperatorLIKE,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField(testCase.tagValue)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.Equal(t, testCase.expected.Name, filterField.Name)
|
||||||
|
assert.Equal(t, testCase.expected.Operator, filterField.Operator)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("Fail on invalid tag value", func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField("field=field_1=fail; operator=EQ")
|
||||||
|
assert.Nil(t, filterField)
|
||||||
|
assert.EqualError(t, err, "invalid tag value: field=field_1=fail")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Fail on invalid operator", func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField("field=field_1; operator=FAIL")
|
||||||
|
assert.Nil(t, filterField)
|
||||||
|
assert.EqualError(t, err, "unknown operator: FAIL")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Fail on invalid value key", func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField("failkey=field_1; operator=FAIL")
|
||||||
|
assert.Nil(t, filterField)
|
||||||
|
assert.EqualError(t, err, "invalid value key: failkey")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Fail on missing field name", func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField("operator=EQ")
|
||||||
|
assert.Nil(t, filterField)
|
||||||
|
assert.EqualError(t, err, "missing field name in tag: operator=EQ")
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Fail on missing operator", func(t *testing.T) {
|
||||||
|
filterField, err := newFilterField("field=field_1")
|
||||||
|
assert.Nil(t, filterField)
|
||||||
|
assert.EqualError(t, err, "missing operator in tag: field=field_1")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type filterWithoutQueryApplier struct{}
|
||||||
|
|
||||||
|
type filterWithQueryApplier struct{}
|
||||||
|
|
||||||
|
func (f filterWithQueryApplier) ApplyQuery(query *gorm.DB) *gorm.DB {
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSmartfilterApplyQuery(t *testing.T) {
|
||||||
|
|
||||||
|
t.Run("Get query applier interface - without interface", func(t *testing.T) {
|
||||||
|
f := filterWithoutQueryApplier{}
|
||||||
|
queryApplier := getQueryApplierInterface(f)
|
||||||
|
assert.Nil(t, queryApplier)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("Get query applier interface - with interface", func(t *testing.T) {
|
||||||
|
f := filterWithQueryApplier{}
|
||||||
|
queryApplier := getQueryApplierInterface(f)
|
||||||
|
assert.NotNil(t, queryApplier)
|
||||||
|
})
|
||||||
|
}
|
||||||
4
go.mod
4
go.mod
@ -3,10 +3,12 @@ module repo-pattern
|
|||||||
go 1.22.3
|
go 1.22.3
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||||
|
github.com/go-playground/assert v1.2.1
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/kelseyhightower/envconfig v1.4.0
|
github.com/kelseyhightower/envconfig v1.4.0
|
||||||
github.com/mozillazg/go-slugify v0.2.0
|
github.com/mozillazg/go-slugify v0.2.0
|
||||||
github.com/stretchr/testify v1.8.1
|
github.com/stretchr/testify v1.9.0
|
||||||
go.uber.org/zap v1.27.0
|
go.uber.org/zap v1.27.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gorm.io/datatypes v1.2.1
|
gorm.io/datatypes v1.2.1
|
||||||
|
|||||||
13
go.sum
13
go.sum
@ -1,8 +1,12 @@
|
|||||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
|
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||||
|
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-playground/assert v1.2.1 h1:ad06XqC+TOv0nJWnbULSlh3ehp5uLuQEojZY5Tq8RgI=
|
||||||
|
github.com/go-playground/assert v1.2.1/go.mod h1:Lgy+k19nOB/wQG/fVSQ7rra5qYugmytMQqvQ2dgjWn8=
|
||||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
@ -26,6 +30,7 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
|||||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
||||||
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
||||||
|
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
|
||||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
@ -43,14 +48,10 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
|||||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||||
|
|||||||
Reference in New Issue
Block a user