database

package
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Overview

Package database provides a robust and flexible abstraction over GORM, supporting both SQLite and MySQL/MariaDB as backend databases.

It offers features such as automatic connection handling, schema migrations, and version tracking. The package also allows registering custom on-connect handlers that are executed once the database connection is successfully established.

Core features:

  • Automatic (re)connection with health checks and retry mechanism
  • Support for SQLite and MySQL/MariaDB with configurable parameters
  • Schema management and automatic migrations
  • Versioning support using the go-core/version package
  • Connection lifecycle management (Connect, Disconnect, AwaitConnection)
  • Thread-safe access with `Execute(func(db *gorm.DB) error)` wrapper
  • Registering on-connect hooks to perform actions like seeding or setup

Example:

package main

import (
	"fmt"
	"time"

	"github.com/valentin-kaiser/go-core/database"
	"github.com/valentin-kaiser/go-core/flag"
	"github.com/valentin-kaiser/go-core/version"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Name     string
	Email    string `gorm:"unique"`
	Password string
}

func main() {
	flag.Init()

	database.RegisterSchema(&User{})
	database.RegisterMigrationStep(version.Version{
		GitTag:    "v1.0.0",
		GitCommit: "abc123",
	}, func(db *gorm.DB) error {
		// Custom migration logic
		return nil
	})

	database.Connect(time.Second, database.Config{
		Driver: "sqlite",
		Name:   "test",
	})
	defer database.Disconnect()

	database.AwaitConnection()

	var ver version.Version
	err := database.Execute(func(db *gorm.DB) error {
		return db.First(&ver).Error
	})
	if err != nil {
		panic(err)
	}

	fmt.Println("Version:", ver.GitTag, ver.GitCommit)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AwaitConnection

func AwaitConnection()

AwaitConnection will block until the database is connected

func Backup added in v1.6.2

func Backup(path string) error

Backup creates a backup of the database to the specified path. For SQLite: copies the database file For MySQL/MariaDB: uses mysqldump For PostgreSQL: uses pg_dump Returns an error if the database is not connected or if the backup fails.

func Connect

func Connect(interval time.Duration, c Config)

Connect will try to connect to the database every interval until it is connected It will also check if the connection is still alive every interval and reconnect if it is not

func Connected

func Connected() bool

Connected returns true if the database is connected, false otherwise

func Disconnect

func Disconnect() error

Disconnect will stop the database connection and wait for the connection to be closed

func Execute

func Execute(call func(db *gorm.DB) error) error

Execute executes a function with a database connection. It will return an error if the database is not connected or if the function returns an error. The function will be executed with a new session, so it will not affect the current transaction.

func Reconnect

func Reconnect(c Config)

Reconnect will set the connected state to false and trigger a reconnect

func RegisterMigrationStep

func RegisterMigrationStep(version version.Release, action func(db *gorm.DB) error)

RegisterMigrationStep registers a new migration step with a version and an action The action is a function that takes a gorm.DB instance and returns an error The version is a struct that must contain the Git tag and commit hash of the migration step

func RegisterOnConnectHandler

func RegisterOnConnectHandler(handler func(db *gorm.DB, config Config) error)

RegisterOnConnectHandler registers a function that will be called when the database connection is established

func RegisterSchema

func RegisterSchema(models ...interface{})

RegisterSchema registers a new schema model to be migrated

func Restore added in v1.6.2

func Restore(backupPath string) error

Restore restores the database from a backup file at the specified path. For SQLite: replaces the current database file with the backup For MySQL/MariaDB: uses mysql client to restore from SQL dump For PostgreSQL: uses psql to restore from SQL dump Returns an error if the database is not connected or if the restore fails. WARNING: This will overwrite the current database. Ensure you have a backup before restoring.

func Transaction added in v1.6.0

func Transaction(call func(tx *gorm.DB) error) error

Transaction executes a function within a database transaction. It will return an error if the database is not connected or if the function returns an error. If the function returns an error, the transaction will be rolled back.

Types

type Config

type Config struct {
	Driver   string `usage:"Database driver. Currently available options are 'mysql', 'mariadb' or 'sqlite'"`
	Host     string `usage:"IP address or hostname of the database server"`
	Port     uint16 `usage:"Port of the database server to connect to"`
	User     string `usage:"Database username"`
	Password string `usage:"Database password"`
	Name     string `usage:"Name of the database or sqlite file"`
}

Config holds the configuration for the database connection This struct can be used with the config core package. You can use this struct or embed it in your own struct.

func (*Config) Changed

func (c *Config) Changed(n *Config) bool

Changed checks if the configuration has changed

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

type Step

type Step struct {
	Version version.Release
	Action  func(db *gorm.DB) error
}

Step represents a migration step with a version and an action to be performed The action is a function that takes a gorm.DB instance and returns an error

Jump to

Keyboard shortcuts

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