72 lines
2.3 KiB
Go
72 lines
2.3 KiB
Go
package examples
|
|
|
|
import (
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// LocationRepository contoh repository dengan soft delete
|
|
type LocationRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewLocationRepository(db *gorm.DB) *LocationRepository {
|
|
return &LocationRepository{db: db}
|
|
}
|
|
|
|
// Create - membuat location baru
|
|
func (r *LocationRepository) Create(location *entities.M_Location) error {
|
|
return r.db.Create(location).Error
|
|
}
|
|
|
|
// FindAll - mengambil semua location yang tidak dihapus (soft delete aware)
|
|
func (r *LocationRepository) FindAll() ([]entities.M_Location, error) {
|
|
var locations []entities.M_Location
|
|
// GORM otomatis akan mengabaikan record yang deleted_at != NULL
|
|
err := r.db.Find(&locations).Error
|
|
return locations, err
|
|
}
|
|
|
|
// FindByID - mencari location berdasarkan ID (soft delete aware)
|
|
func (r *LocationRepository) FindByID(id uuid.UUID) (*entities.M_Location, error) {
|
|
var location entities.M_Location
|
|
err := r.db.First(&location, "id = ?", id).Error
|
|
return &location, err
|
|
}
|
|
|
|
// Update - mengupdate location
|
|
func (r *LocationRepository) Update(location *entities.M_Location) error {
|
|
return r.db.Save(location).Error
|
|
}
|
|
|
|
// Delete - soft delete location
|
|
func (r *LocationRepository) Delete(id uuid.UUID) error {
|
|
// Ini akan melakukan soft delete (set deleted_at timestamp)
|
|
return r.db.Delete(&entities.M_Location{}, id).Error
|
|
}
|
|
|
|
// HardDelete - menghapus permanent dari database
|
|
func (r *LocationRepository) HardDelete(id uuid.UUID) error {
|
|
return r.db.Unscoped().Delete(&entities.M_Location{}, id).Error
|
|
}
|
|
|
|
// FindWithDeleted - mengambil semua location termasuk yang sudah dihapus
|
|
func (r *LocationRepository) FindWithDeleted() ([]entities.M_Location, error) {
|
|
var locations []entities.M_Location
|
|
err := r.db.Unscoped().Find(&locations).Error
|
|
return locations, err
|
|
}
|
|
|
|
// FindOnlyDeleted - mengambil hanya location yang sudah dihapus
|
|
func (r *LocationRepository) FindOnlyDeleted() ([]entities.M_Location, error) {
|
|
var locations []entities.M_Location
|
|
err := r.db.Unscoped().Where("deleted_at IS NOT NULL").Find(&locations).Error
|
|
return locations, err
|
|
}
|
|
|
|
// Restore - mengembalikan location yang sudah di soft delete
|
|
func (r *LocationRepository) Restore(id uuid.UUID) error {
|
|
return r.db.Unscoped().Model(&entities.M_Location{}).Where("id = ?", id).Update("deleted_at", nil).Error
|
|
}
|