|
| 1 | +package example |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/sqlc-dev/quickdb" |
| 12 | + pb "github.com/sqlc-dev/quickdb/v1" |
| 13 | +) |
| 14 | + |
| 15 | +func createDatabase(ctx context.Context, path string) (*pb.CreateEphemeralDatabaseResponse, error) { |
| 16 | + projectID := os.Getenv("SQLC_PROJECT_ID") |
| 17 | + authToken := os.Getenv("SQLC_AUTH_TOKEN") |
| 18 | + if projectID == "" || authToken == "" { |
| 19 | + return nil, fmt.Errorf("missing project id and auth token") |
| 20 | + } |
| 21 | + |
| 22 | + client, err := quickdb.NewClient(projectID, authToken) |
| 23 | + if err != nil { |
| 24 | + return nil, fmt.Errorf("new client: %w", err) |
| 25 | + } |
| 26 | + |
| 27 | + var migrations []string |
| 28 | + files, err := os.ReadDir(path) |
| 29 | + if err != nil { |
| 30 | + return nil, fmt.Errorf("new client: %w", err) |
| 31 | + } |
| 32 | + for _, f := range files { |
| 33 | + contents, err := os.ReadFile(filepath.Join(path, f.Name())) |
| 34 | + if err != nil { |
| 35 | + return nil, fmt.Errorf("read file: %s", err) |
| 36 | + } |
| 37 | + migrations = append(migrations, string(contents)) |
| 38 | + } |
| 39 | + |
| 40 | + resp, err := client.CreateEphemeralDatabase(ctx, &pb.CreateEphemeralDatabaseRequest{ |
| 41 | + Engine: "postgresql", |
| 42 | + Region: quickdb.GetClosestRegion(), |
| 43 | + Migrations: migrations, |
| 44 | + }) |
| 45 | + if err != nil { |
| 46 | + return nil, fmt.Errorf("create db: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + return resp, nil |
| 50 | + |
| 51 | + // cleanup := func() { |
| 52 | + // client.DropEphemeralDatabase(ctx, &pb.DropEphemeralDatabaseRequest{ |
| 53 | + // DatabaseId: resp.DatabaseId, |
| 54 | + // }) |
| 55 | + // } |
| 56 | +} |
| 57 | + |
| 58 | +func TestMain(m *testing.M) { |
| 59 | + ctx := context.Background() |
| 60 | + resp, err := createDatabase(ctx, "path/to/migrations") |
| 61 | + if err != nil { |
| 62 | + log.Fatal(err) |
| 63 | + } |
| 64 | + log.Println(resp.Uri) |
| 65 | + |
| 66 | + os.Exit(m.Run()) |
| 67 | +} |
0 commit comments