commit f7a82ebbd4b679055e9651dc7f962dc16a788c62 Author: Adrian Zürcher Date: Fri Oct 24 14:36:26 2025 +0200 first commit diff --git a/dbHandler.go b/dbHandler.go new file mode 100644 index 0000000..c2c2c50 --- /dev/null +++ b/dbHandler.go @@ -0,0 +1,313 @@ +package AccessHandler + +import ( + "errors" + "fmt" + "path/filepath" + "reflect" + "strings" + + "gitea.tecamino.com/paadi/tecamino-logger/logging" + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +// DBHandler +// +// Description: +// +// Wraps the GORM database connection and provides helper methods for +// common CRUD operations, as well as integrated logging for traceability. +// +// Fields: +// - db: Active GORM database connection. +// - logger: Pointer to a custom logger instance for structured logging. +type DBHandler struct { + db *gorm.DB + logger *logging.Logger +} + +// NewDBHandler +// +// Description: +// +// Creates a new database handler using the specified SQLite database file. +// +// Behavior: +// 1. Opens a GORM connection to the database file at `dbPath`. +// 2. Wraps it in a `DBHandler` struct with logging support. +// +// Parameters: +// - dbPath: Path to the SQLite database file. +// - logger: Logging instance to record DB operations. +// +// Returns: +// - dH: A pointer to the initialized `DBHandler`. +// - err: Any error encountered during database connection. +func NewDBHandler(name, path string, logger *logging.Logger) (dH *DBHandler, err error) { + if logger == nil { + logger, err = logging.NewLogger(filepath.Join(path, name)+".log", nil) + if err != nil { + return + } + } + + dH = &DBHandler{logger: logger} + + if filepath.Ext(name) == "" { + name += ".db" + } + dbPath := filepath.Join(path, name) + logger.Debug("NewDBHandler", "open database "+dbPath) + dH.db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) + return +} + +// addNewTable +// +// Description: +// +// Uses GORM’s `AutoMigrate` to create or update the database schema +// for the provided model type. +// +// Parameters: +// - model: Struct type representing the database table schema. +// +// Returns: +// - error: Any migration error encountered. +func (dH *DBHandler) AddNewTable(model any) error { + return dH.db.AutoMigrate(&model) +} + +// addNewColum +// +// Description: +// +// Inserts a new record into the database table corresponding to `model`. +// +// Parameters: +// - model: Struct instance containing values to be inserted. +// +// Returns: +// - error: Any error encountered during record creation. +func (dH *DBHandler) AddNewColum(model any) error { + return dH.db.Create(model).Error +} + +// getById +// +// Description: +// +// Retrieves a record (or all records) from a table by numeric ID. +// +// Behavior: +// - If `id == 0`, returns all records in the table. +// - Otherwise, fetches the record matching the given ID. +// +// Parameters: +// - model: Pointer to a slice or struct to store the result. +// - id: Numeric ID to query by. +// +// Returns: +// - error: Any query error or “not found” message. +func (dH *DBHandler) GetById(model any, id uint) error { + dH.logger.Debug("getById", "find id "+fmt.Sprint(id)) + + if id == 0 { + return dH.db.Find(model).Error + } + + err := dH.db.First(model, id).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("no record found for id: %v", id) + } else if err != nil { + return fmt.Errorf("query failed: %w", err) + } + return nil +} + +// getByKey +// +// Description: +// +// Retrieves one or more records matching a key/value pair. +// +// Behavior: +// - If `LikeSearch` is true, performs a SQL LIKE query. +// - Otherwise, performs an exact match query. +// +// Parameters: +// - model: Pointer to a slice or struct to store results. +// - key: Column name (e.g., "email"). +// - value: Value to match or partially match. +// - LikeSearch: If true, replaces '*' with '%' for wildcard matching. +// +// Returns: +// - error: Any database query error. +func (dH *DBHandler) GetByKey(model any, key string, value any, LikeSearch bool) error { + if LikeSearch { + value = strings.ReplaceAll(fmt.Sprint(value), "*", "%") + dH.logger.Debug("getByKey", "find like key "+key+" value "+fmt.Sprint(value)) + return dH.db.Where(key+" LIKE ?", value).Find(model).Error + } + + dH.logger.Debug("getByKey", "find equal key "+key+" value "+fmt.Sprint(value)) + return dH.db.Find(model, key+" = ?", value).Error +} + +// updateValuesById +// +// Description: +// +// Updates record fields based on their unique ID. +// +// Behavior: +// 1. Confirms that `model` is a pointer to a struct. +// 2. Fetches the record by ID. +// 3. Updates all non-zero fields using `gorm.Model.Updates`. +// +// Parameters: +// - model: Pointer to struct containing new values. +// - id: Numeric ID of the record to update. +// +// Returns: +// - error: If the model is invalid or query/update fails. +func (dH *DBHandler) UpdateValuesById(model any, id uint) error { + dH.logger.Debug("updateValuesById", "model"+fmt.Sprint(model)) + modelType := reflect.TypeOf(model) + if modelType.Kind() != reflect.Ptr { + return errors.New("model must be a pointer to struct") + } + + lookUpModel := reflect.New(modelType.Elem()).Interface() + if err := dH.GetById(lookUpModel, id); err != nil { + return err + } + return dH.db.Model(lookUpModel).Updates(model).Error +} + +// updateValuesByKey +// +// Description: +// +// Updates records based on a key/value match. +// +// Behavior: +// 1. Confirms model type. +// 2. Fetches the matching record(s) using `getByKey`. +// 3. Updates all non-zero fields. +// +// Parameters: +// - model: Pointer to struct containing updated values. +// - key: Column name to filter by. +// - value: Value to match. +// +// Returns: +// - error: Any query or update error. +func (dH *DBHandler) UpdateValuesByKey(model any, key string, value any) error { + dH.logger.Debug("updateValuesByKey", "model"+fmt.Sprint(model)) + modelType := reflect.TypeOf(model) + if modelType.Kind() != reflect.Ptr { + return errors.New("model must be a pointer to struct") + } + + lookUpModel := reflect.New(modelType.Elem()).Interface() + if err := dH.GetByKey(lookUpModel, key, value, false); err != nil { + return err + } + return dH.db.Model(lookUpModel).Updates(model).Error +} + +// deleteById +// +// Description: +// +// Deletes records by their ID(s). +// +// Behavior: +// - If the first ID == 0, all records in the table are deleted. +// - Otherwise, deletes the provided IDs. +// +// Parameters: +// - model: Model struct type representing the table. +// - id: Variadic list of IDs to delete. +// +// Returns: +// - error: Any deletion error. +func (dH *DBHandler) DeleteById(model any, id ...uint) error { + if id[0] == 0 { + dH.logger.Debug("deleteById", "delete all") + return dH.db.Where("1 = 1").Delete(model).Error + } + + dH.logger.Debug("deleteById", "delete ids"+fmt.Sprint(id)) + if err := dH.Exists(model, "id", id, false); err != nil { + return err + } + return dH.db.Delete(model, id).Error +} + +// deleteByKey +// +// Description: +// +// Deletes records that match a key/value pair. +// +// Behavior: +// - Supports LIKE queries if `LikeSearch` is true. +// +// Parameters: +// - model: Model struct type representing the table. +// - key: Column name to filter by. +// - value: Value to match. +// - LikeSearch: Whether to use wildcard search. +// +// Returns: +// - error: Any deletion error. +func (dH *DBHandler) DeleteByKey(model any, key string, value any, LikeSearch bool) error { + if LikeSearch { + value = strings.ReplaceAll(fmt.Sprint(value), "*", "%") + dH.logger.Debug("deleteByKey", "delete like key "+key+" value "+fmt.Sprint(value)) + return dH.db.Where(key+" LIKE ?", value).Delete(model).Error + } + + dH.logger.Debug("deleteByKey", "delete equal key "+key+" value "+fmt.Sprint(value)) + return dH.db.Where(key+" = ?", value).Delete(model).Error +} + +// exists +// +// Description: +// +// Checks whether a record exists matching the specified key/value filter. +// +// Behavior: +// - Performs a `First` query on the database. +// - If `LikeSearch` is true, performs a LIKE query. +// - Returns an error if the record does not exist or query fails. +// +// Parameters: +// - model: Model struct type to search. +// - key: Column name to filter by. +// - value: Value to match. +// - LikeSearch: Whether to use wildcard search. +// +// Returns: +// - error: “no record found” or DB error. +func (dH *DBHandler) Exists(model any, key string, value any, LikeSearch bool) (err error) { + if LikeSearch { + value = strings.ReplaceAll(fmt.Sprint(value), "*", "%") + key = key + " LIKE ?" + } else { + key = key + " = ?" + } + + dH.logger.Debug("exists", "check if exists key "+key+" value "+fmt.Sprint(value)) + err = dH.db.Where(key, value).First(model).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return fmt.Errorf("no record found for %s %v", key[:len(key)-1], value) + } else if err != nil { + return fmt.Errorf("query failed: %w", err) + } + return +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2204b29 --- /dev/null +++ b/go.mod @@ -0,0 +1,28 @@ +module gitea.tecamino.com/paadi/dbHandler + +go 1.24.5 + +require ( + gitea.tecamino.com/paadi/tecamino-logger v0.2.1 + github.com/glebarez/sqlite v1.11.0 + gorm.io/gorm v1.31.0 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/glebarez/go-sqlite v1.21.2 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + go.uber.org/multierr v1.10.0 // indirect + go.uber.org/zap v1.27.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.20.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect + modernc.org/libc v1.22.5 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/sqlite v1.23.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..539ce33 --- /dev/null +++ b/go.sum @@ -0,0 +1,52 @@ +gitea.tecamino.com/paadi/tecamino-logger v0.2.1 h1:sQTBKYPdzn9mmWX2JXZBtGBvNQH7cuXIwsl4TD0aMgE= +gitea.tecamino.com/paadi/tecamino-logger v0.2.1/go.mod h1:FkzRTldUBBOd/iy2upycArDftSZ5trbsX5Ira5OzJgM= +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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= +github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= +github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= +github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +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/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= +golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/gorm v1.31.0 h1:0VlycGreVhK7RF/Bwt51Fk8v0xLiiiFdbGDPIZQ7mJY= +gorm.io/gorm v1.31.0/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= +modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM= +modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=