Compare commits
19 Commits
c371cbf042
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 176fadbceb | |||
| 86f4550b08 | |||
| f50aaca44d | |||
| f7cf63c2bf | |||
| 30714bb3da | |||
| 8a81173fc8 | |||
| 43824af97c | |||
| 326866dc49 | |||
| 450345ba6b | |||
| bdc978aec1 | |||
| 3dc8d0d79f | |||
| 4615d55309 | |||
| c2bcbea5d2 | |||
| ff51420b71 | |||
| 9958e9103b | |||
| bd510d958b | |||
| 295e915f89 | |||
| 642ac4fba7 | |||
| 39757cde34 |
135
app/main.go
135
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -19,14 +20,31 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type CertFilter struct {
|
type CertFilter struct {
|
||||||
Alive *bool `filterfield:"field=alive,operator=EQ"`
|
Alive *bool `filterfield:"field=alive;operator=EQ"`
|
||||||
SerialNumber *string `filterfield:"field=serial_number,operator=NE"`
|
SerialNumber *string `filterfield:"field=serial_number;operator=NE"`
|
||||||
SerialNumberContains *string `filterfield:"field=serial_number,operator=LIKE"`
|
SerialNumberContains *string `filterfield:"field=serial_number;operator=LIKE"`
|
||||||
IssuerContains *string `filterfield:"field=issuer,operator=ILIKE"`
|
IssuerContains *string `filterfield:"field=issuer;operator=ILIKE"`
|
||||||
Id *string `filterfield:"field=id,operator=EQ"`
|
Id *uuid.UUID `filterfield:"field=id;operator=EQ"`
|
||||||
Ids *[]string `filterfield:"field=id,operator=IN"`
|
Ids *[]uuid.UUID `filterfield:"field=id;operator=IN"`
|
||||||
IdsNot *[]string `filterfield:"field=id,operator=NOT_IN"`
|
IdsNot *[]string `filterfield:"field=id;operator=NOT_IN"`
|
||||||
CreatedAt_Lt *time.Time `filterfield:"field=created_at,operator=LT"`
|
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) {
|
||||||
@ -37,9 +55,14 @@ func doMagic(db *gorm.DB) {
|
|||||||
// serialNumber := "222"
|
// serialNumber := "222"
|
||||||
// serialNumberContains := "323"
|
// serialNumberContains := "323"
|
||||||
// issuer := "FINA"
|
// issuer := "FINA"
|
||||||
// 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)
|
||||||
ids := []string{"eb2bcac6-5173-4dbb-93b7-e7c03b924a03", "db9fb837-3483-4736-819d-f427dc8cda23", "1fece5e7-8e8d-4828-8298-3b1f07fd29ff"}
|
|
||||||
|
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{
|
filter := CertFilter{
|
||||||
// Alive: &FALSE,
|
// Alive: &FALSE,
|
||||||
@ -48,7 +71,7 @@ func doMagic(db *gorm.DB) {
|
|||||||
// SerialNumberContains: &serialNumberContains,
|
// SerialNumberContains: &serialNumberContains,
|
||||||
Ids: &ids,
|
Ids: &ids,
|
||||||
// IssuerContains: &issuer,
|
// IssuerContains: &issuer,
|
||||||
// CreatedAt_Lt: &createdTime,
|
CreatedAt_Lt: &createdTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
query, err = smartfilter.ToQuery(models.Cert{}, filter, query)
|
query, err = smartfilter.ToQuery(models.Cert{}, filter, query)
|
||||||
@ -66,13 +89,13 @@ func doMagic(db *gorm.DB) {
|
|||||||
|
|
||||||
func doList(db *gorm.DB) {
|
func doList(db *gorm.DB) {
|
||||||
repo := repository.RepoBase[models.Cert]{}
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
repo.Init(db)
|
repo.Init(db, nil)
|
||||||
|
|
||||||
filter := CertFilter{
|
filter := CertFilter{
|
||||||
Alive: &TRUE,
|
Alive: &TRUE,
|
||||||
}
|
}
|
||||||
|
|
||||||
certs, err := repo.List(filter)
|
certs, err := repo.List(filter, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
@ -82,28 +105,95 @@ func doList(db *gorm.DB) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
func doGet(db *gorm.DB) {
|
||||||
repo := repository.RepoBase[models.Cert]{}
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
repo.Init(db)
|
repo.Init(db, nil)
|
||||||
|
|
||||||
id := "db9fb837-3483-4736-819d-f427dc8cda23"
|
id, _ := uuid.Parse("db9fb837-3483-4736-819d-f427dc8cda23")
|
||||||
|
|
||||||
filter := CertFilter{
|
filter := CertFilter{
|
||||||
Id: &id,
|
Id: &id,
|
||||||
}
|
}
|
||||||
|
|
||||||
cert, err := repo.Get(filter)
|
cert, err := repo.Get(filter, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
fmt.Printf(">> %+v %s (alive %t)\n", cert.Id, cert.CreatedAt, cert.Alive)
|
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) {
|
func doExists(db *gorm.DB) {
|
||||||
repo := repository.RepoBase[models.Cert]{}
|
repo := repository.RepoBase[models.Cert]{}
|
||||||
repo.Init(db)
|
repo.Init(db, nil)
|
||||||
|
|
||||||
id := "db9fb837-3483-4736-819d-f427dc8cda23"
|
id, _ := uuid.Parse("db9fb837-3483-4736-819d-f427dc8cda23")
|
||||||
|
|
||||||
filter := CertFilter{
|
filter := CertFilter{
|
||||||
Id: &id,
|
Id: &id,
|
||||||
@ -122,10 +212,13 @@ func main() {
|
|||||||
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)
|
// doList(db)
|
||||||
|
doListWithJoins(db)
|
||||||
|
// doCount(db)
|
||||||
|
// doSave(db)
|
||||||
|
// doDelete(db)
|
||||||
// doGet(db)
|
// doGet(db)
|
||||||
// doExists(db)
|
// doExists(db)
|
||||||
// inheritance.DoInheritanceTest()
|
// 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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@ -1,84 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"repo-pattern/app/repository/smartfilter"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/schema"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ListMethod[T schema.Tabler] struct {
|
|
||||||
DbConn *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ListMethod[T]) Init(dbConn *gorm.DB) {
|
|
||||||
m.DbConn = dbConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ListMethod[T]) List(filter interface{}) (*[]T, error) {
|
|
||||||
var (
|
|
||||||
model T
|
|
||||||
models []T
|
|
||||||
)
|
|
||||||
|
|
||||||
query, err := smartfilter.ToQuery(model, filter, m.DbConn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
query.Find(&models)
|
|
||||||
return &models, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetMethod[T schema.Tabler] struct {
|
|
||||||
DbConn *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *GetMethod[T]) Init(dbConn *gorm.DB) {
|
|
||||||
m.DbConn = dbConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m GetMethod[T]) Get(filter interface{}) (*T, error) {
|
|
||||||
var (
|
|
||||||
model T
|
|
||||||
)
|
|
||||||
|
|
||||||
query, err := smartfilter.ToQuery(model, filter, m.DbConn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := query.First(&model)
|
|
||||||
if result.Error != nil {
|
|
||||||
return nil, result.Error
|
|
||||||
}
|
|
||||||
|
|
||||||
return &model, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ExistsMethod[T schema.Tabler] struct {
|
|
||||||
DbConn *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *ExistsMethod[T]) Init(dbConn *gorm.DB) {
|
|
||||||
m.DbConn = dbConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m ExistsMethod[T]) Exists(filter interface{}) (bool, error) {
|
|
||||||
var (
|
|
||||||
model T
|
|
||||||
)
|
|
||||||
|
|
||||||
query := m.DbConn.Model(model)
|
|
||||||
|
|
||||||
query, err := smartfilter.ToQuery(model, filter, query)
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := query.Select("*").First(&model)
|
|
||||||
|
|
||||||
exists := !errors.Is(result.Error, gorm.ErrRecordNotFound) && result.Error == nil
|
|
||||||
return exists, nil
|
|
||||||
}
|
|
||||||
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
|
||||||
|
}
|
||||||
@ -5,25 +5,55 @@ import (
|
|||||||
"gorm.io/gorm/schema"
|
"gorm.io/gorm/schema"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MethodInitInterface interface {
|
const DEFAULT_ID_FIELD = "id"
|
||||||
Init(dbConn *gorm.DB)
|
|
||||||
|
type MethodInitInterface[T schema.Tabler] interface {
|
||||||
|
Init(repo *RepoBase[T])
|
||||||
|
}
|
||||||
|
|
||||||
|
type RepoOptions struct {
|
||||||
|
IdField string
|
||||||
}
|
}
|
||||||
|
|
||||||
type RepoBase[T schema.Tabler] struct {
|
type RepoBase[T schema.Tabler] struct {
|
||||||
DbConn int
|
IdField string
|
||||||
|
dbConn *gorm.DB
|
||||||
|
|
||||||
ListMethod[T]
|
ListMethod[T]
|
||||||
GetMethod[T]
|
GetMethod[T]
|
||||||
ExistsMethod[T]
|
ExistsMethod[T]
|
||||||
methods []MethodInitInterface
|
CountMethod[T]
|
||||||
|
SaveMethod[T]
|
||||||
|
UpdateMethod[T]
|
||||||
|
DeleteMethod[T]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *RepoBase[T]) InitMethods(dbConn *gorm.DB) {
|
func (repo *RepoBase[T]) InitMethods(methods []MethodInitInterface[T]) {
|
||||||
for _, method := range b.methods {
|
for _, method := range methods {
|
||||||
method.Init(dbConn)
|
method.Init(repo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *RepoBase[T]) Init(dbConn *gorm.DB) {
|
func (m *RepoBase[T]) Init(dbConn *gorm.DB, options *RepoOptions) {
|
||||||
m.methods = []MethodInitInterface{&m.ListMethod, &m.GetMethod, &m.ExistsMethod}
|
m.dbConn = dbConn
|
||||||
m.InitMethods(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 {
|
||||||
@ -131,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())
|
||||||
}
|
}
|
||||||
@ -183,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 newSliceGetter(t)
|
return newSliceGetter(t)
|
||||||
// case reflect.Array:
|
case reflect.Array:
|
||||||
// return newArrayGetter(t)
|
if t == reflect.TypeOf(uuid.UUID{}) {
|
||||||
|
return uuidValueGetter
|
||||||
|
}
|
||||||
|
return newArrayGetter(t)
|
||||||
case reflect.Pointer:
|
case reflect.Pointer:
|
||||||
return newPtrValueGetter(t)
|
return newPtrValueGetter(t)
|
||||||
}
|
}
|
||||||
@ -246,6 +274,22 @@ func (sg sliceGetter) getValue(ff *FilterField, v reflect.Value) error {
|
|||||||
ff.appendFloat(element.Float())
|
ff.appendFloat(element.Float())
|
||||||
case reflect.String:
|
case reflect.String:
|
||||||
ff.appendStr(element.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
|
return nil
|
||||||
|
|||||||
@ -11,11 +11,16 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const TAG_NAME = "filterfield"
|
const TAG_NAME = "filterfield"
|
||||||
const TAG_PAIRS_SEPARATOR = ","
|
const TAG_PAIRS_SEPARATOR = ";"
|
||||||
|
const TAG_LIST_SEPARATOR = ","
|
||||||
const TAG_KEYVALUE_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,
|
||||||
@ -67,15 +72,20 @@ func getFilterFields(filter interface{}) []ReflectedStructField {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
func ToQuery(model schema.Tabler, filter interface{}, query *gorm.DB) (*gorm.DB, error) {
|
||||||
st := reflect.TypeOf(filter)
|
st := reflect.TypeOf(filter)
|
||||||
|
|
||||||
tableName := model.TableName()
|
tableName := model.TableName()
|
||||||
modelName := st.Name()
|
modelName := st.Name()
|
||||||
|
|
||||||
fmt.Printf("Table name: %s\n", tableName)
|
|
||||||
fmt.Printf("Model name: %s\n", modelName)
|
|
||||||
|
|
||||||
fields := getFilterFields(filter)
|
fields := getFilterFields(filter)
|
||||||
for _, field := range fields {
|
for _, field := range fields {
|
||||||
filterField, err := newFilterField(field.tagValue)
|
filterField, err := newFilterField(field.tagValue)
|
||||||
@ -97,22 +107,36 @@ func ToQuery(model schema.Tabler, filter interface{}, query *gorm.DB) (*gorm.DB,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// apply custom filters, if interface exists
|
||||||
|
queryApplier := getQueryApplierInterface(filter)
|
||||||
|
if queryApplier != nil {
|
||||||
|
query = queryApplier.ApplyQuery(query)
|
||||||
|
}
|
||||||
|
|
||||||
return query, nil
|
return query, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func splitTrim(value string, separator string) []string {
|
||||||
|
var out []string = []string{}
|
||||||
|
for _, s := range strings.Split(value, separator) {
|
||||||
|
if len(s) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, strings.TrimSpace(s))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
func newFilterField(tagValue string) (*FilterField, error) {
|
func newFilterField(tagValue string) (*FilterField, error) {
|
||||||
filterField := FilterField{}
|
filterField := FilterField{}
|
||||||
|
|
||||||
tagValue = strings.TrimSpace(tagValue)
|
for _, pair := range splitTrim(tagValue, TAG_PAIRS_SEPARATOR) {
|
||||||
pairs := strings.Split(tagValue, TAG_PAIRS_SEPARATOR)
|
kvs := splitTrim(pair, TAG_KEYVALUE_SEPARATOR)
|
||||||
|
|
||||||
for _, pair := range pairs {
|
|
||||||
kvs := strings.Split(pair, TAG_KEYVALUE_SEPARATOR)
|
|
||||||
if len(kvs) != 2 {
|
if len(kvs) != 2 {
|
||||||
return nil, fmt.Errorf("invalid tag value: %s", strings.TrimSpace(pair))
|
return nil, fmt.Errorf("invalid tag value: %s", strings.TrimSpace(pair))
|
||||||
}
|
}
|
||||||
key := strings.TrimSpace(kvs[0])
|
key := kvs[0]
|
||||||
value := strings.TrimSpace(kvs[1])
|
value := kvs[1]
|
||||||
|
|
||||||
switch key {
|
switch key {
|
||||||
case "field":
|
case "field":
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGetFilterFields(t *testing.T) {
|
func TestGetFilterFields(t *testing.T) {
|
||||||
@ -101,11 +102,11 @@ func TestGetFilterFields(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("Skip nil fields", func(t *testing.T) {
|
t.Run("Skip nil fields", func(t *testing.T) {
|
||||||
type TestFilter struct {
|
type TestFilter struct {
|
||||||
Alive *bool `filterfield:"alive,EQ"`
|
Alive *bool `filterfield:"alive;EQ"`
|
||||||
Id *int64 `filterfield:"id,EQ"`
|
Id *int64 `filterfield:"id;EQ"`
|
||||||
Ids *[]uint `filterfield:"id,IN"`
|
Ids *[]uint `filterfield:"id;IN"`
|
||||||
IdsNot *[]uint `filterfield:"id,NOT_IN"`
|
IdsNot *[]uint `filterfield:"id;NOT_IN"`
|
||||||
FirstName *string `filterfield:"first_name,EQ"`
|
FirstName *string `filterfield:"first_name;EQ"`
|
||||||
}
|
}
|
||||||
filter := TestFilter{}
|
filter := TestFilter{}
|
||||||
result := getFilterFields(filter)
|
result := getFilterFields(filter)
|
||||||
@ -119,7 +120,7 @@ func TestGetFilterFields(t *testing.T) {
|
|||||||
)
|
)
|
||||||
type TestFilter struct {
|
type TestFilter struct {
|
||||||
Alive *bool
|
Alive *bool
|
||||||
Id *int64 `funnytag:"created_at,LT"`
|
Id *int64 `funnytag:"created_at;LT"`
|
||||||
}
|
}
|
||||||
filter := TestFilter{
|
filter := TestFilter{
|
||||||
Alive: &alive,
|
Alive: &alive,
|
||||||
@ -140,7 +141,7 @@ func TestFilterField(t *testing.T) {
|
|||||||
testCases := []TagParseTestCase{
|
testCases := []TagParseTestCase{
|
||||||
{
|
{
|
||||||
name: "Parse without spaces",
|
name: "Parse without spaces",
|
||||||
tagValue: "field=field_1,operator=EQ",
|
tagValue: "field=field_1;operator=EQ",
|
||||||
expected: FilterField{
|
expected: FilterField{
|
||||||
Name: "field_1",
|
Name: "field_1",
|
||||||
Operator: OperatorEQ,
|
Operator: OperatorEQ,
|
||||||
@ -148,7 +149,7 @@ func TestFilterField(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Parse spaces between pairs",
|
name: "Parse spaces between pairs",
|
||||||
tagValue: " field=field_2 , operator=LT ",
|
tagValue: " field=field_2 ; operator=LT ",
|
||||||
expected: FilterField{
|
expected: FilterField{
|
||||||
Name: "field_2",
|
Name: "field_2",
|
||||||
Operator: OperatorLT,
|
Operator: OperatorLT,
|
||||||
@ -156,7 +157,7 @@ func TestFilterField(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Parse spaces between around keys and values",
|
name: "Parse spaces between around keys and values",
|
||||||
tagValue: "operator = LIKE , field = field_3",
|
tagValue: "operator = LIKE ; field = field_3",
|
||||||
expected: FilterField{
|
expected: FilterField{
|
||||||
Name: "field_3",
|
Name: "field_3",
|
||||||
Operator: OperatorLIKE,
|
Operator: OperatorLIKE,
|
||||||
@ -174,19 +175,19 @@ func TestFilterField(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
t.Run("Fail on invalid tag value", func(t *testing.T) {
|
t.Run("Fail on invalid tag value", func(t *testing.T) {
|
||||||
filterField, err := newFilterField("field=field_1=fail, operator=EQ")
|
filterField, err := newFilterField("field=field_1=fail; operator=EQ")
|
||||||
assert.Nil(t, filterField)
|
assert.Nil(t, filterField)
|
||||||
assert.EqualError(t, err, "invalid tag value: field=field_1=fail")
|
assert.EqualError(t, err, "invalid tag value: field=field_1=fail")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Fail on invalid operator", func(t *testing.T) {
|
t.Run("Fail on invalid operator", func(t *testing.T) {
|
||||||
filterField, err := newFilterField("field=field_1, operator=FAIL")
|
filterField, err := newFilterField("field=field_1; operator=FAIL")
|
||||||
assert.Nil(t, filterField)
|
assert.Nil(t, filterField)
|
||||||
assert.EqualError(t, err, "unknown operator: FAIL")
|
assert.EqualError(t, err, "unknown operator: FAIL")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Fail on invalid value key", func(t *testing.T) {
|
t.Run("Fail on invalid value key", func(t *testing.T) {
|
||||||
filterField, err := newFilterField("failkey=field_1, operator=FAIL")
|
filterField, err := newFilterField("failkey=field_1; operator=FAIL")
|
||||||
assert.Nil(t, filterField)
|
assert.Nil(t, filterField)
|
||||||
assert.EqualError(t, err, "invalid value key: failkey")
|
assert.EqualError(t, err, "invalid value key: failkey")
|
||||||
})
|
})
|
||||||
@ -203,3 +204,26 @@ func TestFilterField(t *testing.T) {
|
|||||||
assert.EqualError(t, err, "missing operator in tag: field=field_1")
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user