Files
Vishal DalwadiandAbhishek Kondur f9bbbd7efa NM-341: Schema Migration for Serverconf, Generated and Enrollment Keys Table (#4065)
* feat(go): remove enrollment key cache;

* feat(go): add internal schema;

* feat(go): use the new internal table to fetch serverconf records;

* feat(go): move internal key constants to schema/internal.go;

* feat(go): add server conf table migration;

* feat(go): use the new internal table for generated records;

* feat(go): add generated table migration;

* feat(go): use the new internal table for serveruuid records;

* feat(go): add server uuid table migration;

* chore(go): remove empty file;

* feat(go): store license validation cached response in the new internal table;

* chore(go): move table name constants;

* feat(go): use migration job name v1.7.0;

* wip(go): add schema definition for enrollment keys;

* wip(go): use schema.EnrollmentKey in orchestrator pkg;

* wip(go): use schema.EnrollmentKey in host registration and pending host approval;

* wip(go): use schema.EnrollmentKey in gateway/node cleanup;

* wip(go): use schema.EnrollmentKey in network cleanup;

* wip(go): use schema.EnrollmentKey in creating default network enrollment key;

* wip(go): use schema.EnrollmentKey in enrollment key logic/controller;

* wip(go): add schema migration for enrollment keys;

* fix(go): remove ref to non-existent constant;

* fix(go): use correct package+type for orchestrator test;

* feat(go): add internal table to list models function;

* fix(go): use int for enrollment key type;

* fix(go): remove tags from networks;

* fix(go): ensure same response for get enrollment keys as before;

* fix(go): enrollment key migration;

* wip(go): remove sqlite, rqlite, postgres and utils from database package;

* wip(go): remove unused database pkg method DeleteAllRecords;

* wip(go): remove db connection management code and accompanying consts from database/ pkg;

* wip(go): add schema definitions for org, tenant and org settings tables;

* wip(go): add tenant id to add tables in schema/ pkg; add tenant-level unique constraints for network, user invite and pending users;

* wip(go): remove usages of host actions table;

* wip(go): create default org and tenant on migration;

* wip(go): manage kv tables with gorm;

* wip(go): bring network id out of value for acls, dns, extclients, metrics and tags tables;

* wip(go): store user settings in user table;

* wip(go): add server settings migration logic;

* wip(go): replace database/ pkg functions with methods from the schema/ pkg;

* wip(go): add schema definitions for tenant settings; replace database/ pkg functions with methods from the schema/ pkg;

* wip(go): add index on tenant id;

* wip(go): remove tenant id column from user role table;

* wip(go): set tenant_id to default tenant's id on all records in all tables on migration;

* wip(go): extract out network_id on acls, dns, extclients, metrics and tags tables on migration;

* wip(go): add scope pkg with middleware to extract scope from headers or set default scope;

* wip(go): scope (most) apis to tenant;

* wip(go): remove users and user roles table from set tenant id migration function;

* wip(go): handle test case errors;

* wip(go): cache default tenant and org ids;

* feat(go): add utils to get server settings during migration;

* feat(go): check nil before conversion;

* feat(go): use correct arg order;

* wip(go): pass db context;

* wip(go): correct api handler router tag;

* wip(go): add schema definitions for org and tenant membership tables;

* wip(go): use middleware from middleware/ package;

* wip(go): add org role constants;

* wip(go): read user tenant role and groups from tenant membership table;

* wip(go): add migration logic for memberships;

* wip(go): undo inadvertent paste;

* wip(go): add migration logic for migrating user's role and groups to tenant membership table and setting org owner;

* wip(go): use tenant membership table to set user role and groups;

* wip(go): test cases;

* feat(go): check for nil;

* feat(go): move auth type, password and external idp id to tenant membership table;

* wip(go): use middleware from middleware/ package;

* wip(go): add schema definitions for org and tenant membership tables;

* wip(go): add temp default function to use default tenant scoped contexts everywhere;

* wip(go): use scope.Default to set tenant id before db ops;

* wip(go): create default org and tenant for tests as well;

* wip(go): move Default to logic to remove import cycle;

* wip(go): scope auth request to default context;

* wip(go): migration fixes;

* wip(go): use correct column; migrate membership on user migrate;

* fix(go): add smtp tls verify skip setting;

* fix(go): add smtp tls verify skip setting;

---------

Co-authored-by: Abhishek Kondur <[email protected]>
2026-07-06 23:00:21 +05:30

122 lines
2.4 KiB
Go

package db
import (
"context"
"errors"
"time"
"gorm.io/gorm"
)
type ctxKey string
const dbCtxKey ctxKey = "db"
var db *gorm.DB
var ErrDBNotFound = errors.New("no db instance in context")
// InitializeDB initializes a connection to the
// database (if not already done) and ensures it
// has the latest schema.
func InitializeDB(models ...interface{}) error {
if db != nil {
return nil
}
connector, err := newConnector()
if err != nil {
return err
}
// DB / LIFE ADVICE: try 5 times before giving up.
for i := 0; i < 5; i++ {
db, err = connector.connect()
if err == nil {
break
}
// wait 2s if you have the time.
time.Sleep(2 * time.Second)
}
if err != nil {
return err
}
return db.AutoMigrate(models...)
}
// WithContext returns a new context with the db
// connection instance.
//
// Ensure InitializeDB has been called before using
// this function.
//
// To extract the db connection use the FromContext
// function.
func WithContext(ctx context.Context) context.Context {
return context.WithValue(ctx, dbCtxKey, db)
}
// FromContext extracts the db connection instance from
// the given context.
//
// The function panics, if a connection does not exist.
func FromContext(ctx context.Context) *gorm.DB {
db, ok := ctx.Value(dbCtxKey).(*gorm.DB)
if !ok {
panic(ErrDBNotFound)
}
return db
}
func SetPagination(ctx context.Context, page, pageSize int) context.Context {
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 10
}
db := FromContext(ctx)
offset := (page - 1) * pageSize
return context.WithValue(ctx, dbCtxKey, db.Offset(offset).Limit(pageSize))
}
// BeginTx returns a context with a new transaction.
// If the context already has a db connection instance,
// it uses that instance. Otherwise, it uses the
// connection initialized in the package.
//
// Ensure InitializeDB has been called before using
// this function.
func BeginTx(ctx context.Context) context.Context {
dbInCtx, ok := ctx.Value(dbCtxKey).(*gorm.DB)
if !ok {
return context.WithValue(ctx, dbCtxKey, db.Begin())
}
return context.WithValue(ctx, dbCtxKey, dbInCtx.Begin())
}
// CloseDB close a connection to the database
// (if one exists). It panics if any error
// occurs.
func CloseDB() {
if db == nil {
return
}
sqlDB, err := db.DB()
if err != nil {
panic(err)
}
err = sqlDB.Close()
if err != nil {
panic(err)
}
db = nil
}