ORM

Learn more about making use of an ORM in Caesar.

Overview

Caesar offers a simple way to interact with databases using Bun, an ORM developed and used in production by Uptrace.

Currently, the following databases are supported:

Installation

To get started, you need to install the caesar-rocks/orm package:

go get -u github.com/caesar-rocks/orm

Usage

Validate your database-related environment variables

Before you can use the ORM, you need to validate your database-related environment variables. You can do this in a new file called config/environment.go for example:

// ./config/env.go
package config

import (
	"github.com/caesar-rocks/core"
	"github.com/caesar-rocks/orm"
)

// EnvironmentVariables is a struct that holds all the environment variables that need to be validated.
// For full reference, see: https://github.com/go-playground/validator.
type EnvironmentVariables struct {
    // ...
    
    // DBMS is the database management system to use ("postgres", "mysql", "sqlite").
	DBMS orm.DBMS `validate:"oneof=postgres mysql sqlite"`

	// DSN is the data source name, which is a connection string for the database.
	DSN string `validate:"required"`
}

Provide the Database Connection to your Application

To use the ORM, you need to provide the database connection to your application. You can do this in a new file called config/database.go for example:

// ./config/database.go
package config

import (
    "github.com/caesar-rocks/orm"
)

func ProvideDatabase(env *EnvironmentVariables) *orm.Database {
	return orm.NewDatabase(&orm.DatabaseConfig{
		DBMS:  orm.DBMS(env.DBMS),
		DSN:   env.DSN,
		Debug: false, // Set to true to enable debug mode (prints SQL queries).
	})
}

Register the Database Connection in your Application

Finally, you need to register the database connection in your application. You can do this in your config/app.go file for example:

// ./config/app.go
package config

import (
    // ...
)

func ProvideApp(env *EnvironmentVariables) *core.App {
    // ...

	app.RegisterProviders(
        // ...
		ProvideDatabase,
	)

    // ...
}