initial commit

This commit is contained in:
2023-03-19 22:13:49 -04:00
commit 717c9e08d6
12 changed files with 367 additions and 0 deletions

39
sql/client.go Normal file
View File

@@ -0,0 +1,39 @@
package sql
import (
"context"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
type SqlDb struct {
db *sql.DB
created bool
}
var dbConnection SqlDb
func NewDb(file string) (*SqlDb, error) {
if dbConnection.created {
return &dbConnection, nil
}
db, err := sql.Open("sqlite3", file)
if err != nil {
return nil, err
}
dbConnection.db = db
dbConnection.created = true
_, err = dbConnection.db.Conn(context.Background())
if err != nil {
return nil, err
}
return &dbConnection, nil
}
func GetDb() *SqlDb {
return &dbConnection
}

70
sql/guns.go Normal file
View File

@@ -0,0 +1,70 @@
package sql
import (
"database/sql"
"log"
)
func (dbClient *SqlDb) AllGuns() []Gun {
var guns []Gun
rows, _ := dbClient.db.Query("select guns.*, p.id, p.gun_id, p.filename from guns join photos p on guns.id = p.gun_id order by guns.id")
defer func(rows *sql.Rows) {
_ = rows.Close()
}(rows)
for rows.Next() {
i := Gun{}
p := Photo{}
err := rows.Scan(
&i.Id,
&i.Make,
&i.Model,
&i.SerialNumber,
&i.PurchaseAmount,
&i.ValueAmount,
&i.DatePurchased,
&i.Notes,
&p.Id,
&p.GunId,
&p.FileName,
)
if err != nil {
log.Fatal(err)
}
index := -1
for gunIndex, gun := range guns {
if gun.Id == i.Id {
index = gunIndex
continue
}
index = -1
}
if index == -1 {
guns = append(guns, i)
index = len(guns) - 1
}
guns[index].Photos = append(guns[index].Photos, p)
}
return guns
}
func (dbClient *SqlDb) GunById(id uint) (*Gun, error) {
var gun Gun
row, _ := dbClient.db.Query("select guns.*, p.id, p.gun_id, p.filename from guns join photos p on guns.id = p.gun_id where guns.id = ?", id)
err := row.Scan(gun)
if err != nil {
return nil, err
}
return &gun, nil
}

14
sql/photos.go Normal file
View File

@@ -0,0 +1,14 @@
package sql
func (dbClient *SqlDb) GetPhoto(id uint) string {
var photo string
row := dbClient.db.QueryRow("SELECT photo from photos where id = ?", id)
err := row.Scan(&photo)
if err != nil {
panic(err)
}
return photo
}

22
sql/types.go Normal file
View File

@@ -0,0 +1,22 @@
package sql
import "database/sql"
type Gun struct {
Id uint `json:"id"`
Make string `json:"make"`
Model string `json:"model"`
SerialNumber string `json:"serial_number"`
PurchaseAmount uint `json:"purchase_amount"`
ValueAmount uint `json:"value_amount"`
DatePurchased sql.NullString `json:"date_purchased"`
Notes sql.NullString `json:"notes"`
Photos []Photo `json:"photos"`
}
type Photo struct {
Id uint `json:"id"`
GunId uint `json:"gun_id"`
Photo string `json:"photo"`
FileName string `json:"file_name"`
}