75 lines
1.3 KiB
Go
75 lines
1.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
type baseRepository[T any] struct {
|
|
db *sql.DB
|
|
tableName string
|
|
}
|
|
|
|
func NewBaseRepository[T any](db *sql.DB, tableName string) *baseRepository[T] {
|
|
return &baseRepository[T]{
|
|
db: db,
|
|
tableName: tableName,
|
|
}
|
|
}
|
|
|
|
func (r *baseRepository[T]) BuildQuery(baseQuery string) string {
|
|
return fmt.Sprintf(baseQuery, r.tableName)
|
|
}
|
|
|
|
func (r *baseRepository[T]) GetDB() *sql.DB {
|
|
return r.db
|
|
}
|
|
|
|
func (r *baseRepository[T]) GetAll() ([]T, error) {
|
|
query := r.BuildQuery("SELECT * FROM %s ORDER BY id DESC")
|
|
|
|
rows, err := r.db.Query(query)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
entities := make([]T, 0)
|
|
rowsErr := ScanRows(rows, &entities)
|
|
|
|
if rowsErr != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return entities, nil
|
|
}
|
|
|
|
func (r *baseRepository[T]) GetByID(id int) (*T, error) {
|
|
var entity T
|
|
|
|
query := r.BuildQuery("SELECT * FROM %s WHERE id = ?")
|
|
row := r.db.QueryRow(
|
|
query,
|
|
id,
|
|
)
|
|
err := scanRow(row, &entity)
|
|
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
return &entity, nil
|
|
}
|
|
|
|
func (r *baseRepository[T]) Delete(id int) (int64, error) {
|
|
query := r.BuildQuery("DELETE FROM %s WHERE id = ?")
|
|
res, err := r.db.Exec(query, id)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return res.RowsAffected()
|
|
}
|