fxsqlite

package
v0.0.0-...-a8769a9 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Sqlite Module

This module provides support sqlite using the stdlib sql.DB and gorm.

It will provide a *sql.DB to the database with sane default values. If your application uses gorm, you can pull out an *gorm.DB using the same underlying *sql.DB instead. Furthermore it is capable of running a schema migration at system startup using stelling migration package.

This module is great for simple applications, but the stdlib sql library has limitations. If you bump into them you can look at the fxsqlitex package, which has the same module API.

Components

The module lazily provides the following components:

  • A *sql.DB
  • A *gorm.DB

The outputs are marked as private, to make it easy to embed a sqlite database in a module without having to resort to named components.

Options

The module provides the following options:

  • WithMigrations and WithSchemaVersion This allows you to pass in a schema migration that will be run at system startup
  • WithSQLiteOptions These options will be passed to the *sql.DB and allow configuring some of its behaviour

Configuration file

The embeddable configuration only exposes a single option for the moment:

  • path: The filesystem path where the database file should be created or can be opened

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"testing/fstest"

	sconfig "github.com/exoscale/stelling/config"
	"github.com/exoscale/stelling/fxsqlite"
	"go.uber.org/fx"
	"gorm.io/gorm"
)

type Config struct {
	fxsqlite.DB
}

func main() {
	conf := &Config{}
	args := []string{"sqlite-test", "--db.path", "/tmp/db.sqlite"}
	if err := sconfig.Load(conf, args); err != nil {
		panic(err)
	}

	migrations := makeTestFs()

	app := fx.New(fx.Options(
		fxsqlite.NewModule(
			conf,
			fxsqlite.WithMigrations(migrations, "."),
			fxsqlite.WithSQLiteOptions(fxsqlite.WithInMemory()),
		),
		fx.Invoke(run),
	))

	app.Run()

}

type example struct {
	Name  string `gorm:"name"`
	Value int    `gorm:"value"`
}

func run(lc fx.Lifecycle, sd fx.Shutdowner, db *gorm.DB) {
	lc.Append(fx.Hook{
		OnStart: func(ctx context.Context) error {
			row, err := gorm.G[example](db).First(ctx)
			if err != nil {
				return err
			}
			fmt.Println("name", row.Name)
			fmt.Println("value", row.Value)
			return sd.Shutdown()
		},
	})
}

const schemaUp = `CREATE TABLE IF NOT EXISTS examples (
	name text,
	value number,
	PRIMARY KEY(name)
);
INSERT INTO examples(name, value) VALUES ('test', 1);`
const schemaDown = `DELETE TABLE IF EXISTS exampes;`

func makeTestFs() fstest.MapFS {
	output := make(map[string]*fstest.MapFile)

	output["0001_init_schema.up.sql"] = &fstest.MapFile{
		Data: []byte(schemaUp),
	}
	output["0001_init_schema.down.sql"] = &fstest.MapFile{
		Data: []byte(schemaDown),
	}
	return output
}
Output:
name test
value 1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDB

func NewDB(conf DBConfig, opts ...Option) (*sql.DB, error)

func NewGormDB

func NewGormDB(db *sql.DB, logger *zap.Logger) (*gorm.DB, error)

NewGormDB creates a new gorm database from the given sqlite sql.DB

func NewModule

func NewModule(conf DBConfig, opts ...ModuleOption) fx.Option

NewModule adds a module which provides an *sql.DB to your system

Types

type DB

type DB fxsqlitex.DB

func (*DB) DBConfig

func (db *DB) DBConfig() *DB

type DBConfig

type DBConfig interface {
	DBConfig() *DB
}

type ModuleOption

type ModuleOption func() fx.Option

func WithMigrations

func WithMigrations(migrations fs.FS, path string) ModuleOption

WithMigrations will run the migrations at the path in the given FS during system startup By default it will bring the schema to the latest version, but this can be tweaked by using the WithSchemaVersion ModuleOption

func WithSQLiteOptions

func WithSQLiteOptions(sqliteOpts ...Option) ModuleOption

WithSQLiteOptions will provide the given SqliteOptions to the sql.DB produced by the module

func WithSchemaVersion

func WithSchemaVersion(version uint64) ModuleOption

WithSchemaVersion will bring the schema to the given version rather than the latest version It has no effect if WithMigrations is not specified as well

type Option

type Option func(*sqliteConfig)

func WithBusyTimeout

func WithBusyTimeout(busyTimeout time.Duration) Option

WithBusyTimeout sets a busy handler on each connection that waits up to Duration to acquire the write lock See: https://www.sqlite.org/c3ref/busy_timeout.html

func WithInMemory

func WithInMemory() Option

WithInMemory will create a new in memory database rather than opening an existing one from disk

func WithPoolSize

func WithPoolSize(poolSize uint) Option

WithPoolSize sets the maximum number of connections to the sqlite database The default value is 1, since sqlite only allows a single thread to write, but for read intensive applications it can be useful to increase this value

type SchemaVersion

type SchemaVersion uint64

Jump to

Keyboard shortcuts

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