adding better error handling around connections
This commit is contained in:
parent
960f858e77
commit
5e9ba524e9
23
sqlite.go
23
sqlite.go
@ -3,6 +3,7 @@ package lite
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
@ -11,6 +12,10 @@ import (
|
||||
_ "github.com/ncruces/go-sqlite3/embed"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotConnected = errors.New("the connect method must be called before any queries can be executed")
|
||||
)
|
||||
|
||||
type database struct {
|
||||
file string
|
||||
path string
|
||||
@ -22,7 +27,7 @@ type Database interface {
|
||||
Close() error
|
||||
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
Query(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)
|
||||
QueryRow(ctx context.Context, query string, args ...any) *sqlx.Row
|
||||
QueryRow(ctx context.Context, query string, args ...any) (*sqlx.Row, error)
|
||||
QueryIn(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)
|
||||
}
|
||||
|
||||
@ -65,21 +70,33 @@ func (d *database) Close() error {
|
||||
|
||||
// runs any updates, inserts, or any other queries that do not return rows
|
||||
func (d *database) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
if d.sqlite == nil {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
return d.sqlite.ExecContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// runs basic data queries
|
||||
func (d *database) Query(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) {
|
||||
if d.sqlite == nil {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
return d.sqlite.QueryxContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// retrieves a single row from database
|
||||
func (d *database) QueryRow(ctx context.Context, query string, args ...any) *sqlx.Row {
|
||||
return d.sqlite.QueryRowxContext(ctx, query, args...)
|
||||
func (d *database) QueryRow(ctx context.Context, query string, args ...any) (*sqlx.Row, error) {
|
||||
if d.sqlite == nil {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
return d.sqlite.QueryRowxContext(ctx, query, args...), nil
|
||||
}
|
||||
|
||||
// runs queries that require parameters in an IN clause
|
||||
func (d *database) QueryIn(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) {
|
||||
if d.sqlite == nil {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
q, ar, err := sqlx.In(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
Loading…
x
Reference in New Issue
Block a user