99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
. "github.com/go-jet/jet/v2/postgres"
|
|
"log"
|
|
"screenmark/screenmark/.gen/haystack/haystack/model"
|
|
. "screenmark/screenmark/.gen/haystack/haystack/table"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type LocationModel struct {
|
|
dbPool *sql.DB
|
|
}
|
|
|
|
// This looks stupid
|
|
func getValues(location model.Locations) []any {
|
|
arr := make([]any, 0)
|
|
|
|
if location.Address != nil {
|
|
arr = append(arr, *location.Address)
|
|
} else {
|
|
arr = append(arr, nil)
|
|
}
|
|
|
|
if location.Coordinates != nil {
|
|
arr = append(arr, *location.Coordinates)
|
|
} else {
|
|
arr = append(arr, nil)
|
|
}
|
|
|
|
if location.Description != nil {
|
|
arr = append(arr, *location.Description)
|
|
} else {
|
|
arr = append(arr, nil)
|
|
}
|
|
|
|
return arr
|
|
}
|
|
|
|
func (m LocationModel) List(ctx context.Context, userId uuid.UUID) ([]model.Locations, error) {
|
|
listLocationsStmt := SELECT(Locations.AllColumns, ImageLocations.AllColumns, UserImages.AllColumns).
|
|
FROM(
|
|
Locations.
|
|
INNER_JOIN(ImageLocations, ImageLocations.LocationID.EQ(Locations.ID)).
|
|
INNER_JOIN(UserImages, UserImages.ImageID.EQ(ImageLocations.ImageID)),
|
|
).WHERE(UserImages.UserID.EQ(UUID(userId)))
|
|
|
|
locations := []model.Locations{}
|
|
|
|
err := listLocationsStmt.QueryContext(ctx, m.dbPool, &locations)
|
|
|
|
return locations, err
|
|
}
|
|
|
|
func (m LocationModel) Save(ctx context.Context, locations []model.Locations) (model.Locations, error) {
|
|
insertLocationStmt := Locations.
|
|
INSERT(Locations.Name, Locations.Address, Locations.Coordinates, Locations.Description)
|
|
|
|
for _, location := range locations {
|
|
insertLocationStmt = insertLocationStmt.VALUES(location.Name, getValues(location)...)
|
|
}
|
|
|
|
insertLocationStmt = insertLocationStmt.RETURNING(Locations.AllColumns)
|
|
|
|
log.Println(insertLocationStmt.DebugSql())
|
|
|
|
insertedLocation := model.Locations{}
|
|
err := insertLocationStmt.QueryContext(ctx, m.dbPool, &insertedLocation)
|
|
|
|
return insertedLocation, err
|
|
}
|
|
|
|
func (m LocationModel) SaveToImage(ctx context.Context, imageId uuid.UUID, locations []model.Locations) error {
|
|
if len(locations) == 0 {
|
|
return nil
|
|
}
|
|
|
|
location, err := m.Save(ctx, locations)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
insertImageLocationStmt := ImageLocations.
|
|
INSERT(ImageLocations.ImageID, ImageLocations.LocationID).
|
|
VALUES(imageId, location.ID)
|
|
|
|
_, err = insertImageLocationStmt.ExecContext(ctx, m.dbPool)
|
|
|
|
return err
|
|
}
|
|
|
|
func NewLocationModel(db *sql.DB) LocationModel {
|
|
return LocationModel{dbPool: db}
|
|
}
|