Nexus/pkg/nex/cruda/allocator.go

37 lines
861 B
Go
Raw Normal View History

2024-10-20 11:04:41 +00:00
package cruda
import (
"context"
2024-10-20 11:55:52 +00:00
"fmt"
2024-10-20 11:04:41 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/proto"
"google.golang.org/grpc/metadata"
2024-10-20 11:55:52 +00:00
"gorm.io/driver/postgres"
"gorm.io/gorm"
2024-10-20 11:04:41 +00:00
)
2024-10-20 11:55:52 +00:00
func (v *CrudConn) AllocDatabase(name string) (string, error) {
2024-10-20 11:04:41 +00:00
conn := v.Conn.GetNexusGrpcConn()
ctx := context.Background()
ctx = metadata.AppendToOutgoingContext(ctx, "client_id", v.Conn.Info.Id)
out, err := proto.NewDatabaseControllerClient(conn).AllocDatabase(ctx, &proto.AllocDatabaseRequest{
Name: name,
})
if err != nil || !out.GetIsSuccess() {
return "", err
}
2024-10-20 11:55:52 +00:00
dsn := out.GetDsn()
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return "", err
}
v.db = db
return dsn, nil
}
func MigrateModel[T any](v *CrudConn, model T) error {
if v.db == nil {
return fmt.Errorf("database has not been allocated")
}
return v.db.AutoMigrate(model)
2024-10-20 11:04:41 +00:00
}