Compare commits
7 Commits
Author | SHA1 | Date | |
---|---|---|---|
fe00943b01 | |||
20f6e45150 | |||
a2cb04fd09 | |||
006af98328 | |||
8c317fc3b6 | |||
efc047c965 | |||
5e9ba524e9 |
17
option.go
17
option.go
@@ -1,15 +1,26 @@
|
||||
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 {
|
||||
return func(d *database) {
|
||||
return func(d *database) error {
|
||||
if name == "" {
|
||||
return ErrBadFilename
|
||||
}
|
||||
d.file = name
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithPath(path string) Option {
|
||||
return func(d *database) {
|
||||
return func(d *database) error {
|
||||
d.path = path
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
28
sqlite.go
28
sqlite.go
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/ncruces/go-sqlite3/driver"
|
||||
@@ -18,7 +18,6 @@ type database struct {
|
||||
}
|
||||
|
||||
type Database interface {
|
||||
Connect() error
|
||||
Close() error
|
||||
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
Query(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)
|
||||
@@ -27,35 +26,28 @@ type Database interface {
|
||||
}
|
||||
|
||||
func New(opts ...Option) (Database, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defaultFile := "lite-db"
|
||||
|
||||
db := &database{
|
||||
file: defaultFile,
|
||||
path: home,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(db)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// connects to database file
|
||||
func (d *database) Connect() error {
|
||||
db, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s/%s", d.path, d.file))
|
||||
if err != nil {
|
||||
return err
|
||||
filePath := db.file
|
||||
if db.path != "" {
|
||||
filePath = path.Join(db.path, db.file)
|
||||
}
|
||||
|
||||
d.sqlite = db
|
||||
slite, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s", filePath))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.sqlite = slite
|
||||
|
||||
return nil
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// closes database file connection
|
||||
|
Reference in New Issue
Block a user