CreateBucketScopesAndCollections will create the given scopes and collections within the given BucketSpec.
(ctx context.Context, bucketSpec BucketSpec, scopes map[string][]string)
| 796 | |
| 797 | // CreateBucketScopesAndCollections will create the given scopes and collections within the given BucketSpec. |
| 798 | func CreateBucketScopesAndCollections(ctx context.Context, bucketSpec BucketSpec, scopes map[string][]string) error { |
| 799 | atLeastOneScope := false |
| 800 | for _, collections := range scopes { |
| 801 | for range collections { |
| 802 | atLeastOneScope = true |
| 803 | break |
| 804 | } |
| 805 | break |
| 806 | } |
| 807 | if !atLeastOneScope { |
| 808 | // nothing to do here |
| 809 | return nil |
| 810 | } |
| 811 | |
| 812 | un, pw, _ := bucketSpec.Auth.GetCredentials() |
| 813 | var rootCAs *x509.CertPool |
| 814 | if tlsConfig := bucketSpec.TLSConfig(ctx); tlsConfig != nil { |
| 815 | rootCAs = tlsConfig.RootCAs |
| 816 | } |
| 817 | cluster, err := gocb.Connect(bucketSpec.Server, gocb.ClusterOptions{ |
| 818 | Username: un, |
| 819 | Password: pw, |
| 820 | SecurityConfig: gocb.SecurityConfig{ |
| 821 | TLSSkipVerify: bucketSpec.TLSSkipVerify, |
| 822 | TLSRootCAs: rootCAs, |
| 823 | }, |
| 824 | }) |
| 825 | if err != nil { |
| 826 | return fmt.Errorf("failed to connect to cluster: %w", err) |
| 827 | } |
| 828 | defer func() { _ = cluster.Close(nil) }() |
| 829 | |
| 830 | cm := cluster.Bucket(bucketSpec.BucketName).Collections() |
| 831 | |
| 832 | for scopeName, collections := range scopes { |
| 833 | if err := cm.CreateScope(scopeName, nil); err != nil && !errors.Is(err, gocb.ErrScopeExists) { |
| 834 | return fmt.Errorf("failed to create scope %s: %w", scopeName, err) |
| 835 | } |
| 836 | DebugfCtx(ctx, KeySGTest, "Created scope %s", scopeName) |
| 837 | for _, collectionName := range collections { |
| 838 | if err := cm.CreateCollection( |
| 839 | gocb.CollectionSpec{ |
| 840 | Name: collectionName, |
| 841 | ScopeName: scopeName, |
| 842 | }, nil); err != nil && !errors.Is(err, gocb.ErrCollectionExists) { |
| 843 | return fmt.Errorf("failed to create collection %s in scope %s: %w", collectionName, scopeName, err) |
| 844 | } |
| 845 | DebugfCtx(ctx, KeySGTest, "Created collection %s.%s", scopeName, collectionName) |
| 846 | if err := WaitForNoError(ctx, func() error { |
| 847 | _, err := cluster.Bucket(bucketSpec.BucketName).Scope(scopeName).Collection(collectionName).Exists("WaitForExists", nil) |
| 848 | return err |
| 849 | }); err != nil { |
| 850 | return fmt.Errorf("failed to wait for collection %s.%s to exist: %w", scopeName, collectionName, err) |
| 851 | } |
| 852 | DebugfCtx(ctx, KeySGTest, "Collection now exists %s.%s", scopeName, collectionName) |
| 853 | } |
| 854 | } |
| 855 |