Nexus/pkg/nex/cruda/allocator.go

37 lines
852 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) {
conn := v.n.GetNexusGrpcConn()
2024-10-20 11:04:41 +00:00
ctx := context.Background()
ctx = metadata.AppendToOutgoingContext(ctx, "client_id", v.n.Info.Id)
2024-10-21 14:07:36 +00:00
out, err := proto.NewDatabaseServiceClient(conn).AllocDatabase(ctx, &proto.AllocDatabaseRequest{
2024-10-20 11:04:41 +00:00
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
2024-10-20 11:55:52 +00:00
return dsn, nil
}
func MigrateModel[T any](v *CrudConn, model T) error {
if v.Db == nil {
2024-10-20 11:55:52 +00:00
return fmt.Errorf("database has not been allocated")
}
return v.Db.AutoMigrate(model)
2024-10-20 11:04:41 +00:00
}