70 lines
2.0 KiB
Go
70 lines
2.0 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"bunker/client/internal/services/core"
|
|
)
|
|
|
|
// Exec is a proxy for ExecContext from sqlx.
|
|
func (d *database) Exec(ctx context.Context, query string, params ...interface{}) error {
|
|
if strings.Contains(query, "?") {
|
|
query = d.db.Rebind(query)
|
|
}
|
|
|
|
d.logger.Debug("Executing query.", "query", query, "params", fmt.Sprintf("%+v", params))
|
|
|
|
if _, err := d.db.ExecContext(ctx, query, params...); err != nil {
|
|
return fmt.Errorf("%w: failed to Exec(): %w", core.ErrDatabase, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Get is a proxy for GetContext from sqlx.
|
|
func (d *database) Get(ctx context.Context, target interface{}, query string, params ...interface{}) error {
|
|
if strings.Contains(query, "?") {
|
|
query = d.db.Rebind(query)
|
|
}
|
|
|
|
d.logger.Debug("Getting single data from database with query.", "query", query, "params", fmt.Sprintf("%+v", params))
|
|
|
|
if err := d.db.GetContext(ctx, target, query, params...); err != nil {
|
|
return fmt.Errorf("%w: failed to Get(): %w", core.ErrDatabase, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// NamedExec is a proxy for NamedExecContext from sqlx.
|
|
func (d *database) NamedExec(ctx context.Context, query string, param interface{}) error {
|
|
if strings.Contains(query, "?") {
|
|
query = d.db.Rebind(query)
|
|
}
|
|
|
|
d.logger.Debug("Executing named query.", "query", query, "params", fmt.Sprintf("%+v", param))
|
|
|
|
if _, err := d.db.NamedExecContext(ctx, query, param); err != nil {
|
|
return fmt.Errorf("%w: failed to NamedExec(): %w", core.ErrDatabase, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Select is a proxy for SelectContext from sqlx.
|
|
func (d *database) Select(ctx context.Context, target interface{}, query string, params ...interface{}) error {
|
|
if strings.Contains(query, "?") {
|
|
query = d.db.Rebind(query)
|
|
}
|
|
|
|
d.logger.Debug("Selecting from database with query.", "query", query, "params", fmt.Sprintf("%+v", params))
|
|
|
|
if err := d.db.SelectContext(ctx, target, query, params...); err != nil {
|
|
return fmt.Errorf("%w: failed to Select(): %w", core.ErrDatabase, err)
|
|
}
|
|
|
|
return nil
|
|
}
|