From f7cc7d93ace61115248761dcafd938f0cadee68e Mon Sep 17 00:00:00 2001 From: Physcik Date: Sun, 30 Nov 2025 00:10:40 +0500 Subject: The diff query generator --- DAL/DB/CRUD.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'DAL/DB/CRUD.go') diff --git a/DAL/DB/CRUD.go b/DAL/DB/CRUD.go index b466d3c..52268df 100644 --- a/DAL/DB/CRUD.go +++ b/DAL/DB/CRUD.go @@ -10,6 +10,21 @@ type DataTable[T any] struct { TableName string } +func (base *DataTable[T]) GetSimilarFieldsQuery(ref T, fields []string) (string, error) { + var structFields = base.getFieldsMap() + var value = reflect.ValueOf(ref) + var filterMap = make(map[string]any) + for _, v := range fields { + var fieldIndex, exists = structFields[v] + if !exists { + return "", fmt.Errorf("Failed to create a query for the object: there is no such field as %s in %s", v, reflect.TypeFor[T]().Name()) + } + filterMap[v] = value.Field(fieldIndex).Interface() + } + fmt.Println(filterMap) + return base.formQueryWithFilters(filterMap), nil +} + // Filters are stored as KVP where the field is the key and the value is the filter func (base *DataTable[T]) formQueryWithFilters(filters map[string]any) string { if len(filters) == 0 { @@ -67,3 +82,17 @@ func (base *DataTable[T]) getFields() []string { } return outp } + +func (base *DataTable[T]) getFieldsMap() map[string]int { + var zero T + var outp = make(map[string]int) + for i, f := range reflect.VisibleFields(reflect.TypeOf(zero)) { + var tag, exists = f.Tag.Lookup("sql") + if exists { + outp[tag] = i + } else { + outp[f.Name] = i + } + } + return outp +} -- cgit v1.3