database_setup.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "cloud.google.com/go/bigtable"
  6. "google.golang.org/api/option"
  7. )
  8. // sliceContains reports whether the provided string is present in the given slice of strings.
  9. func sliceContains(list []string, target string) bool {
  10. for _, s := range list {
  11. if s == target {
  12. return true
  13. }
  14. }
  15. return false
  16. }
  17. // RunSetup will create a table and column families, if they do not already exist.
  18. func RunSetup(project string, instance string, keyFilePath string) {
  19. ctx := context.Background()
  20. // Set up admin client, tables, and column families.
  21. adminClient, err := bigtable.NewAdminClient(ctx, project, instance, option.WithCredentialsFile(keyFilePath))
  22. if err != nil {
  23. log.Fatalf("Could not create admin client: %v", err)
  24. }
  25. tables, err := adminClient.Tables(ctx)
  26. if err != nil {
  27. log.Fatalf("Could not fetch table list: %v", err)
  28. }
  29. if !sliceContains(tables, tableName) {
  30. log.Printf("Creating table %s", tableName)
  31. if err := adminClient.CreateTable(ctx, tableName); err != nil {
  32. log.Fatalf("Could not create table %s: %v", tableName, err)
  33. }
  34. }
  35. tblInfo, err := adminClient.TableInfo(ctx, tableName)
  36. if err != nil {
  37. log.Fatalf("Could not read info for table %s: %v", tableName, err)
  38. }
  39. for _, familyName := range columnFamilies {
  40. if !sliceContains(tblInfo.Families, familyName) {
  41. if err := adminClient.CreateColumnFamily(ctx, tableName, familyName); err != nil {
  42. log.Fatalf("Could not create column family %s: %v", familyName, err)
  43. }
  44. }
  45. }
  46. if err = adminClient.Close(); err != nil {
  47. log.Fatalf("Could not close admin client: %v", err)
  48. }
  49. }