diff --git a/cmd/insert-user/main.go b/cmd/insert-user/main.go index 73a06d1..53c679a 100644 --- a/cmd/insert-user/main.go +++ b/cmd/insert-user/main.go @@ -1,35 +1,77 @@ // SPDX-License-Identifier: MIT +// insert-user is a utility to create a new member and password package main import ( "bytes" "context" + "flag" "fmt" "os" + "os/user" + "path/filepath" + "strings" "syscall" + refs "go.mindeco.de/ssb-refs" + + "github.com/ssb-ngi-pointer/go-ssb-room/internal/repo" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + _ "github.com/mattn/go-sqlite3" "golang.org/x/crypto/ssh/terminal" - "github.com/ssb-ngi-pointer/go-ssb-room/internal/repo" "github.com/ssb-ngi-pointer/go-ssb-room/roomdb/sqlite" ) func main() { + u, err := user.Current() + check(err) - if len(os.Args) != 3 { - fmt.Fprintf(os.Stderr, "usage: %s \n", os.Args[0]) - fmt.Fprintf(os.Stderr, "repo-location: default is $HOME/.ssb-go-room\n") + var ( + repoPath string + role roomdb.Role + ) + + flag.StringVar(&repoPath, "repo", filepath.Join(u.HomeDir, ".ssb-go-room"), "where the repo of the room is located") + flag.Func("role", "which role the new member should have (ie moderator, admin, member. defaults to admin)", func(val string) error { + if val == "" { + role = roomdb.RoleAdmin + return nil + } + + switch strings.ToLower(val) { + case "admin": + role = roomdb.RoleAdmin + case "moderator": + role = roomdb.RoleAdmin + case "member": + role = roomdb.RoleMember + + default: + return fmt.Errorf("unknown member role: %q", val) + } + + return nil + }) + + flag.Parse() + + if len(os.Args) != 2 { + fmt.Fprintf(os.Stderr, "usage: %s <@theirPublicKey.ed25519>\n", os.Args[0]) + flag.Usage() os.Exit(1) return } - r := repo.New(os.Args[1]) + r := repo.New(repoPath) db, err := sqlite.Open(r) check(err) defer db.Close() + pubKey, err := refs.ParseFeedRef(os.Args[1]) + fmt.Fprintln(os.Stderr, "Enter Password: ") bytePassword, err := terminal.ReadPassword(int(syscall.Stdin)) check(err) @@ -45,10 +87,13 @@ func main() { } ctx := context.Background() - uid, err := db.AuthFallback.Create(ctx, os.Args[2], bytePassword) + mid, err := db.Members.Add(ctx, os.Args[1], *pubKey, role) check(err) - fmt.Fprintln(os.Stderr, "created user with ID", uid) + err = db.AuthFallback.Create(ctx, mid, os.Args[1], bytePassword) + check(err) + + fmt.Fprintln(os.Stderr, "created member with ID", mid) } func check(err error) { diff --git a/roomdb/interface.go b/roomdb/interface.go index 5142f99..7a2164c 100644 --- a/roomdb/interface.go +++ b/roomdb/interface.go @@ -17,22 +17,54 @@ import ( refs "go.mindeco.de/ssb-refs" ) -// AuthFallbackService might be helpful for scenarios where one lost access to his ssb device or key +// AuthFallbackService allows password authentication which might be helpful for scenarios +// where one lost access to his ssb device or key. type AuthFallbackService interface { // Check receives the username and password (in clear) and checks them accordingly. // If it's a valid combination it returns the user ID, or an error if they are not. auth.Auther - Create(ctx context.Context, user string, password []byte) (int64, error) - GetByID(ctx context.Context, uid int64) (*User, error) + Create(_ context.Context, memberID int64, login string, password []byte) error + // GetByID(context.Context, int64) (User, error) + // ListAll() + // ListByMember() + // Remove(pwid) } +// needed?! not sure we need to hold the challanges // AuthWithSSBService defines functions needed for the challange/response system of sign-in with ssb type AuthWithSSBService interface{} -// AllowListService changes the lists of people that are allowed to get into the room -type AllowListService interface { +// MembersService stores and retreives the list of internal users (members, mods and admins). +type MembersService interface { + // Add adds a new member + Add(_ context.Context, nickName string, pubKey refs.FeedRef, r Role) (int64, error) + + // HasFeed returns true if a feed is on the list. + HasFeed(context.Context, refs.FeedRef) bool + + // HasFeed returns true if a feed is on the list. + HasID(context.Context, int64) bool + + // GetByID returns the list entry for that ID or an error + GetByID(context.Context, int64) (Member, error) + + // List returns a list of all the members. + List(context.Context) ([]Member, error) + + // RemoveFeed removes the feed from the list. + RemoveFeed(context.Context, refs.FeedRef) error + + // RemoveID removes the feed for the ID from the list. + RemoveID(context.Context, int64) error + + // SetRole + SetRole(context.Context, int64, Role) error +} + +// DeniedListService changes the lists of people that are Denieded to get into the room +type DeniedListService interface { // Add adds the feed to the list. Add(context.Context, refs.FeedRef) error @@ -46,7 +78,7 @@ type AllowListService interface { GetByID(context.Context, int64) (ListEntry, error) // List returns a list of all the feeds. - List(context.Context) (ListEntries, error) + List(context.Context) ([]ListEntry, error) // RemoveFeed removes the feed from the list. RemoveFeed(context.Context, refs.FeedRef) error @@ -55,8 +87,8 @@ type AllowListService interface { RemoveID(context.Context, int64) error } -// AliasService manages alias handle registration and lookup -type AliasService interface { +// AliasesService manages alias handle registration and lookup +type AliasesService interface { // Resolve returns all the relevant information for that alias or an error if it doesnt exist Resolve(context.Context, string) (Alias, error) @@ -73,8 +105,8 @@ type AliasService interface { Revoke(ctx context.Context, alias string) error } -// InviteService manages creation and consumption of invite tokens for joining the room. -type InviteService interface { +// InvitesService manages creation and consumption of invite tokens for joining the room. +type InvitesService interface { // Create creates a new invite for a new member. It returns the token or an error. // createdBy is user ID of the admin or moderator who created it. // aliasSuggestion is optional (empty string is fine) but can be used to disambiguate open invites. (See https://github.com/ssb-ngi-pointer/rooms2/issues/21) @@ -125,16 +157,18 @@ type NoticesService interface { // for tests we use generated mocks from these interfaces created with https://github.com/maxbrunsfeld/counterfeiter +//go:generate counterfeiter -o mockdb/aliases.go . AliasesService + //go:generate counterfeiter -o mockdb/auth.go . AuthWithSSBService //go:generate counterfeiter -o mockdb/auth_fallback.go . AuthFallbackService -//go:generate counterfeiter -o mockdb/allow.go . AllowListService - -//go:generate counterfeiter -o mockdb/alias.go . AliasService - -//go:generate counterfeiter -o mockdb/invite.go . InviteService +//go:generate counterfeiter -o mockdb/denied.go . DeniedListService //go:generate counterfeiter -o mockdb/fixed_pages.go . PinnedNoticesService +//go:generate counterfeiter -o mockdb/invites.go . InvitesService + +//go:generate counterfeiter -o mockdb/members.go . MembersService + //go:generate counterfeiter -o mockdb/pages.go . NoticesService diff --git a/roomdb/mockdb/alias.go b/roomdb/mockdb/aliases.go similarity index 77% rename from roomdb/mockdb/alias.go rename to roomdb/mockdb/aliases.go index fc1a2d8..7992057 100644 --- a/roomdb/mockdb/alias.go +++ b/roomdb/mockdb/aliases.go @@ -9,7 +9,7 @@ import ( refs "go.mindeco.de/ssb-refs" ) -type FakeAliasService struct { +type FakeAliasesService struct { GetByIDStub func(context.Context, int64) (roomdb.Alias, error) getByIDMutex sync.RWMutex getByIDArgsForCall []struct { @@ -81,7 +81,7 @@ type FakeAliasService struct { invocationsMutex sync.RWMutex } -func (fake *FakeAliasService) GetByID(arg1 context.Context, arg2 int64) (roomdb.Alias, error) { +func (fake *FakeAliasesService) GetByID(arg1 context.Context, arg2 int64) (roomdb.Alias, error) { fake.getByIDMutex.Lock() ret, specificReturn := fake.getByIDReturnsOnCall[len(fake.getByIDArgsForCall)] fake.getByIDArgsForCall = append(fake.getByIDArgsForCall, struct { @@ -101,26 +101,26 @@ func (fake *FakeAliasService) GetByID(arg1 context.Context, arg2 int64) (roomdb. return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeAliasService) GetByIDCallCount() int { +func (fake *FakeAliasesService) GetByIDCallCount() int { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() return len(fake.getByIDArgsForCall) } -func (fake *FakeAliasService) GetByIDCalls(stub func(context.Context, int64) (roomdb.Alias, error)) { +func (fake *FakeAliasesService) GetByIDCalls(stub func(context.Context, int64) (roomdb.Alias, error)) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = stub } -func (fake *FakeAliasService) GetByIDArgsForCall(i int) (context.Context, int64) { +func (fake *FakeAliasesService) GetByIDArgsForCall(i int) (context.Context, int64) { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() argsForCall := fake.getByIDArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAliasService) GetByIDReturns(result1 roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) GetByIDReturns(result1 roomdb.Alias, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -130,7 +130,7 @@ func (fake *FakeAliasService) GetByIDReturns(result1 roomdb.Alias, result2 error }{result1, result2} } -func (fake *FakeAliasService) GetByIDReturnsOnCall(i int, result1 roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) GetByIDReturnsOnCall(i int, result1 roomdb.Alias, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -146,7 +146,7 @@ func (fake *FakeAliasService) GetByIDReturnsOnCall(i int, result1 roomdb.Alias, }{result1, result2} } -func (fake *FakeAliasService) List(arg1 context.Context) ([]roomdb.Alias, error) { +func (fake *FakeAliasesService) List(arg1 context.Context) ([]roomdb.Alias, error) { fake.listMutex.Lock() ret, specificReturn := fake.listReturnsOnCall[len(fake.listArgsForCall)] fake.listArgsForCall = append(fake.listArgsForCall, struct { @@ -165,26 +165,26 @@ func (fake *FakeAliasService) List(arg1 context.Context) ([]roomdb.Alias, error) return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeAliasService) ListCallCount() int { +func (fake *FakeAliasesService) ListCallCount() int { fake.listMutex.RLock() defer fake.listMutex.RUnlock() return len(fake.listArgsForCall) } -func (fake *FakeAliasService) ListCalls(stub func(context.Context) ([]roomdb.Alias, error)) { +func (fake *FakeAliasesService) ListCalls(stub func(context.Context) ([]roomdb.Alias, error)) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = stub } -func (fake *FakeAliasService) ListArgsForCall(i int) context.Context { +func (fake *FakeAliasesService) ListArgsForCall(i int) context.Context { fake.listMutex.RLock() defer fake.listMutex.RUnlock() argsForCall := fake.listArgsForCall[i] return argsForCall.arg1 } -func (fake *FakeAliasService) ListReturns(result1 []roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) ListReturns(result1 []roomdb.Alias, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil @@ -194,7 +194,7 @@ func (fake *FakeAliasService) ListReturns(result1 []roomdb.Alias, result2 error) }{result1, result2} } -func (fake *FakeAliasService) ListReturnsOnCall(i int, result1 []roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) ListReturnsOnCall(i int, result1 []roomdb.Alias, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil @@ -210,7 +210,7 @@ func (fake *FakeAliasService) ListReturnsOnCall(i int, result1 []roomdb.Alias, r }{result1, result2} } -func (fake *FakeAliasService) Register(arg1 context.Context, arg2 string, arg3 refs.FeedRef, arg4 []byte) error { +func (fake *FakeAliasesService) Register(arg1 context.Context, arg2 string, arg3 refs.FeedRef, arg4 []byte) error { var arg4Copy []byte if arg4 != nil { arg4Copy = make([]byte, len(arg4)) @@ -237,26 +237,26 @@ func (fake *FakeAliasService) Register(arg1 context.Context, arg2 string, arg3 r return fakeReturns.result1 } -func (fake *FakeAliasService) RegisterCallCount() int { +func (fake *FakeAliasesService) RegisterCallCount() int { fake.registerMutex.RLock() defer fake.registerMutex.RUnlock() return len(fake.registerArgsForCall) } -func (fake *FakeAliasService) RegisterCalls(stub func(context.Context, string, refs.FeedRef, []byte) error) { +func (fake *FakeAliasesService) RegisterCalls(stub func(context.Context, string, refs.FeedRef, []byte) error) { fake.registerMutex.Lock() defer fake.registerMutex.Unlock() fake.RegisterStub = stub } -func (fake *FakeAliasService) RegisterArgsForCall(i int) (context.Context, string, refs.FeedRef, []byte) { +func (fake *FakeAliasesService) RegisterArgsForCall(i int) (context.Context, string, refs.FeedRef, []byte) { fake.registerMutex.RLock() defer fake.registerMutex.RUnlock() argsForCall := fake.registerArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 } -func (fake *FakeAliasService) RegisterReturns(result1 error) { +func (fake *FakeAliasesService) RegisterReturns(result1 error) { fake.registerMutex.Lock() defer fake.registerMutex.Unlock() fake.RegisterStub = nil @@ -265,7 +265,7 @@ func (fake *FakeAliasService) RegisterReturns(result1 error) { }{result1} } -func (fake *FakeAliasService) RegisterReturnsOnCall(i int, result1 error) { +func (fake *FakeAliasesService) RegisterReturnsOnCall(i int, result1 error) { fake.registerMutex.Lock() defer fake.registerMutex.Unlock() fake.RegisterStub = nil @@ -279,7 +279,7 @@ func (fake *FakeAliasService) RegisterReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeAliasService) Resolve(arg1 context.Context, arg2 string) (roomdb.Alias, error) { +func (fake *FakeAliasesService) Resolve(arg1 context.Context, arg2 string) (roomdb.Alias, error) { fake.resolveMutex.Lock() ret, specificReturn := fake.resolveReturnsOnCall[len(fake.resolveArgsForCall)] fake.resolveArgsForCall = append(fake.resolveArgsForCall, struct { @@ -299,26 +299,26 @@ func (fake *FakeAliasService) Resolve(arg1 context.Context, arg2 string) (roomdb return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeAliasService) ResolveCallCount() int { +func (fake *FakeAliasesService) ResolveCallCount() int { fake.resolveMutex.RLock() defer fake.resolveMutex.RUnlock() return len(fake.resolveArgsForCall) } -func (fake *FakeAliasService) ResolveCalls(stub func(context.Context, string) (roomdb.Alias, error)) { +func (fake *FakeAliasesService) ResolveCalls(stub func(context.Context, string) (roomdb.Alias, error)) { fake.resolveMutex.Lock() defer fake.resolveMutex.Unlock() fake.ResolveStub = stub } -func (fake *FakeAliasService) ResolveArgsForCall(i int) (context.Context, string) { +func (fake *FakeAliasesService) ResolveArgsForCall(i int) (context.Context, string) { fake.resolveMutex.RLock() defer fake.resolveMutex.RUnlock() argsForCall := fake.resolveArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAliasService) ResolveReturns(result1 roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) ResolveReturns(result1 roomdb.Alias, result2 error) { fake.resolveMutex.Lock() defer fake.resolveMutex.Unlock() fake.ResolveStub = nil @@ -328,7 +328,7 @@ func (fake *FakeAliasService) ResolveReturns(result1 roomdb.Alias, result2 error }{result1, result2} } -func (fake *FakeAliasService) ResolveReturnsOnCall(i int, result1 roomdb.Alias, result2 error) { +func (fake *FakeAliasesService) ResolveReturnsOnCall(i int, result1 roomdb.Alias, result2 error) { fake.resolveMutex.Lock() defer fake.resolveMutex.Unlock() fake.ResolveStub = nil @@ -344,7 +344,7 @@ func (fake *FakeAliasService) ResolveReturnsOnCall(i int, result1 roomdb.Alias, }{result1, result2} } -func (fake *FakeAliasService) Revoke(arg1 context.Context, arg2 string) error { +func (fake *FakeAliasesService) Revoke(arg1 context.Context, arg2 string) error { fake.revokeMutex.Lock() ret, specificReturn := fake.revokeReturnsOnCall[len(fake.revokeArgsForCall)] fake.revokeArgsForCall = append(fake.revokeArgsForCall, struct { @@ -364,26 +364,26 @@ func (fake *FakeAliasService) Revoke(arg1 context.Context, arg2 string) error { return fakeReturns.result1 } -func (fake *FakeAliasService) RevokeCallCount() int { +func (fake *FakeAliasesService) RevokeCallCount() int { fake.revokeMutex.RLock() defer fake.revokeMutex.RUnlock() return len(fake.revokeArgsForCall) } -func (fake *FakeAliasService) RevokeCalls(stub func(context.Context, string) error) { +func (fake *FakeAliasesService) RevokeCalls(stub func(context.Context, string) error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = stub } -func (fake *FakeAliasService) RevokeArgsForCall(i int) (context.Context, string) { +func (fake *FakeAliasesService) RevokeArgsForCall(i int) (context.Context, string) { fake.revokeMutex.RLock() defer fake.revokeMutex.RUnlock() argsForCall := fake.revokeArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAliasService) RevokeReturns(result1 error) { +func (fake *FakeAliasesService) RevokeReturns(result1 error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = nil @@ -392,7 +392,7 @@ func (fake *FakeAliasService) RevokeReturns(result1 error) { }{result1} } -func (fake *FakeAliasService) RevokeReturnsOnCall(i int, result1 error) { +func (fake *FakeAliasesService) RevokeReturnsOnCall(i int, result1 error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = nil @@ -406,7 +406,7 @@ func (fake *FakeAliasService) RevokeReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeAliasService) Invocations() map[string][][]interface{} { +func (fake *FakeAliasesService) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.getByIDMutex.RLock() @@ -426,7 +426,7 @@ func (fake *FakeAliasService) Invocations() map[string][][]interface{} { return copiedInvocations } -func (fake *FakeAliasService) recordInvocation(key string, args []interface{}) { +func (fake *FakeAliasesService) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { @@ -438,4 +438,4 @@ func (fake *FakeAliasService) recordInvocation(key string, args []interface{}) { fake.invocations[key] = append(fake.invocations[key], args) } -var _ roomdb.AliasService = new(FakeAliasService) +var _ roomdb.AliasesService = new(FakeAliasesService) diff --git a/roomdb/mockdb/auth_fallback.go b/roomdb/mockdb/auth_fallback.go index 575a8a2..958da03 100644 --- a/roomdb/mockdb/auth_fallback.go +++ b/roomdb/mockdb/auth_fallback.go @@ -23,34 +23,19 @@ type FakeAuthFallbackService struct { result1 interface{} result2 error } - CreateStub func(context.Context, string, []byte) (int64, error) + CreateStub func(context.Context, int64, string, []byte) error createMutex sync.RWMutex createArgsForCall []struct { arg1 context.Context - arg2 string - arg3 []byte + arg2 int64 + arg3 string + arg4 []byte } createReturns struct { - result1 int64 - result2 error + result1 error } createReturnsOnCall map[int]struct { - result1 int64 - result2 error - } - GetByIDStub func(context.Context, int64) (*roomdb.User, error) - getByIDMutex sync.RWMutex - getByIDArgsForCall []struct { - arg1 context.Context - arg2 int64 - } - getByIDReturns struct { - result1 *roomdb.User - result2 error - } - getByIDReturnsOnCall map[int]struct { - result1 *roomdb.User - result2 error + result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex @@ -121,30 +106,31 @@ func (fake *FakeAuthFallbackService) CheckReturnsOnCall(i int, result1 interface }{result1, result2} } -func (fake *FakeAuthFallbackService) Create(arg1 context.Context, arg2 string, arg3 []byte) (int64, error) { - var arg3Copy []byte - if arg3 != nil { - arg3Copy = make([]byte, len(arg3)) - copy(arg3Copy, arg3) +func (fake *FakeAuthFallbackService) Create(arg1 context.Context, arg2 int64, arg3 string, arg4 []byte) error { + var arg4Copy []byte + if arg4 != nil { + arg4Copy = make([]byte, len(arg4)) + copy(arg4Copy, arg4) } fake.createMutex.Lock() ret, specificReturn := fake.createReturnsOnCall[len(fake.createArgsForCall)] fake.createArgsForCall = append(fake.createArgsForCall, struct { arg1 context.Context - arg2 string - arg3 []byte - }{arg1, arg2, arg3Copy}) + arg2 int64 + arg3 string + arg4 []byte + }{arg1, arg2, arg3, arg4Copy}) stub := fake.CreateStub fakeReturns := fake.createReturns - fake.recordInvocation("Create", []interface{}{arg1, arg2, arg3Copy}) + fake.recordInvocation("Create", []interface{}{arg1, arg2, arg3, arg4Copy}) fake.createMutex.Unlock() if stub != nil { - return stub(arg1, arg2, arg3) + return stub(arg1, arg2, arg3, arg4) } if specificReturn { - return ret.result1, ret.result2 + return ret.result1 } - return fakeReturns.result1, fakeReturns.result2 + return fakeReturns.result1 } func (fake *FakeAuthFallbackService) CreateCallCount() int { @@ -153,108 +139,40 @@ func (fake *FakeAuthFallbackService) CreateCallCount() int { return len(fake.createArgsForCall) } -func (fake *FakeAuthFallbackService) CreateCalls(stub func(context.Context, string, []byte) (int64, error)) { +func (fake *FakeAuthFallbackService) CreateCalls(stub func(context.Context, int64, string, []byte) error) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = stub } -func (fake *FakeAuthFallbackService) CreateArgsForCall(i int) (context.Context, string, []byte) { +func (fake *FakeAuthFallbackService) CreateArgsForCall(i int) (context.Context, int64, string, []byte) { fake.createMutex.RLock() defer fake.createMutex.RUnlock() argsForCall := fake.createArgsForCall[i] - return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 } -func (fake *FakeAuthFallbackService) CreateReturns(result1 int64, result2 error) { +func (fake *FakeAuthFallbackService) CreateReturns(result1 error) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = nil fake.createReturns = struct { - result1 int64 - result2 error - }{result1, result2} + result1 error + }{result1} } -func (fake *FakeAuthFallbackService) CreateReturnsOnCall(i int, result1 int64, result2 error) { +func (fake *FakeAuthFallbackService) CreateReturnsOnCall(i int, result1 error) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = nil if fake.createReturnsOnCall == nil { fake.createReturnsOnCall = make(map[int]struct { - result1 int64 - result2 error + result1 error }) } fake.createReturnsOnCall[i] = struct { - result1 int64 - result2 error - }{result1, result2} -} - -func (fake *FakeAuthFallbackService) GetByID(arg1 context.Context, arg2 int64) (*roomdb.User, error) { - fake.getByIDMutex.Lock() - ret, specificReturn := fake.getByIDReturnsOnCall[len(fake.getByIDArgsForCall)] - fake.getByIDArgsForCall = append(fake.getByIDArgsForCall, struct { - arg1 context.Context - arg2 int64 - }{arg1, arg2}) - stub := fake.GetByIDStub - fakeReturns := fake.getByIDReturns - fake.recordInvocation("GetByID", []interface{}{arg1, arg2}) - fake.getByIDMutex.Unlock() - if stub != nil { - return stub(arg1, arg2) - } - if specificReturn { - return ret.result1, ret.result2 - } - return fakeReturns.result1, fakeReturns.result2 -} - -func (fake *FakeAuthFallbackService) GetByIDCallCount() int { - fake.getByIDMutex.RLock() - defer fake.getByIDMutex.RUnlock() - return len(fake.getByIDArgsForCall) -} - -func (fake *FakeAuthFallbackService) GetByIDCalls(stub func(context.Context, int64) (*roomdb.User, error)) { - fake.getByIDMutex.Lock() - defer fake.getByIDMutex.Unlock() - fake.GetByIDStub = stub -} - -func (fake *FakeAuthFallbackService) GetByIDArgsForCall(i int) (context.Context, int64) { - fake.getByIDMutex.RLock() - defer fake.getByIDMutex.RUnlock() - argsForCall := fake.getByIDArgsForCall[i] - return argsForCall.arg1, argsForCall.arg2 -} - -func (fake *FakeAuthFallbackService) GetByIDReturns(result1 *roomdb.User, result2 error) { - fake.getByIDMutex.Lock() - defer fake.getByIDMutex.Unlock() - fake.GetByIDStub = nil - fake.getByIDReturns = struct { - result1 *roomdb.User - result2 error - }{result1, result2} -} - -func (fake *FakeAuthFallbackService) GetByIDReturnsOnCall(i int, result1 *roomdb.User, result2 error) { - fake.getByIDMutex.Lock() - defer fake.getByIDMutex.Unlock() - fake.GetByIDStub = nil - if fake.getByIDReturnsOnCall == nil { - fake.getByIDReturnsOnCall = make(map[int]struct { - result1 *roomdb.User - result2 error - }) - } - fake.getByIDReturnsOnCall[i] = struct { - result1 *roomdb.User - result2 error - }{result1, result2} + result1 error + }{result1} } func (fake *FakeAuthFallbackService) Invocations() map[string][][]interface{} { @@ -264,8 +182,6 @@ func (fake *FakeAuthFallbackService) Invocations() map[string][][]interface{} { defer fake.checkMutex.RUnlock() fake.createMutex.RLock() defer fake.createMutex.RUnlock() - fake.getByIDMutex.RLock() - defer fake.getByIDMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value diff --git a/roomdb/mockdb/allow.go b/roomdb/mockdb/denied.go similarity index 75% rename from roomdb/mockdb/allow.go rename to roomdb/mockdb/denied.go index 6992c81..db73b5d 100644 --- a/roomdb/mockdb/allow.go +++ b/roomdb/mockdb/denied.go @@ -9,7 +9,7 @@ import ( refs "go.mindeco.de/ssb-refs" ) -type FakeAllowListService struct { +type FakeDeniedListService struct { AddStub func(context.Context, refs.FeedRef) error addMutex sync.RWMutex addArgsForCall []struct { @@ -60,17 +60,17 @@ type FakeAllowListService struct { hasIDReturnsOnCall map[int]struct { result1 bool } - ListStub func(context.Context) (roomdb.ListEntries, error) + ListStub func(context.Context) ([]roomdb.ListEntry, error) listMutex sync.RWMutex listArgsForCall []struct { arg1 context.Context } listReturns struct { - result1 roomdb.ListEntries + result1 []roomdb.ListEntry result2 error } listReturnsOnCall map[int]struct { - result1 roomdb.ListEntries + result1 []roomdb.ListEntry result2 error } RemoveFeedStub func(context.Context, refs.FeedRef) error @@ -101,7 +101,7 @@ type FakeAllowListService struct { invocationsMutex sync.RWMutex } -func (fake *FakeAllowListService) Add(arg1 context.Context, arg2 refs.FeedRef) error { +func (fake *FakeDeniedListService) Add(arg1 context.Context, arg2 refs.FeedRef) error { fake.addMutex.Lock() ret, specificReturn := fake.addReturnsOnCall[len(fake.addArgsForCall)] fake.addArgsForCall = append(fake.addArgsForCall, struct { @@ -121,26 +121,26 @@ func (fake *FakeAllowListService) Add(arg1 context.Context, arg2 refs.FeedRef) e return fakeReturns.result1 } -func (fake *FakeAllowListService) AddCallCount() int { +func (fake *FakeDeniedListService) AddCallCount() int { fake.addMutex.RLock() defer fake.addMutex.RUnlock() return len(fake.addArgsForCall) } -func (fake *FakeAllowListService) AddCalls(stub func(context.Context, refs.FeedRef) error) { +func (fake *FakeDeniedListService) AddCalls(stub func(context.Context, refs.FeedRef) error) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = stub } -func (fake *FakeAllowListService) AddArgsForCall(i int) (context.Context, refs.FeedRef) { +func (fake *FakeDeniedListService) AddArgsForCall(i int) (context.Context, refs.FeedRef) { fake.addMutex.RLock() defer fake.addMutex.RUnlock() argsForCall := fake.addArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) AddReturns(result1 error) { +func (fake *FakeDeniedListService) AddReturns(result1 error) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = nil @@ -149,7 +149,7 @@ func (fake *FakeAllowListService) AddReturns(result1 error) { }{result1} } -func (fake *FakeAllowListService) AddReturnsOnCall(i int, result1 error) { +func (fake *FakeDeniedListService) AddReturnsOnCall(i int, result1 error) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = nil @@ -163,7 +163,7 @@ func (fake *FakeAllowListService) AddReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeAllowListService) GetByID(arg1 context.Context, arg2 int64) (roomdb.ListEntry, error) { +func (fake *FakeDeniedListService) GetByID(arg1 context.Context, arg2 int64) (roomdb.ListEntry, error) { fake.getByIDMutex.Lock() ret, specificReturn := fake.getByIDReturnsOnCall[len(fake.getByIDArgsForCall)] fake.getByIDArgsForCall = append(fake.getByIDArgsForCall, struct { @@ -183,26 +183,26 @@ func (fake *FakeAllowListService) GetByID(arg1 context.Context, arg2 int64) (roo return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeAllowListService) GetByIDCallCount() int { +func (fake *FakeDeniedListService) GetByIDCallCount() int { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() return len(fake.getByIDArgsForCall) } -func (fake *FakeAllowListService) GetByIDCalls(stub func(context.Context, int64) (roomdb.ListEntry, error)) { +func (fake *FakeDeniedListService) GetByIDCalls(stub func(context.Context, int64) (roomdb.ListEntry, error)) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = stub } -func (fake *FakeAllowListService) GetByIDArgsForCall(i int) (context.Context, int64) { +func (fake *FakeDeniedListService) GetByIDArgsForCall(i int) (context.Context, int64) { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() argsForCall := fake.getByIDArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) GetByIDReturns(result1 roomdb.ListEntry, result2 error) { +func (fake *FakeDeniedListService) GetByIDReturns(result1 roomdb.ListEntry, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -212,7 +212,7 @@ func (fake *FakeAllowListService) GetByIDReturns(result1 roomdb.ListEntry, resul }{result1, result2} } -func (fake *FakeAllowListService) GetByIDReturnsOnCall(i int, result1 roomdb.ListEntry, result2 error) { +func (fake *FakeDeniedListService) GetByIDReturnsOnCall(i int, result1 roomdb.ListEntry, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -228,7 +228,7 @@ func (fake *FakeAllowListService) GetByIDReturnsOnCall(i int, result1 roomdb.Lis }{result1, result2} } -func (fake *FakeAllowListService) HasFeed(arg1 context.Context, arg2 refs.FeedRef) bool { +func (fake *FakeDeniedListService) HasFeed(arg1 context.Context, arg2 refs.FeedRef) bool { fake.hasFeedMutex.Lock() ret, specificReturn := fake.hasFeedReturnsOnCall[len(fake.hasFeedArgsForCall)] fake.hasFeedArgsForCall = append(fake.hasFeedArgsForCall, struct { @@ -248,26 +248,26 @@ func (fake *FakeAllowListService) HasFeed(arg1 context.Context, arg2 refs.FeedRe return fakeReturns.result1 } -func (fake *FakeAllowListService) HasFeedCallCount() int { +func (fake *FakeDeniedListService) HasFeedCallCount() int { fake.hasFeedMutex.RLock() defer fake.hasFeedMutex.RUnlock() return len(fake.hasFeedArgsForCall) } -func (fake *FakeAllowListService) HasFeedCalls(stub func(context.Context, refs.FeedRef) bool) { +func (fake *FakeDeniedListService) HasFeedCalls(stub func(context.Context, refs.FeedRef) bool) { fake.hasFeedMutex.Lock() defer fake.hasFeedMutex.Unlock() fake.HasFeedStub = stub } -func (fake *FakeAllowListService) HasFeedArgsForCall(i int) (context.Context, refs.FeedRef) { +func (fake *FakeDeniedListService) HasFeedArgsForCall(i int) (context.Context, refs.FeedRef) { fake.hasFeedMutex.RLock() defer fake.hasFeedMutex.RUnlock() argsForCall := fake.hasFeedArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) HasFeedReturns(result1 bool) { +func (fake *FakeDeniedListService) HasFeedReturns(result1 bool) { fake.hasFeedMutex.Lock() defer fake.hasFeedMutex.Unlock() fake.HasFeedStub = nil @@ -276,7 +276,7 @@ func (fake *FakeAllowListService) HasFeedReturns(result1 bool) { }{result1} } -func (fake *FakeAllowListService) HasFeedReturnsOnCall(i int, result1 bool) { +func (fake *FakeDeniedListService) HasFeedReturnsOnCall(i int, result1 bool) { fake.hasFeedMutex.Lock() defer fake.hasFeedMutex.Unlock() fake.HasFeedStub = nil @@ -290,7 +290,7 @@ func (fake *FakeAllowListService) HasFeedReturnsOnCall(i int, result1 bool) { }{result1} } -func (fake *FakeAllowListService) HasID(arg1 context.Context, arg2 int64) bool { +func (fake *FakeDeniedListService) HasID(arg1 context.Context, arg2 int64) bool { fake.hasIDMutex.Lock() ret, specificReturn := fake.hasIDReturnsOnCall[len(fake.hasIDArgsForCall)] fake.hasIDArgsForCall = append(fake.hasIDArgsForCall, struct { @@ -310,26 +310,26 @@ func (fake *FakeAllowListService) HasID(arg1 context.Context, arg2 int64) bool { return fakeReturns.result1 } -func (fake *FakeAllowListService) HasIDCallCount() int { +func (fake *FakeDeniedListService) HasIDCallCount() int { fake.hasIDMutex.RLock() defer fake.hasIDMutex.RUnlock() return len(fake.hasIDArgsForCall) } -func (fake *FakeAllowListService) HasIDCalls(stub func(context.Context, int64) bool) { +func (fake *FakeDeniedListService) HasIDCalls(stub func(context.Context, int64) bool) { fake.hasIDMutex.Lock() defer fake.hasIDMutex.Unlock() fake.HasIDStub = stub } -func (fake *FakeAllowListService) HasIDArgsForCall(i int) (context.Context, int64) { +func (fake *FakeDeniedListService) HasIDArgsForCall(i int) (context.Context, int64) { fake.hasIDMutex.RLock() defer fake.hasIDMutex.RUnlock() argsForCall := fake.hasIDArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) HasIDReturns(result1 bool) { +func (fake *FakeDeniedListService) HasIDReturns(result1 bool) { fake.hasIDMutex.Lock() defer fake.hasIDMutex.Unlock() fake.HasIDStub = nil @@ -338,7 +338,7 @@ func (fake *FakeAllowListService) HasIDReturns(result1 bool) { }{result1} } -func (fake *FakeAllowListService) HasIDReturnsOnCall(i int, result1 bool) { +func (fake *FakeDeniedListService) HasIDReturnsOnCall(i int, result1 bool) { fake.hasIDMutex.Lock() defer fake.hasIDMutex.Unlock() fake.HasIDStub = nil @@ -352,7 +352,7 @@ func (fake *FakeAllowListService) HasIDReturnsOnCall(i int, result1 bool) { }{result1} } -func (fake *FakeAllowListService) List(arg1 context.Context) (roomdb.ListEntries, error) { +func (fake *FakeDeniedListService) List(arg1 context.Context) ([]roomdb.ListEntry, error) { fake.listMutex.Lock() ret, specificReturn := fake.listReturnsOnCall[len(fake.listArgsForCall)] fake.listArgsForCall = append(fake.listArgsForCall, struct { @@ -371,52 +371,52 @@ func (fake *FakeAllowListService) List(arg1 context.Context) (roomdb.ListEntries return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeAllowListService) ListCallCount() int { +func (fake *FakeDeniedListService) ListCallCount() int { fake.listMutex.RLock() defer fake.listMutex.RUnlock() return len(fake.listArgsForCall) } -func (fake *FakeAllowListService) ListCalls(stub func(context.Context) (roomdb.ListEntries, error)) { +func (fake *FakeDeniedListService) ListCalls(stub func(context.Context) ([]roomdb.ListEntry, error)) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = stub } -func (fake *FakeAllowListService) ListArgsForCall(i int) context.Context { +func (fake *FakeDeniedListService) ListArgsForCall(i int) context.Context { fake.listMutex.RLock() defer fake.listMutex.RUnlock() argsForCall := fake.listArgsForCall[i] return argsForCall.arg1 } -func (fake *FakeAllowListService) ListReturns(result1 roomdb.ListEntries, result2 error) { +func (fake *FakeDeniedListService) ListReturns(result1 []roomdb.ListEntry, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil fake.listReturns = struct { - result1 roomdb.ListEntries + result1 []roomdb.ListEntry result2 error }{result1, result2} } -func (fake *FakeAllowListService) ListReturnsOnCall(i int, result1 roomdb.ListEntries, result2 error) { +func (fake *FakeDeniedListService) ListReturnsOnCall(i int, result1 []roomdb.ListEntry, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil if fake.listReturnsOnCall == nil { fake.listReturnsOnCall = make(map[int]struct { - result1 roomdb.ListEntries + result1 []roomdb.ListEntry result2 error }) } fake.listReturnsOnCall[i] = struct { - result1 roomdb.ListEntries + result1 []roomdb.ListEntry result2 error }{result1, result2} } -func (fake *FakeAllowListService) RemoveFeed(arg1 context.Context, arg2 refs.FeedRef) error { +func (fake *FakeDeniedListService) RemoveFeed(arg1 context.Context, arg2 refs.FeedRef) error { fake.removeFeedMutex.Lock() ret, specificReturn := fake.removeFeedReturnsOnCall[len(fake.removeFeedArgsForCall)] fake.removeFeedArgsForCall = append(fake.removeFeedArgsForCall, struct { @@ -436,26 +436,26 @@ func (fake *FakeAllowListService) RemoveFeed(arg1 context.Context, arg2 refs.Fee return fakeReturns.result1 } -func (fake *FakeAllowListService) RemoveFeedCallCount() int { +func (fake *FakeDeniedListService) RemoveFeedCallCount() int { fake.removeFeedMutex.RLock() defer fake.removeFeedMutex.RUnlock() return len(fake.removeFeedArgsForCall) } -func (fake *FakeAllowListService) RemoveFeedCalls(stub func(context.Context, refs.FeedRef) error) { +func (fake *FakeDeniedListService) RemoveFeedCalls(stub func(context.Context, refs.FeedRef) error) { fake.removeFeedMutex.Lock() defer fake.removeFeedMutex.Unlock() fake.RemoveFeedStub = stub } -func (fake *FakeAllowListService) RemoveFeedArgsForCall(i int) (context.Context, refs.FeedRef) { +func (fake *FakeDeniedListService) RemoveFeedArgsForCall(i int) (context.Context, refs.FeedRef) { fake.removeFeedMutex.RLock() defer fake.removeFeedMutex.RUnlock() argsForCall := fake.removeFeedArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) RemoveFeedReturns(result1 error) { +func (fake *FakeDeniedListService) RemoveFeedReturns(result1 error) { fake.removeFeedMutex.Lock() defer fake.removeFeedMutex.Unlock() fake.RemoveFeedStub = nil @@ -464,7 +464,7 @@ func (fake *FakeAllowListService) RemoveFeedReturns(result1 error) { }{result1} } -func (fake *FakeAllowListService) RemoveFeedReturnsOnCall(i int, result1 error) { +func (fake *FakeDeniedListService) RemoveFeedReturnsOnCall(i int, result1 error) { fake.removeFeedMutex.Lock() defer fake.removeFeedMutex.Unlock() fake.RemoveFeedStub = nil @@ -478,7 +478,7 @@ func (fake *FakeAllowListService) RemoveFeedReturnsOnCall(i int, result1 error) }{result1} } -func (fake *FakeAllowListService) RemoveID(arg1 context.Context, arg2 int64) error { +func (fake *FakeDeniedListService) RemoveID(arg1 context.Context, arg2 int64) error { fake.removeIDMutex.Lock() ret, specificReturn := fake.removeIDReturnsOnCall[len(fake.removeIDArgsForCall)] fake.removeIDArgsForCall = append(fake.removeIDArgsForCall, struct { @@ -498,26 +498,26 @@ func (fake *FakeAllowListService) RemoveID(arg1 context.Context, arg2 int64) err return fakeReturns.result1 } -func (fake *FakeAllowListService) RemoveIDCallCount() int { +func (fake *FakeDeniedListService) RemoveIDCallCount() int { fake.removeIDMutex.RLock() defer fake.removeIDMutex.RUnlock() return len(fake.removeIDArgsForCall) } -func (fake *FakeAllowListService) RemoveIDCalls(stub func(context.Context, int64) error) { +func (fake *FakeDeniedListService) RemoveIDCalls(stub func(context.Context, int64) error) { fake.removeIDMutex.Lock() defer fake.removeIDMutex.Unlock() fake.RemoveIDStub = stub } -func (fake *FakeAllowListService) RemoveIDArgsForCall(i int) (context.Context, int64) { +func (fake *FakeDeniedListService) RemoveIDArgsForCall(i int) (context.Context, int64) { fake.removeIDMutex.RLock() defer fake.removeIDMutex.RUnlock() argsForCall := fake.removeIDArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeAllowListService) RemoveIDReturns(result1 error) { +func (fake *FakeDeniedListService) RemoveIDReturns(result1 error) { fake.removeIDMutex.Lock() defer fake.removeIDMutex.Unlock() fake.RemoveIDStub = nil @@ -526,7 +526,7 @@ func (fake *FakeAllowListService) RemoveIDReturns(result1 error) { }{result1} } -func (fake *FakeAllowListService) RemoveIDReturnsOnCall(i int, result1 error) { +func (fake *FakeDeniedListService) RemoveIDReturnsOnCall(i int, result1 error) { fake.removeIDMutex.Lock() defer fake.removeIDMutex.Unlock() fake.RemoveIDStub = nil @@ -540,7 +540,7 @@ func (fake *FakeAllowListService) RemoveIDReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeAllowListService) Invocations() map[string][][]interface{} { +func (fake *FakeDeniedListService) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.addMutex.RLock() @@ -564,7 +564,7 @@ func (fake *FakeAllowListService) Invocations() map[string][][]interface{} { return copiedInvocations } -func (fake *FakeAllowListService) recordInvocation(key string, args []interface{}) { +func (fake *FakeDeniedListService) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { @@ -576,4 +576,4 @@ func (fake *FakeAllowListService) recordInvocation(key string, args []interface{ fake.invocations[key] = append(fake.invocations[key], args) } -var _ roomdb.AllowListService = new(FakeAllowListService) +var _ roomdb.DeniedListService = new(FakeDeniedListService) diff --git a/roomdb/mockdb/invite.go b/roomdb/mockdb/invites.go similarity index 77% rename from roomdb/mockdb/invite.go rename to roomdb/mockdb/invites.go index 36a87a2..5f2df16 100644 --- a/roomdb/mockdb/invite.go +++ b/roomdb/mockdb/invites.go @@ -9,7 +9,7 @@ import ( refs "go.mindeco.de/ssb-refs" ) -type FakeInviteService struct { +type FakeInvitesService struct { ConsumeStub func(context.Context, string, refs.FeedRef) (roomdb.Invite, error) consumeMutex sync.RWMutex consumeArgsForCall []struct { @@ -97,7 +97,7 @@ type FakeInviteService struct { invocationsMutex sync.RWMutex } -func (fake *FakeInviteService) Consume(arg1 context.Context, arg2 string, arg3 refs.FeedRef) (roomdb.Invite, error) { +func (fake *FakeInvitesService) Consume(arg1 context.Context, arg2 string, arg3 refs.FeedRef) (roomdb.Invite, error) { fake.consumeMutex.Lock() ret, specificReturn := fake.consumeReturnsOnCall[len(fake.consumeArgsForCall)] fake.consumeArgsForCall = append(fake.consumeArgsForCall, struct { @@ -118,26 +118,26 @@ func (fake *FakeInviteService) Consume(arg1 context.Context, arg2 string, arg3 r return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeInviteService) ConsumeCallCount() int { +func (fake *FakeInvitesService) ConsumeCallCount() int { fake.consumeMutex.RLock() defer fake.consumeMutex.RUnlock() return len(fake.consumeArgsForCall) } -func (fake *FakeInviteService) ConsumeCalls(stub func(context.Context, string, refs.FeedRef) (roomdb.Invite, error)) { +func (fake *FakeInvitesService) ConsumeCalls(stub func(context.Context, string, refs.FeedRef) (roomdb.Invite, error)) { fake.consumeMutex.Lock() defer fake.consumeMutex.Unlock() fake.ConsumeStub = stub } -func (fake *FakeInviteService) ConsumeArgsForCall(i int) (context.Context, string, refs.FeedRef) { +func (fake *FakeInvitesService) ConsumeArgsForCall(i int) (context.Context, string, refs.FeedRef) { fake.consumeMutex.RLock() defer fake.consumeMutex.RUnlock() argsForCall := fake.consumeArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } -func (fake *FakeInviteService) ConsumeReturns(result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) ConsumeReturns(result1 roomdb.Invite, result2 error) { fake.consumeMutex.Lock() defer fake.consumeMutex.Unlock() fake.ConsumeStub = nil @@ -147,7 +147,7 @@ func (fake *FakeInviteService) ConsumeReturns(result1 roomdb.Invite, result2 err }{result1, result2} } -func (fake *FakeInviteService) ConsumeReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) ConsumeReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { fake.consumeMutex.Lock() defer fake.consumeMutex.Unlock() fake.ConsumeStub = nil @@ -163,7 +163,7 @@ func (fake *FakeInviteService) ConsumeReturnsOnCall(i int, result1 roomdb.Invite }{result1, result2} } -func (fake *FakeInviteService) Create(arg1 context.Context, arg2 int64, arg3 string) (string, error) { +func (fake *FakeInvitesService) Create(arg1 context.Context, arg2 int64, arg3 string) (string, error) { fake.createMutex.Lock() ret, specificReturn := fake.createReturnsOnCall[len(fake.createArgsForCall)] fake.createArgsForCall = append(fake.createArgsForCall, struct { @@ -184,26 +184,26 @@ func (fake *FakeInviteService) Create(arg1 context.Context, arg2 int64, arg3 str return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeInviteService) CreateCallCount() int { +func (fake *FakeInvitesService) CreateCallCount() int { fake.createMutex.RLock() defer fake.createMutex.RUnlock() return len(fake.createArgsForCall) } -func (fake *FakeInviteService) CreateCalls(stub func(context.Context, int64, string) (string, error)) { +func (fake *FakeInvitesService) CreateCalls(stub func(context.Context, int64, string) (string, error)) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = stub } -func (fake *FakeInviteService) CreateArgsForCall(i int) (context.Context, int64, string) { +func (fake *FakeInvitesService) CreateArgsForCall(i int) (context.Context, int64, string) { fake.createMutex.RLock() defer fake.createMutex.RUnlock() argsForCall := fake.createArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } -func (fake *FakeInviteService) CreateReturns(result1 string, result2 error) { +func (fake *FakeInvitesService) CreateReturns(result1 string, result2 error) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = nil @@ -213,7 +213,7 @@ func (fake *FakeInviteService) CreateReturns(result1 string, result2 error) { }{result1, result2} } -func (fake *FakeInviteService) CreateReturnsOnCall(i int, result1 string, result2 error) { +func (fake *FakeInvitesService) CreateReturnsOnCall(i int, result1 string, result2 error) { fake.createMutex.Lock() defer fake.createMutex.Unlock() fake.CreateStub = nil @@ -229,7 +229,7 @@ func (fake *FakeInviteService) CreateReturnsOnCall(i int, result1 string, result }{result1, result2} } -func (fake *FakeInviteService) GetByID(arg1 context.Context, arg2 int64) (roomdb.Invite, error) { +func (fake *FakeInvitesService) GetByID(arg1 context.Context, arg2 int64) (roomdb.Invite, error) { fake.getByIDMutex.Lock() ret, specificReturn := fake.getByIDReturnsOnCall[len(fake.getByIDArgsForCall)] fake.getByIDArgsForCall = append(fake.getByIDArgsForCall, struct { @@ -249,26 +249,26 @@ func (fake *FakeInviteService) GetByID(arg1 context.Context, arg2 int64) (roomdb return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeInviteService) GetByIDCallCount() int { +func (fake *FakeInvitesService) GetByIDCallCount() int { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() return len(fake.getByIDArgsForCall) } -func (fake *FakeInviteService) GetByIDCalls(stub func(context.Context, int64) (roomdb.Invite, error)) { +func (fake *FakeInvitesService) GetByIDCalls(stub func(context.Context, int64) (roomdb.Invite, error)) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = stub } -func (fake *FakeInviteService) GetByIDArgsForCall(i int) (context.Context, int64) { +func (fake *FakeInvitesService) GetByIDArgsForCall(i int) (context.Context, int64) { fake.getByIDMutex.RLock() defer fake.getByIDMutex.RUnlock() argsForCall := fake.getByIDArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeInviteService) GetByIDReturns(result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) GetByIDReturns(result1 roomdb.Invite, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -278,7 +278,7 @@ func (fake *FakeInviteService) GetByIDReturns(result1 roomdb.Invite, result2 err }{result1, result2} } -func (fake *FakeInviteService) GetByIDReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) GetByIDReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { fake.getByIDMutex.Lock() defer fake.getByIDMutex.Unlock() fake.GetByIDStub = nil @@ -294,7 +294,7 @@ func (fake *FakeInviteService) GetByIDReturnsOnCall(i int, result1 roomdb.Invite }{result1, result2} } -func (fake *FakeInviteService) GetByToken(arg1 context.Context, arg2 string) (roomdb.Invite, error) { +func (fake *FakeInvitesService) GetByToken(arg1 context.Context, arg2 string) (roomdb.Invite, error) { fake.getByTokenMutex.Lock() ret, specificReturn := fake.getByTokenReturnsOnCall[len(fake.getByTokenArgsForCall)] fake.getByTokenArgsForCall = append(fake.getByTokenArgsForCall, struct { @@ -314,26 +314,26 @@ func (fake *FakeInviteService) GetByToken(arg1 context.Context, arg2 string) (ro return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeInviteService) GetByTokenCallCount() int { +func (fake *FakeInvitesService) GetByTokenCallCount() int { fake.getByTokenMutex.RLock() defer fake.getByTokenMutex.RUnlock() return len(fake.getByTokenArgsForCall) } -func (fake *FakeInviteService) GetByTokenCalls(stub func(context.Context, string) (roomdb.Invite, error)) { +func (fake *FakeInvitesService) GetByTokenCalls(stub func(context.Context, string) (roomdb.Invite, error)) { fake.getByTokenMutex.Lock() defer fake.getByTokenMutex.Unlock() fake.GetByTokenStub = stub } -func (fake *FakeInviteService) GetByTokenArgsForCall(i int) (context.Context, string) { +func (fake *FakeInvitesService) GetByTokenArgsForCall(i int) (context.Context, string) { fake.getByTokenMutex.RLock() defer fake.getByTokenMutex.RUnlock() argsForCall := fake.getByTokenArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeInviteService) GetByTokenReturns(result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) GetByTokenReturns(result1 roomdb.Invite, result2 error) { fake.getByTokenMutex.Lock() defer fake.getByTokenMutex.Unlock() fake.GetByTokenStub = nil @@ -343,7 +343,7 @@ func (fake *FakeInviteService) GetByTokenReturns(result1 roomdb.Invite, result2 }{result1, result2} } -func (fake *FakeInviteService) GetByTokenReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) GetByTokenReturnsOnCall(i int, result1 roomdb.Invite, result2 error) { fake.getByTokenMutex.Lock() defer fake.getByTokenMutex.Unlock() fake.GetByTokenStub = nil @@ -359,7 +359,7 @@ func (fake *FakeInviteService) GetByTokenReturnsOnCall(i int, result1 roomdb.Inv }{result1, result2} } -func (fake *FakeInviteService) List(arg1 context.Context) ([]roomdb.Invite, error) { +func (fake *FakeInvitesService) List(arg1 context.Context) ([]roomdb.Invite, error) { fake.listMutex.Lock() ret, specificReturn := fake.listReturnsOnCall[len(fake.listArgsForCall)] fake.listArgsForCall = append(fake.listArgsForCall, struct { @@ -378,26 +378,26 @@ func (fake *FakeInviteService) List(arg1 context.Context) ([]roomdb.Invite, erro return fakeReturns.result1, fakeReturns.result2 } -func (fake *FakeInviteService) ListCallCount() int { +func (fake *FakeInvitesService) ListCallCount() int { fake.listMutex.RLock() defer fake.listMutex.RUnlock() return len(fake.listArgsForCall) } -func (fake *FakeInviteService) ListCalls(stub func(context.Context) ([]roomdb.Invite, error)) { +func (fake *FakeInvitesService) ListCalls(stub func(context.Context) ([]roomdb.Invite, error)) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = stub } -func (fake *FakeInviteService) ListArgsForCall(i int) context.Context { +func (fake *FakeInvitesService) ListArgsForCall(i int) context.Context { fake.listMutex.RLock() defer fake.listMutex.RUnlock() argsForCall := fake.listArgsForCall[i] return argsForCall.arg1 } -func (fake *FakeInviteService) ListReturns(result1 []roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) ListReturns(result1 []roomdb.Invite, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil @@ -407,7 +407,7 @@ func (fake *FakeInviteService) ListReturns(result1 []roomdb.Invite, result2 erro }{result1, result2} } -func (fake *FakeInviteService) ListReturnsOnCall(i int, result1 []roomdb.Invite, result2 error) { +func (fake *FakeInvitesService) ListReturnsOnCall(i int, result1 []roomdb.Invite, result2 error) { fake.listMutex.Lock() defer fake.listMutex.Unlock() fake.ListStub = nil @@ -423,7 +423,7 @@ func (fake *FakeInviteService) ListReturnsOnCall(i int, result1 []roomdb.Invite, }{result1, result2} } -func (fake *FakeInviteService) Revoke(arg1 context.Context, arg2 int64) error { +func (fake *FakeInvitesService) Revoke(arg1 context.Context, arg2 int64) error { fake.revokeMutex.Lock() ret, specificReturn := fake.revokeReturnsOnCall[len(fake.revokeArgsForCall)] fake.revokeArgsForCall = append(fake.revokeArgsForCall, struct { @@ -443,26 +443,26 @@ func (fake *FakeInviteService) Revoke(arg1 context.Context, arg2 int64) error { return fakeReturns.result1 } -func (fake *FakeInviteService) RevokeCallCount() int { +func (fake *FakeInvitesService) RevokeCallCount() int { fake.revokeMutex.RLock() defer fake.revokeMutex.RUnlock() return len(fake.revokeArgsForCall) } -func (fake *FakeInviteService) RevokeCalls(stub func(context.Context, int64) error) { +func (fake *FakeInvitesService) RevokeCalls(stub func(context.Context, int64) error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = stub } -func (fake *FakeInviteService) RevokeArgsForCall(i int) (context.Context, int64) { +func (fake *FakeInvitesService) RevokeArgsForCall(i int) (context.Context, int64) { fake.revokeMutex.RLock() defer fake.revokeMutex.RUnlock() argsForCall := fake.revokeArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } -func (fake *FakeInviteService) RevokeReturns(result1 error) { +func (fake *FakeInvitesService) RevokeReturns(result1 error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = nil @@ -471,7 +471,7 @@ func (fake *FakeInviteService) RevokeReturns(result1 error) { }{result1} } -func (fake *FakeInviteService) RevokeReturnsOnCall(i int, result1 error) { +func (fake *FakeInvitesService) RevokeReturnsOnCall(i int, result1 error) { fake.revokeMutex.Lock() defer fake.revokeMutex.Unlock() fake.RevokeStub = nil @@ -485,7 +485,7 @@ func (fake *FakeInviteService) RevokeReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeInviteService) Invocations() map[string][][]interface{} { +func (fake *FakeInvitesService) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.consumeMutex.RLock() @@ -507,7 +507,7 @@ func (fake *FakeInviteService) Invocations() map[string][][]interface{} { return copiedInvocations } -func (fake *FakeInviteService) recordInvocation(key string, args []interface{}) { +func (fake *FakeInvitesService) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { @@ -519,4 +519,4 @@ func (fake *FakeInviteService) recordInvocation(key string, args []interface{}) fake.invocations[key] = append(fake.invocations[key], args) } -var _ roomdb.InviteService = new(FakeInviteService) +var _ roomdb.InvitesService = new(FakeInvitesService) diff --git a/roomdb/mockdb/members.go b/roomdb/mockdb/members.go new file mode 100644 index 0000000..b56f394 --- /dev/null +++ b/roomdb/mockdb/members.go @@ -0,0 +1,666 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package mockdb + +import ( + "context" + "sync" + + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + refs "go.mindeco.de/ssb-refs" +) + +type FakeMembersService struct { + AddStub func(context.Context, string, refs.FeedRef, roomdb.Role) (int64, error) + addMutex sync.RWMutex + addArgsForCall []struct { + arg1 context.Context + arg2 string + arg3 refs.FeedRef + arg4 roomdb.Role + } + addReturns struct { + result1 int64 + result2 error + } + addReturnsOnCall map[int]struct { + result1 int64 + result2 error + } + GetByIDStub func(context.Context, int64) (roomdb.Member, error) + getByIDMutex sync.RWMutex + getByIDArgsForCall []struct { + arg1 context.Context + arg2 int64 + } + getByIDReturns struct { + result1 roomdb.Member + result2 error + } + getByIDReturnsOnCall map[int]struct { + result1 roomdb.Member + result2 error + } + HasFeedStub func(context.Context, refs.FeedRef) bool + hasFeedMutex sync.RWMutex + hasFeedArgsForCall []struct { + arg1 context.Context + arg2 refs.FeedRef + } + hasFeedReturns struct { + result1 bool + } + hasFeedReturnsOnCall map[int]struct { + result1 bool + } + HasIDStub func(context.Context, int64) bool + hasIDMutex sync.RWMutex + hasIDArgsForCall []struct { + arg1 context.Context + arg2 int64 + } + hasIDReturns struct { + result1 bool + } + hasIDReturnsOnCall map[int]struct { + result1 bool + } + ListStub func(context.Context) ([]roomdb.Member, error) + listMutex sync.RWMutex + listArgsForCall []struct { + arg1 context.Context + } + listReturns struct { + result1 []roomdb.Member + result2 error + } + listReturnsOnCall map[int]struct { + result1 []roomdb.Member + result2 error + } + RemoveFeedStub func(context.Context, refs.FeedRef) error + removeFeedMutex sync.RWMutex + removeFeedArgsForCall []struct { + arg1 context.Context + arg2 refs.FeedRef + } + removeFeedReturns struct { + result1 error + } + removeFeedReturnsOnCall map[int]struct { + result1 error + } + RemoveIDStub func(context.Context, int64) error + removeIDMutex sync.RWMutex + removeIDArgsForCall []struct { + arg1 context.Context + arg2 int64 + } + removeIDReturns struct { + result1 error + } + removeIDReturnsOnCall map[int]struct { + result1 error + } + SetRoleStub func(context.Context, int64, roomdb.Role) error + setRoleMutex sync.RWMutex + setRoleArgsForCall []struct { + arg1 context.Context + arg2 int64 + arg3 roomdb.Role + } + setRoleReturns struct { + result1 error + } + setRoleReturnsOnCall map[int]struct { + result1 error + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeMembersService) Add(arg1 context.Context, arg2 string, arg3 refs.FeedRef, arg4 roomdb.Role) (int64, error) { + fake.addMutex.Lock() + ret, specificReturn := fake.addReturnsOnCall[len(fake.addArgsForCall)] + fake.addArgsForCall = append(fake.addArgsForCall, struct { + arg1 context.Context + arg2 string + arg3 refs.FeedRef + arg4 roomdb.Role + }{arg1, arg2, arg3, arg4}) + stub := fake.AddStub + fakeReturns := fake.addReturns + fake.recordInvocation("Add", []interface{}{arg1, arg2, arg3, arg4}) + fake.addMutex.Unlock() + if stub != nil { + return stub(arg1, arg2, arg3, arg4) + } + if specificReturn { + return ret.result1, ret.result2 + } + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeMembersService) AddCallCount() int { + fake.addMutex.RLock() + defer fake.addMutex.RUnlock() + return len(fake.addArgsForCall) +} + +func (fake *FakeMembersService) AddCalls(stub func(context.Context, string, refs.FeedRef, roomdb.Role) (int64, error)) { + fake.addMutex.Lock() + defer fake.addMutex.Unlock() + fake.AddStub = stub +} + +func (fake *FakeMembersService) AddArgsForCall(i int) (context.Context, string, refs.FeedRef, roomdb.Role) { + fake.addMutex.RLock() + defer fake.addMutex.RUnlock() + argsForCall := fake.addArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 +} + +func (fake *FakeMembersService) AddReturns(result1 int64, result2 error) { + fake.addMutex.Lock() + defer fake.addMutex.Unlock() + fake.AddStub = nil + fake.addReturns = struct { + result1 int64 + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) AddReturnsOnCall(i int, result1 int64, result2 error) { + fake.addMutex.Lock() + defer fake.addMutex.Unlock() + fake.AddStub = nil + if fake.addReturnsOnCall == nil { + fake.addReturnsOnCall = make(map[int]struct { + result1 int64 + result2 error + }) + } + fake.addReturnsOnCall[i] = struct { + result1 int64 + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) GetByID(arg1 context.Context, arg2 int64) (roomdb.Member, error) { + fake.getByIDMutex.Lock() + ret, specificReturn := fake.getByIDReturnsOnCall[len(fake.getByIDArgsForCall)] + fake.getByIDArgsForCall = append(fake.getByIDArgsForCall, struct { + arg1 context.Context + arg2 int64 + }{arg1, arg2}) + stub := fake.GetByIDStub + fakeReturns := fake.getByIDReturns + fake.recordInvocation("GetByID", []interface{}{arg1, arg2}) + fake.getByIDMutex.Unlock() + if stub != nil { + return stub(arg1, arg2) + } + if specificReturn { + return ret.result1, ret.result2 + } + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeMembersService) GetByIDCallCount() int { + fake.getByIDMutex.RLock() + defer fake.getByIDMutex.RUnlock() + return len(fake.getByIDArgsForCall) +} + +func (fake *FakeMembersService) GetByIDCalls(stub func(context.Context, int64) (roomdb.Member, error)) { + fake.getByIDMutex.Lock() + defer fake.getByIDMutex.Unlock() + fake.GetByIDStub = stub +} + +func (fake *FakeMembersService) GetByIDArgsForCall(i int) (context.Context, int64) { + fake.getByIDMutex.RLock() + defer fake.getByIDMutex.RUnlock() + argsForCall := fake.getByIDArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeMembersService) GetByIDReturns(result1 roomdb.Member, result2 error) { + fake.getByIDMutex.Lock() + defer fake.getByIDMutex.Unlock() + fake.GetByIDStub = nil + fake.getByIDReturns = struct { + result1 roomdb.Member + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) GetByIDReturnsOnCall(i int, result1 roomdb.Member, result2 error) { + fake.getByIDMutex.Lock() + defer fake.getByIDMutex.Unlock() + fake.GetByIDStub = nil + if fake.getByIDReturnsOnCall == nil { + fake.getByIDReturnsOnCall = make(map[int]struct { + result1 roomdb.Member + result2 error + }) + } + fake.getByIDReturnsOnCall[i] = struct { + result1 roomdb.Member + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) HasFeed(arg1 context.Context, arg2 refs.FeedRef) bool { + fake.hasFeedMutex.Lock() + ret, specificReturn := fake.hasFeedReturnsOnCall[len(fake.hasFeedArgsForCall)] + fake.hasFeedArgsForCall = append(fake.hasFeedArgsForCall, struct { + arg1 context.Context + arg2 refs.FeedRef + }{arg1, arg2}) + stub := fake.HasFeedStub + fakeReturns := fake.hasFeedReturns + fake.recordInvocation("HasFeed", []interface{}{arg1, arg2}) + fake.hasFeedMutex.Unlock() + if stub != nil { + return stub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeMembersService) HasFeedCallCount() int { + fake.hasFeedMutex.RLock() + defer fake.hasFeedMutex.RUnlock() + return len(fake.hasFeedArgsForCall) +} + +func (fake *FakeMembersService) HasFeedCalls(stub func(context.Context, refs.FeedRef) bool) { + fake.hasFeedMutex.Lock() + defer fake.hasFeedMutex.Unlock() + fake.HasFeedStub = stub +} + +func (fake *FakeMembersService) HasFeedArgsForCall(i int) (context.Context, refs.FeedRef) { + fake.hasFeedMutex.RLock() + defer fake.hasFeedMutex.RUnlock() + argsForCall := fake.hasFeedArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeMembersService) HasFeedReturns(result1 bool) { + fake.hasFeedMutex.Lock() + defer fake.hasFeedMutex.Unlock() + fake.HasFeedStub = nil + fake.hasFeedReturns = struct { + result1 bool + }{result1} +} + +func (fake *FakeMembersService) HasFeedReturnsOnCall(i int, result1 bool) { + fake.hasFeedMutex.Lock() + defer fake.hasFeedMutex.Unlock() + fake.HasFeedStub = nil + if fake.hasFeedReturnsOnCall == nil { + fake.hasFeedReturnsOnCall = make(map[int]struct { + result1 bool + }) + } + fake.hasFeedReturnsOnCall[i] = struct { + result1 bool + }{result1} +} + +func (fake *FakeMembersService) HasID(arg1 context.Context, arg2 int64) bool { + fake.hasIDMutex.Lock() + ret, specificReturn := fake.hasIDReturnsOnCall[len(fake.hasIDArgsForCall)] + fake.hasIDArgsForCall = append(fake.hasIDArgsForCall, struct { + arg1 context.Context + arg2 int64 + }{arg1, arg2}) + stub := fake.HasIDStub + fakeReturns := fake.hasIDReturns + fake.recordInvocation("HasID", []interface{}{arg1, arg2}) + fake.hasIDMutex.Unlock() + if stub != nil { + return stub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeMembersService) HasIDCallCount() int { + fake.hasIDMutex.RLock() + defer fake.hasIDMutex.RUnlock() + return len(fake.hasIDArgsForCall) +} + +func (fake *FakeMembersService) HasIDCalls(stub func(context.Context, int64) bool) { + fake.hasIDMutex.Lock() + defer fake.hasIDMutex.Unlock() + fake.HasIDStub = stub +} + +func (fake *FakeMembersService) HasIDArgsForCall(i int) (context.Context, int64) { + fake.hasIDMutex.RLock() + defer fake.hasIDMutex.RUnlock() + argsForCall := fake.hasIDArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeMembersService) HasIDReturns(result1 bool) { + fake.hasIDMutex.Lock() + defer fake.hasIDMutex.Unlock() + fake.HasIDStub = nil + fake.hasIDReturns = struct { + result1 bool + }{result1} +} + +func (fake *FakeMembersService) HasIDReturnsOnCall(i int, result1 bool) { + fake.hasIDMutex.Lock() + defer fake.hasIDMutex.Unlock() + fake.HasIDStub = nil + if fake.hasIDReturnsOnCall == nil { + fake.hasIDReturnsOnCall = make(map[int]struct { + result1 bool + }) + } + fake.hasIDReturnsOnCall[i] = struct { + result1 bool + }{result1} +} + +func (fake *FakeMembersService) List(arg1 context.Context) ([]roomdb.Member, error) { + fake.listMutex.Lock() + ret, specificReturn := fake.listReturnsOnCall[len(fake.listArgsForCall)] + fake.listArgsForCall = append(fake.listArgsForCall, struct { + arg1 context.Context + }{arg1}) + stub := fake.ListStub + fakeReturns := fake.listReturns + fake.recordInvocation("List", []interface{}{arg1}) + fake.listMutex.Unlock() + if stub != nil { + return stub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeMembersService) ListCallCount() int { + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + return len(fake.listArgsForCall) +} + +func (fake *FakeMembersService) ListCalls(stub func(context.Context) ([]roomdb.Member, error)) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = stub +} + +func (fake *FakeMembersService) ListArgsForCall(i int) context.Context { + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + argsForCall := fake.listArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeMembersService) ListReturns(result1 []roomdb.Member, result2 error) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = nil + fake.listReturns = struct { + result1 []roomdb.Member + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) ListReturnsOnCall(i int, result1 []roomdb.Member, result2 error) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = nil + if fake.listReturnsOnCall == nil { + fake.listReturnsOnCall = make(map[int]struct { + result1 []roomdb.Member + result2 error + }) + } + fake.listReturnsOnCall[i] = struct { + result1 []roomdb.Member + result2 error + }{result1, result2} +} + +func (fake *FakeMembersService) RemoveFeed(arg1 context.Context, arg2 refs.FeedRef) error { + fake.removeFeedMutex.Lock() + ret, specificReturn := fake.removeFeedReturnsOnCall[len(fake.removeFeedArgsForCall)] + fake.removeFeedArgsForCall = append(fake.removeFeedArgsForCall, struct { + arg1 context.Context + arg2 refs.FeedRef + }{arg1, arg2}) + stub := fake.RemoveFeedStub + fakeReturns := fake.removeFeedReturns + fake.recordInvocation("RemoveFeed", []interface{}{arg1, arg2}) + fake.removeFeedMutex.Unlock() + if stub != nil { + return stub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeMembersService) RemoveFeedCallCount() int { + fake.removeFeedMutex.RLock() + defer fake.removeFeedMutex.RUnlock() + return len(fake.removeFeedArgsForCall) +} + +func (fake *FakeMembersService) RemoveFeedCalls(stub func(context.Context, refs.FeedRef) error) { + fake.removeFeedMutex.Lock() + defer fake.removeFeedMutex.Unlock() + fake.RemoveFeedStub = stub +} + +func (fake *FakeMembersService) RemoveFeedArgsForCall(i int) (context.Context, refs.FeedRef) { + fake.removeFeedMutex.RLock() + defer fake.removeFeedMutex.RUnlock() + argsForCall := fake.removeFeedArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeMembersService) RemoveFeedReturns(result1 error) { + fake.removeFeedMutex.Lock() + defer fake.removeFeedMutex.Unlock() + fake.RemoveFeedStub = nil + fake.removeFeedReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) RemoveFeedReturnsOnCall(i int, result1 error) { + fake.removeFeedMutex.Lock() + defer fake.removeFeedMutex.Unlock() + fake.RemoveFeedStub = nil + if fake.removeFeedReturnsOnCall == nil { + fake.removeFeedReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.removeFeedReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) RemoveID(arg1 context.Context, arg2 int64) error { + fake.removeIDMutex.Lock() + ret, specificReturn := fake.removeIDReturnsOnCall[len(fake.removeIDArgsForCall)] + fake.removeIDArgsForCall = append(fake.removeIDArgsForCall, struct { + arg1 context.Context + arg2 int64 + }{arg1, arg2}) + stub := fake.RemoveIDStub + fakeReturns := fake.removeIDReturns + fake.recordInvocation("RemoveID", []interface{}{arg1, arg2}) + fake.removeIDMutex.Unlock() + if stub != nil { + return stub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeMembersService) RemoveIDCallCount() int { + fake.removeIDMutex.RLock() + defer fake.removeIDMutex.RUnlock() + return len(fake.removeIDArgsForCall) +} + +func (fake *FakeMembersService) RemoveIDCalls(stub func(context.Context, int64) error) { + fake.removeIDMutex.Lock() + defer fake.removeIDMutex.Unlock() + fake.RemoveIDStub = stub +} + +func (fake *FakeMembersService) RemoveIDArgsForCall(i int) (context.Context, int64) { + fake.removeIDMutex.RLock() + defer fake.removeIDMutex.RUnlock() + argsForCall := fake.removeIDArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeMembersService) RemoveIDReturns(result1 error) { + fake.removeIDMutex.Lock() + defer fake.removeIDMutex.Unlock() + fake.RemoveIDStub = nil + fake.removeIDReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) RemoveIDReturnsOnCall(i int, result1 error) { + fake.removeIDMutex.Lock() + defer fake.removeIDMutex.Unlock() + fake.RemoveIDStub = nil + if fake.removeIDReturnsOnCall == nil { + fake.removeIDReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.removeIDReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) SetRole(arg1 context.Context, arg2 int64, arg3 roomdb.Role) error { + fake.setRoleMutex.Lock() + ret, specificReturn := fake.setRoleReturnsOnCall[len(fake.setRoleArgsForCall)] + fake.setRoleArgsForCall = append(fake.setRoleArgsForCall, struct { + arg1 context.Context + arg2 int64 + arg3 roomdb.Role + }{arg1, arg2, arg3}) + stub := fake.SetRoleStub + fakeReturns := fake.setRoleReturns + fake.recordInvocation("SetRole", []interface{}{arg1, arg2, arg3}) + fake.setRoleMutex.Unlock() + if stub != nil { + return stub(arg1, arg2, arg3) + } + if specificReturn { + return ret.result1 + } + return fakeReturns.result1 +} + +func (fake *FakeMembersService) SetRoleCallCount() int { + fake.setRoleMutex.RLock() + defer fake.setRoleMutex.RUnlock() + return len(fake.setRoleArgsForCall) +} + +func (fake *FakeMembersService) SetRoleCalls(stub func(context.Context, int64, roomdb.Role) error) { + fake.setRoleMutex.Lock() + defer fake.setRoleMutex.Unlock() + fake.SetRoleStub = stub +} + +func (fake *FakeMembersService) SetRoleArgsForCall(i int) (context.Context, int64, roomdb.Role) { + fake.setRoleMutex.RLock() + defer fake.setRoleMutex.RUnlock() + argsForCall := fake.setRoleArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 +} + +func (fake *FakeMembersService) SetRoleReturns(result1 error) { + fake.setRoleMutex.Lock() + defer fake.setRoleMutex.Unlock() + fake.SetRoleStub = nil + fake.setRoleReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) SetRoleReturnsOnCall(i int, result1 error) { + fake.setRoleMutex.Lock() + defer fake.setRoleMutex.Unlock() + fake.SetRoleStub = nil + if fake.setRoleReturnsOnCall == nil { + fake.setRoleReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.setRoleReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeMembersService) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.addMutex.RLock() + defer fake.addMutex.RUnlock() + fake.getByIDMutex.RLock() + defer fake.getByIDMutex.RUnlock() + fake.hasFeedMutex.RLock() + defer fake.hasFeedMutex.RUnlock() + fake.hasIDMutex.RLock() + defer fake.hasIDMutex.RUnlock() + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + fake.removeFeedMutex.RLock() + defer fake.removeFeedMutex.RUnlock() + fake.removeIDMutex.RLock() + defer fake.removeIDMutex.RUnlock() + fake.setRoleMutex.RLock() + defer fake.setRoleMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeMembersService) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ roomdb.MembersService = new(FakeMembersService) diff --git a/roomdb/role_string.go b/roomdb/role_string.go new file mode 100644 index 0000000..c3d6c56 --- /dev/null +++ b/roomdb/role_string.go @@ -0,0 +1,26 @@ +// Code generated by "stringer -type=Role"; DO NOT EDIT. + +package roomdb + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[RoleUnknown-0] + _ = x[RoleMember-1] + _ = x[RoleModerator-2] + _ = x[RoleAdmin-3] +} + +const _Role_name = "RoleUnknownRoleMemberRoleModeratorRoleAdmin" + +var _Role_index = [...]uint8{0, 11, 21, 34, 43} + +func (i Role) String() string { + if i >= Role(len(_Role_index)-1) { + return "Role(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Role_name[_Role_index[i]:_Role_index[i+1]] +} diff --git a/roomdb/sqlite/aliases.go b/roomdb/sqlite/aliases.go index 56dbdae..e45afd4 100644 --- a/roomdb/sqlite/aliases.go +++ b/roomdb/sqlite/aliases.go @@ -16,7 +16,7 @@ import ( ) // compiler assertion to ensure the struct fullfills the interface -var _ roomdb.AliasService = (*Aliases)(nil) +var _ roomdb.AliasesService = (*Aliases)(nil) type Aliases struct { db *sql.DB @@ -35,8 +35,8 @@ func (a Aliases) GetByID(ctx context.Context, id int64) (roomdb.Alias, error) { func (a Aliases) findOne(ctx context.Context, by qm.QueryMod) (roomdb.Alias, error) { var found roomdb.Alias - // construct query which resolves the User relation and by which we shoudl look for it - qry := append([]qm.QueryMod{qm.Load("User")}, by) + // construct query which resolves the Member relation and by which we shoudl look for it + qry := append([]qm.QueryMod{qm.Load("Member")}, by) entry, err := models.Aliases(qry...).One(ctx, a.db) if err != nil { @@ -50,14 +50,14 @@ func (a Aliases) findOne(ctx context.Context, by qm.QueryMod) (roomdb.Alias, err found.ID = entry.ID found.Name = entry.Name found.Signature = entry.Signature - found.Feed = entry.R.User.PubKey.FeedRef + found.Feed = entry.R.Member.PubKey.FeedRef return found, nil } // List returns a list of all registerd aliases func (a Aliases) List(ctx context.Context) ([]roomdb.Alias, error) { - all, err := models.Aliases(qm.Load("User")).All(ctx, a.db) + all, err := models.Aliases(qm.Load("Member")).All(ctx, a.db) if err != nil { return nil, err } @@ -68,7 +68,7 @@ func (a Aliases) List(ctx context.Context) ([]roomdb.Alias, error) { aliases[i] = roomdb.Alias{ ID: entry.ID, Name: entry.Name, - Feed: entry.R.User.PubKey.FeedRef, + Feed: entry.R.Member.PubKey.FeedRef, Signature: entry.Signature, } } @@ -80,7 +80,7 @@ func (a Aliases) List(ctx context.Context) ([]roomdb.Alias, error) { func (a Aliases) Register(ctx context.Context, alias string, userFeed refs.FeedRef, signature []byte) error { return transact(a.db, func(tx *sql.Tx) error { // check we have a members entry for the feed and load it to get its ID - allowListEntry, err := models.AllowLists(qm.Where("pub_key = ?", userFeed.Ref())).One(ctx, tx) + memberEntry, err := models.Members(qm.Where("pub_key = ?", userFeed.Ref())).One(ctx, tx) if err != nil { if errors.Is(err, sql.ErrNoRows) { return roomdb.ErrNotFound @@ -90,7 +90,7 @@ func (a Aliases) Register(ctx context.Context, alias string, userFeed refs.FeedR var newEntry models.Alias newEntry.Name = alias - newEntry.UserID = allowListEntry.ID + newEntry.MemberID = memberEntry.ID newEntry.Signature = signature err = newEntry.Insert(ctx, tx, boil.Infer()) @@ -102,7 +102,7 @@ func (a Aliases) Register(ctx context.Context, alias string, userFeed refs.FeedR // Revoke removes an alias from the system func (a Aliases) Revoke(ctx context.Context, alias string) error { return transact(a.db, func(tx *sql.Tx) error { - qry := append([]qm.QueryMod{qm.Load("User")}, qm.Where("name = ?", alias)) + qry := append([]qm.QueryMod{qm.Load("Member")}, qm.Where("name = ?", alias)) entry, err := models.Aliases(qry...).One(ctx, a.db) if err != nil { diff --git a/roomdb/sqlite/aliases_test.go b/roomdb/sqlite/aliases_test.go index 3222e8e..646f71a 100644 --- a/roomdb/sqlite/aliases_test.go +++ b/roomdb/sqlite/aliases_test.go @@ -65,7 +65,7 @@ func TestAliases(t *testing.T) { r.Error(err) // allow the member - err = db.AllowList.Add(ctx, newMember) + _, err = db.Members.Add(ctx, "flaky's nick", newMember, roomdb.RoleMember) r.NoError(err) err = db.Aliases.Register(ctx, testName, newMember, testSig) diff --git a/roomdb/sqlite/auth_fallback.go b/roomdb/sqlite/auth_fallback.go index 9a37c2b..185b759 100644 --- a/roomdb/sqlite/auth_fallback.go +++ b/roomdb/sqlite/auth_fallback.go @@ -8,13 +8,11 @@ import ( "fmt" "github.com/volatiletech/sqlboiler/v4/boil" - + "github.com/volatiletech/sqlboiler/v4/queries/qm" "golang.org/x/crypto/bcrypt" - "github.com/ssb-ngi-pointer/go-ssb-room/roomdb/sqlite/models" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb/sqlite/models" ) // compiler assertion to ensure the struct fullfills the interface @@ -26,9 +24,12 @@ type AuthFallback struct { // Check receives the username and password (in clear) and checks them accordingly. // If it's a valid combination it returns the user ID, or an error if they are not. -func (af AuthFallback) Check(name, password string) (interface{}, error) { +func (af AuthFallback) Check(login, password string) (interface{}, error) { ctx := context.Background() - found, err := models.AuthFallbacks(qm.Where("name = ?", name)).One(ctx, af.db) + found, err := models.FallbackPasswords( + qm.Load("Member"), + qm.Where("login = ?", login), + ).One(ctx, af.db) if err != nil { return nil, err } @@ -38,35 +39,35 @@ func (af AuthFallback) Check(name, password string) (interface{}, error) { return nil, fmt.Errorf("auth/fallback: password missmatch") } - return found.ID, nil + return found.R.Member.ID, nil } -func (af AuthFallback) Create(ctx context.Context, name string, password []byte) (int64, error) { - var u models.AuthFallback - u.Name = name +func (af AuthFallback) Create(ctx context.Context, memberID int64, login string, password []byte) error { + var newPasswordEntry models.FallbackPassword + newPasswordEntry.MemberID = memberID + newPasswordEntry.Login = login hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { - return -1, fmt.Errorf("auth/fallback: failed to hash password for new user") + return fmt.Errorf("auth/fallback: failed to hash password for new user") } + newPasswordEntry.PasswordHash = hashed - u.PasswordHash = hashed - - err = u.Insert(ctx, af.db, boil.Infer()) + err = newPasswordEntry.Insert(ctx, af.db, boil.Infer()) if err != nil { - return -1, fmt.Errorf("auth/fallback: failed to insert new user: %w", err) + return fmt.Errorf("auth/fallback: failed to insert new user: %w", err) } - return u.ID, nil + return nil } -func (af AuthFallback) GetByID(ctx context.Context, uid int64) (*roomdb.User, error) { - modelU, err := models.FindAuthFallback(ctx, af.db, uid) - if err != nil { - return nil, err - } - return &roomdb.User{ - ID: modelU.ID, - Name: modelU.Name, - }, nil -} +// func (af AuthFallback) GetByID(ctx context.Context, uid int64) (roomdb.Member, error) { +// modelU, err := models.FindFallbackPassword(ctx, af.db, uid) +// if err != nil { +// return roomdb.Member{}, err +// } +// return roomdb.Member{ +// ID: modelU.ID, +// Nickname: modelU.R.Member.Nick, +// }, nil +// } diff --git a/roomdb/sqlite/roomcfg.go b/roomdb/sqlite/denied.go similarity index 63% rename from roomdb/sqlite/roomcfg.go rename to roomdb/sqlite/denied.go index 84f2b9d..868f34e 100644 --- a/roomdb/sqlite/roomcfg.go +++ b/roomdb/sqlite/denied.go @@ -1,5 +1,7 @@ // SPDX-License-Identifier: MIT +// +build ignore + package sqlite import ( @@ -18,14 +20,15 @@ import ( ) // compiler assertion to ensure the struct fullfills the interface -var _ roomdb.AllowListService = (*AllowList)(nil) +var _ roomdb.DeniedListService = (*DeniedList)(nil) -type AllowList struct { +// The DeniedList is backed by the members table +type DeniedList struct { db *sql.DB } // Add adds the feed to the list. -func (al AllowList) Add(ctx context.Context, a refs.FeedRef) error { +func (al DeniedList) Add(ctx context.Context, a refs.FeedRef) error { // single insert transaction but this makes it easier to re-use in invites.Consume return transact(al.db, func(tx *sql.Tx) error { return al.add(ctx, tx, a) @@ -33,13 +36,13 @@ func (al AllowList) Add(ctx context.Context, a refs.FeedRef) error { } // this add is not exported and for internal use with transactions. -func (al AllowList) add(ctx context.Context, tx *sql.Tx, a refs.FeedRef) error { +func (al DeniedList) add(ctx context.Context, tx *sql.Tx, a refs.FeedRef) error { // TODO: better valid if _, err := refs.ParseFeedRef(a.Ref()); err != nil { return err } - var entry models.AllowList + var entry models.Member entry.PubKey.FeedRef = a err := entry.Insert(ctx, tx, boil.Whitelist("pub_key")) @@ -49,15 +52,15 @@ func (al AllowList) add(ctx context.Context, tx *sql.Tx, a refs.FeedRef) error { return roomdb.ErrAlreadyAdded{Ref: a} } - return fmt.Errorf("allow-list: failed to insert new entry %s: %w - type:%T", entry.PubKey, err, err) + return fmt.Errorf("Denied-list: failed to insert new entry %s: %w - type:%T", entry.PubKey, err, err) } return nil } // HasFeed returns true if a feed is on the list. -func (al AllowList) HasFeed(ctx context.Context, h refs.FeedRef) bool { - _, err := models.AllowLists(qm.Where("pub_key = ?", h.Ref())).One(ctx, al.db) +func (al DeniedList) HasFeed(ctx context.Context, h refs.FeedRef) bool { + _, err := models.DeniedLists(qm.Where("pub_key = ?", h.Ref())).One(ctx, al.db) if err != nil { return false } @@ -65,8 +68,8 @@ func (al AllowList) HasFeed(ctx context.Context, h refs.FeedRef) bool { } // HasID returns true if a feed is on the list. -func (al AllowList) HasID(ctx context.Context, id int64) bool { - _, err := models.FindAllowList(ctx, al.db, id) +func (al DeniedList) HasID(ctx context.Context, id int64) bool { + _, err := models.FindDeniedList(ctx, al.db, id) if err != nil { return false } @@ -74,9 +77,9 @@ func (al AllowList) HasID(ctx context.Context, id int64) bool { } // GetByID returns the entry if a feed with that ID is on the list. -func (al AllowList) GetByID(ctx context.Context, id int64) (roomdb.ListEntry, error) { +func (al DeniedList) GetByID(ctx context.Context, id int64) (roomdb.ListEntry, error) { var le roomdb.ListEntry - entry, err := models.FindAllowList(ctx, al.db, id) + entry, err := models.FindDeniedList(ctx, al.db, id) if err != nil { if errors.Is(err, sql.ErrNoRows) { return le, roomdb.ErrNotFound @@ -91,17 +94,17 @@ func (al AllowList) GetByID(ctx context.Context, id int64) (roomdb.ListEntry, er } // List returns a list of all the feeds. -func (al AllowList) List(ctx context.Context) (roomdb.ListEntries, error) { - all, err := models.AllowLists().All(ctx, al.db) +func (al DeniedList) List(ctx context.Context) (roomdb.ListEntries, error) { + all, err := models.DeniedLists().All(ctx, al.db) if err != nil { return nil, err } var asRefs = make(roomdb.ListEntries, len(all)) - for i, allowed := range all { + for i, Denieded := range all { asRefs[i] = roomdb.ListEntry{ - ID: allowed.ID, - PubKey: allowed.PubKey.FeedRef, + ID: Denieded.ID, + PubKey: Denieded.PubKey.FeedRef, } } @@ -109,8 +112,8 @@ func (al AllowList) List(ctx context.Context) (roomdb.ListEntries, error) { } // RemoveFeed removes the feed from the list. -func (al AllowList) RemoveFeed(ctx context.Context, r refs.FeedRef) error { - entry, err := models.AllowLists(qm.Where("pub_key = ?", r.Ref())).One(ctx, al.db) +func (al DeniedList) RemoveFeed(ctx context.Context, r refs.FeedRef) error { + entry, err := models.DeniedLists(qm.Where("pub_key = ?", r.Ref())).One(ctx, al.db) if err != nil { if errors.Is(err, sql.ErrNoRows) { return roomdb.ErrNotFound @@ -127,8 +130,8 @@ func (al AllowList) RemoveFeed(ctx context.Context, r refs.FeedRef) error { } // RemoveID removes the feed from the list. -func (al AllowList) RemoveID(ctx context.Context, id int64) error { - entry, err := models.FindAllowList(ctx, al.db, id) +func (al DeniedList) RemoveID(ctx context.Context, id int64) error { + entry, err := models.FindDeniedList(ctx, al.db, id) if err != nil { if errors.Is(err, sql.ErrNoRows) { return roomdb.ErrNotFound diff --git a/roomdb/sqlite/roomcfg_test.go b/roomdb/sqlite/denied_test.go similarity index 65% rename from roomdb/sqlite/roomcfg_test.go rename to roomdb/sqlite/denied_test.go index f848e92..c5f1098 100644 --- a/roomdb/sqlite/roomcfg_test.go +++ b/roomdb/sqlite/denied_test.go @@ -1,3 +1,5 @@ +// +build ignore + package sqlite import ( @@ -15,7 +17,7 @@ import ( refs "go.mindeco.de/ssb-refs" ) -func TestAllowList(t *testing.T) { +func TestDeniedList(t *testing.T) { r := require.New(t) ctx := context.Background() @@ -28,49 +30,49 @@ func TestAllowList(t *testing.T) { require.NoError(t, err) tf := refs.FeedRef{ID: bytes.Repeat([]byte("fooo"), 8), Algo: "nope"} - err = db.AllowList.Add(ctx, tf) + err = db.DeniedList.Add(ctx, tf) r.Error(err) // looks ok at least okFeed := refs.FeedRef{ID: bytes.Repeat([]byte("acab"), 8), Algo: refs.RefAlgoFeedSSB1} - err = db.AllowList.Add(ctx, okFeed) + err = db.DeniedList.Add(ctx, okFeed) r.NoError(err) // hack into the interface to get the concrete database/sql instance - sqlDB := db.AllowList.(*AllowList).db + sqlDB := db.DeniedList.(*DeniedList).db - count, err := models.AllowLists().Count(ctx, sqlDB) + count, err := models.DeniedLists().Count(ctx, sqlDB) r.NoError(err) r.EqualValues(count, 1) - lst, err := db.AllowList.List(ctx) + lst, err := db.DeniedList.List(ctx) r.NoError(err) r.Len(lst, 1) - yes := db.AllowList.HasFeed(ctx, okFeed) + yes := db.DeniedList.HasFeed(ctx, okFeed) r.True(yes) - yes = db.AllowList.HasFeed(ctx, tf) + yes = db.DeniedList.HasFeed(ctx, tf) r.False(yes) - err = db.AllowList.RemoveFeed(ctx, okFeed) + err = db.DeniedList.RemoveFeed(ctx, okFeed) r.NoError(err) - count, err = models.AllowLists().Count(ctx, sqlDB) + count, err = models.DeniedLists().Count(ctx, sqlDB) r.NoError(err) r.EqualValues(count, 0) - lst, err = db.AllowList.List(ctx) + lst, err = db.DeniedList.List(ctx) r.NoError(err) r.Len(lst, 0) - yes = db.AllowList.HasFeed(ctx, okFeed) + yes = db.DeniedList.HasFeed(ctx, okFeed) r.False(yes) r.NoError(db.Close()) } -func TestAllowListUnique(t *testing.T) { +func TestDeniedListUnique(t *testing.T) { r := require.New(t) ctx := context.Background() @@ -83,20 +85,20 @@ func TestAllowListUnique(t *testing.T) { require.NoError(t, err) feedA := refs.FeedRef{ID: bytes.Repeat([]byte("1312"), 8), Algo: refs.RefAlgoFeedSSB1} - err = db.AllowList.Add(ctx, feedA) + err = db.DeniedList.Add(ctx, feedA) r.NoError(err) - err = db.AllowList.Add(ctx, feedA) + err = db.DeniedList.Add(ctx, feedA) r.Error(err) - lst, err := db.AllowList.List(ctx) + lst, err := db.DeniedList.List(ctx) r.NoError(err) r.Len(lst, 1) r.NoError(db.Close()) } -func TestAllowListByID(t *testing.T) { +func TestDeniedListByID(t *testing.T) { r := require.New(t) ctx := context.Background() @@ -109,26 +111,26 @@ func TestAllowListByID(t *testing.T) { require.NoError(t, err) feedA := refs.FeedRef{ID: bytes.Repeat([]byte("1312"), 8), Algo: refs.RefAlgoFeedSSB1} - err = db.AllowList.Add(ctx, feedA) + err = db.DeniedList.Add(ctx, feedA) r.NoError(err) - lst, err := db.AllowList.List(ctx) + lst, err := db.DeniedList.List(ctx) r.NoError(err) r.Len(lst, 1) - yes := db.AllowList.HasID(ctx, lst[0].ID) + yes := db.DeniedList.HasID(ctx, lst[0].ID) r.True(yes) - yes = db.AllowList.HasID(ctx, 666) + yes = db.DeniedList.HasID(ctx, 666) r.False(yes) - err = db.AllowList.RemoveID(ctx, 666) + err = db.DeniedList.RemoveID(ctx, 666) r.Error(err) r.EqualError(err, roomdb.ErrNotFound.Error()) - err = db.AllowList.RemoveID(ctx, lst[0].ID) + err = db.DeniedList.RemoveID(ctx, lst[0].ID) r.NoError(err) - yes = db.AllowList.HasID(ctx, lst[0].ID) + yes = db.DeniedList.HasID(ctx, lst[0].ID) r.False(yes) } diff --git a/roomdb/sqlite/generate_models.sh b/roomdb/sqlite/generate_models.sh index fbaea5a..4a379ae 100644 --- a/roomdb/sqlite/generate_models.sh +++ b/roomdb/sqlite/generate_models.sh @@ -6,11 +6,11 @@ set -e go get github.com/volatiletech/sqlboiler/v4 go get github.com/volatiletech/sqlboiler-sqlite3 -# run the migrations (creates testrun/TestSimple/roomdb) -go test -run Simple +# run the migrations (creates testrun/TestSchema/roomdb) +go test -run Schema # make sure the sqlite file was created -test -f testrun/TestSimple/roomdb || { +test -f testrun/TestSchema/roomdb || { echo 'roomdb file missing' exit 1 } diff --git a/roomdb/sqlite/invites.go b/roomdb/sqlite/invites.go index 8c7d376..0fc7909 100644 --- a/roomdb/sqlite/invites.go +++ b/roomdb/sqlite/invites.go @@ -20,14 +20,14 @@ import ( ) // compiler assertion to ensure the struct fullfills the interface -var _ roomdb.InviteService = (*Invites)(nil) +var _ roomdb.InvitesService = (*Invites)(nil) // Invites implements the roomdb.InviteService. // Tokens are stored as sha256 hashes on disk to protect against attackers gaining database read-access. type Invites struct { db *sql.DB - allowList *AllowList + members Members } // Create creates a new invite for a new member. It returns the token or an error. @@ -56,7 +56,7 @@ func (i Invites) Create(ctx context.Context, createdBy int64, aliasSuggestion st // hash the binary of the token for storage h := sha256.New() h.Write(tokenBytes) - newInvite.Token = fmt.Sprintf("%x", h.Sum(nil)) + newInvite.HashedToken = fmt.Sprintf("%x", h.Sum(nil)) // insert the new invite err := newInvite.Insert(ctx, tx, boil.Infer()) @@ -99,14 +99,19 @@ func (i Invites) Consume(ctx context.Context, token string, newMember refs.FeedR err = transact(i.db, func(tx *sql.Tx) error { entry, err := models.Invites( - qm.Where("active = true AND token = ?", hashedToken), - qm.Load("CreatedByAuthFallback"), + qm.Where("active = true AND hashed_token = ?", hashedToken), + qm.Load("CreatedByMember"), ).One(ctx, tx) if err != nil { return err } - err = i.allowList.add(ctx, tx, newMember) + memberNick := time.Now().Format("new-member 2006-01-02") + memberNick += "(invited by:" + entry.R.CreatedByMember.Nick + ")" + if entry.AliasSuggestion != "" { + memberNick = entry.AliasSuggestion + } + _, err = i.members.add(ctx, tx, memberNick, newMember, roomdb.RoleMember) if err != nil { return err } @@ -121,8 +126,9 @@ func (i Invites) Consume(ctx context.Context, token string, newMember refs.FeedR inv.ID = entry.ID inv.CreatedAt = entry.CreatedAt inv.AliasSuggestion = entry.AliasSuggestion - inv.CreatedBy.ID = entry.R.CreatedByAuthFallback.ID - inv.CreatedBy.Name = entry.R.CreatedByAuthFallback.Name + inv.CreatedBy.ID = entry.R.CreatedByMember.ID + inv.CreatedBy.Role = roomdb.Role(entry.R.CreatedByMember.Role) + inv.CreatedBy.Nickname = entry.R.CreatedByMember.Nick return nil }) @@ -157,7 +163,7 @@ func (i Invites) GetByToken(ctx context.Context, token string) (roomdb.Invite, e entry, err := models.Invites( qm.Where("active = true AND token = ?", ht), - qm.Load("CreatedByAuthFallback"), + qm.Load("CreatedByMember"), ).One(ctx, i.db) if err != nil { if errors.Is(err, sql.ErrNoRows) { @@ -169,8 +175,9 @@ func (i Invites) GetByToken(ctx context.Context, token string) (roomdb.Invite, e inv.ID = entry.ID inv.CreatedAt = entry.CreatedAt inv.AliasSuggestion = entry.AliasSuggestion - inv.CreatedBy.ID = entry.R.CreatedByAuthFallback.ID - inv.CreatedBy.Name = entry.R.CreatedByAuthFallback.Name + inv.CreatedBy.ID = entry.R.CreatedByMember.ID + inv.CreatedBy.Role = roomdb.Role(entry.R.CreatedByMember.Role) + inv.CreatedBy.Nickname = entry.R.CreatedByMember.Nick return inv, nil } @@ -180,7 +187,7 @@ func (i Invites) GetByID(ctx context.Context, id int64) (roomdb.Invite, error) { entry, err := models.Invites( qm.Where("active = true AND id = ?", id), - qm.Load("CreatedByAuthFallback"), + qm.Load("CreatedByMember"), ).One(ctx, i.db) if err != nil { if errors.Is(err, sql.ErrNoRows) { @@ -192,8 +199,9 @@ func (i Invites) GetByID(ctx context.Context, id int64) (roomdb.Invite, error) { inv.ID = entry.ID inv.CreatedAt = entry.CreatedAt inv.AliasSuggestion = entry.AliasSuggestion - inv.CreatedBy.ID = entry.R.CreatedByAuthFallback.ID - inv.CreatedBy.Name = entry.R.CreatedByAuthFallback.Name + inv.CreatedBy.ID = entry.R.CreatedByMember.ID + inv.CreatedBy.Role = roomdb.Role(entry.R.CreatedByMember.Role) + inv.CreatedBy.Nickname = entry.R.CreatedByMember.Nick return inv, nil } @@ -205,7 +213,7 @@ func (i Invites) List(ctx context.Context) ([]roomdb.Invite, error) { err := transact(i.db, func(tx *sql.Tx) error { entries, err := models.Invites( qm.Where("active = true"), - qm.Load("CreatedByAuthFallback"), + qm.Load("CreatedByMember"), ).All(ctx, tx) if err != nil { return err @@ -217,8 +225,8 @@ func (i Invites) List(ctx context.Context) ([]roomdb.Invite, error) { inv.ID = e.ID inv.CreatedAt = e.CreatedAt inv.AliasSuggestion = e.AliasSuggestion - inv.CreatedBy.ID = e.R.CreatedByAuthFallback.ID - inv.CreatedBy.Name = e.R.CreatedByAuthFallback.Name + inv.CreatedBy.ID = e.R.CreatedByMember.ID + inv.CreatedBy.Nickname = e.R.CreatedByMember.Nick invs[idx] = inv } diff --git a/roomdb/sqlite/invites_test.go b/roomdb/sqlite/invites_test.go index c1b4ce6..cc7a28a 100644 --- a/roomdb/sqlite/invites_test.go +++ b/roomdb/sqlite/invites_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ssb-ngi-pointer/go-ssb-room/internal/repo" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" refs "go.mindeco.de/ssb-refs" ) @@ -50,8 +51,9 @@ func TestInvites(t *testing.T) { r.Error(err, "can't create invite for invalid user") }) - testUserName := "test-user" - uid, err := db.AuthFallback.Create(ctx, testUserName, []byte("bad-password")) + testMemberNick := "test-user" + invitingMember := refs.FeedRef{ID: bytes.Repeat([]byte("ohai"), 8), Algo: refs.RefAlgoFeedSSB1} + uid, err := db.Members.Add(ctx, testMemberNick, invitingMember, roomdb.RoleModerator) require.NoError(t, err, "failed to create test user") t.Run("simple create and consume", func(t *testing.T) { @@ -71,20 +73,20 @@ func TestInvites(t *testing.T) { r.Len(lst, 1, "expected 1 invite") r.Equal("bestie", lst[0].AliasSuggestion) - r.Equal(testUserName, lst[0].CreatedBy.Name) + r.Equal(testMemberNick, lst[0].CreatedBy.Nickname) r.True(lst[0].CreatedAt.After(before), "expected CreatedAt to be after the start marker") - nope := db.AllowList.HasFeed(ctx, newMember) + nope := db.Members.HasFeed(ctx, newMember) r.False(nope, "expected feed to not yet be on the allow list") inv, err := db.Invites.Consume(ctx, tok, newMember) r.NoError(err, "failed to consume the invite") - r.Equal(testUserName, inv.CreatedBy.Name) + r.Equal(testMemberNick, inv.CreatedBy.Nickname) r.NotEqualValues(0, inv.ID, "invite ID unset") r.True(inv.CreatedAt.After(before), "expected CreatedAt to be after the start marker") // consume also adds it to the allow list - yes := db.AllowList.HasFeed(ctx, newMember) + yes := db.Members.HasFeed(ctx, newMember) r.True(yes, "expected feed on the allow list") lst, err = db.Invites.List(ctx) @@ -108,7 +110,7 @@ func TestInvites(t *testing.T) { r.Len(lst, 1, "expected 1 invite") r.Equal("bestie", lst[0].AliasSuggestion) - r.Equal(testUserName, lst[0].CreatedBy.Name) + r.Equal(testMemberNick, lst[0].CreatedBy.Nickname) err = db.Invites.Revoke(ctx, lst[0].ID) r.NoError(err, "failed to consume the invite") diff --git a/roomdb/sqlite/members.go b/roomdb/sqlite/members.go new file mode 100644 index 0000000..2f99522 --- /dev/null +++ b/roomdb/sqlite/members.go @@ -0,0 +1,149 @@ +package sqlite + +import ( + "context" + "database/sql" + "fmt" + + "github.com/friendsofgo/errors" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb/sqlite/models" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + refs "go.mindeco.de/ssb-refs" +) + +// compiler assertion to ensure the struct fullfills the interface +var _ roomdb.MembersService = (*Members)(nil) + +type Members struct { + db *sql.DB +} + +func (m Members) Add(ctx context.Context, nick string, pubKey refs.FeedRef, role roomdb.Role) (int64, error) { + var newID int64 + err := transact(m.db, func(tx *sql.Tx) error { + var err error + newID, err = m.add(ctx, tx, nick, pubKey, role) + return err + }) + if err != nil { + return -1, err + } + return newID, nil +} + +// no receiver name because it needs to use the passed transaction +func (Members) add(ctx context.Context, tx *sql.Tx, nick string, pubKey refs.FeedRef, role roomdb.Role) (int64, error) { + if err := role.IsValid(); err != nil { + return -1, err + } + + if _, err := refs.ParseFeedRef(pubKey.Ref()); err != nil { + return -1, err + } + + var newMember models.Member + newMember.Nick = nick + newMember.PubKey = roomdb.DBFeedRef{FeedRef: pubKey} + newMember.Role = int64(role) + + err := newMember.Insert(ctx, tx, boil.Infer()) + if err != nil { + return -1, fmt.Errorf("members: failed to insert new user: %w", err) + } + + return newMember.ID, nil +} + +func (m Members) GetByID(ctx context.Context, mid int64) (roomdb.Member, error) { + modelU, err := models.FindMember(ctx, m.db, mid) + if err != nil { + return roomdb.Member{}, err + } + return roomdb.Member{ + ID: modelU.ID, + Nickname: modelU.Nick, + }, nil +} + +// HasFeed returns true if a feed is on the list. +func (m Members) HasFeed(ctx context.Context, h refs.FeedRef) bool { + _, err := models.Members(qm.Where("pub_key = ?", h.Ref())).One(ctx, m.db) + if err != nil { + return false + } + return true +} + +// HasID returns true if a feed is on the list. +func (m Members) HasID(ctx context.Context, id int64) bool { + _, err := models.FindMember(ctx, m.db, id) + if err != nil { + return false + } + return true +} + +// List returns a list of all the feeds. +func (m Members) List(ctx context.Context) ([]roomdb.Member, error) { + all, err := models.Members().All(ctx, m.db) + if err != nil { + return nil, err + } + + var members = make([]roomdb.Member, len(all)) + for i, listEntry := range all { + members[i].ID = listEntry.ID + members[i].Nickname = listEntry.Nick + members[i].Role = roomdb.Role(listEntry.Role) + members[i].PubKey = listEntry.PubKey.FeedRef + } + + return members, nil +} + +// RemoveFeed removes the feed from the list. +func (m Members) RemoveFeed(ctx context.Context, r refs.FeedRef) error { + entry, err := models.Members(qm.Where("pub_key = ?", r.Ref())).One(ctx, m.db) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return roomdb.ErrNotFound + } + return err + } + + _, err = entry.Delete(ctx, m.db) + if err != nil { + return err + } + + return nil +} + +// RemoveID removes the feed from the list. +func (m Members) RemoveID(ctx context.Context, id int64) error { + entry, err := models.FindMember(ctx, m.db, id) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return roomdb.ErrNotFound + } + return err + } + + _, err = entry.Delete(ctx, m.db) + if err != nil { + return err + } + + return nil +} + +// SetRole updates the role r of the passed memberID. +func (m Members) SetRole(ctx context.Context, id int64, r roomdb.Role) error { + if err := r.IsValid(); err != nil { + return err + } + + panic("TODO") +} diff --git a/roomdb/sqlite/members_test.go b/roomdb/sqlite/members_test.go new file mode 100644 index 0000000..befdb26 --- /dev/null +++ b/roomdb/sqlite/members_test.go @@ -0,0 +1,132 @@ +package sqlite + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + + "github.com/ssb-ngi-pointer/go-ssb-room/internal/repo" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb/sqlite/models" + "github.com/stretchr/testify/require" + refs "go.mindeco.de/ssb-refs" +) + +func TestMembers(t *testing.T) { + r := require.New(t) + ctx := context.Background() + + testRepo := filepath.Join("testrun", t.Name()) + os.RemoveAll(testRepo) + + tr := repo.New(testRepo) + + db, err := Open(tr) + require.NoError(t, err) + + // broken feed (unknown algo) + tf := refs.FeedRef{ID: bytes.Repeat([]byte("fooo"), 8), Algo: "nope"} + _, err = db.Members.Add(ctx, "dont-add-me", tf, roomdb.RoleMember) + r.Error(err) + + // looks ok at least + okFeed := refs.FeedRef{ID: bytes.Repeat([]byte("acab"), 8), Algo: refs.RefAlgoFeedSSB1} + _, err = db.Members.Add(ctx, "should-add-me", okFeed, roomdb.RoleMember) + r.NoError(err) + + sqlDB := db.Members.db + count, err := models.Members().Count(ctx, sqlDB) + r.NoError(err) + r.EqualValues(count, 1) + + lst, err := db.Members.List(ctx) + r.NoError(err) + r.Len(lst, 1) + + yes := db.Members.HasFeed(ctx, okFeed) + r.True(yes) + + yes = db.Members.HasFeed(ctx, tf) + r.False(yes) + + err = db.Members.RemoveFeed(ctx, okFeed) + r.NoError(err) + + count, err = models.Members().Count(ctx, sqlDB) + r.NoError(err) + r.EqualValues(count, 0) + + lst, err = db.Members.List(ctx) + r.NoError(err) + r.Len(lst, 0) + + yes = db.Members.HasFeed(ctx, okFeed) + r.False(yes) + + r.NoError(db.Close()) +} + +func TestMembersUnique(t *testing.T) { + r := require.New(t) + ctx := context.Background() + + testRepo := filepath.Join("testrun", t.Name()) + os.RemoveAll(testRepo) + + tr := repo.New(testRepo) + + db, err := Open(tr) + require.NoError(t, err) + + feedA := refs.FeedRef{ID: bytes.Repeat([]byte("1312"), 8), Algo: refs.RefAlgoFeedSSB1} + _, err = db.Members.Add(ctx, "add-me-first", feedA, roomdb.RoleMember) + r.NoError(err) + + _, err = db.Members.Add(ctx, "dont-add-me-twice", feedA, roomdb.RoleMember) + r.Error(err) + + lst, err := db.Members.List(ctx) + r.NoError(err) + r.Len(lst, 1) + + r.NoError(db.Close()) +} + +func TestMembersByID(t *testing.T) { + r := require.New(t) + ctx := context.Background() + + testRepo := filepath.Join("testrun", t.Name()) + os.RemoveAll(testRepo) + + tr := repo.New(testRepo) + + db, err := Open(tr) + require.NoError(t, err) + + feedA := refs.FeedRef{ID: bytes.Repeat([]byte("1312"), 8), Algo: refs.RefAlgoFeedSSB1} + _, err = db.Members.Add(ctx, "add-me", feedA, roomdb.RoleMember) + r.NoError(err) + + lst, err := db.Members.List(ctx) + r.NoError(err) + r.Len(lst, 1) + + yes := db.Members.HasID(ctx, lst[0].ID) + r.True(yes) + + yes = db.Members.HasID(ctx, 666) + r.False(yes) + + err = db.Members.RemoveID(ctx, 666) + r.Error(err) + r.EqualError(err, roomdb.ErrNotFound.Error()) + + err = db.Members.RemoveID(ctx, lst[0].ID) + r.NoError(err) + + yes = db.Members.HasID(ctx, lst[0].ID) + r.False(yes) +} diff --git a/roomdb/sqlite/migrations/01-consolidated.sql b/roomdb/sqlite/migrations/01-consolidated.sql new file mode 100644 index 0000000..469e07a --- /dev/null +++ b/roomdb/sqlite/migrations/01-consolidated.sql @@ -0,0 +1,78 @@ +-- +migrate Up +-- the internal users table (people who used an invite) +CREATE TABLE members ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + role INTEGER NOT NULL, -- member, moderator or admin + nick TEXT NOT NULL, -- a nick name for the user (not an alias) + pub_key TEXT NOT NULL UNIQUE, + + CHECK(role > 0) +); +CREATE INDEX members_pubkeys ON members(pub_key); + +-- password login for members (in case they can't use sign-in with ssb, for whatever reason) +CREATE TABLE fallback_passwords ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + login TEXT NOT NULL UNIQUE, + password_hash BLOB NOT NULL, + + member_id INTEGER NOT NULL, + + FOREIGN KEY ( member_id ) REFERENCES members( "id" ) +); +CREATE INDEX fallback_passwords_by_login ON fallback_passwords(login); + +-- single use tokens for becoming members +CREATE TABLE invites ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + hashed_token TEXT UNIQUE NOT NULL, + created_by INTEGER NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + + alias_suggestion TEXT NOT NULL DEFAULT "", -- optional + active boolean NOT NULL DEFAULT TRUE, + + FOREIGN KEY ( created_by ) REFERENCES members( "id" ) +); +CREATE INDEX invite_active_ids ON invites(id) WHERE active=TRUE; +CREATE UNIQUE INDEX invite_active_tokens ON invites(hashed_token) WHERE active=TRUE; +CREATE INDEX invite_inactive ON invites(active); + +-- name -> public key mappings +CREATE TABLE aliases ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + name TEXT UNIQUE NOT NULL, + member_id INTEGER NOT NULL, + signature BLOB NOT NULL, + + FOREIGN KEY ( member_id ) REFERENCES members( "id" ) +); +CREATE UNIQUE INDEX aliases_ids ON aliases(id); +CREATE UNIQUE INDEX aliases_names ON aliases(name); + +-- public keys that should never ever be let into the room +CREATE TABLE denied_keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + pub_key TEXT NOT NULL UNIQUE, + comment TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX denied_keys_by_pubkey ON invites(active); + +-- +migrate Down +DROP TABLE members; + +DROP TABLE fallback_passwords; +DROP INDEX fallback_passwords_by_login; + +DROP TABLE invites; +DROP INDEX invite_active_ids; +DROP INDEX invite_active_tokens; +DROP INDEX invite_inactive; + +DROP TABLE aliases; +DROP INDEX aliases_ids; +DROP INDEX aliases_names; + +DROP TABLE denied_keys; +DROP INDEX denied_keys_by_pubkey; \ No newline at end of file diff --git a/roomdb/sqlite/migrations/3-notices.sql b/roomdb/sqlite/migrations/02-notices.sql similarity index 100% rename from roomdb/sqlite/migrations/3-notices.sql rename to roomdb/sqlite/migrations/02-notices.sql diff --git a/roomdb/sqlite/migrations/1-create-auth-fallback.sql b/roomdb/sqlite/migrations/1-create-auth-fallback.sql deleted file mode 100644 index 751621d..0000000 --- a/roomdb/sqlite/migrations/1-create-auth-fallback.sql +++ /dev/null @@ -1,9 +0,0 @@ --- +migrate Up -CREATE TABLE auth_fallback ( - id integer PRIMARY KEY AUTOINCREMENT NOT NULL, - name text NOT NULL UNIQUE, - password_hash blob not null -); - --- +migrate Down -DROP TABLE auth_fallback; \ No newline at end of file diff --git a/roomdb/sqlite/migrations/2-create-allow-list.sql b/roomdb/sqlite/migrations/2-create-allow-list.sql deleted file mode 100644 index 49cf059..0000000 --- a/roomdb/sqlite/migrations/2-create-allow-list.sql +++ /dev/null @@ -1,8 +0,0 @@ --- +migrate Up -CREATE TABLE allow_list ( - id integer PRIMARY KEY AUTOINCREMENT NOT NULL, - pub_key text NOT NULL UNIQUE -); - --- +migrate Down -DROP TABLE allow_list; \ No newline at end of file diff --git a/roomdb/sqlite/migrations/4-invites.sql b/roomdb/sqlite/migrations/4-invites.sql deleted file mode 100644 index 45edf41..0000000 --- a/roomdb/sqlite/migrations/4-invites.sql +++ /dev/null @@ -1,22 +0,0 @@ --- +migrate Up -CREATE TABLE invites ( - id integer PRIMARY KEY AUTOINCREMENT NOT NULL, - token text UNIQUE NOT NULL, - created_by integer NOT NULL, - alias_suggestion text NOT NULL DEFAULT "", -- optional - active boolean NOT NULL DEFAULT true, - - -- TODO: replace auth_fallback with a user table once we do "sign in with ssb" - FOREIGN KEY ( created_by ) REFERENCES auth_fallback( "id" ) -); - -CREATE INDEX invite_active_ids ON invites(id) WHERE active=true; -CREATE UNIQUE INDEX invite_active_tokens ON invites(token) WHERE active=true; -CREATE INDEX invite_inactive ON invites(active); - --- +migrate Down -DROP TABLE invites; - -DROP INDEX invite_active_ids; -DROP INDEX invite_active_tokens; -DROP INDEX invite_inactive; diff --git a/roomdb/sqlite/migrations/5-aliases.sql b/roomdb/sqlite/migrations/5-aliases.sql deleted file mode 100644 index 604b965..0000000 --- a/roomdb/sqlite/migrations/5-aliases.sql +++ /dev/null @@ -1,18 +0,0 @@ --- +migrate Up -CREATE TABLE aliases ( - id integer PRIMARY KEY AUTOINCREMENT NOT NULL, - name text UNIQUE NOT NULL, - user_id integer NOT NULL, - signature blob not null, - - FOREIGN KEY ( user_id ) REFERENCES allow_list( "id" ) -); - -CREATE UNIQUE INDEX aliases_ids ON aliases(id); -CREATE UNIQUE INDEX aliases_names ON aliases(name); - --- +migrate Down -DROP TABLE aliases; - -DROP INDEX aliases_ids; -DROP INDEX aliases_names; diff --git a/roomdb/sqlite/migrations/6-invite-createdAt.sql b/roomdb/sqlite/migrations/6-invite-createdAt.sql deleted file mode 100644 index 1ceff52..0000000 --- a/roomdb/sqlite/migrations/6-invite-createdAt.sql +++ /dev/null @@ -1,10 +0,0 @@ --- +migrate Up -ALTER TABLE invites ADD COLUMN created_at datetime NOT NULL DEFAULT 0; --- because of the restrictions in 4. https://www.sqlite.org/lang_altertable.html --- the actual default should be date('now') but can't be. --- this needs to be fixed once we merge the migrations into a signle schema prior to the next point release. --- at which point we dont need to insert the current time into the db from the application anymore. -UPDATE invites set created_at=date('now'); - --- +migrate Down -ALTER TABLE invites DROP COLUMN created_at; \ No newline at end of file diff --git a/roomdb/sqlite/models/aliases.go b/roomdb/sqlite/models/aliases.go index fca1b89..abb9a4a 100644 --- a/roomdb/sqlite/models/aliases.go +++ b/roomdb/sqlite/models/aliases.go @@ -24,7 +24,7 @@ import ( type Alias struct { ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` Name string `boil:"name" json:"name" toml:"name" yaml:"name"` - UserID int64 `boil:"user_id" json:"user_id" toml:"user_id" yaml:"user_id"` + MemberID int64 `boil:"member_id" json:"member_id" toml:"member_id" yaml:"member_id"` Signature []byte `boil:"signature" json:"signature" toml:"signature" yaml:"signature"` R *aliasR `boil:"-" json:"-" toml:"-" yaml:"-"` @@ -34,12 +34,12 @@ type Alias struct { var AliasColumns = struct { ID string Name string - UserID string + MemberID string Signature string }{ ID: "id", Name: "name", - UserID: "user_id", + MemberID: "member_id", Signature: "signature", } @@ -103,25 +103,25 @@ func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.f var AliasWhere = struct { ID whereHelperint64 Name whereHelperstring - UserID whereHelperint64 + MemberID whereHelperint64 Signature whereHelper__byte }{ ID: whereHelperint64{field: "\"aliases\".\"id\""}, Name: whereHelperstring{field: "\"aliases\".\"name\""}, - UserID: whereHelperint64{field: "\"aliases\".\"user_id\""}, + MemberID: whereHelperint64{field: "\"aliases\".\"member_id\""}, Signature: whereHelper__byte{field: "\"aliases\".\"signature\""}, } // AliasRels is where relationship names are stored. var AliasRels = struct { - User string + Member string }{ - User: "User", + Member: "Member", } // aliasR is where relationships are stored. type aliasR struct { - User *AllowList `boil:"User" json:"User" toml:"User" yaml:"User"` + Member *Member `boil:"Member" json:"Member" toml:"Member" yaml:"Member"` } // NewStruct creates a new relationship struct @@ -133,9 +133,9 @@ func (*aliasR) NewStruct() *aliasR { type aliasL struct{} var ( - aliasAllColumns = []string{"id", "name", "user_id", "signature"} + aliasAllColumns = []string{"id", "name", "member_id", "signature"} aliasColumnsWithoutDefault = []string{} - aliasColumnsWithDefault = []string{"id", "name", "user_id", "signature"} + aliasColumnsWithDefault = []string{"id", "name", "member_id", "signature"} aliasPrimaryKeyColumns = []string{"id"} ) @@ -414,23 +414,23 @@ func (q aliasQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool return count > 0, nil } -// User pointed to by the foreign key. -func (o *Alias) User(mods ...qm.QueryMod) allowListQuery { +// Member pointed to by the foreign key. +func (o *Alias) Member(mods ...qm.QueryMod) memberQuery { queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.UserID), + qm.Where("\"id\" = ?", o.MemberID), } queryMods = append(queryMods, mods...) - query := AllowLists(queryMods...) - queries.SetFrom(query.Query, "\"allow_list\"") + query := Members(queryMods...) + queries.SetFrom(query.Query, "\"members\"") return query } -// LoadUser allows an eager lookup of values, cached into the +// LoadMember allows an eager lookup of values, cached into the // loaded structs of the objects. This is for an N-1 relationship. -func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAlias interface{}, mods queries.Applicator) error { +func (aliasL) LoadMember(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAlias interface{}, mods queries.Applicator) error { var slice []*Alias var object *Alias @@ -445,7 +445,7 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo if object.R == nil { object.R = &aliasR{} } - args = append(args, object.UserID) + args = append(args, object.MemberID) } else { Outer: @@ -455,12 +455,12 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo } for _, a := range args { - if a == obj.UserID { + if a == obj.MemberID { continue Outer } } - args = append(args, obj.UserID) + args = append(args, obj.MemberID) } } @@ -470,8 +470,8 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo } query := NewQuery( - qm.From(`allow_list`), - qm.WhereIn(`allow_list.id in ?`, args...), + qm.From(`members`), + qm.WhereIn(`members.id in ?`, args...), ) if mods != nil { mods.Apply(query) @@ -479,19 +479,19 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo results, err := query.QueryContext(ctx, e) if err != nil { - return errors.Wrap(err, "failed to eager load AllowList") + return errors.Wrap(err, "failed to eager load Member") } - var resultSlice []*AllowList + var resultSlice []*Member if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice AllowList") + return errors.Wrap(err, "failed to bind eager loaded slice Member") } if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for allow_list") + return errors.Wrap(err, "failed to close results of eager load for members") } if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for allow_list") + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for members") } if len(aliasAfterSelectHooks) != 0 { @@ -508,22 +508,22 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo if singular { foreign := resultSlice[0] - object.R.User = foreign + object.R.Member = foreign if foreign.R == nil { - foreign.R = &allowListR{} + foreign.R = &memberR{} } - foreign.R.UserAliases = append(foreign.R.UserAliases, object) + foreign.R.Aliases = append(foreign.R.Aliases, object) return nil } for _, local := range slice { for _, foreign := range resultSlice { - if local.UserID == foreign.ID { - local.R.User = foreign + if local.MemberID == foreign.ID { + local.R.Member = foreign if foreign.R == nil { - foreign.R = &allowListR{} + foreign.R = &memberR{} } - foreign.R.UserAliases = append(foreign.R.UserAliases, local) + foreign.R.Aliases = append(foreign.R.Aliases, local) break } } @@ -532,10 +532,10 @@ func (aliasL) LoadUser(ctx context.Context, e boil.ContextExecutor, singular boo return nil } -// SetUser of the alias to the related item. -// Sets o.R.User to related. -// Adds o to related.R.UserAliases. -func (o *Alias) SetUser(ctx context.Context, exec boil.ContextExecutor, insert bool, related *AllowList) error { +// SetMember of the alias to the related item. +// Sets o.R.Member to related. +// Adds o to related.R.Aliases. +func (o *Alias) SetMember(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Member) error { var err error if insert { if err = related.Insert(ctx, exec, boil.Infer()); err != nil { @@ -545,7 +545,7 @@ func (o *Alias) SetUser(ctx context.Context, exec boil.ContextExecutor, insert b updateQuery := fmt.Sprintf( "UPDATE \"aliases\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, []string{"user_id"}), + strmangle.SetParamNames("\"", "\"", 0, []string{"member_id"}), strmangle.WhereClause("\"", "\"", 0, aliasPrimaryKeyColumns), ) values := []interface{}{related.ID, o.ID} @@ -559,21 +559,21 @@ func (o *Alias) SetUser(ctx context.Context, exec boil.ContextExecutor, insert b return errors.Wrap(err, "failed to update local table") } - o.UserID = related.ID + o.MemberID = related.ID if o.R == nil { o.R = &aliasR{ - User: related, + Member: related, } } else { - o.R.User = related + o.R.Member = related } if related.R == nil { - related.R = &allowListR{ - UserAliases: AliasSlice{o}, + related.R = &memberR{ + Aliases: AliasSlice{o}, } } else { - related.R.UserAliases = append(related.R.UserAliases, o) + related.R.Aliases = append(related.R.Aliases, o) } return nil diff --git a/roomdb/sqlite/models/allow_list.go b/roomdb/sqlite/models/allow_list.go deleted file mode 100644 index 72685e7..0000000 --- a/roomdb/sqlite/models/allow_list.go +++ /dev/null @@ -1,977 +0,0 @@ -// Code generated by SQLBoiler 4.5.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "strings" - "sync" - "time" - - "github.com/friendsofgo/errors" - "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" - "github.com/volatiletech/sqlboiler/v4/boil" - "github.com/volatiletech/sqlboiler/v4/queries" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" - "github.com/volatiletech/strmangle" -) - -// AllowList is an object representing the database table. -type AllowList struct { - ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` - PubKey roomdb.DBFeedRef `boil:"pub_key" json:"pub_key" toml:"pub_key" yaml:"pub_key"` - - R *allowListR `boil:"-" json:"-" toml:"-" yaml:"-"` - L allowListL `boil:"-" json:"-" toml:"-" yaml:"-"` -} - -var AllowListColumns = struct { - ID string - PubKey string -}{ - ID: "id", - PubKey: "pub_key", -} - -// Generated where - -type whereHelperroomdb_DBFeedRef struct{ field string } - -func (w whereHelperroomdb_DBFeedRef) EQ(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.EQ, x) -} -func (w whereHelperroomdb_DBFeedRef) NEQ(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.NEQ, x) -} -func (w whereHelperroomdb_DBFeedRef) LT(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LT, x) -} -func (w whereHelperroomdb_DBFeedRef) LTE(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LTE, x) -} -func (w whereHelperroomdb_DBFeedRef) GT(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GT, x) -} -func (w whereHelperroomdb_DBFeedRef) GTE(x roomdb.DBFeedRef) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GTE, x) -} - -var AllowListWhere = struct { - ID whereHelperint64 - PubKey whereHelperroomdb_DBFeedRef -}{ - ID: whereHelperint64{field: "\"allow_list\".\"id\""}, - PubKey: whereHelperroomdb_DBFeedRef{field: "\"allow_list\".\"pub_key\""}, -} - -// AllowListRels is where relationship names are stored. -var AllowListRels = struct { - UserAliases string -}{ - UserAliases: "UserAliases", -} - -// allowListR is where relationships are stored. -type allowListR struct { - UserAliases AliasSlice `boil:"UserAliases" json:"UserAliases" toml:"UserAliases" yaml:"UserAliases"` -} - -// NewStruct creates a new relationship struct -func (*allowListR) NewStruct() *allowListR { - return &allowListR{} -} - -// allowListL is where Load methods for each relationship are stored. -type allowListL struct{} - -var ( - allowListAllColumns = []string{"id", "pub_key"} - allowListColumnsWithoutDefault = []string{} - allowListColumnsWithDefault = []string{"id", "pub_key"} - allowListPrimaryKeyColumns = []string{"id"} -) - -type ( - // AllowListSlice is an alias for a slice of pointers to AllowList. - // This should generally be used opposed to []AllowList. - AllowListSlice []*AllowList - // AllowListHook is the signature for custom AllowList hook methods - AllowListHook func(context.Context, boil.ContextExecutor, *AllowList) error - - allowListQuery struct { - *queries.Query - } -) - -// Cache for insert, update and upsert -var ( - allowListType = reflect.TypeOf(&AllowList{}) - allowListMapping = queries.MakeStructMapping(allowListType) - allowListPrimaryKeyMapping, _ = queries.BindMapping(allowListType, allowListMapping, allowListPrimaryKeyColumns) - allowListInsertCacheMut sync.RWMutex - allowListInsertCache = make(map[string]insertCache) - allowListUpdateCacheMut sync.RWMutex - allowListUpdateCache = make(map[string]updateCache) - allowListUpsertCacheMut sync.RWMutex - allowListUpsertCache = make(map[string]insertCache) -) - -var ( - // Force time package dependency for automated UpdatedAt/CreatedAt. - _ = time.Second - // Force qmhelper dependency for where clause generation (which doesn't - // always happen) - _ = qmhelper.Where -) - -var allowListBeforeInsertHooks []AllowListHook -var allowListBeforeUpdateHooks []AllowListHook -var allowListBeforeDeleteHooks []AllowListHook -var allowListBeforeUpsertHooks []AllowListHook - -var allowListAfterInsertHooks []AllowListHook -var allowListAfterSelectHooks []AllowListHook -var allowListAfterUpdateHooks []AllowListHook -var allowListAfterDeleteHooks []AllowListHook -var allowListAfterUpsertHooks []AllowListHook - -// doBeforeInsertHooks executes all "before insert" hooks. -func (o *AllowList) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListBeforeInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpdateHooks executes all "before Update" hooks. -func (o *AllowList) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListBeforeUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *AllowList) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListBeforeDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *AllowList) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListBeforeUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterInsertHooks executes all "after Insert" hooks. -func (o *AllowList) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListAfterInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterSelectHooks executes all "after Select" hooks. -func (o *AllowList) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListAfterSelectHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpdateHooks executes all "after Update" hooks. -func (o *AllowList) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListAfterUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterDeleteHooks executes all "after Delete" hooks. -func (o *AllowList) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListAfterDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *AllowList) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range allowListAfterUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// AddAllowListHook registers your hook function for all future operations. -func AddAllowListHook(hookPoint boil.HookPoint, allowListHook AllowListHook) { - switch hookPoint { - case boil.BeforeInsertHook: - allowListBeforeInsertHooks = append(allowListBeforeInsertHooks, allowListHook) - case boil.BeforeUpdateHook: - allowListBeforeUpdateHooks = append(allowListBeforeUpdateHooks, allowListHook) - case boil.BeforeDeleteHook: - allowListBeforeDeleteHooks = append(allowListBeforeDeleteHooks, allowListHook) - case boil.BeforeUpsertHook: - allowListBeforeUpsertHooks = append(allowListBeforeUpsertHooks, allowListHook) - case boil.AfterInsertHook: - allowListAfterInsertHooks = append(allowListAfterInsertHooks, allowListHook) - case boil.AfterSelectHook: - allowListAfterSelectHooks = append(allowListAfterSelectHooks, allowListHook) - case boil.AfterUpdateHook: - allowListAfterUpdateHooks = append(allowListAfterUpdateHooks, allowListHook) - case boil.AfterDeleteHook: - allowListAfterDeleteHooks = append(allowListAfterDeleteHooks, allowListHook) - case boil.AfterUpsertHook: - allowListAfterUpsertHooks = append(allowListAfterUpsertHooks, allowListHook) - } -} - -// One returns a single allowList record from the query. -func (q allowListQuery) One(ctx context.Context, exec boil.ContextExecutor) (*AllowList, error) { - o := &AllowList{} - - queries.SetLimit(q.Query, 1) - - err := q.Bind(ctx, exec, o) - if err != nil { - if errors.Cause(err) == sql.ErrNoRows { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: failed to execute a one query for allow_list") - } - - if err := o.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - - return o, nil -} - -// All returns all AllowList records from the query. -func (q allowListQuery) All(ctx context.Context, exec boil.ContextExecutor) (AllowListSlice, error) { - var o []*AllowList - - err := q.Bind(ctx, exec, &o) - if err != nil { - return nil, errors.Wrap(err, "models: failed to assign all query results to AllowList slice") - } - - if len(allowListAfterSelectHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - } - } - - return o, nil -} - -// Count returns the count of all AllowList records in the query. -func (q allowListQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return 0, errors.Wrap(err, "models: failed to count allow_list rows") - } - - return count, nil -} - -// Exists checks if the row exists in the table. -func (q allowListQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - queries.SetLimit(q.Query, 1) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return false, errors.Wrap(err, "models: failed to check if allow_list exists") - } - - return count > 0, nil -} - -// UserAliases retrieves all the alias's Aliases with an executor via user_id column. -func (o *AllowList) UserAliases(mods ...qm.QueryMod) aliasQuery { - var queryMods []qm.QueryMod - if len(mods) != 0 { - queryMods = append(queryMods, mods...) - } - - queryMods = append(queryMods, - qm.Where("\"aliases\".\"user_id\"=?", o.ID), - ) - - query := Aliases(queryMods...) - queries.SetFrom(query.Query, "\"aliases\"") - - if len(queries.GetSelect(query.Query)) == 0 { - queries.SetSelect(query.Query, []string{"\"aliases\".*"}) - } - - return query -} - -// LoadUserAliases allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-M or N-M relationship. -func (allowListL) LoadUserAliases(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAllowList interface{}, mods queries.Applicator) error { - var slice []*AllowList - var object *AllowList - - if singular { - object = maybeAllowList.(*AllowList) - } else { - slice = *maybeAllowList.(*[]*AllowList) - } - - args := make([]interface{}, 0, 1) - if singular { - if object.R == nil { - object.R = &allowListR{} - } - args = append(args, object.ID) - } else { - Outer: - for _, obj := range slice { - if obj.R == nil { - obj.R = &allowListR{} - } - - for _, a := range args { - if a == obj.ID { - continue Outer - } - } - - args = append(args, obj.ID) - } - } - - if len(args) == 0 { - return nil - } - - query := NewQuery( - qm.From(`aliases`), - qm.WhereIn(`aliases.user_id in ?`, args...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load aliases") - } - - var resultSlice []*Alias - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice aliases") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results in eager load on aliases") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for aliases") - } - - if len(aliasAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - if singular { - object.R.UserAliases = resultSlice - for _, foreign := range resultSlice { - if foreign.R == nil { - foreign.R = &aliasR{} - } - foreign.R.User = object - } - return nil - } - - for _, foreign := range resultSlice { - for _, local := range slice { - if local.ID == foreign.UserID { - local.R.UserAliases = append(local.R.UserAliases, foreign) - if foreign.R == nil { - foreign.R = &aliasR{} - } - foreign.R.User = local - break - } - } - } - - return nil -} - -// AddUserAliases adds the given related objects to the existing relationships -// of the allow_list, optionally inserting them as new records. -// Appends related to o.R.UserAliases. -// Sets related.R.User appropriately. -func (o *AllowList) AddUserAliases(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*Alias) error { - var err error - for _, rel := range related { - if insert { - rel.UserID = o.ID - if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"aliases\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, []string{"user_id"}), - strmangle.WhereClause("\"", "\"", 0, aliasPrimaryKeyColumns), - ) - values := []interface{}{o.ID, rel.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - rel.UserID = o.ID - } - } - - if o.R == nil { - o.R = &allowListR{ - UserAliases: related, - } - } else { - o.R.UserAliases = append(o.R.UserAliases, related...) - } - - for _, rel := range related { - if rel.R == nil { - rel.R = &aliasR{ - User: o, - } - } else { - rel.R.User = o - } - } - return nil -} - -// AllowLists retrieves all the records using an executor. -func AllowLists(mods ...qm.QueryMod) allowListQuery { - mods = append(mods, qm.From("\"allow_list\"")) - return allowListQuery{NewQuery(mods...)} -} - -// FindAllowList retrieves a single record by ID with an executor. -// If selectCols is empty Find will return all columns. -func FindAllowList(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*AllowList, error) { - allowListObj := &AllowList{} - - sel := "*" - if len(selectCols) > 0 { - sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") - } - query := fmt.Sprintf( - "select %s from \"allow_list\" where \"id\"=?", sel, - ) - - q := queries.Raw(query, iD) - - err := q.Bind(ctx, exec, allowListObj) - if err != nil { - if errors.Cause(err) == sql.ErrNoRows { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: unable to select from allow_list") - } - - return allowListObj, nil -} - -// Insert a single record using an executor. -// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *AllowList) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { - if o == nil { - return errors.New("models: no allow_list provided for insertion") - } - - var err error - - if err := o.doBeforeInsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(allowListColumnsWithDefault, o) - - key := makeCacheKey(columns, nzDefaults) - allowListInsertCacheMut.RLock() - cache, cached := allowListInsertCache[key] - allowListInsertCacheMut.RUnlock() - - if !cached { - wl, returnColumns := columns.InsertColumnSet( - allowListAllColumns, - allowListColumnsWithDefault, - allowListColumnsWithoutDefault, - nzDefaults, - ) - - cache.valueMapping, err = queries.BindMapping(allowListType, allowListMapping, wl) - if err != nil { - return err - } - cache.retMapping, err = queries.BindMapping(allowListType, allowListMapping, returnColumns) - if err != nil { - return err - } - if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"allow_list\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) - } else { - cache.query = "INSERT INTO \"allow_list\" %sDEFAULT VALUES%s" - } - - var queryOutput, queryReturning string - - if len(cache.retMapping) != 0 { - cache.retQuery = fmt.Sprintf("SELECT \"%s\" FROM \"allow_list\" WHERE %s", strings.Join(returnColumns, "\",\""), strmangle.WhereClause("\"", "\"", 0, allowListPrimaryKeyColumns)) - } - - cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - result, err := exec.ExecContext(ctx, cache.query, vals...) - - if err != nil { - return errors.Wrap(err, "models: unable to insert into allow_list") - } - - var lastID int64 - var identifierCols []interface{} - - if len(cache.retMapping) == 0 { - goto CacheNoHooks - } - - lastID, err = result.LastInsertId() - if err != nil { - return ErrSyncFail - } - - o.ID = int64(lastID) - if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == allowListMapping["id"] { - goto CacheNoHooks - } - - identifierCols = []interface{}{ - o.ID, - } - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.retQuery) - fmt.Fprintln(writer, identifierCols...) - } - err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) - if err != nil { - return errors.Wrap(err, "models: unable to populate default values for allow_list") - } - -CacheNoHooks: - if !cached { - allowListInsertCacheMut.Lock() - allowListInsertCache[key] = cache - allowListInsertCacheMut.Unlock() - } - - return o.doAfterInsertHooks(ctx, exec) -} - -// Update uses an executor to update the AllowList. -// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. -// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *AllowList) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { - var err error - if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { - return 0, err - } - key := makeCacheKey(columns, nil) - allowListUpdateCacheMut.RLock() - cache, cached := allowListUpdateCache[key] - allowListUpdateCacheMut.RUnlock() - - if !cached { - wl := columns.UpdateColumnSet( - allowListAllColumns, - allowListPrimaryKeyColumns, - ) - - if !columns.IsWhitelist() { - wl = strmangle.SetComplement(wl, []string{"created_at"}) - } - if len(wl) == 0 { - return 0, errors.New("models: unable to update allow_list, could not build whitelist") - } - - cache.query = fmt.Sprintf("UPDATE \"allow_list\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, wl), - strmangle.WhereClause("\"", "\"", 0, allowListPrimaryKeyColumns), - ) - cache.valueMapping, err = queries.BindMapping(allowListType, allowListMapping, append(wl, allowListPrimaryKeyColumns...)) - if err != nil { - return 0, err - } - } - - values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, values) - } - var result sql.Result - result, err = exec.ExecContext(ctx, cache.query, values...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update allow_list row") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by update for allow_list") - } - - if !cached { - allowListUpdateCacheMut.Lock() - allowListUpdateCache[key] = cache - allowListUpdateCacheMut.Unlock() - } - - return rowsAff, o.doAfterUpdateHooks(ctx, exec) -} - -// UpdateAll updates all rows with the specified column values. -func (q allowListQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - queries.SetUpdate(q.Query, cols) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all for allow_list") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected for allow_list") - } - - return rowsAff, nil -} - -// UpdateAll updates all rows with the specified column values, using an executor. -func (o AllowListSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - ln := int64(len(o)) - if ln == 0 { - return 0, nil - } - - if len(cols) == 0 { - return 0, errors.New("models: update all requires at least one column argument") - } - - colNames := make([]string, len(cols)) - args := make([]interface{}, len(cols)) - - i := 0 - for name, value := range cols { - colNames[i] = name - args[i] = value - i++ - } - - // Append all of the primary key values for each column - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), allowListPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := fmt.Sprintf("UPDATE \"allow_list\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, allowListPrimaryKeyColumns, len(o))) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all in allowList slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all allowList") - } - return rowsAff, nil -} - -// Delete deletes a single AllowList record with an executor. -// Delete will match against the primary key column to find the record to delete. -func (o *AllowList) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if o == nil { - return 0, errors.New("models: no AllowList provided for delete") - } - - if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), allowListPrimaryKeyMapping) - sql := "DELETE FROM \"allow_list\" WHERE \"id\"=?" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete from allow_list") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by delete for allow_list") - } - - if err := o.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - return rowsAff, nil -} - -// DeleteAll deletes all matching rows. -func (q allowListQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if q.Query == nil { - return 0, errors.New("models: no allowListQuery provided for delete all") - } - - queries.SetDelete(q.Query) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from allow_list") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for allow_list") - } - - return rowsAff, nil -} - -// DeleteAll deletes all rows in the slice, using an executor. -func (o AllowListSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if len(o) == 0 { - return 0, nil - } - - if len(allowListBeforeDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - var args []interface{} - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), allowListPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "DELETE FROM \"allow_list\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, allowListPrimaryKeyColumns, len(o)) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from allowList slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for allow_list") - } - - if len(allowListAfterDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - return rowsAff, nil -} - -// Reload refetches the object from the database -// using the primary keys with an executor. -func (o *AllowList) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindAllowList(ctx, exec, o.ID) - if err != nil { - return err - } - - *o = *ret - return nil -} - -// ReloadAll refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *AllowListSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { - if o == nil || len(*o) == 0 { - return nil - } - - slice := AllowListSlice{} - var args []interface{} - for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), allowListPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "SELECT \"allow_list\".* FROM \"allow_list\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, allowListPrimaryKeyColumns, len(*o)) - - q := queries.Raw(sql, args...) - - err := q.Bind(ctx, exec, &slice) - if err != nil { - return errors.Wrap(err, "models: unable to reload all in AllowListSlice") - } - - *o = slice - - return nil -} - -// AllowListExists checks if the AllowList row exists. -func AllowListExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) { - var exists bool - sql := "select exists(select 1 from \"allow_list\" where \"id\"=? limit 1)" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, iD) - } - row := exec.QueryRowContext(ctx, sql, iD) - - err := row.Scan(&exists) - if err != nil { - return false, errors.Wrap(err, "models: unable to check if allow_list exists") - } - - return exists, nil -} diff --git a/roomdb/sqlite/models/auth_fallback.go b/roomdb/sqlite/models/auth_fallback.go deleted file mode 100644 index bd241a3..0000000 --- a/roomdb/sqlite/models/auth_fallback.go +++ /dev/null @@ -1,960 +0,0 @@ -// Code generated by SQLBoiler 4.5.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "strings" - "sync" - "time" - - "github.com/friendsofgo/errors" - "github.com/volatiletech/sqlboiler/v4/boil" - "github.com/volatiletech/sqlboiler/v4/queries" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" - "github.com/volatiletech/strmangle" -) - -// AuthFallback is an object representing the database table. -type AuthFallback struct { - ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` - Name string `boil:"name" json:"name" toml:"name" yaml:"name"` - PasswordHash []byte `boil:"password_hash" json:"password_hash" toml:"password_hash" yaml:"password_hash"` - - R *authFallbackR `boil:"-" json:"-" toml:"-" yaml:"-"` - L authFallbackL `boil:"-" json:"-" toml:"-" yaml:"-"` -} - -var AuthFallbackColumns = struct { - ID string - Name string - PasswordHash string -}{ - ID: "id", - Name: "name", - PasswordHash: "password_hash", -} - -// Generated where - -var AuthFallbackWhere = struct { - ID whereHelperint64 - Name whereHelperstring - PasswordHash whereHelper__byte -}{ - ID: whereHelperint64{field: "\"auth_fallback\".\"id\""}, - Name: whereHelperstring{field: "\"auth_fallback\".\"name\""}, - PasswordHash: whereHelper__byte{field: "\"auth_fallback\".\"password_hash\""}, -} - -// AuthFallbackRels is where relationship names are stored. -var AuthFallbackRels = struct { - CreatedByInvites string -}{ - CreatedByInvites: "CreatedByInvites", -} - -// authFallbackR is where relationships are stored. -type authFallbackR struct { - CreatedByInvites InviteSlice `boil:"CreatedByInvites" json:"CreatedByInvites" toml:"CreatedByInvites" yaml:"CreatedByInvites"` -} - -// NewStruct creates a new relationship struct -func (*authFallbackR) NewStruct() *authFallbackR { - return &authFallbackR{} -} - -// authFallbackL is where Load methods for each relationship are stored. -type authFallbackL struct{} - -var ( - authFallbackAllColumns = []string{"id", "name", "password_hash"} - authFallbackColumnsWithoutDefault = []string{} - authFallbackColumnsWithDefault = []string{"id", "name", "password_hash"} - authFallbackPrimaryKeyColumns = []string{"id"} -) - -type ( - // AuthFallbackSlice is an alias for a slice of pointers to AuthFallback. - // This should generally be used opposed to []AuthFallback. - AuthFallbackSlice []*AuthFallback - // AuthFallbackHook is the signature for custom AuthFallback hook methods - AuthFallbackHook func(context.Context, boil.ContextExecutor, *AuthFallback) error - - authFallbackQuery struct { - *queries.Query - } -) - -// Cache for insert, update and upsert -var ( - authFallbackType = reflect.TypeOf(&AuthFallback{}) - authFallbackMapping = queries.MakeStructMapping(authFallbackType) - authFallbackPrimaryKeyMapping, _ = queries.BindMapping(authFallbackType, authFallbackMapping, authFallbackPrimaryKeyColumns) - authFallbackInsertCacheMut sync.RWMutex - authFallbackInsertCache = make(map[string]insertCache) - authFallbackUpdateCacheMut sync.RWMutex - authFallbackUpdateCache = make(map[string]updateCache) - authFallbackUpsertCacheMut sync.RWMutex - authFallbackUpsertCache = make(map[string]insertCache) -) - -var ( - // Force time package dependency for automated UpdatedAt/CreatedAt. - _ = time.Second - // Force qmhelper dependency for where clause generation (which doesn't - // always happen) - _ = qmhelper.Where -) - -var authFallbackBeforeInsertHooks []AuthFallbackHook -var authFallbackBeforeUpdateHooks []AuthFallbackHook -var authFallbackBeforeDeleteHooks []AuthFallbackHook -var authFallbackBeforeUpsertHooks []AuthFallbackHook - -var authFallbackAfterInsertHooks []AuthFallbackHook -var authFallbackAfterSelectHooks []AuthFallbackHook -var authFallbackAfterUpdateHooks []AuthFallbackHook -var authFallbackAfterDeleteHooks []AuthFallbackHook -var authFallbackAfterUpsertHooks []AuthFallbackHook - -// doBeforeInsertHooks executes all "before insert" hooks. -func (o *AuthFallback) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackBeforeInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpdateHooks executes all "before Update" hooks. -func (o *AuthFallback) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackBeforeUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *AuthFallback) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackBeforeDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *AuthFallback) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackBeforeUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterInsertHooks executes all "after Insert" hooks. -func (o *AuthFallback) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackAfterInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterSelectHooks executes all "after Select" hooks. -func (o *AuthFallback) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackAfterSelectHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpdateHooks executes all "after Update" hooks. -func (o *AuthFallback) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackAfterUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterDeleteHooks executes all "after Delete" hooks. -func (o *AuthFallback) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackAfterDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *AuthFallback) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range authFallbackAfterUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// AddAuthFallbackHook registers your hook function for all future operations. -func AddAuthFallbackHook(hookPoint boil.HookPoint, authFallbackHook AuthFallbackHook) { - switch hookPoint { - case boil.BeforeInsertHook: - authFallbackBeforeInsertHooks = append(authFallbackBeforeInsertHooks, authFallbackHook) - case boil.BeforeUpdateHook: - authFallbackBeforeUpdateHooks = append(authFallbackBeforeUpdateHooks, authFallbackHook) - case boil.BeforeDeleteHook: - authFallbackBeforeDeleteHooks = append(authFallbackBeforeDeleteHooks, authFallbackHook) - case boil.BeforeUpsertHook: - authFallbackBeforeUpsertHooks = append(authFallbackBeforeUpsertHooks, authFallbackHook) - case boil.AfterInsertHook: - authFallbackAfterInsertHooks = append(authFallbackAfterInsertHooks, authFallbackHook) - case boil.AfterSelectHook: - authFallbackAfterSelectHooks = append(authFallbackAfterSelectHooks, authFallbackHook) - case boil.AfterUpdateHook: - authFallbackAfterUpdateHooks = append(authFallbackAfterUpdateHooks, authFallbackHook) - case boil.AfterDeleteHook: - authFallbackAfterDeleteHooks = append(authFallbackAfterDeleteHooks, authFallbackHook) - case boil.AfterUpsertHook: - authFallbackAfterUpsertHooks = append(authFallbackAfterUpsertHooks, authFallbackHook) - } -} - -// One returns a single authFallback record from the query. -func (q authFallbackQuery) One(ctx context.Context, exec boil.ContextExecutor) (*AuthFallback, error) { - o := &AuthFallback{} - - queries.SetLimit(q.Query, 1) - - err := q.Bind(ctx, exec, o) - if err != nil { - if errors.Cause(err) == sql.ErrNoRows { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: failed to execute a one query for auth_fallback") - } - - if err := o.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - - return o, nil -} - -// All returns all AuthFallback records from the query. -func (q authFallbackQuery) All(ctx context.Context, exec boil.ContextExecutor) (AuthFallbackSlice, error) { - var o []*AuthFallback - - err := q.Bind(ctx, exec, &o) - if err != nil { - return nil, errors.Wrap(err, "models: failed to assign all query results to AuthFallback slice") - } - - if len(authFallbackAfterSelectHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - } - } - - return o, nil -} - -// Count returns the count of all AuthFallback records in the query. -func (q authFallbackQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return 0, errors.Wrap(err, "models: failed to count auth_fallback rows") - } - - return count, nil -} - -// Exists checks if the row exists in the table. -func (q authFallbackQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - queries.SetLimit(q.Query, 1) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return false, errors.Wrap(err, "models: failed to check if auth_fallback exists") - } - - return count > 0, nil -} - -// CreatedByInvites retrieves all the invite's Invites with an executor via created_by column. -func (o *AuthFallback) CreatedByInvites(mods ...qm.QueryMod) inviteQuery { - var queryMods []qm.QueryMod - if len(mods) != 0 { - queryMods = append(queryMods, mods...) - } - - queryMods = append(queryMods, - qm.Where("\"invites\".\"created_by\"=?", o.ID), - ) - - query := Invites(queryMods...) - queries.SetFrom(query.Query, "\"invites\"") - - if len(queries.GetSelect(query.Query)) == 0 { - queries.SetSelect(query.Query, []string{"\"invites\".*"}) - } - - return query -} - -// LoadCreatedByInvites allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-M or N-M relationship. -func (authFallbackL) LoadCreatedByInvites(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAuthFallback interface{}, mods queries.Applicator) error { - var slice []*AuthFallback - var object *AuthFallback - - if singular { - object = maybeAuthFallback.(*AuthFallback) - } else { - slice = *maybeAuthFallback.(*[]*AuthFallback) - } - - args := make([]interface{}, 0, 1) - if singular { - if object.R == nil { - object.R = &authFallbackR{} - } - args = append(args, object.ID) - } else { - Outer: - for _, obj := range slice { - if obj.R == nil { - obj.R = &authFallbackR{} - } - - for _, a := range args { - if a == obj.ID { - continue Outer - } - } - - args = append(args, obj.ID) - } - } - - if len(args) == 0 { - return nil - } - - query := NewQuery( - qm.From(`invites`), - qm.WhereIn(`invites.created_by in ?`, args...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load invites") - } - - var resultSlice []*Invite - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice invites") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results in eager load on invites") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for invites") - } - - if len(inviteAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - if singular { - object.R.CreatedByInvites = resultSlice - for _, foreign := range resultSlice { - if foreign.R == nil { - foreign.R = &inviteR{} - } - foreign.R.CreatedByAuthFallback = object - } - return nil - } - - for _, foreign := range resultSlice { - for _, local := range slice { - if local.ID == foreign.CreatedBy { - local.R.CreatedByInvites = append(local.R.CreatedByInvites, foreign) - if foreign.R == nil { - foreign.R = &inviteR{} - } - foreign.R.CreatedByAuthFallback = local - break - } - } - } - - return nil -} - -// AddCreatedByInvites adds the given related objects to the existing relationships -// of the auth_fallback, optionally inserting them as new records. -// Appends related to o.R.CreatedByInvites. -// Sets related.R.CreatedByAuthFallback appropriately. -func (o *AuthFallback) AddCreatedByInvites(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*Invite) error { - var err error - for _, rel := range related { - if insert { - rel.CreatedBy = o.ID - if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"invites\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, []string{"created_by"}), - strmangle.WhereClause("\"", "\"", 0, invitePrimaryKeyColumns), - ) - values := []interface{}{o.ID, rel.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - rel.CreatedBy = o.ID - } - } - - if o.R == nil { - o.R = &authFallbackR{ - CreatedByInvites: related, - } - } else { - o.R.CreatedByInvites = append(o.R.CreatedByInvites, related...) - } - - for _, rel := range related { - if rel.R == nil { - rel.R = &inviteR{ - CreatedByAuthFallback: o, - } - } else { - rel.R.CreatedByAuthFallback = o - } - } - return nil -} - -// AuthFallbacks retrieves all the records using an executor. -func AuthFallbacks(mods ...qm.QueryMod) authFallbackQuery { - mods = append(mods, qm.From("\"auth_fallback\"")) - return authFallbackQuery{NewQuery(mods...)} -} - -// FindAuthFallback retrieves a single record by ID with an executor. -// If selectCols is empty Find will return all columns. -func FindAuthFallback(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*AuthFallback, error) { - authFallbackObj := &AuthFallback{} - - sel := "*" - if len(selectCols) > 0 { - sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") - } - query := fmt.Sprintf( - "select %s from \"auth_fallback\" where \"id\"=?", sel, - ) - - q := queries.Raw(query, iD) - - err := q.Bind(ctx, exec, authFallbackObj) - if err != nil { - if errors.Cause(err) == sql.ErrNoRows { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "models: unable to select from auth_fallback") - } - - return authFallbackObj, nil -} - -// Insert a single record using an executor. -// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *AuthFallback) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { - if o == nil { - return errors.New("models: no auth_fallback provided for insertion") - } - - var err error - - if err := o.doBeforeInsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(authFallbackColumnsWithDefault, o) - - key := makeCacheKey(columns, nzDefaults) - authFallbackInsertCacheMut.RLock() - cache, cached := authFallbackInsertCache[key] - authFallbackInsertCacheMut.RUnlock() - - if !cached { - wl, returnColumns := columns.InsertColumnSet( - authFallbackAllColumns, - authFallbackColumnsWithDefault, - authFallbackColumnsWithoutDefault, - nzDefaults, - ) - - cache.valueMapping, err = queries.BindMapping(authFallbackType, authFallbackMapping, wl) - if err != nil { - return err - } - cache.retMapping, err = queries.BindMapping(authFallbackType, authFallbackMapping, returnColumns) - if err != nil { - return err - } - if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"auth_fallback\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) - } else { - cache.query = "INSERT INTO \"auth_fallback\" %sDEFAULT VALUES%s" - } - - var queryOutput, queryReturning string - - if len(cache.retMapping) != 0 { - cache.retQuery = fmt.Sprintf("SELECT \"%s\" FROM \"auth_fallback\" WHERE %s", strings.Join(returnColumns, "\",\""), strmangle.WhereClause("\"", "\"", 0, authFallbackPrimaryKeyColumns)) - } - - cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - result, err := exec.ExecContext(ctx, cache.query, vals...) - - if err != nil { - return errors.Wrap(err, "models: unable to insert into auth_fallback") - } - - var lastID int64 - var identifierCols []interface{} - - if len(cache.retMapping) == 0 { - goto CacheNoHooks - } - - lastID, err = result.LastInsertId() - if err != nil { - return ErrSyncFail - } - - o.ID = int64(lastID) - if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == authFallbackMapping["id"] { - goto CacheNoHooks - } - - identifierCols = []interface{}{ - o.ID, - } - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.retQuery) - fmt.Fprintln(writer, identifierCols...) - } - err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) - if err != nil { - return errors.Wrap(err, "models: unable to populate default values for auth_fallback") - } - -CacheNoHooks: - if !cached { - authFallbackInsertCacheMut.Lock() - authFallbackInsertCache[key] = cache - authFallbackInsertCacheMut.Unlock() - } - - return o.doAfterInsertHooks(ctx, exec) -} - -// Update uses an executor to update the AuthFallback. -// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. -// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *AuthFallback) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { - var err error - if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { - return 0, err - } - key := makeCacheKey(columns, nil) - authFallbackUpdateCacheMut.RLock() - cache, cached := authFallbackUpdateCache[key] - authFallbackUpdateCacheMut.RUnlock() - - if !cached { - wl := columns.UpdateColumnSet( - authFallbackAllColumns, - authFallbackPrimaryKeyColumns, - ) - - if !columns.IsWhitelist() { - wl = strmangle.SetComplement(wl, []string{"created_at"}) - } - if len(wl) == 0 { - return 0, errors.New("models: unable to update auth_fallback, could not build whitelist") - } - - cache.query = fmt.Sprintf("UPDATE \"auth_fallback\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, wl), - strmangle.WhereClause("\"", "\"", 0, authFallbackPrimaryKeyColumns), - ) - cache.valueMapping, err = queries.BindMapping(authFallbackType, authFallbackMapping, append(wl, authFallbackPrimaryKeyColumns...)) - if err != nil { - return 0, err - } - } - - values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, values) - } - var result sql.Result - result, err = exec.ExecContext(ctx, cache.query, values...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update auth_fallback row") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by update for auth_fallback") - } - - if !cached { - authFallbackUpdateCacheMut.Lock() - authFallbackUpdateCache[key] = cache - authFallbackUpdateCacheMut.Unlock() - } - - return rowsAff, o.doAfterUpdateHooks(ctx, exec) -} - -// UpdateAll updates all rows with the specified column values. -func (q authFallbackQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - queries.SetUpdate(q.Query, cols) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all for auth_fallback") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected for auth_fallback") - } - - return rowsAff, nil -} - -// UpdateAll updates all rows with the specified column values, using an executor. -func (o AuthFallbackSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - ln := int64(len(o)) - if ln == 0 { - return 0, nil - } - - if len(cols) == 0 { - return 0, errors.New("models: update all requires at least one column argument") - } - - colNames := make([]string, len(cols)) - args := make([]interface{}, len(cols)) - - i := 0 - for name, value := range cols { - colNames[i] = name - args[i] = value - i++ - } - - // Append all of the primary key values for each column - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), authFallbackPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := fmt.Sprintf("UPDATE \"auth_fallback\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 0, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, authFallbackPrimaryKeyColumns, len(o))) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to update all in authFallback slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all authFallback") - } - return rowsAff, nil -} - -// Delete deletes a single AuthFallback record with an executor. -// Delete will match against the primary key column to find the record to delete. -func (o *AuthFallback) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if o == nil { - return 0, errors.New("models: no AuthFallback provided for delete") - } - - if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), authFallbackPrimaryKeyMapping) - sql := "DELETE FROM \"auth_fallback\" WHERE \"id\"=?" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete from auth_fallback") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by delete for auth_fallback") - } - - if err := o.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - return rowsAff, nil -} - -// DeleteAll deletes all matching rows. -func (q authFallbackQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if q.Query == nil { - return 0, errors.New("models: no authFallbackQuery provided for delete all") - } - - queries.SetDelete(q.Query) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from auth_fallback") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for auth_fallback") - } - - return rowsAff, nil -} - -// DeleteAll deletes all rows in the slice, using an executor. -func (o AuthFallbackSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if len(o) == 0 { - return 0, nil - } - - if len(authFallbackBeforeDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - var args []interface{} - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), authFallbackPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "DELETE FROM \"auth_fallback\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, authFallbackPrimaryKeyColumns, len(o)) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "models: unable to delete all from authFallback slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for auth_fallback") - } - - if len(authFallbackAfterDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - return rowsAff, nil -} - -// Reload refetches the object from the database -// using the primary keys with an executor. -func (o *AuthFallback) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindAuthFallback(ctx, exec, o.ID) - if err != nil { - return err - } - - *o = *ret - return nil -} - -// ReloadAll refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *AuthFallbackSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { - if o == nil || len(*o) == 0 { - return nil - } - - slice := AuthFallbackSlice{} - var args []interface{} - for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), authFallbackPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "SELECT \"auth_fallback\".* FROM \"auth_fallback\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, authFallbackPrimaryKeyColumns, len(*o)) - - q := queries.Raw(sql, args...) - - err := q.Bind(ctx, exec, &slice) - if err != nil { - return errors.Wrap(err, "models: unable to reload all in AuthFallbackSlice") - } - - *o = slice - - return nil -} - -// AuthFallbackExists checks if the AuthFallback row exists. -func AuthFallbackExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) { - var exists bool - sql := "select exists(select 1 from \"auth_fallback\" where \"id\"=? limit 1)" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, iD) - } - row := exec.QueryRowContext(ctx, sql, iD) - - err := row.Scan(&exists) - if err != nil { - return false, errors.Wrap(err, "models: unable to check if auth_fallback exists") - } - - return exists, nil -} diff --git a/roomdb/sqlite/models/boil_table_names.go b/roomdb/sqlite/models/boil_table_names.go index f241943..162de03 100644 --- a/roomdb/sqlite/models/boil_table_names.go +++ b/roomdb/sqlite/models/boil_table_names.go @@ -4,19 +4,21 @@ package models var TableNames = struct { - Aliases string - AllowList string - AuthFallback string - Invites string - Notices string - PinNotices string - Pins string + Aliases string + DeniedKeys string + FallbackPasswords string + Invites string + Members string + Notices string + PinNotices string + Pins string }{ - Aliases: "aliases", - AllowList: "allow_list", - AuthFallback: "auth_fallback", - Invites: "invites", - Notices: "notices", - PinNotices: "pin_notices", - Pins: "pins", + Aliases: "aliases", + DeniedKeys: "denied_keys", + FallbackPasswords: "fallback_passwords", + Invites: "invites", + Members: "members", + Notices: "notices", + PinNotices: "pin_notices", + Pins: "pins", } diff --git a/roomdb/sqlite/models/denied_keys.go b/roomdb/sqlite/models/denied_keys.go new file mode 100644 index 0000000..95286ec --- /dev/null +++ b/roomdb/sqlite/models/denied_keys.go @@ -0,0 +1,839 @@ +// Code generated by SQLBoiler 4.5.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package models + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// DeniedKey is an object representing the database table. +type DeniedKey struct { + ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` + PubKey roomdb.DBFeedRef `boil:"pub_key" json:"pub_key" toml:"pub_key" yaml:"pub_key"` + Comment string `boil:"comment" json:"comment" toml:"comment" yaml:"comment"` + CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` + + R *deniedKeyR `boil:"-" json:"-" toml:"-" yaml:"-"` + L deniedKeyL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var DeniedKeyColumns = struct { + ID string + PubKey string + Comment string + CreatedAt string +}{ + ID: "id", + PubKey: "pub_key", + Comment: "comment", + CreatedAt: "created_at", +} + +// Generated where + +type whereHelperroomdb_DBFeedRef struct{ field string } + +func (w whereHelperroomdb_DBFeedRef) EQ(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.EQ, x) +} +func (w whereHelperroomdb_DBFeedRef) NEQ(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.NEQ, x) +} +func (w whereHelperroomdb_DBFeedRef) LT(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LT, x) +} +func (w whereHelperroomdb_DBFeedRef) LTE(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LTE, x) +} +func (w whereHelperroomdb_DBFeedRef) GT(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GT, x) +} +func (w whereHelperroomdb_DBFeedRef) GTE(x roomdb.DBFeedRef) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GTE, x) +} + +type whereHelpertime_Time struct{ field string } + +func (w whereHelpertime_Time) EQ(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.EQ, x) +} +func (w whereHelpertime_Time) NEQ(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.NEQ, x) +} +func (w whereHelpertime_Time) LT(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LT, x) +} +func (w whereHelpertime_Time) LTE(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.LTE, x) +} +func (w whereHelpertime_Time) GT(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GT, x) +} +func (w whereHelpertime_Time) GTE(x time.Time) qm.QueryMod { + return qmhelper.Where(w.field, qmhelper.GTE, x) +} + +var DeniedKeyWhere = struct { + ID whereHelperint64 + PubKey whereHelperroomdb_DBFeedRef + Comment whereHelperstring + CreatedAt whereHelpertime_Time +}{ + ID: whereHelperint64{field: "\"denied_keys\".\"id\""}, + PubKey: whereHelperroomdb_DBFeedRef{field: "\"denied_keys\".\"pub_key\""}, + Comment: whereHelperstring{field: "\"denied_keys\".\"comment\""}, + CreatedAt: whereHelpertime_Time{field: "\"denied_keys\".\"created_at\""}, +} + +// DeniedKeyRels is where relationship names are stored. +var DeniedKeyRels = struct { +}{} + +// deniedKeyR is where relationships are stored. +type deniedKeyR struct { +} + +// NewStruct creates a new relationship struct +func (*deniedKeyR) NewStruct() *deniedKeyR { + return &deniedKeyR{} +} + +// deniedKeyL is where Load methods for each relationship are stored. +type deniedKeyL struct{} + +var ( + deniedKeyAllColumns = []string{"id", "pub_key", "comment", "created_at"} + deniedKeyColumnsWithoutDefault = []string{} + deniedKeyColumnsWithDefault = []string{"id", "pub_key", "comment", "created_at"} + deniedKeyPrimaryKeyColumns = []string{"id"} +) + +type ( + // DeniedKeySlice is an alias for a slice of pointers to DeniedKey. + // This should generally be used opposed to []DeniedKey. + DeniedKeySlice []*DeniedKey + // DeniedKeyHook is the signature for custom DeniedKey hook methods + DeniedKeyHook func(context.Context, boil.ContextExecutor, *DeniedKey) error + + deniedKeyQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + deniedKeyType = reflect.TypeOf(&DeniedKey{}) + deniedKeyMapping = queries.MakeStructMapping(deniedKeyType) + deniedKeyPrimaryKeyMapping, _ = queries.BindMapping(deniedKeyType, deniedKeyMapping, deniedKeyPrimaryKeyColumns) + deniedKeyInsertCacheMut sync.RWMutex + deniedKeyInsertCache = make(map[string]insertCache) + deniedKeyUpdateCacheMut sync.RWMutex + deniedKeyUpdateCache = make(map[string]updateCache) + deniedKeyUpsertCacheMut sync.RWMutex + deniedKeyUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var deniedKeyBeforeInsertHooks []DeniedKeyHook +var deniedKeyBeforeUpdateHooks []DeniedKeyHook +var deniedKeyBeforeDeleteHooks []DeniedKeyHook +var deniedKeyBeforeUpsertHooks []DeniedKeyHook + +var deniedKeyAfterInsertHooks []DeniedKeyHook +var deniedKeyAfterSelectHooks []DeniedKeyHook +var deniedKeyAfterUpdateHooks []DeniedKeyHook +var deniedKeyAfterDeleteHooks []DeniedKeyHook +var deniedKeyAfterUpsertHooks []DeniedKeyHook + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *DeniedKey) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *DeniedKey) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *DeniedKey) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *DeniedKey) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *DeniedKey) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *DeniedKey) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *DeniedKey) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *DeniedKey) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *DeniedKey) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range deniedKeyAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddDeniedKeyHook registers your hook function for all future operations. +func AddDeniedKeyHook(hookPoint boil.HookPoint, deniedKeyHook DeniedKeyHook) { + switch hookPoint { + case boil.BeforeInsertHook: + deniedKeyBeforeInsertHooks = append(deniedKeyBeforeInsertHooks, deniedKeyHook) + case boil.BeforeUpdateHook: + deniedKeyBeforeUpdateHooks = append(deniedKeyBeforeUpdateHooks, deniedKeyHook) + case boil.BeforeDeleteHook: + deniedKeyBeforeDeleteHooks = append(deniedKeyBeforeDeleteHooks, deniedKeyHook) + case boil.BeforeUpsertHook: + deniedKeyBeforeUpsertHooks = append(deniedKeyBeforeUpsertHooks, deniedKeyHook) + case boil.AfterInsertHook: + deniedKeyAfterInsertHooks = append(deniedKeyAfterInsertHooks, deniedKeyHook) + case boil.AfterSelectHook: + deniedKeyAfterSelectHooks = append(deniedKeyAfterSelectHooks, deniedKeyHook) + case boil.AfterUpdateHook: + deniedKeyAfterUpdateHooks = append(deniedKeyAfterUpdateHooks, deniedKeyHook) + case boil.AfterDeleteHook: + deniedKeyAfterDeleteHooks = append(deniedKeyAfterDeleteHooks, deniedKeyHook) + case boil.AfterUpsertHook: + deniedKeyAfterUpsertHooks = append(deniedKeyAfterUpsertHooks, deniedKeyHook) + } +} + +// One returns a single deniedKey record from the query. +func (q deniedKeyQuery) One(ctx context.Context, exec boil.ContextExecutor) (*DeniedKey, error) { + o := &DeniedKey{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: failed to execute a one query for denied_keys") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// All returns all DeniedKey records from the query. +func (q deniedKeyQuery) All(ctx context.Context, exec boil.ContextExecutor) (DeniedKeySlice, error) { + var o []*DeniedKey + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "models: failed to assign all query results to DeniedKey slice") + } + + if len(deniedKeyAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// Count returns the count of all DeniedKey records in the query. +func (q deniedKeyQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "models: failed to count denied_keys rows") + } + + return count, nil +} + +// Exists checks if the row exists in the table. +func (q deniedKeyQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "models: failed to check if denied_keys exists") + } + + return count > 0, nil +} + +// DeniedKeys retrieves all the records using an executor. +func DeniedKeys(mods ...qm.QueryMod) deniedKeyQuery { + mods = append(mods, qm.From("\"denied_keys\"")) + return deniedKeyQuery{NewQuery(mods...)} +} + +// FindDeniedKey retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindDeniedKey(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*DeniedKey, error) { + deniedKeyObj := &DeniedKey{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"denied_keys\" where \"id\"=?", sel, + ) + + q := queries.Raw(query, iD) + + err := q.Bind(ctx, exec, deniedKeyObj) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: unable to select from denied_keys") + } + + return deniedKeyObj, nil +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *DeniedKey) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("models: no denied_keys provided for insertion") + } + + var err error + if !boil.TimestampsAreSkipped(ctx) { + currTime := time.Now().In(boil.GetLocation()) + + if o.CreatedAt.IsZero() { + o.CreatedAt = currTime + } + } + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(deniedKeyColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + deniedKeyInsertCacheMut.RLock() + cache, cached := deniedKeyInsertCache[key] + deniedKeyInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + deniedKeyAllColumns, + deniedKeyColumnsWithDefault, + deniedKeyColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(deniedKeyType, deniedKeyMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(deniedKeyType, deniedKeyMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"denied_keys\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"denied_keys\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + cache.retQuery = fmt.Sprintf("SELECT \"%s\" FROM \"denied_keys\" WHERE %s", strings.Join(returnColumns, "\",\""), strmangle.WhereClause("\"", "\"", 0, deniedKeyPrimaryKeyColumns)) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + result, err := exec.ExecContext(ctx, cache.query, vals...) + + if err != nil { + return errors.Wrap(err, "models: unable to insert into denied_keys") + } + + var lastID int64 + var identifierCols []interface{} + + if len(cache.retMapping) == 0 { + goto CacheNoHooks + } + + lastID, err = result.LastInsertId() + if err != nil { + return ErrSyncFail + } + + o.ID = int64(lastID) + if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == deniedKeyMapping["id"] { + goto CacheNoHooks + } + + identifierCols = []interface{}{ + o.ID, + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.retQuery) + fmt.Fprintln(writer, identifierCols...) + } + err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + if err != nil { + return errors.Wrap(err, "models: unable to populate default values for denied_keys") + } + +CacheNoHooks: + if !cached { + deniedKeyInsertCacheMut.Lock() + deniedKeyInsertCache[key] = cache + deniedKeyInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// Update uses an executor to update the DeniedKey. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *DeniedKey) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + deniedKeyUpdateCacheMut.RLock() + cache, cached := deniedKeyUpdateCache[key] + deniedKeyUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + deniedKeyAllColumns, + deniedKeyPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("models: unable to update denied_keys, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"denied_keys\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, wl), + strmangle.WhereClause("\"", "\"", 0, deniedKeyPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(deniedKeyType, deniedKeyMapping, append(wl, deniedKeyPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update denied_keys row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by update for denied_keys") + } + + if !cached { + deniedKeyUpdateCacheMut.Lock() + deniedKeyUpdateCache[key] = cache + deniedKeyUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAll updates all rows with the specified column values. +func (q deniedKeyQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all for denied_keys") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for denied_keys") + } + + return rowsAff, nil +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o DeniedKeySlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("models: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), deniedKeyPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"denied_keys\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, deniedKeyPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all in deniedKey slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all deniedKey") + } + return rowsAff, nil +} + +// Delete deletes a single DeniedKey record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *DeniedKey) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("models: no DeniedKey provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), deniedKeyPrimaryKeyMapping) + sql := "DELETE FROM \"denied_keys\" WHERE \"id\"=?" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete from denied_keys") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for denied_keys") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +// DeleteAll deletes all matching rows. +func (q deniedKeyQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("models: no deniedKeyQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from denied_keys") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for denied_keys") + } + + return rowsAff, nil +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o DeniedKeySlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(deniedKeyBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), deniedKeyPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"denied_keys\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, deniedKeyPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from deniedKey slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for denied_keys") + } + + if len(deniedKeyAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *DeniedKey) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindDeniedKey(ctx, exec, o.ID) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *DeniedKeySlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := DeniedKeySlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), deniedKeyPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"denied_keys\".* FROM \"denied_keys\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, deniedKeyPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "models: unable to reload all in DeniedKeySlice") + } + + *o = slice + + return nil +} + +// DeniedKeyExists checks if the DeniedKey row exists. +func DeniedKeyExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"denied_keys\" where \"id\"=? limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, iD) + } + row := exec.QueryRowContext(ctx, sql, iD) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "models: unable to check if denied_keys exists") + } + + return exists, nil +} diff --git a/roomdb/sqlite/models/fallback_passwords.go b/roomdb/sqlite/models/fallback_passwords.go new file mode 100644 index 0000000..d112ffe --- /dev/null +++ b/roomdb/sqlite/models/fallback_passwords.go @@ -0,0 +1,958 @@ +// Code generated by SQLBoiler 4.5.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package models + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// FallbackPassword is an object representing the database table. +type FallbackPassword struct { + ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` + Login string `boil:"login" json:"login" toml:"login" yaml:"login"` + PasswordHash []byte `boil:"password_hash" json:"password_hash" toml:"password_hash" yaml:"password_hash"` + MemberID int64 `boil:"member_id" json:"member_id" toml:"member_id" yaml:"member_id"` + + R *fallbackPasswordR `boil:"-" json:"-" toml:"-" yaml:"-"` + L fallbackPasswordL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var FallbackPasswordColumns = struct { + ID string + Login string + PasswordHash string + MemberID string +}{ + ID: "id", + Login: "login", + PasswordHash: "password_hash", + MemberID: "member_id", +} + +// Generated where + +var FallbackPasswordWhere = struct { + ID whereHelperint64 + Login whereHelperstring + PasswordHash whereHelper__byte + MemberID whereHelperint64 +}{ + ID: whereHelperint64{field: "\"fallback_passwords\".\"id\""}, + Login: whereHelperstring{field: "\"fallback_passwords\".\"login\""}, + PasswordHash: whereHelper__byte{field: "\"fallback_passwords\".\"password_hash\""}, + MemberID: whereHelperint64{field: "\"fallback_passwords\".\"member_id\""}, +} + +// FallbackPasswordRels is where relationship names are stored. +var FallbackPasswordRels = struct { + Member string +}{ + Member: "Member", +} + +// fallbackPasswordR is where relationships are stored. +type fallbackPasswordR struct { + Member *Member `boil:"Member" json:"Member" toml:"Member" yaml:"Member"` +} + +// NewStruct creates a new relationship struct +func (*fallbackPasswordR) NewStruct() *fallbackPasswordR { + return &fallbackPasswordR{} +} + +// fallbackPasswordL is where Load methods for each relationship are stored. +type fallbackPasswordL struct{} + +var ( + fallbackPasswordAllColumns = []string{"id", "login", "password_hash", "member_id"} + fallbackPasswordColumnsWithoutDefault = []string{} + fallbackPasswordColumnsWithDefault = []string{"id", "login", "password_hash", "member_id"} + fallbackPasswordPrimaryKeyColumns = []string{"id"} +) + +type ( + // FallbackPasswordSlice is an alias for a slice of pointers to FallbackPassword. + // This should generally be used opposed to []FallbackPassword. + FallbackPasswordSlice []*FallbackPassword + // FallbackPasswordHook is the signature for custom FallbackPassword hook methods + FallbackPasswordHook func(context.Context, boil.ContextExecutor, *FallbackPassword) error + + fallbackPasswordQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + fallbackPasswordType = reflect.TypeOf(&FallbackPassword{}) + fallbackPasswordMapping = queries.MakeStructMapping(fallbackPasswordType) + fallbackPasswordPrimaryKeyMapping, _ = queries.BindMapping(fallbackPasswordType, fallbackPasswordMapping, fallbackPasswordPrimaryKeyColumns) + fallbackPasswordInsertCacheMut sync.RWMutex + fallbackPasswordInsertCache = make(map[string]insertCache) + fallbackPasswordUpdateCacheMut sync.RWMutex + fallbackPasswordUpdateCache = make(map[string]updateCache) + fallbackPasswordUpsertCacheMut sync.RWMutex + fallbackPasswordUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var fallbackPasswordBeforeInsertHooks []FallbackPasswordHook +var fallbackPasswordBeforeUpdateHooks []FallbackPasswordHook +var fallbackPasswordBeforeDeleteHooks []FallbackPasswordHook +var fallbackPasswordBeforeUpsertHooks []FallbackPasswordHook + +var fallbackPasswordAfterInsertHooks []FallbackPasswordHook +var fallbackPasswordAfterSelectHooks []FallbackPasswordHook +var fallbackPasswordAfterUpdateHooks []FallbackPasswordHook +var fallbackPasswordAfterDeleteHooks []FallbackPasswordHook +var fallbackPasswordAfterUpsertHooks []FallbackPasswordHook + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *FallbackPassword) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *FallbackPassword) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *FallbackPassword) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *FallbackPassword) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *FallbackPassword) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *FallbackPassword) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *FallbackPassword) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *FallbackPassword) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *FallbackPassword) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range fallbackPasswordAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddFallbackPasswordHook registers your hook function for all future operations. +func AddFallbackPasswordHook(hookPoint boil.HookPoint, fallbackPasswordHook FallbackPasswordHook) { + switch hookPoint { + case boil.BeforeInsertHook: + fallbackPasswordBeforeInsertHooks = append(fallbackPasswordBeforeInsertHooks, fallbackPasswordHook) + case boil.BeforeUpdateHook: + fallbackPasswordBeforeUpdateHooks = append(fallbackPasswordBeforeUpdateHooks, fallbackPasswordHook) + case boil.BeforeDeleteHook: + fallbackPasswordBeforeDeleteHooks = append(fallbackPasswordBeforeDeleteHooks, fallbackPasswordHook) + case boil.BeforeUpsertHook: + fallbackPasswordBeforeUpsertHooks = append(fallbackPasswordBeforeUpsertHooks, fallbackPasswordHook) + case boil.AfterInsertHook: + fallbackPasswordAfterInsertHooks = append(fallbackPasswordAfterInsertHooks, fallbackPasswordHook) + case boil.AfterSelectHook: + fallbackPasswordAfterSelectHooks = append(fallbackPasswordAfterSelectHooks, fallbackPasswordHook) + case boil.AfterUpdateHook: + fallbackPasswordAfterUpdateHooks = append(fallbackPasswordAfterUpdateHooks, fallbackPasswordHook) + case boil.AfterDeleteHook: + fallbackPasswordAfterDeleteHooks = append(fallbackPasswordAfterDeleteHooks, fallbackPasswordHook) + case boil.AfterUpsertHook: + fallbackPasswordAfterUpsertHooks = append(fallbackPasswordAfterUpsertHooks, fallbackPasswordHook) + } +} + +// One returns a single fallbackPassword record from the query. +func (q fallbackPasswordQuery) One(ctx context.Context, exec boil.ContextExecutor) (*FallbackPassword, error) { + o := &FallbackPassword{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: failed to execute a one query for fallback_passwords") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// All returns all FallbackPassword records from the query. +func (q fallbackPasswordQuery) All(ctx context.Context, exec boil.ContextExecutor) (FallbackPasswordSlice, error) { + var o []*FallbackPassword + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "models: failed to assign all query results to FallbackPassword slice") + } + + if len(fallbackPasswordAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// Count returns the count of all FallbackPassword records in the query. +func (q fallbackPasswordQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "models: failed to count fallback_passwords rows") + } + + return count, nil +} + +// Exists checks if the row exists in the table. +func (q fallbackPasswordQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "models: failed to check if fallback_passwords exists") + } + + return count > 0, nil +} + +// Member pointed to by the foreign key. +func (o *FallbackPassword) Member(mods ...qm.QueryMod) memberQuery { + queryMods := []qm.QueryMod{ + qm.Where("\"id\" = ?", o.MemberID), + } + + queryMods = append(queryMods, mods...) + + query := Members(queryMods...) + queries.SetFrom(query.Query, "\"members\"") + + return query +} + +// LoadMember allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for an N-1 relationship. +func (fallbackPasswordL) LoadMember(ctx context.Context, e boil.ContextExecutor, singular bool, maybeFallbackPassword interface{}, mods queries.Applicator) error { + var slice []*FallbackPassword + var object *FallbackPassword + + if singular { + object = maybeFallbackPassword.(*FallbackPassword) + } else { + slice = *maybeFallbackPassword.(*[]*FallbackPassword) + } + + args := make([]interface{}, 0, 1) + if singular { + if object.R == nil { + object.R = &fallbackPasswordR{} + } + args = append(args, object.MemberID) + + } else { + Outer: + for _, obj := range slice { + if obj.R == nil { + obj.R = &fallbackPasswordR{} + } + + for _, a := range args { + if a == obj.MemberID { + continue Outer + } + } + + args = append(args, obj.MemberID) + + } + } + + if len(args) == 0 { + return nil + } + + query := NewQuery( + qm.From(`members`), + qm.WhereIn(`members.id in ?`, args...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load Member") + } + + var resultSlice []*Member + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice Member") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results of eager load for members") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for members") + } + + if len(fallbackPasswordAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + + if len(resultSlice) == 0 { + return nil + } + + if singular { + foreign := resultSlice[0] + object.R.Member = foreign + if foreign.R == nil { + foreign.R = &memberR{} + } + foreign.R.FallbackPasswords = append(foreign.R.FallbackPasswords, object) + return nil + } + + for _, local := range slice { + for _, foreign := range resultSlice { + if local.MemberID == foreign.ID { + local.R.Member = foreign + if foreign.R == nil { + foreign.R = &memberR{} + } + foreign.R.FallbackPasswords = append(foreign.R.FallbackPasswords, local) + break + } + } + } + + return nil +} + +// SetMember of the fallbackPassword to the related item. +// Sets o.R.Member to related. +// Adds o to related.R.FallbackPasswords. +func (o *FallbackPassword) SetMember(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Member) error { + var err error + if insert { + if err = related.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } + + updateQuery := fmt.Sprintf( + "UPDATE \"fallback_passwords\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, []string{"member_id"}), + strmangle.WhereClause("\"", "\"", 0, fallbackPasswordPrimaryKeyColumns), + ) + values := []interface{}{related.ID, o.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update local table") + } + + o.MemberID = related.ID + if o.R == nil { + o.R = &fallbackPasswordR{ + Member: related, + } + } else { + o.R.Member = related + } + + if related.R == nil { + related.R = &memberR{ + FallbackPasswords: FallbackPasswordSlice{o}, + } + } else { + related.R.FallbackPasswords = append(related.R.FallbackPasswords, o) + } + + return nil +} + +// FallbackPasswords retrieves all the records using an executor. +func FallbackPasswords(mods ...qm.QueryMod) fallbackPasswordQuery { + mods = append(mods, qm.From("\"fallback_passwords\"")) + return fallbackPasswordQuery{NewQuery(mods...)} +} + +// FindFallbackPassword retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindFallbackPassword(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*FallbackPassword, error) { + fallbackPasswordObj := &FallbackPassword{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"fallback_passwords\" where \"id\"=?", sel, + ) + + q := queries.Raw(query, iD) + + err := q.Bind(ctx, exec, fallbackPasswordObj) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: unable to select from fallback_passwords") + } + + return fallbackPasswordObj, nil +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *FallbackPassword) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("models: no fallback_passwords provided for insertion") + } + + var err error + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(fallbackPasswordColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + fallbackPasswordInsertCacheMut.RLock() + cache, cached := fallbackPasswordInsertCache[key] + fallbackPasswordInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + fallbackPasswordAllColumns, + fallbackPasswordColumnsWithDefault, + fallbackPasswordColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(fallbackPasswordType, fallbackPasswordMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(fallbackPasswordType, fallbackPasswordMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"fallback_passwords\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"fallback_passwords\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + cache.retQuery = fmt.Sprintf("SELECT \"%s\" FROM \"fallback_passwords\" WHERE %s", strings.Join(returnColumns, "\",\""), strmangle.WhereClause("\"", "\"", 0, fallbackPasswordPrimaryKeyColumns)) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + result, err := exec.ExecContext(ctx, cache.query, vals...) + + if err != nil { + return errors.Wrap(err, "models: unable to insert into fallback_passwords") + } + + var lastID int64 + var identifierCols []interface{} + + if len(cache.retMapping) == 0 { + goto CacheNoHooks + } + + lastID, err = result.LastInsertId() + if err != nil { + return ErrSyncFail + } + + o.ID = int64(lastID) + if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == fallbackPasswordMapping["id"] { + goto CacheNoHooks + } + + identifierCols = []interface{}{ + o.ID, + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.retQuery) + fmt.Fprintln(writer, identifierCols...) + } + err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + if err != nil { + return errors.Wrap(err, "models: unable to populate default values for fallback_passwords") + } + +CacheNoHooks: + if !cached { + fallbackPasswordInsertCacheMut.Lock() + fallbackPasswordInsertCache[key] = cache + fallbackPasswordInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// Update uses an executor to update the FallbackPassword. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *FallbackPassword) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + fallbackPasswordUpdateCacheMut.RLock() + cache, cached := fallbackPasswordUpdateCache[key] + fallbackPasswordUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + fallbackPasswordAllColumns, + fallbackPasswordPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("models: unable to update fallback_passwords, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"fallback_passwords\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, wl), + strmangle.WhereClause("\"", "\"", 0, fallbackPasswordPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(fallbackPasswordType, fallbackPasswordMapping, append(wl, fallbackPasswordPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update fallback_passwords row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by update for fallback_passwords") + } + + if !cached { + fallbackPasswordUpdateCacheMut.Lock() + fallbackPasswordUpdateCache[key] = cache + fallbackPasswordUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAll updates all rows with the specified column values. +func (q fallbackPasswordQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all for fallback_passwords") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for fallback_passwords") + } + + return rowsAff, nil +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o FallbackPasswordSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("models: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), fallbackPasswordPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"fallback_passwords\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, fallbackPasswordPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all in fallbackPassword slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all fallbackPassword") + } + return rowsAff, nil +} + +// Delete deletes a single FallbackPassword record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *FallbackPassword) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("models: no FallbackPassword provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), fallbackPasswordPrimaryKeyMapping) + sql := "DELETE FROM \"fallback_passwords\" WHERE \"id\"=?" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete from fallback_passwords") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for fallback_passwords") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +// DeleteAll deletes all matching rows. +func (q fallbackPasswordQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("models: no fallbackPasswordQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from fallback_passwords") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for fallback_passwords") + } + + return rowsAff, nil +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o FallbackPasswordSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(fallbackPasswordBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), fallbackPasswordPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"fallback_passwords\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, fallbackPasswordPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from fallbackPassword slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for fallback_passwords") + } + + if len(fallbackPasswordAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *FallbackPassword) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindFallbackPassword(ctx, exec, o.ID) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *FallbackPasswordSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := FallbackPasswordSlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), fallbackPasswordPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"fallback_passwords\".* FROM \"fallback_passwords\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, fallbackPasswordPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "models: unable to reload all in FallbackPasswordSlice") + } + + *o = slice + + return nil +} + +// FallbackPasswordExists checks if the FallbackPassword row exists. +func FallbackPasswordExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"fallback_passwords\" where \"id\"=? limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, iD) + } + row := exec.QueryRowContext(ctx, sql, iD) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "models: unable to check if fallback_passwords exists") + } + + return exists, nil +} diff --git a/roomdb/sqlite/models/invites.go b/roomdb/sqlite/models/invites.go index e91805c..e1bf22c 100644 --- a/roomdb/sqlite/models/invites.go +++ b/roomdb/sqlite/models/invites.go @@ -23,11 +23,11 @@ import ( // Invite is an object representing the database table. type Invite struct { ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` - Token string `boil:"token" json:"token" toml:"token" yaml:"token"` + HashedToken string `boil:"hashed_token" json:"hashed_token" toml:"hashed_token" yaml:"hashed_token"` CreatedBy int64 `boil:"created_by" json:"created_by" toml:"created_by" yaml:"created_by"` + CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` AliasSuggestion string `boil:"alias_suggestion" json:"alias_suggestion" toml:"alias_suggestion" yaml:"alias_suggestion"` Active bool `boil:"active" json:"active" toml:"active" yaml:"active"` - CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"` R *inviteR `boil:"-" json:"-" toml:"-" yaml:"-"` L inviteL `boil:"-" json:"-" toml:"-" yaml:"-"` @@ -35,18 +35,18 @@ type Invite struct { var InviteColumns = struct { ID string - Token string + HashedToken string CreatedBy string + CreatedAt string AliasSuggestion string Active string - CreatedAt string }{ ID: "id", - Token: "token", + HashedToken: "hashed_token", CreatedBy: "created_by", + CreatedAt: "created_at", AliasSuggestion: "alias_suggestion", Active: "active", - CreatedAt: "created_at", } // Generated where @@ -60,53 +60,32 @@ func (w whereHelperbool) LTE(x bool) qm.QueryMod { return qmhelper.Where(w.field func (w whereHelperbool) GT(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } func (w whereHelperbool) GTE(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } -type whereHelpertime_Time struct{ field string } - -func (w whereHelpertime_Time) EQ(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.EQ, x) -} -func (w whereHelpertime_Time) NEQ(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.NEQ, x) -} -func (w whereHelpertime_Time) LT(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LT, x) -} -func (w whereHelpertime_Time) LTE(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.LTE, x) -} -func (w whereHelpertime_Time) GT(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GT, x) -} -func (w whereHelpertime_Time) GTE(x time.Time) qm.QueryMod { - return qmhelper.Where(w.field, qmhelper.GTE, x) -} - var InviteWhere = struct { ID whereHelperint64 - Token whereHelperstring + HashedToken whereHelperstring CreatedBy whereHelperint64 + CreatedAt whereHelpertime_Time AliasSuggestion whereHelperstring Active whereHelperbool - CreatedAt whereHelpertime_Time }{ ID: whereHelperint64{field: "\"invites\".\"id\""}, - Token: whereHelperstring{field: "\"invites\".\"token\""}, + HashedToken: whereHelperstring{field: "\"invites\".\"hashed_token\""}, CreatedBy: whereHelperint64{field: "\"invites\".\"created_by\""}, + CreatedAt: whereHelpertime_Time{field: "\"invites\".\"created_at\""}, AliasSuggestion: whereHelperstring{field: "\"invites\".\"alias_suggestion\""}, Active: whereHelperbool{field: "\"invites\".\"active\""}, - CreatedAt: whereHelpertime_Time{field: "\"invites\".\"created_at\""}, } // InviteRels is where relationship names are stored. var InviteRels = struct { - CreatedByAuthFallback string + CreatedByMember string }{ - CreatedByAuthFallback: "CreatedByAuthFallback", + CreatedByMember: "CreatedByMember", } // inviteR is where relationships are stored. type inviteR struct { - CreatedByAuthFallback *AuthFallback `boil:"CreatedByAuthFallback" json:"CreatedByAuthFallback" toml:"CreatedByAuthFallback" yaml:"CreatedByAuthFallback"` + CreatedByMember *Member `boil:"CreatedByMember" json:"CreatedByMember" toml:"CreatedByMember" yaml:"CreatedByMember"` } // NewStruct creates a new relationship struct @@ -118,9 +97,9 @@ func (*inviteR) NewStruct() *inviteR { type inviteL struct{} var ( - inviteAllColumns = []string{"id", "token", "created_by", "alias_suggestion", "active", "created_at"} + inviteAllColumns = []string{"id", "hashed_token", "created_by", "created_at", "alias_suggestion", "active"} inviteColumnsWithoutDefault = []string{} - inviteColumnsWithDefault = []string{"id", "token", "created_by", "alias_suggestion", "active", "created_at"} + inviteColumnsWithDefault = []string{"id", "hashed_token", "created_by", "created_at", "alias_suggestion", "active"} invitePrimaryKeyColumns = []string{"id"} ) @@ -399,23 +378,23 @@ func (q inviteQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (boo return count > 0, nil } -// CreatedByAuthFallback pointed to by the foreign key. -func (o *Invite) CreatedByAuthFallback(mods ...qm.QueryMod) authFallbackQuery { +// CreatedByMember pointed to by the foreign key. +func (o *Invite) CreatedByMember(mods ...qm.QueryMod) memberQuery { queryMods := []qm.QueryMod{ qm.Where("\"id\" = ?", o.CreatedBy), } queryMods = append(queryMods, mods...) - query := AuthFallbacks(queryMods...) - queries.SetFrom(query.Query, "\"auth_fallback\"") + query := Members(queryMods...) + queries.SetFrom(query.Query, "\"members\"") return query } -// LoadCreatedByAuthFallback allows an eager lookup of values, cached into the +// LoadCreatedByMember allows an eager lookup of values, cached into the // loaded structs of the objects. This is for an N-1 relationship. -func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExecutor, singular bool, maybeInvite interface{}, mods queries.Applicator) error { +func (inviteL) LoadCreatedByMember(ctx context.Context, e boil.ContextExecutor, singular bool, maybeInvite interface{}, mods queries.Applicator) error { var slice []*Invite var object *Invite @@ -455,8 +434,8 @@ func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExec } query := NewQuery( - qm.From(`auth_fallback`), - qm.WhereIn(`auth_fallback.id in ?`, args...), + qm.From(`members`), + qm.WhereIn(`members.id in ?`, args...), ) if mods != nil { mods.Apply(query) @@ -464,19 +443,19 @@ func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExec results, err := query.QueryContext(ctx, e) if err != nil { - return errors.Wrap(err, "failed to eager load AuthFallback") + return errors.Wrap(err, "failed to eager load Member") } - var resultSlice []*AuthFallback + var resultSlice []*Member if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice AuthFallback") + return errors.Wrap(err, "failed to bind eager loaded slice Member") } if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for auth_fallback") + return errors.Wrap(err, "failed to close results of eager load for members") } if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for auth_fallback") + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for members") } if len(inviteAfterSelectHooks) != 0 { @@ -493,9 +472,9 @@ func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExec if singular { foreign := resultSlice[0] - object.R.CreatedByAuthFallback = foreign + object.R.CreatedByMember = foreign if foreign.R == nil { - foreign.R = &authFallbackR{} + foreign.R = &memberR{} } foreign.R.CreatedByInvites = append(foreign.R.CreatedByInvites, object) return nil @@ -504,9 +483,9 @@ func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExec for _, local := range slice { for _, foreign := range resultSlice { if local.CreatedBy == foreign.ID { - local.R.CreatedByAuthFallback = foreign + local.R.CreatedByMember = foreign if foreign.R == nil { - foreign.R = &authFallbackR{} + foreign.R = &memberR{} } foreign.R.CreatedByInvites = append(foreign.R.CreatedByInvites, local) break @@ -517,10 +496,10 @@ func (inviteL) LoadCreatedByAuthFallback(ctx context.Context, e boil.ContextExec return nil } -// SetCreatedByAuthFallback of the invite to the related item. -// Sets o.R.CreatedByAuthFallback to related. +// SetCreatedByMember of the invite to the related item. +// Sets o.R.CreatedByMember to related. // Adds o to related.R.CreatedByInvites. -func (o *Invite) SetCreatedByAuthFallback(ctx context.Context, exec boil.ContextExecutor, insert bool, related *AuthFallback) error { +func (o *Invite) SetCreatedByMember(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Member) error { var err error if insert { if err = related.Insert(ctx, exec, boil.Infer()); err != nil { @@ -547,14 +526,14 @@ func (o *Invite) SetCreatedByAuthFallback(ctx context.Context, exec boil.Context o.CreatedBy = related.ID if o.R == nil { o.R = &inviteR{ - CreatedByAuthFallback: related, + CreatedByMember: related, } } else { - o.R.CreatedByAuthFallback = related + o.R.CreatedByMember = related } if related.R == nil { - related.R = &authFallbackR{ + related.R = &memberR{ CreatedByInvites: InviteSlice{o}, } } else { diff --git a/roomdb/sqlite/models/members.go b/roomdb/sqlite/models/members.go new file mode 100644 index 0000000..21292e6 --- /dev/null +++ b/roomdb/sqlite/models/members.go @@ -0,0 +1,1316 @@ +// Code generated by SQLBoiler 4.5.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package models + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// Member is an object representing the database table. +type Member struct { + ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"` + Role int64 `boil:"role" json:"role" toml:"role" yaml:"role"` + Nick string `boil:"nick" json:"nick" toml:"nick" yaml:"nick"` + PubKey roomdb.DBFeedRef `boil:"pub_key" json:"pub_key" toml:"pub_key" yaml:"pub_key"` + + R *memberR `boil:"-" json:"-" toml:"-" yaml:"-"` + L memberL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var MemberColumns = struct { + ID string + Role string + Nick string + PubKey string +}{ + ID: "id", + Role: "role", + Nick: "nick", + PubKey: "pub_key", +} + +// Generated where + +var MemberWhere = struct { + ID whereHelperint64 + Role whereHelperint64 + Nick whereHelperstring + PubKey whereHelperroomdb_DBFeedRef +}{ + ID: whereHelperint64{field: "\"members\".\"id\""}, + Role: whereHelperint64{field: "\"members\".\"role\""}, + Nick: whereHelperstring{field: "\"members\".\"nick\""}, + PubKey: whereHelperroomdb_DBFeedRef{field: "\"members\".\"pub_key\""}, +} + +// MemberRels is where relationship names are stored. +var MemberRels = struct { + Aliases string + FallbackPasswords string + CreatedByInvites string +}{ + Aliases: "Aliases", + FallbackPasswords: "FallbackPasswords", + CreatedByInvites: "CreatedByInvites", +} + +// memberR is where relationships are stored. +type memberR struct { + Aliases AliasSlice `boil:"Aliases" json:"Aliases" toml:"Aliases" yaml:"Aliases"` + FallbackPasswords FallbackPasswordSlice `boil:"FallbackPasswords" json:"FallbackPasswords" toml:"FallbackPasswords" yaml:"FallbackPasswords"` + CreatedByInvites InviteSlice `boil:"CreatedByInvites" json:"CreatedByInvites" toml:"CreatedByInvites" yaml:"CreatedByInvites"` +} + +// NewStruct creates a new relationship struct +func (*memberR) NewStruct() *memberR { + return &memberR{} +} + +// memberL is where Load methods for each relationship are stored. +type memberL struct{} + +var ( + memberAllColumns = []string{"id", "role", "nick", "pub_key"} + memberColumnsWithoutDefault = []string{} + memberColumnsWithDefault = []string{"id", "role", "nick", "pub_key"} + memberPrimaryKeyColumns = []string{"id"} +) + +type ( + // MemberSlice is an alias for a slice of pointers to Member. + // This should generally be used opposed to []Member. + MemberSlice []*Member + // MemberHook is the signature for custom Member hook methods + MemberHook func(context.Context, boil.ContextExecutor, *Member) error + + memberQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + memberType = reflect.TypeOf(&Member{}) + memberMapping = queries.MakeStructMapping(memberType) + memberPrimaryKeyMapping, _ = queries.BindMapping(memberType, memberMapping, memberPrimaryKeyColumns) + memberInsertCacheMut sync.RWMutex + memberInsertCache = make(map[string]insertCache) + memberUpdateCacheMut sync.RWMutex + memberUpdateCache = make(map[string]updateCache) + memberUpsertCacheMut sync.RWMutex + memberUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var memberBeforeInsertHooks []MemberHook +var memberBeforeUpdateHooks []MemberHook +var memberBeforeDeleteHooks []MemberHook +var memberBeforeUpsertHooks []MemberHook + +var memberAfterInsertHooks []MemberHook +var memberAfterSelectHooks []MemberHook +var memberAfterUpdateHooks []MemberHook +var memberAfterDeleteHooks []MemberHook +var memberAfterUpsertHooks []MemberHook + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *Member) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *Member) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *Member) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *Member) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *Member) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *Member) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *Member) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *Member) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *Member) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range memberAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddMemberHook registers your hook function for all future operations. +func AddMemberHook(hookPoint boil.HookPoint, memberHook MemberHook) { + switch hookPoint { + case boil.BeforeInsertHook: + memberBeforeInsertHooks = append(memberBeforeInsertHooks, memberHook) + case boil.BeforeUpdateHook: + memberBeforeUpdateHooks = append(memberBeforeUpdateHooks, memberHook) + case boil.BeforeDeleteHook: + memberBeforeDeleteHooks = append(memberBeforeDeleteHooks, memberHook) + case boil.BeforeUpsertHook: + memberBeforeUpsertHooks = append(memberBeforeUpsertHooks, memberHook) + case boil.AfterInsertHook: + memberAfterInsertHooks = append(memberAfterInsertHooks, memberHook) + case boil.AfterSelectHook: + memberAfterSelectHooks = append(memberAfterSelectHooks, memberHook) + case boil.AfterUpdateHook: + memberAfterUpdateHooks = append(memberAfterUpdateHooks, memberHook) + case boil.AfterDeleteHook: + memberAfterDeleteHooks = append(memberAfterDeleteHooks, memberHook) + case boil.AfterUpsertHook: + memberAfterUpsertHooks = append(memberAfterUpsertHooks, memberHook) + } +} + +// One returns a single member record from the query. +func (q memberQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Member, error) { + o := &Member{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: failed to execute a one query for members") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// All returns all Member records from the query. +func (q memberQuery) All(ctx context.Context, exec boil.ContextExecutor) (MemberSlice, error) { + var o []*Member + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "models: failed to assign all query results to Member slice") + } + + if len(memberAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// Count returns the count of all Member records in the query. +func (q memberQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "models: failed to count members rows") + } + + return count, nil +} + +// Exists checks if the row exists in the table. +func (q memberQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "models: failed to check if members exists") + } + + return count > 0, nil +} + +// Aliases retrieves all the alias's Aliases with an executor. +func (o *Member) Aliases(mods ...qm.QueryMod) aliasQuery { + var queryMods []qm.QueryMod + if len(mods) != 0 { + queryMods = append(queryMods, mods...) + } + + queryMods = append(queryMods, + qm.Where("\"aliases\".\"member_id\"=?", o.ID), + ) + + query := Aliases(queryMods...) + queries.SetFrom(query.Query, "\"aliases\"") + + if len(queries.GetSelect(query.Query)) == 0 { + queries.SetSelect(query.Query, []string{"\"aliases\".*"}) + } + + return query +} + +// FallbackPasswords retrieves all the fallback_password's FallbackPasswords with an executor. +func (o *Member) FallbackPasswords(mods ...qm.QueryMod) fallbackPasswordQuery { + var queryMods []qm.QueryMod + if len(mods) != 0 { + queryMods = append(queryMods, mods...) + } + + queryMods = append(queryMods, + qm.Where("\"fallback_passwords\".\"member_id\"=?", o.ID), + ) + + query := FallbackPasswords(queryMods...) + queries.SetFrom(query.Query, "\"fallback_passwords\"") + + if len(queries.GetSelect(query.Query)) == 0 { + queries.SetSelect(query.Query, []string{"\"fallback_passwords\".*"}) + } + + return query +} + +// CreatedByInvites retrieves all the invite's Invites with an executor via created_by column. +func (o *Member) CreatedByInvites(mods ...qm.QueryMod) inviteQuery { + var queryMods []qm.QueryMod + if len(mods) != 0 { + queryMods = append(queryMods, mods...) + } + + queryMods = append(queryMods, + qm.Where("\"invites\".\"created_by\"=?", o.ID), + ) + + query := Invites(queryMods...) + queries.SetFrom(query.Query, "\"invites\"") + + if len(queries.GetSelect(query.Query)) == 0 { + queries.SetSelect(query.Query, []string{"\"invites\".*"}) + } + + return query +} + +// LoadAliases allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for a 1-M or N-M relationship. +func (memberL) LoadAliases(ctx context.Context, e boil.ContextExecutor, singular bool, maybeMember interface{}, mods queries.Applicator) error { + var slice []*Member + var object *Member + + if singular { + object = maybeMember.(*Member) + } else { + slice = *maybeMember.(*[]*Member) + } + + args := make([]interface{}, 0, 1) + if singular { + if object.R == nil { + object.R = &memberR{} + } + args = append(args, object.ID) + } else { + Outer: + for _, obj := range slice { + if obj.R == nil { + obj.R = &memberR{} + } + + for _, a := range args { + if a == obj.ID { + continue Outer + } + } + + args = append(args, obj.ID) + } + } + + if len(args) == 0 { + return nil + } + + query := NewQuery( + qm.From(`aliases`), + qm.WhereIn(`aliases.member_id in ?`, args...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load aliases") + } + + var resultSlice []*Alias + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice aliases") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results in eager load on aliases") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for aliases") + } + + if len(aliasAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + if singular { + object.R.Aliases = resultSlice + for _, foreign := range resultSlice { + if foreign.R == nil { + foreign.R = &aliasR{} + } + foreign.R.Member = object + } + return nil + } + + for _, foreign := range resultSlice { + for _, local := range slice { + if local.ID == foreign.MemberID { + local.R.Aliases = append(local.R.Aliases, foreign) + if foreign.R == nil { + foreign.R = &aliasR{} + } + foreign.R.Member = local + break + } + } + } + + return nil +} + +// LoadFallbackPasswords allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for a 1-M or N-M relationship. +func (memberL) LoadFallbackPasswords(ctx context.Context, e boil.ContextExecutor, singular bool, maybeMember interface{}, mods queries.Applicator) error { + var slice []*Member + var object *Member + + if singular { + object = maybeMember.(*Member) + } else { + slice = *maybeMember.(*[]*Member) + } + + args := make([]interface{}, 0, 1) + if singular { + if object.R == nil { + object.R = &memberR{} + } + args = append(args, object.ID) + } else { + Outer: + for _, obj := range slice { + if obj.R == nil { + obj.R = &memberR{} + } + + for _, a := range args { + if a == obj.ID { + continue Outer + } + } + + args = append(args, obj.ID) + } + } + + if len(args) == 0 { + return nil + } + + query := NewQuery( + qm.From(`fallback_passwords`), + qm.WhereIn(`fallback_passwords.member_id in ?`, args...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load fallback_passwords") + } + + var resultSlice []*FallbackPassword + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice fallback_passwords") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results in eager load on fallback_passwords") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for fallback_passwords") + } + + if len(fallbackPasswordAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + if singular { + object.R.FallbackPasswords = resultSlice + for _, foreign := range resultSlice { + if foreign.R == nil { + foreign.R = &fallbackPasswordR{} + } + foreign.R.Member = object + } + return nil + } + + for _, foreign := range resultSlice { + for _, local := range slice { + if local.ID == foreign.MemberID { + local.R.FallbackPasswords = append(local.R.FallbackPasswords, foreign) + if foreign.R == nil { + foreign.R = &fallbackPasswordR{} + } + foreign.R.Member = local + break + } + } + } + + return nil +} + +// LoadCreatedByInvites allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for a 1-M or N-M relationship. +func (memberL) LoadCreatedByInvites(ctx context.Context, e boil.ContextExecutor, singular bool, maybeMember interface{}, mods queries.Applicator) error { + var slice []*Member + var object *Member + + if singular { + object = maybeMember.(*Member) + } else { + slice = *maybeMember.(*[]*Member) + } + + args := make([]interface{}, 0, 1) + if singular { + if object.R == nil { + object.R = &memberR{} + } + args = append(args, object.ID) + } else { + Outer: + for _, obj := range slice { + if obj.R == nil { + obj.R = &memberR{} + } + + for _, a := range args { + if a == obj.ID { + continue Outer + } + } + + args = append(args, obj.ID) + } + } + + if len(args) == 0 { + return nil + } + + query := NewQuery( + qm.From(`invites`), + qm.WhereIn(`invites.created_by in ?`, args...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load invites") + } + + var resultSlice []*Invite + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice invites") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results in eager load on invites") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for invites") + } + + if len(inviteAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + if singular { + object.R.CreatedByInvites = resultSlice + for _, foreign := range resultSlice { + if foreign.R == nil { + foreign.R = &inviteR{} + } + foreign.R.CreatedByMember = object + } + return nil + } + + for _, foreign := range resultSlice { + for _, local := range slice { + if local.ID == foreign.CreatedBy { + local.R.CreatedByInvites = append(local.R.CreatedByInvites, foreign) + if foreign.R == nil { + foreign.R = &inviteR{} + } + foreign.R.CreatedByMember = local + break + } + } + } + + return nil +} + +// AddAliases adds the given related objects to the existing relationships +// of the member, optionally inserting them as new records. +// Appends related to o.R.Aliases. +// Sets related.R.Member appropriately. +func (o *Member) AddAliases(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*Alias) error { + var err error + for _, rel := range related { + if insert { + rel.MemberID = o.ID + if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } else { + updateQuery := fmt.Sprintf( + "UPDATE \"aliases\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, []string{"member_id"}), + strmangle.WhereClause("\"", "\"", 0, aliasPrimaryKeyColumns), + ) + values := []interface{}{o.ID, rel.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update foreign table") + } + + rel.MemberID = o.ID + } + } + + if o.R == nil { + o.R = &memberR{ + Aliases: related, + } + } else { + o.R.Aliases = append(o.R.Aliases, related...) + } + + for _, rel := range related { + if rel.R == nil { + rel.R = &aliasR{ + Member: o, + } + } else { + rel.R.Member = o + } + } + return nil +} + +// AddFallbackPasswords adds the given related objects to the existing relationships +// of the member, optionally inserting them as new records. +// Appends related to o.R.FallbackPasswords. +// Sets related.R.Member appropriately. +func (o *Member) AddFallbackPasswords(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*FallbackPassword) error { + var err error + for _, rel := range related { + if insert { + rel.MemberID = o.ID + if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } else { + updateQuery := fmt.Sprintf( + "UPDATE \"fallback_passwords\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, []string{"member_id"}), + strmangle.WhereClause("\"", "\"", 0, fallbackPasswordPrimaryKeyColumns), + ) + values := []interface{}{o.ID, rel.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update foreign table") + } + + rel.MemberID = o.ID + } + } + + if o.R == nil { + o.R = &memberR{ + FallbackPasswords: related, + } + } else { + o.R.FallbackPasswords = append(o.R.FallbackPasswords, related...) + } + + for _, rel := range related { + if rel.R == nil { + rel.R = &fallbackPasswordR{ + Member: o, + } + } else { + rel.R.Member = o + } + } + return nil +} + +// AddCreatedByInvites adds the given related objects to the existing relationships +// of the member, optionally inserting them as new records. +// Appends related to o.R.CreatedByInvites. +// Sets related.R.CreatedByMember appropriately. +func (o *Member) AddCreatedByInvites(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*Invite) error { + var err error + for _, rel := range related { + if insert { + rel.CreatedBy = o.ID + if err = rel.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } else { + updateQuery := fmt.Sprintf( + "UPDATE \"invites\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, []string{"created_by"}), + strmangle.WhereClause("\"", "\"", 0, invitePrimaryKeyColumns), + ) + values := []interface{}{o.ID, rel.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update foreign table") + } + + rel.CreatedBy = o.ID + } + } + + if o.R == nil { + o.R = &memberR{ + CreatedByInvites: related, + } + } else { + o.R.CreatedByInvites = append(o.R.CreatedByInvites, related...) + } + + for _, rel := range related { + if rel.R == nil { + rel.R = &inviteR{ + CreatedByMember: o, + } + } else { + rel.R.CreatedByMember = o + } + } + return nil +} + +// Members retrieves all the records using an executor. +func Members(mods ...qm.QueryMod) memberQuery { + mods = append(mods, qm.From("\"members\"")) + return memberQuery{NewQuery(mods...)} +} + +// FindMember retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindMember(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*Member, error) { + memberObj := &Member{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"members\" where \"id\"=?", sel, + ) + + q := queries.Raw(query, iD) + + err := q.Bind(ctx, exec, memberObj) + if err != nil { + if errors.Cause(err) == sql.ErrNoRows { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "models: unable to select from members") + } + + return memberObj, nil +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *Member) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("models: no members provided for insertion") + } + + var err error + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(memberColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + memberInsertCacheMut.RLock() + cache, cached := memberInsertCache[key] + memberInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + memberAllColumns, + memberColumnsWithDefault, + memberColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(memberType, memberMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(memberType, memberMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"members\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"members\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + cache.retQuery = fmt.Sprintf("SELECT \"%s\" FROM \"members\" WHERE %s", strings.Join(returnColumns, "\",\""), strmangle.WhereClause("\"", "\"", 0, memberPrimaryKeyColumns)) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + result, err := exec.ExecContext(ctx, cache.query, vals...) + + if err != nil { + return errors.Wrap(err, "models: unable to insert into members") + } + + var lastID int64 + var identifierCols []interface{} + + if len(cache.retMapping) == 0 { + goto CacheNoHooks + } + + lastID, err = result.LastInsertId() + if err != nil { + return ErrSyncFail + } + + o.ID = int64(lastID) + if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == memberMapping["id"] { + goto CacheNoHooks + } + + identifierCols = []interface{}{ + o.ID, + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.retQuery) + fmt.Fprintln(writer, identifierCols...) + } + err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + if err != nil { + return errors.Wrap(err, "models: unable to populate default values for members") + } + +CacheNoHooks: + if !cached { + memberInsertCacheMut.Lock() + memberInsertCache[key] = cache + memberInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// Update uses an executor to update the Member. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *Member) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + memberUpdateCacheMut.RLock() + cache, cached := memberUpdateCache[key] + memberUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + memberAllColumns, + memberPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("models: unable to update members, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"members\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, wl), + strmangle.WhereClause("\"", "\"", 0, memberPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(memberType, memberMapping, append(wl, memberPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update members row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by update for members") + } + + if !cached { + memberUpdateCacheMut.Lock() + memberUpdateCache[key] = cache + memberUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAll updates all rows with the specified column values. +func (q memberQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all for members") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected for members") + } + + return rowsAff, nil +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o MemberSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("models: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), memberPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"members\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 0, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, memberPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to update all in member slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all member") + } + return rowsAff, nil +} + +// Delete deletes a single Member record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *Member) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("models: no Member provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), memberPrimaryKeyMapping) + sql := "DELETE FROM \"members\" WHERE \"id\"=?" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete from members") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by delete for members") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +// DeleteAll deletes all matching rows. +func (q memberQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("models: no memberQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from members") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for members") + } + + return rowsAff, nil +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o MemberSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(memberBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), memberPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"members\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, memberPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "models: unable to delete all from member slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for members") + } + + if len(memberAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *Member) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindMember(ctx, exec, o.ID) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *MemberSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := MemberSlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), memberPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"members\".* FROM \"members\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, memberPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "models: unable to reload all in MemberSlice") + } + + *o = slice + + return nil +} + +// MemberExists checks if the Member row exists. +func MemberExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"members\" where \"id\"=? limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, iD) + } + row := exec.QueryRowContext(ctx, sql, iD) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "models: unable to check if members exists") + } + + return exists, nil +} diff --git a/roomdb/sqlite/new.go b/roomdb/sqlite/new.go index 19917fe..50ad0fd 100644 --- a/roomdb/sqlite/new.go +++ b/roomdb/sqlite/new.go @@ -33,16 +33,16 @@ import ( type Database struct { db *sql.DB - AuthWithSSB roomdb.AuthWithSSBService AuthFallback roomdb.AuthFallbackService - AllowList roomdb.AllowListService - Aliases roomdb.AliasService + Members Members + Aliases Aliases - PinnedNotices roomdb.PinnedNoticesService - Notices roomdb.NoticesService + PinnedNotices PinnedNotices + Notices Notices - Invites roomdb.InviteService + Invites Invites + // DeniedList Denied } // Open looks for a database file 'fname' @@ -95,19 +95,21 @@ func Open(r repo.Interface) (*Database, error) { } }() - al := &AllowList{db} + ml := Members{db} + admindb := &Database{ - db: db, - AuthWithSSB: AuthWithSSB{db}, - AuthFallback: AuthFallback{db}, - AllowList: al, + db: db, + // DeniedList: DeniedList{db}, Aliases: Aliases{db}, + AuthFallback: AuthFallback{db}, PinnedNotices: PinnedNotices{db}, Notices: Notices{db}, + Members: ml, + Invites: Invites{ - db: db, - allowList: al, + db: db, + members: ml, }, } diff --git a/roomdb/sqlite/new_test.go b/roomdb/sqlite/new_test.go index bbac8c4..0f64e7f 100644 --- a/roomdb/sqlite/new_test.go +++ b/roomdb/sqlite/new_test.go @@ -1,6 +1,7 @@ package sqlite import ( + "bytes" "context" "os" "path/filepath" @@ -8,11 +9,26 @@ import ( _ "github.com/mattn/go-sqlite3" "github.com/ssb-ngi-pointer/go-ssb-room/internal/repo" + "github.com/ssb-ngi-pointer/go-ssb-room/roomdb" "github.com/stretchr/testify/require" + refs "go.mindeco.de/ssb-refs" ) // verify the database opens and migrates successfully from zero state -func TestSimple(t *testing.T) { +func TestSchema(t *testing.T) { + testRepo := filepath.Join("testrun", t.Name()) + os.RemoveAll(testRepo) + + tr := repo.New(testRepo) + + db, err := Open(tr) + require.NoError(t, err) + + err = db.Close() + require.NoError(t, err) +} + +func TestBasic(t *testing.T) { testRepo := filepath.Join("testrun", t.Name()) os.RemoveAll(testRepo) @@ -22,9 +38,13 @@ func TestSimple(t *testing.T) { require.NoError(t, err) ctx := context.Background() - uid, err := db.AuthFallback.Create(ctx, "testUser", []byte("super-cheesy-password-12345")) + feedA := refs.FeedRef{ID: bytes.Repeat([]byte("1312"), 8), Algo: refs.RefAlgoFeedSSB1} + memberID, err := db.Members.Add(ctx, "testNick", feedA, roomdb.RoleMember) + require.NoError(t, err) + require.NotEqual(t, 0, memberID) + + err = db.AuthFallback.Create(ctx, memberID, "testLogin", []byte("super-cheesy-password-12345")) require.NoError(t, err) - require.NotEqual(t, 0, uid) err = db.Close() require.NoError(t, err) diff --git a/roomdb/sqlite/sqlboiler.toml b/roomdb/sqlite/sqlboiler.toml index b39202b..d135811 100644 --- a/roomdb/sqlite/sqlboiler.toml +++ b/roomdb/sqlite/sqlboiler.toml @@ -1,6 +1,6 @@ [sqlite3] # go test in the admindb/sqlite package will create this -dbname = "testrun/TestSimple/roomdb" +dbname = "testrun/TestSchema/roomdb" blacklist = ["gorp_migrations"] diff --git a/roomdb/types.go b/roomdb/types.go index c6c3b05..4eb8797 100644 --- a/roomdb/types.go +++ b/roomdb/types.go @@ -26,12 +26,38 @@ type Alias struct { Signature []byte } -// User holds all the information an authenticated user of the site has. -type User struct { - ID int64 - Name string +// Member holds all the information an internal user of the room has. +type Member struct { + ID int64 + Nickname string // a common handle for the user (no-one want's to remember public keys) + Role Role + PubKey refs.FeedRef } +//go:generate stringer -type=Role + +// Role describes the authorization level of an internal user (or member). +// Valid roles are Member, Moderator or Admin. +// The zero value Uknown is used to detect missing initializion while not falling into a bad default. +type Role uint + +func (r Role) IsValid() error { + if r == RoleUnknown { + return errors.New("uknown member role") + } + if r > RoleAdmin { + return errors.New("invalid member role") + } + return nil +} + +const ( + RoleUnknown Role = iota + RoleMember + RoleModerator + RoleAdmin +) + type ErrAlreadyAdded struct { Ref refs.FeedRef } @@ -45,21 +71,18 @@ func (aa ErrAlreadyAdded) Error() string { type Invite struct { ID int64 - CreatedBy User + CreatedBy Member CreatedAt time.Time AliasSuggestion string } -// ListEntry values are returned by Allow- and DenyListServices +// ListEntry values are returned by the DenyListServices type ListEntry struct { ID int64 PubKey refs.FeedRef } -// ListEntries is a slice of ListEntries -type ListEntries []ListEntry - // DBFeedRef wraps a feed reference and implements the SQL marshaling interfaces. type DBFeedRef struct{ refs.FeedRef }