lazydb

package module
v0.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 30, 2025 License: MIT Imports: 15 Imported by: 0

README

LazyDB

Go Reference GitHub Release Go Report Card

Go SQLite collection for lazy people.

Include these feature:

  • Create SQLite database file
  • Migration with fs.fs
  • Auto Backup when migration
  • Manual backup by call function

Note: You must has CGO enabled to compile this project.

Get Started

Run this command:

go get github.com/dark-person/lazydb

An example to use this package as:

import (
    "embed"
    "fmt"

    "github.com/dark-person/lazydb"
)

//go:embed all:schema
var schema embed.FS

func main() {
    var err error

    // Init db
    db := lazydb.New(
        lazydb.DbPath("path/data.db"),    // Database path
        lazydb.Migrate(schema, "schema"), // Migration schema location
        lazydb.BackupDir("./backup"),     // Set auto backup directory
        lazydb.Version(2),                // Specify Version
    )

    // Connect to db, which will create file if necessary
    err = db.Connect()
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Force Backup
    err = db.BackupTo("somewhere/backup.db")
    if err != nil {
        panic(err)
    }

    // Migration performed
    backup, err := db.Migrate()
    if err != nil {
        panic(err)
    }

    if backup != "" {
        fmt.Println("Auto backup as migration performed: " + backup)
    }

    // Optional: Ensure connection is success
    if !db.Connected() {
        fmt.Println("Database is not connected")
    }

    // Usage here...
}

Documentation

Index

Constants

View Source
const DatabaseType = "sqlite3"

Database driver type. Only support sqlite3.

Variables

View Source
var Dir = "schema"

Default folder path that store schema migration script in embed.FS.

View Source
var ErrEmptyDir = errors.New("empty string for migration directory")

Error when migration directory is empty string.

View Source
var ErrEmptyPath = errors.New("empty database file path")

Error when user pass empty string as database path parameter.

View Source
var ErrEmptyStmt = errors.New("no statement to execute")

Error when try to execute multiple statement with nil/empty slice.

View Source
var ErrInvalidDir = errors.New("invalid migration directory structure")

Error when migration directory structure is not correct.

View Source
var ErrInvalidExt = errors.New("invalid file extension of database")

Error when user try to create a new database that not ".db" extension.

View Source
var ErrNilDatabase = errors.New("database is nil")

Error when database is nil value, no operation can perform.

View Source
var Latest uint = 0

Latest schema version that supported. Use zero to get latest schema version as possible.

View Source
var Path = "data.db"

Default File path of database.

Functions

func IsFileExist

func IsFileExist(path string) bool

Check the file is exist or not.

Please note that this function will not check filepath valid or not.

func LargestSchemaVer

func LargestSchemaVer(fileSys fs.FS, folder string) (uint, error)

Get largest schema version in given fs.FS, by checking prefix of sql filename. This function NOT ensure migration can be performed successfully.

Any failure when attempt will return error and version = 0.

Types

type DatabaseOption

type DatabaseOption interface {
	// contains filtered or unexported methods
}

Option of database.

func BackupDir

func BackupDir(path string) DatabaseOption

Backup to given directory before migration. The backup filename is fixed to {original_name}_bk_{time}.{ext}.

func DbPath

func DbPath(path string) DatabaseOption

Use given database path.

func Migrate

func Migrate(f fs.FS, dir string) DatabaseOption

Use given file system (e.g. embed.FS) to perform migration.

func Version

func Version(ver int) DatabaseOption

Specific version of schema to be used.

If value is <= 0, then it will use as latest version as possible that defined in migration schema fs.

type LazyDB

type LazyDB struct {
	// contains filtered or unexported fields
}

The database implementation for lazy people. Using sqlite3.

Support multiple lazy feature:

  • Lazy creation for *sql.DB with sqlite3
  • Wrapper function to simplify sql.stmt
  • Migration support if migration fs & directory is properly set

func New

func New(opts ...DatabaseOption) *LazyDB

Create a new LazyDB.

func (*LazyDB) BackupTo added in v0.1.4

func (l *LazyDB) BackupTo(dest string) (err error)

Create a backup of current database to given path.

This function will ignore backup directory setting.

func (*LazyDB) Close

func (l *LazyDB) Close() error

Close all existing database connection.

If LazyDB has no database connected, then this function has no effect, with no error returned.

func (*LazyDB) Connect

func (l *LazyDB) Connect() error

Connect to database, when path already stored in LazyDB.

func (*LazyDB) Connected added in v0.1.6

func (l *LazyDB) Connected() bool

Check if database is connected. Its value only changed when Connect() is called successfully.

func (*LazyDB) DB

func (l *LazyDB) DB() *sql.DB

Get *sql.DB created.

func (*LazyDB) Exec

func (l *LazyDB) Exec(query string, args ...any) (sql.Result, error)

Execute given query, by prepared statement.

func (*LazyDB) ExecMultiple

func (l *LazyDB) ExecMultiple(pQueries []ParamQuery) ([]sql.Result, error)

Execute given query, by prepared statement & transaction.

Any failed query will cause a rollback, and return nil []sql.Result. Only all queries successful will return valid sql.Result slices.

func (*LazyDB) Migrate

func (l *LazyDB) Migrate() (backupPath string, err error)

Migrate database to latest supported version, which is defined when create new LazyDB.

If backup directory is set, and migration is actually performed, then this function will also return backup database path. Otherwise empty string will be returned.

func (*LazyDB) MigrateTo

func (l *LazyDB) MigrateTo(version uint) (backupPath string, err error)

Migrate database to specified version.

When version is 0, then it will migrate to latest version as possible, otherwise it will migrate to specified version.

If backup directory is set, and migration is actually performed, then this function will also return backup database path. Otherwise empty string will be returned.

func (*LazyDB) Query

func (l *LazyDB) Query(query string, args ...any) (*sql.Rows, error)

Wrapper for Query() function, using prepared statement.

func (*LazyDB) QueryRow

func (l *LazyDB) QueryRow(query string, args ...any) (*sql.Row, error)

Wrapper for QueryRow() function, using prepared statement.

type ParamQuery

type ParamQuery struct {
	Query string
	Args  []any
}

Container for create & execute prepared statements. Read only after creation.

func Param

func Param(query string, args ...any) ParamQuery

Create ParamQuery by given parameters. Value are not able to modify after creation.

func (*ParamQuery) Filled

func (p *ParamQuery) Filled() string

Return filled version of query.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL