Skip to content

Latest commit

 

History

History

orm

ORM Module

ci go report codecov Deps PkgGoDev

ORM module based on GORM.

Installation

go get github.com/ankorstore/yokai/orm

Documentation

Usage

This module provides a OrmFactory, allowing to build an gorm.DB instance.

The following database drivers are supported:

  • SQLite
  • MySQL
  • PostgreSQL
  • SQL Server
package main

import (
	"github.com/ankorstore/yokai/orm"
)

// with MySQL driver
var db, _ = orm.NewDefaultOrmFactory().Create(
	orm.WithDriver(orm.Mysql),
	orm.WithDsn("user:pass@tcp(127.0.0.1:3306)/dbname?parseTime=True"),
)

// or with SQLite driver
var db, _ = orm.NewDefaultOrmFactory().Create(
	orm.WithDriver(orm.Sqlite),
	orm.WithDsn("file::memory:?cache=shared"),
)

See GORM documentation for more details.

Add-ons

This module provides several add-ons ready to use to enrich your ORM.

Logger

This module provides an CtxOrmLogger, compatible with the log module:

package main

import (
	"github.com/ankorstore/yokai/orm"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func main() {
	ormLogger := orm.NewCtxOrmLogger(logger.Info, false)

	db, _ := orm.NewDefaultOrmFactory().Create(
		orm.WithConfig(gorm.Config{
			Logger: ormLogger,
		}),
	)
}

If needed, you can set the parameter withValues to true to append SQL query parameter values in the log records:

ormLogger := orm.NewCtxOrmLogger(logger.Info, true)

Tracer

This module provides an OrmTracerPlugin, compatible with the trace module:

package main

import (
	"github.com/ankorstore/yokai/orm"
	"github.com/ankorstore/yokai/orm/plugin"
	"github.com/ankorstore/yokai/trace"
)

func main() {
	tracerProvider, _ := trace.NewDefaultTracerProviderFactory().Create()

	db, _ := orm.NewDefaultOrmFactory().Create()

	db.Use(plugin.NewOrmTracerPlugin(tracerProvider, false))
}

If needed, you can set the parameter withValues to true to append SQL query parameter values in the trace spans:

db.Use(plugin.NewOrmTracerPlugin(tracerProvider, true))

Healthcheck

This module provides an OrmProbe, compatible with the healthcheck module:

package main

import (
	"context"

	hc "github.com/ankorstore/yokai/healthcheck"
	"github.com/ankorstore/yokai/orm"
	"github.com/ankorstore/yokai/orm/healthcheck"
)

func main() {
	db, _ := orm.NewDefaultOrmFactory().Create()

	checker, _ := hc.NewDefaultCheckerFactory().Create(
		hc.WithProbe(healthcheck.NewOrmProbe(db)),
	)

	checker.Check(context.Background(), hc.Readiness)
}

This probe performs a ping to the configured database connection.