1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package db
- import (
- "database/sql"
- "fmt"
- "reflect"
- _ "github.com/mattn/go-sqlite3"
- )
- var Conn *sql.DB
- func Connect(fp string) error {
- var err error
- Conn, err = sql.Open("sqlite3", fp)
- if err != nil {
- fmt.Println("db.Connect() Error connecting to database")
- return err
- }
- Conn.Exec(`
- PRAGMA journal_mode=ON
- PRAGMA journal_mode=WAL;
- PRAGMA synchronous=ON
- PRAGMA auto_vacuum=ON
- PRAGMA foreign_keys=ON
- `)
- return nil
- }
- // Pass fields struct as a pointer
- func Get(fieldsPtr interface{}, query string, vals []any) {
- err := Conn.QueryRow(query, vals...).Scan(StructPointers(fieldsPtr)...)
- if err != nil {
- fmt.Printf("ERROR: %s\n", err)
- return
- }
- }
- func All(sliceInt interface{}, query string, vals []any) {
- slicePtr := reflect.ValueOf(sliceInt)
- sliceVal := slicePtr.Elem()
- modelType := sliceVal.Type().Elem()
- rows, _ := Conn.Query(query, vals...)
- var set []reflect.Value
- for rows.Next() {
- tmpModel := reflect.New(modelType)
- rows.Scan(StructPointers(tmpModel.Interface())...)
- set = append(set, tmpModel.Elem())
- }
- rows.Close()
- newSlice := reflect.Append(sliceVal, set...)
- sliceVal.Set(newSlice)
- }
- func Close() {
- Conn.Close()
- }
|