Skip to content

Commit

Permalink
Return duplicate error when creating a duplicate dataset
Browse files Browse the repository at this point in the history
  • Loading branch information
ohaibbq committed Apr 14, 2024
1 parent 5ad569f commit 76f8e9e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
5 changes: 4 additions & 1 deletion internal/metadata/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ package metadata
import (
"context"
"database/sql"
"errors"
"fmt"
"sync"
)

var ErrDuplicatedDataset = errors.New("dataset is already created")

type Project struct {
ID string
datasets []*Dataset
Expand Down Expand Up @@ -69,7 +72,7 @@ func (p *Project) AddDataset(ctx context.Context, tx *sql.Tx, dataset *Dataset)
p.mu.Lock()
defer p.mu.Unlock()
if _, exists := p.datasetMap[dataset.ID]; exists {
return fmt.Errorf("dataset %s is already created", dataset.ID)
return fmt.Errorf("dataset %s: %w", dataset.ID, ErrDuplicatedDataset)
}
if err := dataset.Insert(ctx, tx); err != nil {
return err
Expand Down
6 changes: 6 additions & 0 deletions server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,13 @@ func (h *datasetsInsertHandler) ServeHTTP(w http.ResponseWriter, r *http.Request
project: project,
dataset: &dataset,
})

if err != nil {
if errors.Is(err, metadata.ErrDuplicatedDataset) {
errorResponse(ctx, w, errDuplicate(err.Error()))
return
}

errorResponse(ctx, w, errInternalError(err.Error()))
return
}
Expand Down
41 changes: 41 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -852,6 +853,46 @@ func TestDuplicateTableWithSchema(t *testing.T) {
}
}

func TestDuplicateDataset(t *testing.T) {
const (
projectName = "test"
datasetName = "dataset1"
)

ctx := context.Background()

bqServer, err := server.New(server.TempStorage)
if err != nil {
t.Fatal(err)
}
project := types.NewProject(projectName, types.NewDataset(datasetName))
if err := bqServer.Load(server.StructSource(project)); err != nil {
t.Fatal(err)
}

testServer := bqServer.TestServer()
defer func() {
testServer.Close()
bqServer.Stop(ctx)
}()

client, err := bigquery.NewClient(
ctx,
projectName,
option.WithEndpoint(testServer.URL),
option.WithoutAuthentication(),
)
if err != nil {
t.Fatal(err)
}
defer client.Close()
dataset := client.Dataset(datasetName)
err = dataset.Create(ctx, nil)
if err == nil || !strings.HasSuffix(err.Error(), "duplicate") {
t.Fatalf("expected duplicate error; got %s", err)
}
}

func TestDataFromStruct(t *testing.T) {
ctx := context.Background()

Expand Down

0 comments on commit 76f8e9e

Please sign in to comment.