package dbconnection import ( "context" "database/sql" "log" "strconv" ) type SQLiteRepository struct { db *sql.DB } func NewSQLiteRepository(db *sql.DB) *SQLiteRepository { return &SQLiteRepository{ db: db, } } func (r *SQLiteRepository) All() ([]Menu, error) { rows, err := r.db.Query("SELECT _id, short, hash, name, meat, mealtype FROM menu") if err != nil { return nil, err } defer rows.Close() var all []Menu for rows.Next() { var menu Menu if err := rows.Scan(&menu._ID, &menu.Short, &menu.Hash, &menu.Name, &menu.Meat, &menu.Mealtype); err != nil { return nil, err } all = append(all, menu) } return all, nil } func (r *SQLiteRepository) GetOneShort(ShortCode string) (Menu, error) { rows, err := r.db.Query("select md from menu where short = ?", ShortCode) var empty Menu if err != nil { return empty, err } defer rows.Close() var item Menu for rows.Next() { var menu Menu if err := rows.Scan(&menu.Md); err != nil { return empty, err } item = menu } return item, nil } func (r *SQLiteRepository) GetOneHash(Hash string) (Menu, error) { log.Printf("Get one hash: %s\n", Hash) rows, err := r.db.Query("select * from menu where hash = ?", Hash) var empty Menu if err != nil { log.Println("GetOneHash query error") return empty, err } defer rows.Close() var item Menu for rows.Next() { var menu Menu if err := rows.Scan(&menu._ID, &menu.Name, &menu.Url, &menu.Md, &menu.Short, &menu.Hash, &menu.Meat, &menu.Mealtype, &menu.Lastused); err != nil { return empty, err } item = menu } log.Printf("%+v\n", item) return item, nil } func (r *SQLiteRepository) InsertOne(newitem MenuStrings) (InsertedType, error) { log.Printf("Insert One: %s\n", newitem) stmt, err := r.db.Prepare("INSERT INTO menu(name, url, md, short, hash, meat, mealtype, lastused) VALUES (?,?,?,?,?,?,?,?)") if err != nil { log.Fatal(err) } defer stmt.Close() meat, _ := strconv.ParseInt(newitem.Meat, 10, 64) mealtype, _ := strconv.ParseInt(newitem.Meat, 10, 64) lastused, _ := strconv.ParseInt(newitem.Meat, 10, 64) b, err := stmt.Exec(newitem.Name, newitem.Url, newitem.Md, newitem.Short, newitem.Hash, meat, mealtype, lastused) if err != nil { log.Println(err) } var returnVal InsertedType lastID, err := b.LastInsertId() if err == nil { returnVal = InsertedType{ Msg: "Row inserted", _ID: strconv.FormatInt(lastID, 10), } log.Printf("B:%+v\n", b) } return returnVal, err } func (r *SQLiteRepository) GetRandom(timestamp int64) ([]Menu, error) { ts := strconv.FormatInt(timestamp, 10) rows, err := r.db.Query("SELECT _id, short, hash, name, meat, mealtype FROM menu where mealtype =1 and lastused