Compare commits
4 Commits
8c317fc3b6
...
main
Author | SHA1 | Date | |
---|---|---|---|
fe00943b01 | |||
20f6e45150 | |||
a2cb04fd09 | |||
006af98328 |
17
option.go
17
option.go
@@ -1,15 +1,26 @@
|
|||||||
package lite
|
package lite
|
||||||
|
|
||||||
type Option func(d *database)
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrBadFilename error = errors.New("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 {
|
func WithPath(path string) Option {
|
||||||
return func(d *database) {
|
return func(d *database) error {
|
||||||
d.path = path
|
d.path = path
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
15
sqlite.go
15
sqlite.go
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"path"
|
||||||
|
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
_ "github.com/ncruces/go-sqlite3/driver"
|
_ "github.com/ncruces/go-sqlite3/driver"
|
||||||
@@ -26,23 +26,22 @@ type Database interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func New(opts ...Option) (Database, error) {
|
func New(opts ...Option) (Database, error) {
|
||||||
home, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
defaultFile := "lite-db"
|
defaultFile := "lite-db"
|
||||||
|
|
||||||
db := &database{
|
db := &database{
|
||||||
file: defaultFile,
|
file: defaultFile,
|
||||||
path: home,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
opt(db)
|
opt(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
slite, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s/%s", db.path, 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
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user