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-24 15:52:38 +00:00
|
|
|
conn := v.n.GetNexusGrpcConn()
|
2024-10-20 11:04:41 +00:00
|
|
|
ctx := context.Background()
|
2024-10-24 15:52:38 +00:00
|
|
|
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
|
|
|
|
}
|
2024-10-24 15:52:38 +00:00
|
|
|
v.Db = db
|
2024-10-20 11:55:52 +00:00
|
|
|
return dsn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func MigrateModel[T any](v *CrudConn, model T) error {
|
2024-10-24 15:52:38 +00:00
|
|
|
if v.Db == nil {
|
2024-10-20 11:55:52 +00:00
|
|
|
return fmt.Errorf("database has not been allocated")
|
|
|
|
}
|
2024-10-24 15:52:38 +00:00
|
|
|
return v.Db.AutoMigrate(model)
|
2024-10-20 11:04:41 +00:00
|
|
|
}
|