feat: started working on the head part of the split models
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -183,14 +184,64 @@ func MyParseForm(r *http.Request) (vs url.Values, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type JustId struct { Id string }
|
||||
|
||||
type Generic struct{ reflect.Type }
|
||||
|
||||
var NotFoundError = errors.New("Not found")
|
||||
|
||||
func GetDbMultitple[T interface{}](c *Context, tablename string, args ...any) ([]*T, error) {
|
||||
t := reflect.TypeFor[T]()
|
||||
nargs := t.NumField()
|
||||
|
||||
query := ""
|
||||
|
||||
for i := 0; i < nargs; i += 1 {
|
||||
query += strings.ToLower(t.Field(i).Name) + ","
|
||||
}
|
||||
|
||||
// Remove the last comma
|
||||
query = query[0 : len(query)-1]
|
||||
|
||||
rows, err := c.Db.Query(fmt.Sprintf("select %s from %s", query, tablename), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
list := []*T{}
|
||||
|
||||
for rows.Next() {
|
||||
item := new(T)
|
||||
if err = mapRow(item, rows, nargs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list = append(list, item)
|
||||
}
|
||||
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func mapRow(store interface{}, rows *sql.Rows, nargs int) (err error) {
|
||||
err = nil
|
||||
|
||||
val := reflect.Indirect(reflect.ValueOf(store))
|
||||
scan_args := make([]interface{}, nargs);
|
||||
for i := 0; i < nargs; i++ {
|
||||
valueField := val.Field(i)
|
||||
scan_args[i] = valueField.Addr().Interface()
|
||||
}
|
||||
|
||||
err = rows.Scan(scan_args...)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetDBOnce(c *Context, store interface{}, tablename string, args ...any) error {
|
||||
|
||||
t := reflect.TypeOf(store).Elem()
|
||||
|
||||
nargs := t.NumField()
|
||||
|
||||
query := ""
|
||||
@@ -199,10 +250,10 @@ func GetDBOnce(c *Context, store interface{}, tablename string, args ...any) err
|
||||
query += strings.ToLower(t.Field(i).Name) + ","
|
||||
}
|
||||
|
||||
// Remove the last comma
|
||||
query = query[0 : len(query)-1]
|
||||
|
||||
rows, err := c.Db.Query(fmt.Sprintf("select %s from %s", query, tablename), args...)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -212,6 +263,7 @@ func GetDBOnce(c *Context, store interface{}, tablename string, args ...any) err
|
||||
return NotFoundError
|
||||
}
|
||||
|
||||
err = nil
|
||||
|
||||
val := reflect.ValueOf(store).Elem()
|
||||
scan_args := make([]interface{}, nargs);
|
||||
@@ -227,3 +279,4 @@ func GetDBOnce(c *Context, store interface{}, tablename string, args ...any) err
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user