db.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package db
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "reflect"
  6. _ "github.com/mattn/go-sqlite3"
  7. )
  8. var Conn *sql.DB
  9. func Connect(fp string) error {
  10. var err error
  11. Conn, err = sql.Open("sqlite3", fp)
  12. if err != nil {
  13. fmt.Println("db.Connect() Error connecting to database")
  14. return err
  15. }
  16. Conn.Exec(`
  17. PRAGMA journal_mode=ON
  18. PRAGMA journal_mode=WAL;
  19. PRAGMA synchronous=ON
  20. PRAGMA auto_vacuum=ON
  21. PRAGMA foreign_keys=ON
  22. `)
  23. return nil
  24. }
  25. // Pass fields struct as a pointer
  26. func Get(fieldsPtr interface{}, query string, vals []any) {
  27. err := Conn.QueryRow(query, vals...).Scan(StructPointers(fieldsPtr)...)
  28. if err != nil {
  29. fmt.Printf("ERROR: %s\n", err)
  30. return
  31. }
  32. }
  33. func All(sliceInt interface{}, query string, vals []any) {
  34. slicePtr := reflect.ValueOf(sliceInt)
  35. sliceVal := slicePtr.Elem()
  36. modelType := sliceVal.Type().Elem()
  37. rows, _ := Conn.Query(query, vals...)
  38. var set []reflect.Value
  39. for rows.Next() {
  40. tmpModel := reflect.New(modelType)
  41. rows.Scan(StructPointers(tmpModel.Interface())...)
  42. set = append(set, tmpModel.Elem())
  43. }
  44. rows.Close()
  45. newSlice := reflect.Append(sliceVal, set...)
  46. sliceVal.Set(newSlice)
  47. }
  48. func Close() {
  49. Conn.Close()
  50. }