hiling_go/db/sqlc/images.go

100 lines
2.1 KiB
Go

package db
import (
"context"
"strings"
"time"
"git.nochill.in/nochill/hiling_go/util"
)
type GetImagesByLocationParams struct {
Limit int32
Offset int32
LocationId int32
}
type GetImagesByLocationRow struct {
ID int32 `json:"id"`
Src string `json:"src"`
CreatedAt time.Time `json:"created_at"`
UploadedBy string `json:"uploaded_by"`
}
const getImagesByLocationQ = `
SELECT
i.id,
i.image_url as src,
i.created_at,
u.username as uploaded_by
FROM images i
JOIN users u on i.uploaded_by = u.id
WHERE i.image_type = 'locations' AND image_of = $1
LIMIT $2
OFFSET $3
`
func (q *Queries) GetImagesByLocation(ctx context.Context, arg GetImagesByLocationParams) ([]GetImagesByLocationRow, error) {
rows, err := q.db.QueryContext(ctx, getImagesByLocationQ, arg.LocationId, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
items := []GetImagesByLocationRow{}
for rows.Next() {
var i GetImagesByLocationRow
if err := rows.Scan(
&i.ID,
&i.Src,
&i.CreatedAt,
&i.UploadedBy,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
type CreateImageParams struct {
ImageUrl string `json:"url"`
UploadedBy int32 `json:"uploaded_by"`
ImageType string `json:"image_type"`
ImageOf int32 `json:"image_of"`
}
func (q *Queries) CreateImage(ctx context.Context, arg []CreateImageParams) error {
values := []interface{}{}
queryStr := ` INSERT INTO
images(image_url, uploaded_by, image_type, image_of)
VALUES
`
for _, row := range arg {
queryStr += "(?, ?, ?, ?),"
values = append(values, row.ImageUrl, row.UploadedBy, row.ImageType, row.ImageOf)
}
queryStr = strings.TrimSuffix(queryStr, ",")
// Replacing ? with $n for postgres
queryStr = util.ReplaceSQL(queryStr, "?")
// prepare the statement
stmt, _ := q.db.PrepareContext(ctx, queryStr)
// format all vals at once
_, err := stmt.ExecContext(ctx, values...)
return err
}