diff --git a/models/forgefed/federationinfo.go b/models/forgefed/federationinfo.go index e4ce51d93e..99018433f9 100644 --- a/models/forgefed/federationinfo.go +++ b/models/forgefed/federationinfo.go @@ -12,7 +12,7 @@ import ( // swagger:model type FederationInfo struct { ID int64 `xorm:"pk autoincr"` - HostFqdn string `xorm:"INDEX VARCHAR(255) NOT NULL"` + HostFqdn string `xorm:"host_fqdn UNIQUE INDEX VARCHAR(255) NOT NULL"` NodeInfo NodeInfo `xorm:"NOT NULL"` LatestActivity timeutil.TimeStamp `xorm:"NOT NULL"` Create timeutil.TimeStamp `xorm:"created"` diff --git a/models/forgefed/federationinfo_repository.go b/models/forgefed/federationinfo_repository.go index cf1e27fa9e..e2e43e6fc4 100644 --- a/models/forgefed/federationinfo_repository.go +++ b/models/forgefed/federationinfo_repository.go @@ -4,9 +4,41 @@ package forgefed import ( + "context" + "fmt" + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/validation" ) func init() { db.RegisterModel(new(FederationInfo)) } + +func GetFederationInfo(ctx context.Context, ID int64) (*FederationInfo, error) { + info := new(FederationInfo) + has, err := db.GetEngine(ctx).Where("id=?", ID).Get(info) + if err != nil { + return nil, err + } else if !has { + return nil, fmt.Errorf("FederationInfo record %v does not exist", ID) + } + if res, err := validation.IsValid(info); !res { + return nil, fmt.Errorf("FederationInfo is not valid: %v", err) + } + return info, nil +} + +func GetFederationInfoByHostFqdn(ctx context.Context, fqdn string) (*FederationInfo, error) { + info := new(FederationInfo) + has, err := db.GetEngine(ctx).Where("host_fqdn=?", fqdn).Get(info) + if err != nil { + return nil, err + } else if !has { + return nil, fmt.Errorf("FederationInfo record %v does not exist", fqdn) + } + if res, err := validation.IsValid(info); !res { + return nil, fmt.Errorf("FederationInfo is not valid: %v", err) + } + return info, nil +} diff --git a/models/forgefed/federationinfo_test.go b/models/forgefed/federationinfo_test.go index b6185dddeb..d40d42dc02 100644 --- a/models/forgefed/federationinfo_test.go +++ b/models/forgefed/federationinfo_test.go @@ -10,7 +10,7 @@ import ( "code.gitea.io/gitea/modules/validation" ) -func Test_ValidateMaxLen(t *testing.T) { +func Test_FederationInfoValidation(t *testing.T) { sut := FederationInfo{ HostFqdn: "host.do.main", NodeInfo: NodeInfo{ @@ -21,4 +21,13 @@ func Test_ValidateMaxLen(t *testing.T) { if res, err := validation.IsValid(sut); !res { t.Errorf("sut should be valid but was %q", err) } + + sut = FederationInfo{ + HostFqdn: "host.do.main", + NodeInfo: NodeInfo{}, + LatestActivity: timeutil.TimeStampNow(), + } + if res, _ := validation.IsValid(sut); res { + t.Errorf("sut should be invalid") + } }