finish setup insert method, refactor sql migration file
This commit is contained in:
@@ -1,5 +1,12 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Media struct {
|
||||
ID uint
|
||||
|
||||
@@ -7,3 +14,40 @@ type Media struct {
|
||||
URL string
|
||||
Caption string
|
||||
}
|
||||
|
||||
func (m *Media) Query(data *InsertId[string]) {
|
||||
data.query = fmt.Sprintf(`
|
||||
INSERT INTO media (%s, type, url, caption)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id`, data.fieldName)
|
||||
}
|
||||
|
||||
func (m *Media) Insert(tx *sqlx.Tx, data *InsertId[string]) error {
|
||||
if data.query == "" {
|
||||
return ErrNoQuery
|
||||
}
|
||||
|
||||
args := []any{data.id, m.Type, m.URL, m.Caption}
|
||||
|
||||
err := tx.QueryRow(data.query, args...).Scan(&m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Media) InsertCtx(ctx context.Context, tx *sqlx.Tx, data *InsertId[string]) error {
|
||||
if data.query == "" {
|
||||
return ErrNoQuery
|
||||
}
|
||||
|
||||
args := []any{data.id, m.Type, m.URL, m.Caption}
|
||||
|
||||
err := tx.QueryRowContext(ctx, data.query, args...).Scan(&m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user