adding in file path option #2

Merged
jake merged 2 commits from new/file-path into main 2025-09-08 21:05:10 +00:00
2 changed files with 29 additions and 3 deletions
Showing only changes of commit a2cb04fd09 - Show all commits

View File

@ -1,9 +1,28 @@
package lite package lite
type Option func(d *database) import (
"fmt"
)
var (
ErrBadFilename error = fmt.Errorf("database filename cannot be empty")
)
type Option func(d *database) error
func WithFile(name string) Option { func WithFile(name string) Option {
return func(d *database) { return func(d *database) error {
if name == "" {
return ErrBadFilename
}
d.file = name d.file = name
return nil
}
}
func WithPath(path string) Option {
return func(d *database) error {
d.path = path
return nil
} }
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"database/sql" "database/sql"
"fmt" "fmt"
"path"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
_ "github.com/ncruces/go-sqlite3/driver" _ "github.com/ncruces/go-sqlite3/driver"
@ -12,6 +13,7 @@ import (
type database struct { type database struct {
file string file string
path string
sqlite *sqlx.DB sqlite *sqlx.DB
} }
@ -34,7 +36,12 @@ func New(opts ...Option) (Database, error) {
opt(db) opt(db)
} }
slite, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s", db.file)) filePath := db.file
if db.path != "" {
filePath = path.Join(db.path, db.file)
}
slite, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s", filePath))
if err != nil { if err != nil {
return nil, err return nil, err
} }