75 lines
1.5 KiB
Go
75 lines
1.5 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
"golang.org/x/sync/errgroup"
|
|
)
|
|
|
|
type Item struct {
|
|
ID string
|
|
|
|
Img string
|
|
Name string
|
|
Type string
|
|
Folder string
|
|
Sort int
|
|
Stats Stats
|
|
Ownership []OwnershipString
|
|
}
|
|
|
|
func (i *Item) Query(data *InsertId[uint]) {
|
|
data.query = fmt.Sprintf(`
|
|
INSERT INTO world_folder (%s, id, img, name, type, folder, sort)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
RETURNING id`, data.fieldName)
|
|
}
|
|
|
|
func (i *Item) InsertObjects(tx *sqlx.Tx) error {
|
|
group, ctx := errgroup.WithContext(context.Background())
|
|
|
|
relId := InsertId[string]{id: i.ID, fieldName: "item_id"}
|
|
InsertWithCtxParallel(group, ctx, tx, i.Stats, relId)
|
|
InsertSliceParallel(group, tx, i.Ownership, relId)
|
|
|
|
err := group.Wait()
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (i *Item) Insert(tx *sqlx.Tx, data *InsertId[uint]) error {
|
|
if data.query == "" {
|
|
return ErrNoQuery
|
|
}
|
|
|
|
args := []any{data.id, i.ID, i.Img, i.Name, i.Type, i.Folder, i.Sort}
|
|
|
|
_, err := tx.Exec(data.query, args...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return i.InsertObjects(tx)
|
|
}
|
|
|
|
func (i *Item) InsertCtx(ctx context.Context, tx *sqlx.Tx, data *InsertId[uint]) error {
|
|
if data.query == "" {
|
|
return ErrNoQuery
|
|
}
|
|
|
|
args := []any{data.id, i.ID, i.Img, i.Name, i.Type, i.Folder, i.Sort}
|
|
|
|
_, err := tx.ExecContext(ctx, data.query, args...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return i.InsertObjects(tx)
|
|
}
|